diff options
Diffstat (limited to 'chromium/content/common')
108 files changed, 2157 insertions, 3359 deletions
diff --git a/chromium/content/common/BUILD.gn b/chromium/content/common/BUILD.gn index cdce63391b1..64f33a3027b 100644 --- a/chromium/content/common/BUILD.gn +++ b/chromium/content/common/BUILD.gn @@ -5,6 +5,7 @@ import("//build/buildflag_header.gni") import("//build/config/features.gni") import("//build/config/ui.gni") +import("//content/public/common/zygote/features.gni") import("//ipc/features.gni") import("//mojo/public/tools/bindings/mojom.gni") import("//ppapi/buildflags/buildflags.gni") @@ -40,6 +41,8 @@ source_set("common") { sources = [ "all_messages.h", + "android/cpu_time_metrics.cc", + "android/cpu_time_metrics.h", "android/gin_java_bridge_errors.cc", "android/gin_java_bridge_errors.h", "android/gin_java_bridge_value.cc", @@ -55,6 +58,9 @@ source_set("common") { "appcache_interfaces.h", "ax_content_node_data.cc", "ax_content_node_data.h", + "ax_content_tree_data.cc", + "ax_content_tree_data.h", + "ax_content_tree_update.h", "ax_serialization_utils.cc", "ax_serialization_utils.h", "background_fetch/background_fetch_types.cc", @@ -88,7 +94,6 @@ source_set("common") { "cursors/webcursor_android.cc", "cursors/webcursor_aura.cc", "cursors/webcursor_aurawin.cc", - "cursors/webcursor_aurax11.cc", "cursors/webcursor_mac.mm", "cursors/webcursor_ozone.cc", "drag_event_source_info.h", @@ -120,14 +125,8 @@ source_set("common") { "input/event_with_latency_info.h", "input/gesture_event_stream_validator.cc", "input/gesture_event_stream_validator.h", - "input/ime_text_span_conversions.cc", - "input/ime_text_span_conversions.h", - "input/input_event.cc", - "input/input_event.h", "input/input_event_ack_state.cc", "input/input_event_dispatch_type.h", - "input/input_event_mojom_traits.cc", - "input/input_event_mojom_traits.h", "input/input_event_stream_validator.cc", "input/input_event_stream_validator.h", "input/synthetic_gesture_params.cc", @@ -144,23 +143,21 @@ source_set("common") { "input/synthetic_smooth_scroll_gesture_params.h", "input/synthetic_tap_gesture_params.cc", "input/synthetic_tap_gesture_params.h", - "input/synthetic_web_input_event_builders.cc", - "input/synthetic_web_input_event_builders.h", "input/touch_event_stream_validator.cc", "input/touch_event_stream_validator.h", - "input/web_mouse_wheel_event_traits.cc", - "input/web_mouse_wheel_event_traits.h", "input/web_touch_event_traits.cc", "input/web_touch_event_traits.h", "input_messages.h", "inter_process_time_ticks_converter.cc", "inter_process_time_ticks_converter.h", - "mac/attributed_string_coder.h", - "mac/attributed_string_coder.mm", + "mac/attributed_string_type_converters.h", + "mac/attributed_string_type_converters.mm", "mac/font_loader.h", "mac/font_loader.mm", "media/cdm_info.cc", "media/media_player_delegate_messages.h", + "mojo_core_library_support.cc", + "mojo_core_library_support.h", "navigation_gesture.h", "navigation_params.cc", "navigation_params.h", @@ -183,7 +180,6 @@ source_set("common") { "sandbox_init_linux.cc", "sandbox_init_mac.cc", "sandbox_init_win.cc", - "savable_subframe.h", "service_manager/service_manager_connection_impl.cc", "service_manager/service_manager_connection_impl.h", "service_worker/service_worker_loader_helpers.cc", @@ -192,9 +188,8 @@ source_set("common") { "service_worker/service_worker_utils.h", "skia_utils.cc", "skia_utils.h", + "state_transitions.h", "text_input_client_messages.h", - "text_input_state.cc", - "text_input_state.h", "thread_pool_util.cc", "thread_pool_util.h", "unfreezable_frame_messages.h", @@ -230,7 +225,7 @@ source_set("common") { "//third_party/blink/public/common", "//ui/accessibility", "//ui/accessibility/mojom", - "//ui/base/cursor", + "//ui/base/cursor:cursor_base", "//ui/base/cursor/mojom:cursor_type", "//ui/events/ipc", ] @@ -276,8 +271,8 @@ source_set("common") { "//services/network/public/cpp", "//services/network/public/mojom", "//services/resource_coordinator/public/cpp/memory_instrumentation", + "//services/service_manager/embedder:embedder_result_codes", "//services/service_manager/public/mojom", - "//services/service_manager/zygote:zygote_buildflags", "//services/video_capture/public/mojom", "//services/viz/public/mojom", "//skia", @@ -347,26 +342,34 @@ source_set("common") { deps += [ "//ppapi/proxy:ipc_sources" ] } - if (use_ozone) { - deps += [ "//ui/ozone" ] - } else { + if (!use_x11 && !use_ozone) { sources -= [ "cursors/webcursor_ozone.cc" ] } - if (!use_aura) { - sources -= [ "cursors/webcursor_aura.cc" ] - } - - if (!use_aura || !use_x11) { - sources -= [ "cursors/webcursor_aurax11.cc" ] + if (use_aura) { + deps += [ "//ui/base/cursor" ] } else { - deps += [ "//ui/gfx/x" ] + sources -= [ "cursors/webcursor_aura.cc" ] } if (is_linux) { + sources += [ + "zygote/sandbox_support_linux.cc", + "zygote/send_zygote_child_ping_linux.cc", + "zygote/zygote_commands_linux.h", + "zygote/zygote_communication_linux.cc", + "zygote/zygote_communication_linux.h", + ] deps += [ "//third_party/fontconfig" ] } + if (use_zygote_handle) { + sources += [ + "zygote/zygote_handle_impl_linux.h", + "zygote/zygote_handle_linux.cc", + ] + } + if (is_mac || is_win || is_android || is_fuchsia) { sources -= [ "font_list_fontconfig.cc" ] } @@ -447,9 +450,7 @@ mojom("mojo_bindings") { "frame_proxy.mojom", "frame_sink_provider.mojom", "histogram_fetcher.mojom", - "input/input_handler.mojom", "input/input_injector.mojom", - "input/synchronous_compositor.mojom", "media/media_log_records.mojom", "media/renderer_audio_input_stream_factory.mojom", "media/renderer_audio_output_stream_factory.mojom", @@ -464,7 +465,6 @@ mojom("mojo_bindings") { "renderer.mojom", "renderer_host.mojom", "renderer_variations_configuration.mojom", - "widget.mojom", ] enabled_features = [] @@ -549,19 +549,22 @@ mojom("mojo_bindings") { cpp = "::content::ContentSecurityPolicy" }, { - mojom = "content.mojom.Event" - cpp = "::std::unique_ptr<::content::InputEvent>" - move_only = true - }, - { mojom = "content.mojom.FrameReplicationState" cpp = "::content::FrameReplicationState" }, { + mojom = "content.mojom.NavigationDownloadPolicy" + cpp = "::content::NavigationDownloadPolicy" + }, + { mojom = "content.mojom.NetworkConnectionType" cpp = "::net::NetworkChangeNotifier::ConnectionType" }, { + mojom = "content.mojom.Impression" + cpp = "::content::Impression" + }, + { mojom = "content.mojom.ScrollGranularity" cpp = "::ui::ScrollGranularity" }, @@ -590,6 +593,10 @@ mojom("mojo_bindings") { cpp = "::ui::NativeTheme::SystemThemeColor" }, { + mojom = "content.mojom.TriggeringEventInfo" + cpp = "::blink::TriggeringEventInfo" + }, + { mojom = "content.mojom.VisualProperties" cpp = "::content::VisualProperties" }, @@ -607,7 +614,6 @@ mojom("mojo_bindings") { "//cc/input/touch_action.h", "//content/common/cursors/webcursor.h", "//content/common/frame_replication_state.h", - "//content/common/input/input_event.h", "//content/common/input/synthetic_pinch_gesture_params.h", "//content/common/input/synthetic_pointer_action_list_params.h", "//content/common/input/synthetic_smooth_drag_gesture_params.h", @@ -616,10 +622,12 @@ mojom("mojo_bindings") { "//content/common/visual_properties.h", "//content/public/common/web_preferences.h", "//net/base/network_change_notifier.h", + "//third_party/blink/public/common/input/web_coalesced_input_event_mojom_traits.h", "//third_party/blink/public/common/input/web_input_event.h", "//third_party/blink/public/common/input/web_mouse_wheel_event.h", "//third_party/blink/public/common/input/web_pointer_properties.h", "//third_party/blink/public/common/input/web_touch_point.h", + "//third_party/blink/public/common/navigation/triggering_event_info.h", "//ui/events/blink/did_overscroll_params.h", "//ui/events/blink/web_input_event_traits.h", "//ui/latency/ipc/latency_info_param_traits.h", @@ -628,7 +636,6 @@ mojom("mojo_bindings") { traits_private_headers = [ "//content/common/frame_messages.h", - "//content/common/input/input_event_mojom_traits.h", "//content/common/input_messages.h", "//content/common/view_messages.h", "//content/common/widget_messages.h", @@ -651,7 +658,7 @@ mojom("mojo_bindings") { "//services/network/public/cpp", "//third_party/blink/public/common", "//ui/accessibility", - "//ui/base/cursor", + "//ui/base/cursor:cursor_base", "//ui/base/ime:text_input_types", "//ui/events/blink", "//ui/gfx/ipc", @@ -763,18 +770,12 @@ mojom("mojo_bindings") { { types = [ { - mojom = "content.mojom.EncodedAttributedString" - cpp = "::mac::AttributedStringCoder::EncodedString" - }, - { mojom = "content.mojom.ScrollerStyle" cpp = "::blink::ScrollerStyle" }, ] - traits_headers = [ - "//content/common/mac/attributed_string_coder.h", - "//third_party/blink/public/platform/mac/web_scrollbar_theme.h", - ] + traits_headers = + [ "//third_party/blink/public/platform/mac/web_scrollbar_theme.h" ] traits_private_headers = [ "//content/common/view_messages.h" ] traits_public_deps = [ "//third_party/blink/public:blink_headers" ] }, diff --git a/chromium/content/common/DEPS b/chromium/content/common/DEPS index 2c808941169..8154671148c 100644 --- a/chromium/content/common/DEPS +++ b/chromium/content/common/DEPS @@ -23,7 +23,7 @@ include_rules = [ "+third_party/blink/public/mojom", "+third_party/blink/public/platform/viewport_intersection_state.h", "+third_party/blink/public/platform/web_content_security_policy.h", - "+third_party/blink/public/platform/web_drag_operation.h", + "+third_party/blink/public/common/page/web_drag_operation.h", "+third_party/blink/public/platform/web_float_rect.h", "+third_party/blink/public/platform/web_float_size.h", "+third_party/blink/public/platform/web_fullscreen_video_status.h", @@ -42,7 +42,6 @@ include_rules = [ "+third_party/blink/public/web/web_device_emulation_params.h", "+third_party/blink/public/web/web_drag_status.h", "+third_party/blink/public/web/web_frame_owner_properties.h", - "+third_party/blink/public/web/web_ime_text_span.h", "+third_party/blink/public/web/win/web_font_rendering.h", ] specific_include_rules = { diff --git a/chromium/content/common/android/cpu_time_metrics.cc b/chromium/content/common/android/cpu_time_metrics.cc new file mode 100644 index 00000000000..9c5490d76a0 --- /dev/null +++ b/chromium/content/common/android/cpu_time_metrics.cc @@ -0,0 +1,400 @@ +// Copyright 2020 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 "content/common/android/cpu_time_metrics.h" + +#include <stdint.h> + +#include <atomic> +#include <memory> + +#include "base/bind_helpers.h" +#include "base/command_line.h" +#include "base/containers/flat_map.h" +#include "base/lazy_instance.h" +#include "base/message_loop/message_loop_current.h" +#include "base/metrics/histogram_macros.h" +#include "base/no_destructor.h" +#include "base/process/process_metrics.h" +#include "base/sequence_checker.h" +#include "base/strings/pattern.h" +#include "base/strings/string_util.h" +#include "base/task/post_task.h" +#include "base/task/task_observer.h" +#include "base/threading/platform_thread.h" +#include "base/threading/thread_id_name_manager.h" +#include "base/threading/thread_task_runner_handle.h" +#include "content/public/common/content_switches.h" +#include "content/public/common/process_type.h" + +namespace content { +namespace { + +// Histogram macros expect an enum class with kMaxValue. Because +// content::ProcessType cannot be migrated to this style at the moment, we +// specify a separate version here. Keep in sync with content::ProcessType. +// TODO(eseckler): Replace with content::ProcessType after its migration. +enum class ProcessTypeForUma { + kUnknown = 1, + kBrowser, + kRenderer, + kPluginDeprecated, + kWorkerDeprecated, + kUtility, + kZygote, + kSandboxHelper, + kGpu, + kPpapiPlugin, + kPpapiBroker, + kMaxValue = kPpapiBroker, +}; + +static_assert(static_cast<int>(ProcessTypeForUma::kMaxValue) == + PROCESS_TYPE_PPAPI_BROKER, + "ProcessTypeForUma and CurrentProcessType() require updating"); + +ProcessTypeForUma CurrentProcessType() { + std::string process_type = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kProcessType); + if (process_type.empty()) + return ProcessTypeForUma::kBrowser; + if (process_type == switches::kRendererProcess) + return ProcessTypeForUma::kRenderer; + if (process_type == switches::kUtilityProcess) + return ProcessTypeForUma::kUtility; + if (process_type == switches::kSandboxIPCProcess) + return ProcessTypeForUma::kSandboxHelper; + if (process_type == switches::kGpuProcess) + return ProcessTypeForUma::kGpu; + if (process_type == switches::kPpapiPluginProcess) + return ProcessTypeForUma::kPpapiPlugin; + if (process_type == switches::kPpapiBrokerProcess) + return ProcessTypeForUma::kPpapiBroker; + NOTREACHED() << "Unexpected process type: " << process_type; + return ProcessTypeForUma::kUnknown; +} + +const char* GetPerThreadHistogramNameForProcessType(ProcessTypeForUma type) { + switch (type) { + case ProcessTypeForUma::kBrowser: + return "Power.CpuTimeSecondsPerThreadType.Browser"; + case ProcessTypeForUma::kRenderer: + return "Power.CpuTimeSecondsPerThreadType.Renderer"; + case ProcessTypeForUma::kGpu: + return "Power.CpuTimeSecondsPerThreadType.GPU"; + default: + return "Power.CpuTimeSecondsPerThreadType.Other"; + } +} + +// Keep in sync with CpuTimeMetricsThreadType in +// //tools/metrics/histograms/enums.xml. +enum class CpuTimeMetricsThreadType { + kUnattributedThread = 0, + kOtherThread, + kMainThread, + kIOThread, + kThreadPoolBackgroundWorkerThread, + kThreadPoolForegroundWorkerThread, + kThreadPoolServiceThread, + kCompositorThread, + kCompositorTileWorkerThread, + kVizCompositorThread, + kRendererUnspecifiedWorkerThread, + kRendererDedicatedWorkerThread, + kRendererSharedWorkerThread, + kRendererAnimationAndPaintWorkletThread, + kRendererServiceWorkerThread, + kRendererAudioWorkletThread, + kRendererFileThread, + kRendererDatabaseThread, + kRendererOfflineAudioRenderThread, + kRendererReverbConvolutionBackgroundThread, + kRendererHRTFDatabaseLoaderThread, + kRendererAudioEncoderThread, + kRendererVideoEncoderThread, + kMemoryInfraThread, + kSamplingProfilerThread, + kNetworkServiceThread, + kAudioThread, + kInProcessUtilityThread, + kInProcessRendererThread, + kInProcessGpuThread, + kMaxValue = kInProcessGpuThread, +}; + +CpuTimeMetricsThreadType GetThreadTypeFromName(const char* const thread_name) { + if (!thread_name) + return CpuTimeMetricsThreadType::kOtherThread; + + if (base::MatchPattern(thread_name, "Cr*Main")) { + return CpuTimeMetricsThreadType::kMainThread; + } else if (base::MatchPattern(thread_name, "Chrome*IOThread")) { + return CpuTimeMetricsThreadType::kIOThread; + } else if (base::MatchPattern(thread_name, "ThreadPool*Foreground*")) { + return CpuTimeMetricsThreadType::kThreadPoolForegroundWorkerThread; + } else if (base::MatchPattern(thread_name, "ThreadPool*Background*")) { + return CpuTimeMetricsThreadType::kThreadPoolBackgroundWorkerThread; + } else if (base::MatchPattern(thread_name, "ThreadPoolService*")) { + return CpuTimeMetricsThreadType::kThreadPoolServiceThread; + } else if (base::MatchPattern(thread_name, "Compositor")) { + return CpuTimeMetricsThreadType::kCompositorThread; + } else if (base::MatchPattern(thread_name, "CompositorTileWorker*")) { + return CpuTimeMetricsThreadType::kCompositorTileWorkerThread; + } else if (base::MatchPattern(thread_name, "VizCompositor*")) { + return CpuTimeMetricsThreadType::kVizCompositorThread; + } else if (base::MatchPattern(thread_name, "unspecified worker*")) { + return CpuTimeMetricsThreadType::kRendererUnspecifiedWorkerThread; + } else if (base::MatchPattern(thread_name, "DedicatedWorker*")) { + return CpuTimeMetricsThreadType::kRendererDedicatedWorkerThread; + } else if (base::MatchPattern(thread_name, "SharedWorker*")) { + return CpuTimeMetricsThreadType::kRendererSharedWorkerThread; + } else if (base::MatchPattern(thread_name, "AnimationWorklet*")) { + return CpuTimeMetricsThreadType::kRendererAnimationAndPaintWorkletThread; + } else if (base::MatchPattern(thread_name, "ServiceWorker*")) { + return CpuTimeMetricsThreadType::kRendererServiceWorkerThread; + } else if (base::MatchPattern(thread_name, "AudioWorklet*")) { + return CpuTimeMetricsThreadType::kRendererAudioWorkletThread; + } else if (base::MatchPattern(thread_name, "File thread")) { + return CpuTimeMetricsThreadType::kRendererFileThread; + } else if (base::MatchPattern(thread_name, "Database thread")) { + return CpuTimeMetricsThreadType::kRendererDatabaseThread; + } else if (base::MatchPattern(thread_name, "OfflineAudioRender*")) { + return CpuTimeMetricsThreadType::kRendererOfflineAudioRenderThread; + } else if (base::MatchPattern(thread_name, "Reverb convolution*")) { + return CpuTimeMetricsThreadType::kRendererReverbConvolutionBackgroundThread; + } else if (base::MatchPattern(thread_name, "HRTF*")) { + return CpuTimeMetricsThreadType::kRendererHRTFDatabaseLoaderThread; + } else if (base::MatchPattern(thread_name, "Audio encoder*")) { + return CpuTimeMetricsThreadType::kRendererAudioEncoderThread; + } else if (base::MatchPattern(thread_name, "Video encoder*")) { + return CpuTimeMetricsThreadType::kRendererVideoEncoderThread; + } else if (base::MatchPattern(thread_name, "MemoryInfra")) { + return CpuTimeMetricsThreadType::kMemoryInfraThread; + } else if (base::MatchPattern(thread_name, "StackSamplingProfiler")) { + return CpuTimeMetricsThreadType::kSamplingProfilerThread; + } else if (base::MatchPattern(thread_name, "NetworkService")) { + return CpuTimeMetricsThreadType::kNetworkServiceThread; + } else if (base::MatchPattern(thread_name, "AudioThread")) { + return CpuTimeMetricsThreadType::kAudioThread; + } else if (base::MatchPattern(thread_name, "Chrome_InProcUtilityThread")) { + return CpuTimeMetricsThreadType::kInProcessUtilityThread; + } else if (base::MatchPattern(thread_name, "Chrome_InProcRendererThread")) { + return CpuTimeMetricsThreadType::kInProcessRendererThread; + } else if (base::MatchPattern(thread_name, "Chrome_InProcGpuThread")) { + return CpuTimeMetricsThreadType::kInProcessGpuThread; + } + + // TODO(eseckler): Also break out Android's RenderThread here somehow? + + return CpuTimeMetricsThreadType::kOtherThread; +} + +// Samples the process's CPU time after a specific number of task were executed +// on the current thread (process main). The number of tasks is a crude proxy +// for CPU activity within this process. We sample more frequently when the +// process is more active, thus ensuring we lose little CPU time attribution +// when the process is terminated, even after it was very active. +class ProcessCpuTimeTaskObserver : public base::TaskObserver { + public: + static ProcessCpuTimeTaskObserver* GetInstance() { + static base::NoDestructor<ProcessCpuTimeTaskObserver> instance; + return instance.get(); + } + + ProcessCpuTimeTaskObserver() + : task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, + // TODO(eseckler): Consider hooking into process shutdown on + // desktop to reduce metric data loss. + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), + process_metrics_(base::ProcessMetrics::CreateCurrentProcessMetrics()), + process_type_(CurrentProcessType()), + // The observer is created on the main thread of the process. + main_thread_id_(base::PlatformThread::CurrentId()) { + // Browser and GPU processes have a longer lifetime (don't disappear between + // navigations), and typically execute a large number of small main-thread + // tasks. For these processes, choose a higher reporting interval. + if (process_type_ == ProcessTypeForUma::kBrowser || + process_type_ == ProcessTypeForUma::kGpu) { + reporting_interval_ = kReportAfterEveryNTasksPersistentProcess; + } else { + reporting_interval_ = kReportAfterEveryNTasksOtherProcess; + } + DETACH_FROM_SEQUENCE(thread_pool_); + } + + // base::TaskObserver implementation: + void WillProcessTask(const base::PendingTask& pending_task, + bool was_blocked_or_low_priority) override {} + + void DidProcessTask(const base::PendingTask& pending_task) override { + DCHECK_CALLED_ON_VALID_SEQUENCE(main_thread_); + // We perform the collection from a background thread. Only schedule another + // one after a reasonably large amount of work was executed after the last + // collection completed. std::memory_order_relaxed because we only care that + // we pick up the change back by the posted task eventually. + if (collection_in_progress_.load(std::memory_order_relaxed)) + return; + task_counter_++; + if (task_counter_ == reporting_interval_) { + // PostTask() applies a barrier, so this will be applied before the thread + // pool task executes and sets |collection_in_progress_| back to false. + collection_in_progress_.store(true, std::memory_order_relaxed); + task_runner_->PostTask( + FROM_HERE, + base::BindOnce( + &ProcessCpuTimeTaskObserver::CollectAndReportCpuTimeOnThreadPool, + base::Unretained(this))); + task_counter_ = 0; + } + } + + void CollectAndReportCpuTimeOnThreadPool() { + DCHECK_CALLED_ON_VALID_SEQUENCE(thread_pool_); + + // This might overflow. We only care that it is different for each cycle. + current_cycle_++; + + // GetCumulativeCPUUsage() may return a negative value if sampling failed. + base::TimeDelta cumulative_cpu_time = + process_metrics_->GetCumulativeCPUUsage(); + base::TimeDelta cpu_time_delta = cumulative_cpu_time - reported_cpu_time_; + if (cpu_time_delta > base::TimeDelta()) { + UMA_HISTOGRAM_SCALED_ENUMERATION( + "Power.CpuTimeSecondsPerProcessType", process_type_, + cpu_time_delta.InMicroseconds(), base::Time::kMicrosecondsPerSecond); + reported_cpu_time_ = cumulative_cpu_time; + } + + // Also report a breakdown by thread type. + base::TimeDelta unattributed_delta = cpu_time_delta; + if (process_metrics_->GetCumulativeCPUUsagePerThread( + cumulative_thread_times_)) { + for (const auto& entry : cumulative_thread_times_) { + base::PlatformThreadId tid = entry.first; + base::TimeDelta cumulative_time = entry.second; + + auto it_and_inserted = thread_details_.emplace( + tid, ThreadDetails{base::TimeDelta(), current_cycle_}); + ThreadDetails* thread_details = &it_and_inserted.first->second; + + if (it_and_inserted.second) { + // New thread. + thread_details->type = GuessThreadType(tid); + } + + thread_details->last_updated_cycle = current_cycle_; + + // Skip negative or null values, might be a transient collection error. + if (cumulative_time <= base::TimeDelta()) + continue; + + if (cumulative_time < thread_details->reported_cpu_time) { + // PlatformThreadId was likely reused, reset the details. + thread_details->reported_cpu_time = base::TimeDelta(); + thread_details->type = GuessThreadType(tid); + } + + base::TimeDelta thread_delta = + cumulative_time - thread_details->reported_cpu_time; + unattributed_delta -= thread_delta; + + ReportThreadCpuTimeDelta(thread_details->type, thread_delta); + thread_details->reported_cpu_time = cumulative_time; + } + + // Erase tracking for threads that have disappeared, as their + // PlatformThreadId may be reused later. + for (auto it = thread_details_.begin(); it != thread_details_.end();) { + if (it->second.last_updated_cycle == current_cycle_) { + it++; + } else { + it = thread_details_.erase(it); + } + } + } + + // Report the difference of the process's total CPU time and all thread's + // CPU time as unattributed time (e.g. time consumed by threads that died). + if (unattributed_delta > base::TimeDelta()) { + ReportThreadCpuTimeDelta(CpuTimeMetricsThreadType::kUnattributedThread, + unattributed_delta); + } + + collection_in_progress_.store(false, std::memory_order_relaxed); + } + + private: + struct ThreadDetails { + base::TimeDelta reported_cpu_time; + uint32_t last_updated_cycle = 0; + CpuTimeMetricsThreadType type = CpuTimeMetricsThreadType::kOtherThread; + }; + + void ReportThreadCpuTimeDelta(CpuTimeMetricsThreadType type, + base::TimeDelta cpu_time_delta) { + // Histogram name cannot change after being used once. That's ok since this + // only depends on the process type, which also doesn't change. + static const char* histogram_name = + GetPerThreadHistogramNameForProcessType(process_type_); + UMA_HISTOGRAM_SCALED_ENUMERATION(histogram_name, type, + cpu_time_delta.InMicroseconds(), + base::Time::kMicrosecondsPerSecond); + } + + CpuTimeMetricsThreadType GuessThreadType(base::PlatformThreadId tid) { + // Match the main thread by TID, so that this also works for WebView, where + // the main thread can have an arbitrary name. + if (tid == main_thread_id_) + return CpuTimeMetricsThreadType::kMainThread; + const char* name = base::ThreadIdNameManager::GetInstance()->GetName(tid); + return GetThreadTypeFromName(name); + } + + // Sample CPU time after a certain number of main-thread task to balance + // overhead of sampling and loss at process termination. + static constexpr int kReportAfterEveryNTasksPersistentProcess = 500; + static constexpr int kReportAfterEveryNTasksOtherProcess = 100; + + // Accessed on main thread. + SEQUENCE_CHECKER(main_thread_); + scoped_refptr<base::SequencedTaskRunner> task_runner_; + int task_counter_ = 0; + int reporting_interval_ = 0; // set in constructor. + + // Accessed on |task_runner_|. + SEQUENCE_CHECKER(thread_pool_); + uint32_t current_cycle_ = 0; + std::unique_ptr<base::ProcessMetrics> process_metrics_; + ProcessTypeForUma process_type_; + base::PlatformThreadId main_thread_id_; + base::TimeDelta reported_cpu_time_; + // Stored as instance variable to avoid allocation churn. + base::ProcessMetrics::CPUUsagePerThread cumulative_thread_times_; + base::flat_map<base::PlatformThreadId, ThreadDetails> thread_details_; + + // Accessed on both sequences. + std::atomic<bool> collection_in_progress_; +}; + +} // namespace + +void SetupCpuTimeMetrics() { + // May be called multiple times for in-process renderer/utility/GPU processes. + static bool did_setup = false; + if (did_setup) + return; + base::MessageLoopCurrent::Get()->AddTaskObserver( + ProcessCpuTimeTaskObserver::GetInstance()); + did_setup = true; +} + +void SampleCpuTimeMetricsForTesting() { + ProcessCpuTimeTaskObserver::GetInstance() + ->CollectAndReportCpuTimeOnThreadPool(); +} + +} // namespace content diff --git a/chromium/content/common/android/cpu_time_metrics.h b/chromium/content/common/android/cpu_time_metrics.h new file mode 100644 index 00000000000..38c4c2a750c --- /dev/null +++ b/chromium/content/common/android/cpu_time_metrics.h @@ -0,0 +1,28 @@ +// Copyright 2020 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 CONTENT_COMMON_ANDROID_CPU_TIME_METRICS_H_ +#define CONTENT_COMMON_ANDROID_CPU_TIME_METRICS_H_ + +#include "content/common/content_export.h" + +namespace content { + +// Sets up periodic collection/reporting of the process's CPU time. Should be +// called on the process's main thread. +// +// The current process's CPU time usage is recorded periodically and reported it +// into UMA histograms. The histogram data can later be used to approximate the +// power consumption / efficiency of the app. Currently only supports Android, +// where the sandbox allows isolated processes to read from /proc/self/stats. +CONTENT_EXPORT void SetupCpuTimeMetrics(); + +// Sample and report the CPU time UMA metrics immediately on the current thread. +// Beware: Should only be used for testing and never in combination with +// SetupCpuTimeMetrics(). +CONTENT_EXPORT void SampleCpuTimeMetricsForTesting(); + +} // namespace content + +#endif // CONTENT_COMMON_ANDROID_CPU_TIME_METRICS_H_ diff --git a/chromium/content/common/android/cpu_time_metrics_unittest.cc b/chromium/content/common/android/cpu_time_metrics_unittest.cc new file mode 100644 index 00000000000..8e383d42198 --- /dev/null +++ b/chromium/content/common/android/cpu_time_metrics_unittest.cc @@ -0,0 +1,66 @@ +// Copyright 2020 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 "content/common/android/cpu_time_metrics.h" + +#include "base/synchronization/waitable_event.h" +#include "base/test/metrics/histogram_tester.h" +#include "base/test/task_environment.h" +#include "base/threading/thread.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace content { +namespace { + +void WorkForOneCpuSec(base::WaitableEvent* event) { + auto initial_ticks = base::ThreadTicks::Now(); + while (!event->IsSignaled()) { + if (base::ThreadTicks::Now() > + initial_ticks + base::TimeDelta::FromSeconds(1)) { + event->Signal(); + } + } +} + +TEST(CpuTimeMetricsTest, RecordsMetrics) { + base::test::TaskEnvironment task_environment; + base::HistogramTester histograms; + base::Thread thread1("StackSamplingProfiler"); + + thread1.StartAndWaitForTesting(); + ASSERT_TRUE(thread1.IsRunning()); + + base::WaitableEvent event; + + thread1.task_runner()->PostTask( + FROM_HERE, BindOnce(&WorkForOneCpuSec, base::Unretained(&event))); + + // Wait until the thread has consumed one second of CPU time. + event.Wait(); + + // Update current metrics. + SampleCpuTimeMetricsForTesting(); + + // The test process has no process-type command line flag, so is recognized as + // the browser process. The thread created above is named like a sampling + // profiler thread. + static constexpr int kBrowserProcessBucket = 2; + static constexpr int kSamplingProfilerThreadBucket = 24; + + // Expect that the CPU second spent by the thread above is represented in the + // metrics. + int browser_cpu_seconds = histograms.GetBucketCount( + "Power.CpuTimeSecondsPerProcessType", kBrowserProcessBucket); + EXPECT_GE(browser_cpu_seconds, 1); + + int thread_cpu_seconds = + histograms.GetBucketCount("Power.CpuTimeSecondsPerThreadType.Browser", + kSamplingProfilerThreadBucket); + EXPECT_GE(thread_cpu_seconds, 1); + + thread1.Stop(); +} + +} // namespace +} // namespace content
\ No newline at end of file diff --git a/chromium/content/common/ax_content_node_data.cc b/chromium/content/common/ax_content_node_data.cc index 69d550e8d23..d40a068fabe 100644 --- a/chromium/content/common/ax_content_node_data.cc +++ b/chromium/content/common/ax_content_node_data.cc @@ -25,15 +25,4 @@ std::string AXContentNodeData::ToString() const { return result; } -std::string AXContentTreeData::ToString() const { - std::string result = AXTreeData::ToString(); - - if (routing_id != MSG_ROUTING_NONE) - result += " routing_id=" + NumberToString(routing_id); - if (parent_routing_id != MSG_ROUTING_NONE) - result += " parent_routing_id=" + NumberToString(parent_routing_id); - - return result; -} - } // namespace ui diff --git a/chromium/content/common/ax_content_node_data.h b/chromium/content/common/ax_content_node_data.h index ab7d4225665..af23817eb94 100644 --- a/chromium/content/common/ax_content_node_data.h +++ b/chromium/content/common/ax_content_node_data.h @@ -10,8 +10,6 @@ #include "content/common/content_export.h" #include "ipc/ipc_message.h" #include "ui/accessibility/ax_node_data.h" -#include "ui/accessibility/ax_tree_data.h" -#include "ui/accessibility/ax_tree_update.h" namespace content { @@ -30,25 +28,6 @@ struct CONTENT_EXPORT AXContentNodeData : public ui::AXNodeData { int32_t child_routing_id = MSG_ROUTING_NONE; }; -// A subclass of AXTreeData that contains extra fields for -// content-layer-specific AX attributes. -struct CONTENT_EXPORT AXContentTreeData : public ui::AXTreeData { - AXContentTreeData() = default; - ~AXContentTreeData() override = default; - - // Return a string representation of this data, for debugging. - std::string ToString() const override; - - // The routing ID of this frame. - int routing_id = MSG_ROUTING_NONE; - - // The routing ID of the parent frame. - int parent_routing_id = MSG_ROUTING_NONE; -}; - -typedef ui::AXTreeUpdateBase<content::AXContentNodeData, - content::AXContentTreeData> AXContentTreeUpdate; - } // namespace content #endif // CONTENT_COMMON_AX_CONTENT_NODE_DATA_H_ diff --git a/chromium/content/common/ax_content_tree_data.cc b/chromium/content/common/ax_content_tree_data.cc new file mode 100644 index 00000000000..a9c6fc86484 --- /dev/null +++ b/chromium/content/common/ax_content_tree_data.cc @@ -0,0 +1,24 @@ +// Copyright 2020 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 "content/common/ax_content_tree_data.h" + +#include "base/strings/string_number_conversions.h" + +using base::NumberToString; + +namespace content { + +std::string AXContentTreeData::ToString() const { + std::string result = AXTreeData::ToString(); + + if (routing_id != MSG_ROUTING_NONE) + result += " routing_id=" + NumberToString(routing_id); + if (parent_routing_id != MSG_ROUTING_NONE) + result += " parent_routing_id=" + NumberToString(parent_routing_id); + + return result; +} + +} // namespace content diff --git a/chromium/content/common/ax_content_tree_data.h b/chromium/content/common/ax_content_tree_data.h new file mode 100644 index 00000000000..31c849cb8d9 --- /dev/null +++ b/chromium/content/common/ax_content_tree_data.h @@ -0,0 +1,34 @@ +// Copyright 2020 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 CONTENT_COMMON_AX_CONTENT_TREE_DATA_H_ +#define CONTENT_COMMON_AX_CONTENT_TREE_DATA_H_ + +#include <stdint.h> + +#include "content/common/content_export.h" +#include "ipc/ipc_message.h" +#include "ui/accessibility/ax_tree_data.h" + +namespace content { + +// A subclass of AXTreeData that contains extra fields for +// content-layer-specific AX attributes. +struct CONTENT_EXPORT AXContentTreeData : public ui::AXTreeData { + AXContentTreeData() = default; + ~AXContentTreeData() override = default; + + // Return a string representation of this data, for debugging. + std::string ToString() const override; + + // The routing ID of this frame. + int routing_id = MSG_ROUTING_NONE; + + // The routing ID of the parent frame. + int parent_routing_id = MSG_ROUTING_NONE; +}; + +} // namespace content + +#endif // CONTENT_COMMON_AX_CONTENT_TREE_DATA_H_ diff --git a/chromium/content/common/ax_content_tree_data_mojom_traits.h b/chromium/content/common/ax_content_tree_data_mojom_traits.h index ef3657ee92b..2dbbd42b8bd 100644 --- a/chromium/content/common/ax_content_tree_data_mojom_traits.h +++ b/chromium/content/common/ax_content_tree_data_mojom_traits.h @@ -5,7 +5,7 @@ #ifndef CONTENT_COMMON_AX_CONTENT_TREE_DATA_MOJOM_TRAITS_H_ #define CONTENT_COMMON_AX_CONTENT_TREE_DATA_MOJOM_TRAITS_H_ -#include "content/common/ax_content_node_data.h" +#include "content/common/ax_content_tree_data.h" #include "content/common/ax_content_tree_data.mojom-shared.h" #include "ui/accessibility/ax_tree_data.h" diff --git a/chromium/content/common/ax_content_tree_update.h b/chromium/content/common/ax_content_tree_update.h new file mode 100644 index 00000000000..3bc36481888 --- /dev/null +++ b/chromium/content/common/ax_content_tree_update.h @@ -0,0 +1,21 @@ +// Copyright 2020 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 CONTENT_COMMON_AX_CONTENT_TREE_UPDATE_H_ +#define CONTENT_COMMON_AX_CONTENT_TREE_UPDATE_H_ + +#include "content/common/ax_content_node_data.h" +#include "content/common/ax_content_tree_data.h" +#include "content/common/content_export.h" +#include "ui/accessibility/ax_tree_update.h" + +namespace content { + +typedef ui::AXTreeUpdateBase<content::AXContentNodeData, + content::AXContentTreeData> + AXContentTreeUpdate; + +} // namespace content + +#endif // CONTENT_COMMON_AX_CONTENT_TREE_UPDATE_H_ diff --git a/chromium/content/common/ax_content_tree_update.mojom b/chromium/content/common/ax_content_tree_update.mojom index 73730652ecc..2b09af73695 100644 --- a/chromium/content/common/ax_content_tree_update.mojom +++ b/chromium/content/common/ax_content_tree_update.mojom @@ -7,8 +7,9 @@ module ax.mojom; import "ui/accessibility/ax_enums.mojom"; import "content/common/ax_content_node_data.mojom"; import "content/common/ax_content_tree_data.mojom"; +import "ui/accessibility/mojom/ax_event_intent.mojom"; -// See content::AXContentTreeUpdate for comments / explanations of these fields. +// See ui::AXTreeUpdate for comments / explanations of these fields. struct AXContentTreeUpdate { bool has_tree_data; AXContentTreeData tree_data; @@ -16,4 +17,5 @@ struct AXContentTreeUpdate { int32 root_id; array<AXContentNodeData> nodes; ax.mojom.EventFrom event_from; + array<EventIntent> event_intents; }; diff --git a/chromium/content/common/ax_content_tree_update_mojom_traits.cc b/chromium/content/common/ax_content_tree_update_mojom_traits.cc index 9793bb2d206..58b8fb1635c 100644 --- a/chromium/content/common/ax_content_tree_update_mojom_traits.cc +++ b/chromium/content/common/ax_content_tree_update_mojom_traits.cc @@ -22,7 +22,7 @@ bool StructTraits<ax::mojom::AXContentTreeUpdateDataView, out->root_id = data.root_id(); out->event_from = data.event_from(); - return true; + return data.ReadEventIntents(&out->event_intents); } } // namespace mojo diff --git a/chromium/content/common/ax_content_tree_update_mojom_traits.h b/chromium/content/common/ax_content_tree_update_mojom_traits.h index 015de489b7d..2c6cc08b674 100644 --- a/chromium/content/common/ax_content_tree_update_mojom_traits.h +++ b/chromium/content/common/ax_content_tree_update_mojom_traits.h @@ -7,8 +7,11 @@ #include "content/common/ax_content_node_data.h" #include "content/common/ax_content_node_data_mojom_traits.h" +#include "content/common/ax_content_tree_data.h" #include "content/common/ax_content_tree_data_mojom_traits.h" +#include "content/common/ax_content_tree_update.h" #include "content/common/ax_content_tree_update.mojom-shared.h" +#include "ui/accessibility/mojom/ax_event_intent_mojom_traits.h" namespace mojo { @@ -38,6 +41,11 @@ struct StructTraits<ax::mojom::AXContentTreeUpdateDataView, return p.event_from; } + static std::vector<ui::AXEventIntent> event_intents( + const content::AXContentTreeUpdate& p) { + return p.event_intents; + } + static bool Read(ax::mojom::AXContentTreeUpdateDataView data, content::AXContentTreeUpdate* out); }; diff --git a/chromium/content/common/background_fetch/background_fetch_types.cc b/chromium/content/common/background_fetch/background_fetch_types.cc index baa486878af..b6923364844 100644 --- a/chromium/content/common/background_fetch/background_fetch_types.cc +++ b/chromium/content/common/background_fetch/background_fetch_types.cc @@ -32,13 +32,14 @@ blink::mojom::FetchAPIResponsePtr BackgroundFetchSettledFetch::CloneResponse( return blink::mojom::FetchAPIResponse::New( response->url_list, response->status_code, response->status_text, response->response_type, response->response_source, response->headers, - CloneSerializedBlob(response->blob), response->error, + response->mime_type, CloneSerializedBlob(response->blob), response->error, response->response_time, response->cache_storage_cache_name, response->cors_exposed_header_names, CloneSerializedBlob(response->side_data_blob), CloneSerializedBlob(response->side_data_blob_for_cache_put), - mojo::Clone(response->parsed_headers), - response->loaded_with_credentials); + mojo::Clone(response->parsed_headers), response->connection_info, + response->alpn_negotiated_protocol, response->loaded_with_credentials, + response->was_fetched_via_spdy); } // static diff --git a/chromium/content/common/common_param_traits_macros.h b/chromium/content/common/common_param_traits_macros.h index 0701e8396a5..1209aecf01a 100644 --- a/chromium/content/common/common_param_traits_macros.h +++ b/chromium/content/common/common_param_traits_macros.h @@ -56,6 +56,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::VisualProperties) IPC_STRUCT_TRAITS_MEMBER(capture_sequence_number) IPC_STRUCT_TRAITS_MEMBER(zoom_level) IPC_STRUCT_TRAITS_MEMBER(page_scale_factor) + IPC_STRUCT_TRAITS_MEMBER(root_widget_window_segments) IPC_STRUCT_TRAITS_MEMBER(is_pinch_gesture_active) IPC_STRUCT_TRAITS_END() diff --git a/chromium/content/common/content_constants_internal.cc b/chromium/content/common/content_constants_internal.cc index 5cd58371095..089e1f62395 100644 --- a/chromium/content/common/content_constants_internal.cc +++ b/chromium/content/common/content_constants_internal.cc @@ -4,22 +4,8 @@ #include "content/common/content_constants_internal.h" -#include "build/build_config.h" - namespace content { -#if defined(OS_ANDROID) -const int64_t kHungRendererDelayMs = 5000; -#else -// TODO(jdduke): Consider shortening this delay on desktop. It was originally -// set to 5 seconds but was extended to accomodate less responsive plugins. -const int64_t kHungRendererDelayMs = 30000; -#endif - -const int64_t kNewContentRenderingDelayMs = 4000; - -const int64_t kAsyncHitTestTimeoutMs = 5000; - // 20MiB const size_t kMaxLengthOfDataURLString = 1024 * 1024 * 20; diff --git a/chromium/content/common/content_constants_internal.h b/chromium/content/common/content_constants_internal.h index 0ea9c734bd8..c19566321a9 100644 --- a/chromium/content/common/content_constants_internal.h +++ b/chromium/content/common/content_constants_internal.h @@ -8,21 +8,19 @@ #include <stddef.h> #include <stdint.h> +#include "base/time/time.h" #include "build/build_config.h" #include "content/common/content_export.h" namespace content { -// How long to wait before we consider a renderer hung. -CONTENT_EXPORT extern const int64_t kHungRendererDelayMs; - -// How long to wait for newly loaded content to send a compositor frame -// before clearing previously displayed graphics. -extern const int64_t kNewContentRenderingDelayMs; - -// Maximum wait time for an asynchronous hit test request sent to a renderer -// process (in milliseconds). -CONTENT_EXPORT extern const int64_t kAsyncHitTestTimeoutMs; +#if defined(OS_ANDROID) +constexpr base::TimeDelta kHungRendererDelay = base::TimeDelta::FromSeconds(5); +#else +// TODO(jdduke): Consider shortening this delay on desktop. It was originally +// set to 5 seconds but was extended to accommodate less responsive plugins. +constexpr base::TimeDelta kHungRendererDelay = base::TimeDelta::FromSeconds(30); +#endif // The maximum length of string as data url. extern const size_t kMaxLengthOfDataURLString; diff --git a/chromium/content/common/content_navigation_policy.cc b/chromium/content/common/content_navigation_policy.cc index aa1f35b439b..6b932f006ea 100644 --- a/chromium/content/common/content_navigation_policy.cc +++ b/chromium/content/common/content_navigation_policy.cc @@ -47,7 +47,8 @@ constexpr base::FeatureParam<ProactivelySwapBrowsingInstanceLevel>::Option {ProactivelySwapBrowsingInstanceLevel::kCrossSiteSwapProcess, "CrossSiteSwapProcess"}, {ProactivelySwapBrowsingInstanceLevel::kCrossSiteReuseProcess, - "CrossSiteReuseProcess"}}; + "CrossSiteReuseProcess"}, + {ProactivelySwapBrowsingInstanceLevel::kSameSite, "SameSite"}}; const base::FeatureParam<ProactivelySwapBrowsingInstanceLevel> proactively_swap_browsing_instance_level{ &features::kProactivelySwapBrowsingInstance, @@ -55,6 +56,24 @@ const base::FeatureParam<ProactivelySwapBrowsingInstanceLevel> ProactivelySwapBrowsingInstanceLevel::kDisabled, &proactively_swap_browsing_instance_levels}; +std::string GetProactivelySwapBrowsingInstanceLevelName( + ProactivelySwapBrowsingInstanceLevel level) { + return proactively_swap_browsing_instance_level.GetName(level); +} + +std::array<std::string, + static_cast<size_t>(ProactivelySwapBrowsingInstanceLevel::kMaxValue)> +ProactivelySwapBrowsingInstanceFeatureEnabledLevelValues() { + return { + GetProactivelySwapBrowsingInstanceLevelName( + ProactivelySwapBrowsingInstanceLevel::kCrossSiteSwapProcess), + GetProactivelySwapBrowsingInstanceLevelName( + ProactivelySwapBrowsingInstanceLevel::kCrossSiteReuseProcess), + GetProactivelySwapBrowsingInstanceLevelName( + ProactivelySwapBrowsingInstanceLevel::kSameSite), + }; +} + ProactivelySwapBrowsingInstanceLevel GetProactivelySwapBrowsingInstanceLevel() { if (base::FeatureList::IsEnabled(features::kProactivelySwapBrowsingInstance)) return proactively_swap_browsing_instance_level.Get(); @@ -70,6 +89,12 @@ bool IsProactivelySwapBrowsingInstanceWithProcessReuseEnabled() { return GetProactivelySwapBrowsingInstanceLevel() >= ProactivelySwapBrowsingInstanceLevel::kCrossSiteReuseProcess; } + +bool IsProactivelySwapBrowsingInstanceOnSameSiteNavigationEnabled() { + return GetProactivelySwapBrowsingInstanceLevel() >= + ProactivelySwapBrowsingInstanceLevel::kSameSite; +} + const char kRenderDocumentLevelParameterName[] = "level"; constexpr base::FeatureParam<RenderDocumentLevel>::Option diff --git a/chromium/content/common/content_navigation_policy.h b/chromium/content/common/content_navigation_policy.h index 3d9abb7db17..e7d1aaedd76 100644 --- a/chromium/content/common/content_navigation_policy.h +++ b/chromium/content/common/content_navigation_policy.h @@ -7,6 +7,7 @@ #include "content/common/content_export.h" +#include <array> #include <string> namespace content { @@ -24,12 +25,33 @@ enum class ProactivelySwapBrowsingInstanceLevel { // Swap BrowsingInstance on cross-site navigations, but try to reuse the // current renderer process if possible. kCrossSiteReuseProcess = 2, - // TODO(rakina): Add another level for BrowsingInstance swap on same-site - // navigations with process reuse. + // Swap BrowsingInstance swap on same-site navigations, with process reuse. + kSameSite = 3, + + kMaxValue = kSameSite, }; + +// Levels of ProactivelySwapBrowsingInstance as strings (excluding kDisabled). +CONTENT_EXPORT std::array< + std::string, + static_cast<size_t>(ProactivelySwapBrowsingInstanceLevel::kMaxValue)> +ProactivelySwapBrowsingInstanceFeatureEnabledLevelValues(); + +// Whether ProactivelySwapBrowsingInstance is enabled or not. Will return true +// if the value is set to either of {kCrossSiteSwapProcess, +// kCrossSiteReuseProcess, kSameSite}. CONTENT_EXPORT bool IsProactivelySwapBrowsingInstanceEnabled(); +// Whether ProactivelySwapBrowsingInstance with process reuse is enabled or not. +// Will return true if the value is set to either of {kCrossSiteReuseProcess, +// kSameSite}. CONTENT_EXPORT bool IsProactivelySwapBrowsingInstanceWithProcessReuseEnabled(); + +// Whether ProactivelySwapBrowsingInstance for same-site navigation is enabled +// or not. Will return true if the value is set to kSameSite. +CONTENT_EXPORT bool +IsProactivelySwapBrowsingInstanceOnSameSiteNavigationEnabled(); + CONTENT_EXPORT extern const char kProactivelySwapBrowsingInstanceLevelParameterName[]; diff --git a/chromium/content/common/content_param_traits.cc b/chromium/content/common/content_param_traits.cc index 5bdbdccf393..581ffdeda2b 100644 --- a/chromium/content/common/content_param_traits.cc +++ b/chromium/content/common/content_param_traits.cc @@ -24,7 +24,6 @@ #include "third_party/blink/public/common/messaging/message_port_descriptor.h" #include "third_party/blink/public/common/messaging/transferable_message.h" #include "third_party/blink/public/mojom/feature_policy/policy_value.mojom.h" -#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "ui/accessibility/ax_mode.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" @@ -237,81 +236,6 @@ struct ParamTraits< } }; -void ParamTraits<scoped_refptr<base::RefCountedData< - blink::TransferableMessage>>>::Write(base::Pickle* m, const param_type& p) { - m->WriteData(reinterpret_cast<const char*>(p->data.encoded_message.data()), - p->data.encoded_message.size()); - WriteParam(m, p->data.blobs); - WriteParam(m, p->data.stack_trace_id); - WriteParam(m, p->data.stack_trace_debugger_id_first); - WriteParam(m, p->data.stack_trace_debugger_id_second); - WriteParam(m, p->data.stack_trace_should_pause); - WriteParam(m, p->data.locked_agent_cluster_id); - WriteParam(m, p->data.ports); - WriteParam(m, p->data.stream_channels); - WriteParam(m, !!p->data.user_activation); - WriteParam(m, p->data.transfer_user_activation); - WriteParam(m, p->data.allow_autoplay); - WriteParam(m, p->data.sender_origin); - WriteParam(m, p->data.native_file_system_tokens); - if (p->data.user_activation) { - WriteParam(m, p->data.user_activation->has_been_active); - WriteParam(m, p->data.user_activation->was_active); - } -} - -bool ParamTraits< - scoped_refptr<base::RefCountedData<blink::TransferableMessage>>>:: - Read(const base::Pickle* m, base::PickleIterator* iter, param_type* r) { - *r = new base::RefCountedData<blink::TransferableMessage>(); - - const char* data; - int length; - if (!iter->ReadData(&data, &length)) - return false; - // This just makes encoded_message point into the IPC message buffer. Usually - // code receiving a TransferableMessage will synchronously process the message - // so this avoids an unnecessary copy. If a receiver needs to hold on to the - // message longer, it should make sure to call EnsureDataIsOwned on the - // returned message. - (*r)->data.encoded_message = - base::make_span(reinterpret_cast<const uint8_t*>(data), length); - bool has_activation = false; - if (!ReadParam(m, iter, &(*r)->data.blobs) || - !ReadParam(m, iter, &(*r)->data.stack_trace_id) || - !ReadParam(m, iter, &(*r)->data.stack_trace_debugger_id_first) || - !ReadParam(m, iter, &(*r)->data.stack_trace_debugger_id_second) || - !ReadParam(m, iter, &(*r)->data.stack_trace_should_pause) || - !ReadParam(m, iter, &(*r)->data.locked_agent_cluster_id) || - !ReadParam(m, iter, &(*r)->data.ports) || - !ReadParam(m, iter, &(*r)->data.stream_channels) || - !ReadParam(m, iter, &has_activation) || - !ReadParam(m, iter, &(*r)->data.transfer_user_activation) || - !ReadParam(m, iter, &(*r)->data.allow_autoplay) || - !ReadParam(m, iter, &(*r)->data.sender_origin) || - !ReadParam(m, iter, &(*r)->data.native_file_system_tokens)) { - return false; - } - - if (has_activation) { - bool has_been_active; - bool was_active; - if (!ReadParam(m, iter, &has_been_active) || - !ReadParam(m, iter, &was_active)) { - return false; - } - (*r)->data.user_activation = - blink::mojom::UserActivationSnapshot::New(has_been_active, was_active); - } - return true; -} - -void ParamTraits<scoped_refptr< - base::RefCountedData<blink::TransferableMessage>>>::Log(const param_type& p, - std::string* l) { - l->append("<blink::TransferableMessage>"); -} - void ParamTraits<viz::FrameSinkId>::Write(base::Pickle* m, const param_type& p) { DCHECK(p.is_valid()); @@ -509,7 +433,6 @@ void ParamTraits<content::RecordContentToVisibleTimeRequest>::Write( const param_type& p) { WriteParam(m, p.event_start_time); WriteParam(m, p.destination_is_loaded); - WriteParam(m, p.destination_is_frozen); WriteParam(m, p.show_reason_tab_switching); WriteParam(m, p.show_reason_unoccluded); WriteParam(m, p.show_reason_bfcache_restore); @@ -521,7 +444,6 @@ bool ParamTraits<content::RecordContentToVisibleTimeRequest>::Read( param_type* r) { if (!ReadParam(m, iter, &r->event_start_time) || !ReadParam(m, iter, &r->destination_is_loaded) || - !ReadParam(m, iter, &r->destination_is_frozen) || !ReadParam(m, iter, &r->show_reason_tab_switching) || !ReadParam(m, iter, &r->show_reason_unoccluded) || !ReadParam(m, iter, &r->show_reason_bfcache_restore)) { diff --git a/chromium/content/common/content_param_traits.h b/chromium/content/common/content_param_traits.h index d034ad813e8..baf38a42f55 100644 --- a/chromium/content/common/content_param_traits.h +++ b/chromium/content/common/content_param_traits.h @@ -26,7 +26,6 @@ namespace blink { class PolicyValue; class MessagePortChannel; class MessagePortDescriptor; -struct TransferableMessage; } namespace content { @@ -94,18 +93,6 @@ struct CONTENT_EXPORT ParamTraits<ui::AXMode> { }; template <> -struct CONTENT_EXPORT ParamTraits< - scoped_refptr<base::RefCountedData<blink::TransferableMessage>>> { - typedef scoped_refptr<base::RefCountedData<blink::TransferableMessage>> - param_type; - static void Write(base::Pickle* m, const param_type& p); - static bool Read(const base::Pickle* m, - base::PickleIterator* iter, - param_type* r); - static void Log(const param_type& p, std::string* l); -}; - -template <> struct CONTENT_EXPORT ParamTraits<viz::FrameSinkId> { typedef viz::FrameSinkId param_type; static void Write(base::Pickle* m, const param_type& p); diff --git a/chromium/content/common/content_param_traits_macros.h b/chromium/content/common/content_param_traits_macros.h index f65cd7dd823..34fe4506b51 100644 --- a/chromium/content/common/content_param_traits_macros.h +++ b/chromium/content/common/content_param_traits_macros.h @@ -18,7 +18,6 @@ #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom.h" #include "third_party/blink/public/mojom/loader/resource_load_info.mojom.h" #include "third_party/blink/public/platform/web_text_autosizer_page_info.h" -#include "third_party/blink/public/web/web_ime_text_span.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/gfx/gpu_memory_buffer.h" #include "ui/gfx/ipc/geometry/gfx_param_traits.h" @@ -39,10 +38,6 @@ IPC_ENUM_TRAITS_MAX_VALUE(network::mojom::ContentSecurityPolicyType, IPC_ENUM_TRAITS_MIN_MAX_VALUE(ui::mojom::CursorType, ui::mojom::CursorType::kNull, ui::mojom::CursorType::kMaxValue) -IPC_ENUM_TRAITS_MAX_VALUE(blink::WebImeTextSpan::Type, - blink::WebImeTextSpan::Type::kMisspellingSuggestion) -IPC_ENUM_TRAITS_MAX_VALUE(ui::mojom::ImeTextSpanThickness, - ui::mojom::ImeTextSpanThickness::kThick) IPC_ENUM_TRAITS_MAX_VALUE(content::PageVisibilityState, content::PageVisibilityState::kMaxValue) @@ -51,18 +46,6 @@ IPC_STRUCT_TRAITS_BEGIN(viz::Selection<gfx::SelectionBound>) IPC_STRUCT_TRAITS_MEMBER(end) IPC_STRUCT_TRAITS_END() -IPC_STRUCT_TRAITS_BEGIN(blink::WebImeTextSpan) - IPC_STRUCT_TRAITS_MEMBER(type) - IPC_STRUCT_TRAITS_MEMBER(start_offset) - IPC_STRUCT_TRAITS_MEMBER(end_offset) - IPC_STRUCT_TRAITS_MEMBER(underline_color) - IPC_STRUCT_TRAITS_MEMBER(thickness) - IPC_STRUCT_TRAITS_MEMBER(background_color) - IPC_STRUCT_TRAITS_MEMBER(suggestion_highlight_color) - IPC_STRUCT_TRAITS_MEMBER(remove_on_finish_composing) - IPC_STRUCT_TRAITS_MEMBER(suggestions) -IPC_STRUCT_TRAITS_END() - IPC_STRUCT_TRAITS_BEGIN(blink::WebTextAutosizerPageInfo) IPC_STRUCT_TRAITS_MEMBER(main_frame_width) IPC_STRUCT_TRAITS_MEMBER(main_frame_layout_width) diff --git a/chromium/content/common/content_to_visible_time_reporter.cc b/chromium/content/common/content_to_visible_time_reporter.cc index ea1159af400..430b98102d0 100644 --- a/chromium/content/common/content_to_visible_time_reporter.cc +++ b/chromium/content/common/content_to_visible_time_reporter.cc @@ -34,11 +34,7 @@ const char* GetHistogramSuffix( return "WithSavedFrames"; if (IsOptionalValueTrue(start_state.destination_is_loaded)) { - if (IsOptionalValueTrue(start_state.destination_is_frozen)) { - return "NoSavedFrames_Loaded_Frozen"; - } else { - return "NoSavedFrames_Loaded_NotFrozen"; - } + return "NoSavedFrames_Loaded"; } else { return "NoSavedFrames_NotLoaded"; } @@ -77,13 +73,11 @@ RecordContentToVisibleTimeRequest::RecordContentToVisibleTimeRequest( RecordContentToVisibleTimeRequest::RecordContentToVisibleTimeRequest( base::TimeTicks event_start_time, base::Optional<bool> destination_is_loaded, - base::Optional<bool> destination_is_frozen, bool show_reason_tab_switching, bool show_reason_unoccluded, bool show_reason_bfcache_restore) : event_start_time(event_start_time), destination_is_loaded(destination_is_loaded), - destination_is_frozen(destination_is_frozen), show_reason_tab_switching(show_reason_tab_switching), show_reason_unoccluded(show_reason_unoccluded), show_reason_bfcache_restore(show_reason_bfcache_restore) {} @@ -94,9 +88,6 @@ void RecordContentToVisibleTimeRequest::UpdateRequest( if (IsOptionalValueTrue(other.destination_is_loaded)) destination_is_loaded = other.destination_is_loaded; - if (IsOptionalValueTrue(other.destination_is_frozen)) - destination_is_frozen = other.destination_is_frozen; - show_reason_tab_switching |= other.show_reason_tab_switching; show_reason_unoccluded |= other.show_reason_unoccluded; show_reason_bfcache_restore |= other.show_reason_bfcache_restore; @@ -188,15 +179,6 @@ void ContentToVisibleTimeReporter::RecordHistogramsAndTraceEvents( tab_switch_duration.InMillisecondsF()); ++g_num_trace_events_in_process; - // Each value recorded to a histogram with suffix .NoSavedFrames_Loaded_Frozen - // or .NoSavedFrames_Loaded_NotFrozen is also recorded to a histogram with - // suffix .NoSavedFrames_Loaded to facilitate assessing the impact of - // experiments that affect the number of frozen tab on tab switch time. - const bool is_no_saved_frames_loaded = - !has_saved_frames_ && - IsOptionalValueTrue( - tab_switch_start_state_.value().destination_is_loaded); - // Record result histogram. base::UmaHistogramEnumeration( std::string("Browser.Tabs.TabSwitchResult.") + @@ -204,11 +186,6 @@ void ContentToVisibleTimeReporter::RecordHistogramsAndTraceEvents( tab_switch_start_state_.value()), tab_switch_result); - if (is_no_saved_frames_loaded) { - UMA_HISTOGRAM_ENUMERATION( - "Browser.Tabs.TabSwitchResult.NoSavedFrames_Loaded", tab_switch_result); - } - // Record latency histogram. switch (tab_switch_result) { case TabSwitchResult::kSuccess: { @@ -217,12 +194,6 @@ void ContentToVisibleTimeReporter::RecordHistogramsAndTraceEvents( GetHistogramSuffix(has_saved_frames_, tab_switch_start_state_.value()), tab_switch_duration); - - if (is_no_saved_frames_loaded) { - UMA_HISTOGRAM_TIMES( - "Browser.Tabs.TotalSwitchDuration.NoSavedFrames_Loaded", - tab_switch_duration); - } break; } case TabSwitchResult::kIncomplete: { @@ -231,12 +202,6 @@ void ContentToVisibleTimeReporter::RecordHistogramsAndTraceEvents( GetHistogramSuffix(has_saved_frames_, tab_switch_start_state_.value()), tab_switch_duration); - - if (is_no_saved_frames_loaded) { - UMA_HISTOGRAM_TIMES( - "Browser.Tabs.TotalIncompleteSwitchDuration.NoSavedFrames_Loaded", - tab_switch_duration); - } break; } case TabSwitchResult::kPresentationFailure: { diff --git a/chromium/content/common/content_to_visible_time_reporter.h b/chromium/content/common/content_to_visible_time_reporter.h index 60811bfe584..3ff0824af0c 100644 --- a/chromium/content/common/content_to_visible_time_reporter.h +++ b/chromium/content/common/content_to_visible_time_reporter.h @@ -31,7 +31,6 @@ struct CONTENT_EXPORT RecordContentToVisibleTimeRequest { RecordContentToVisibleTimeRequest(base::TimeTicks event_start_time, base::Optional<bool> destination_is_loaded, - base::Optional<bool> destination_is_frozen, bool show_reason_tab_switching, bool show_reason_unoccluded, bool show_reason_bfcache_restore); @@ -43,8 +42,6 @@ struct CONTENT_EXPORT RecordContentToVisibleTimeRequest { base::TimeTicks event_start_time = base::TimeTicks(); // Indicates if the destination tab is loaded when initiating the tab switch. base::Optional<bool> destination_is_loaded; - // Indicates if the destination tab is frozen when initiating the tab switch. - base::Optional<bool> destination_is_frozen; // If |show_reason_tab_switching| is true, web contents has become visible // because of tab switching. bool show_reason_tab_switching = false; diff --git a/chromium/content/common/cursors/DEPS b/chromium/content/common/cursors/DEPS index b2f32dda35c..dc180c4a76e 100644 --- a/chromium/content/common/cursors/DEPS +++ b/chromium/content/common/cursors/DEPS @@ -1,11 +1,3 @@ include_rules = [ "+third_party/blink/public/platform", ] - -specific_include_rules = { - # TODO(crbug.com/734668): Dependencies on ozone should be removed, as content - # embedded in mus won't be able to talk to the native ozone. - "webcursor_ozone.cc": [ - "+ui/ozone/public/cursor_factory_ozone.h", - ], -} diff --git a/chromium/content/common/cursors/webcursor.cc b/chromium/content/common/cursors/webcursor.cc index f1ae85d145f..a9d5a6f64fb 100644 --- a/chromium/content/common/cursors/webcursor.cc +++ b/chromium/content/common/cursors/webcursor.cc @@ -61,11 +61,11 @@ bool WebCursor::SetCursor(const ui::Cursor& cursor) { } bool WebCursor::operator==(const WebCursor& other) const { - return cursor_ == other.cursor_ && + return #if defined(USE_AURA) || defined(USE_OZONE) - rotation_ == other.rotation_ && + rotation_ == other.rotation_ && #endif - IsPlatformDataEqual(other); + cursor_ == other.cursor_; } bool WebCursor::operator!=(const WebCursor& other) const { diff --git a/chromium/content/common/cursors/webcursor.h b/chromium/content/common/cursors/webcursor.h index 6ae0aa5f459..0d51b09ac86 100644 --- a/chromium/content/common/cursors/webcursor.h +++ b/chromium/content/common/cursors/webcursor.h @@ -61,9 +61,6 @@ class CONTENT_EXPORT WebCursor { #endif private: - // Returns true if this cursor's platform data matches that of |other|. - bool IsPlatformDataEqual(const WebCursor& other) const; - // Copies all data from |other| to this object. void CopyAllData(const WebCursor& other); diff --git a/chromium/content/common/cursors/webcursor_android.cc b/chromium/content/common/cursors/webcursor_android.cc index 9cf5a2a8e6d..59989ccb0ad 100644 --- a/chromium/content/common/cursors/webcursor_android.cc +++ b/chromium/content/common/cursors/webcursor_android.cc @@ -18,10 +18,6 @@ gfx::NativeCursor WebCursor::GetNativeCursor() { void WebCursor::SetDisplayInfo(const display::Display& display) {} #endif -bool WebCursor::IsPlatformDataEqual(const WebCursor& other) const { - return true; -} - void WebCursor::CleanupPlatformData() {} void WebCursor::CopyPlatformData(const WebCursor& other) {} diff --git a/chromium/content/common/cursors/webcursor_aurawin.cc b/chromium/content/common/cursors/webcursor_aurawin.cc index 03a751fdcb8..567733c90e1 100644 --- a/chromium/content/common/cursors/webcursor_aurawin.cc +++ b/chromium/content/common/cursors/webcursor_aurawin.cc @@ -6,29 +6,25 @@ #include <windows.h> -#include "ui/base/cursor/cursor_lookup.h" +#include "base/check_op.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/gfx/icon_util.h" namespace content { ui::PlatformCursor WebCursor::GetPlatformCursor(const ui::Cursor& cursor) { - if (cursor_.type() != ui::mojom::CursorType::kCustom) - return LoadCursor(nullptr, IDC_ARROW); + // The other cursor types are set in CursorLoaderWin + DCHECK_EQ(cursor.type(), ui::mojom::CursorType::kCustom); if (platform_cursor_) return platform_cursor_; - platform_cursor_ = IconUtil::CreateCursorFromSkBitmap( - GetCursorBitmap(cursor), GetCursorHotspot(cursor)) + platform_cursor_ = IconUtil::CreateCursorFromSkBitmap(cursor.custom_bitmap(), + cursor.custom_hotspot()) .release(); return platform_cursor_; } -bool WebCursor::IsPlatformDataEqual(const WebCursor& other) const { - return true; -} - void WebCursor::CleanupPlatformData() { if (platform_cursor_) { DestroyIcon(platform_cursor_); diff --git a/chromium/content/common/cursors/webcursor_aurax11.cc b/chromium/content/common/cursors/webcursor_aurax11.cc deleted file mode 100644 index 2fdcd9f9610..00000000000 --- a/chromium/content/common/cursors/webcursor_aurax11.cc +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2012 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 "content/common/cursors/webcursor.h" - - -#include "ui/base/cursor/cursor.h" -#include "ui/base/cursor/cursor_loader_x11.h" -#include "ui/base/cursor/cursor_lookup.h" -#include "ui/base/x/x11_util.h" -#include "ui/gfx/x/x11.h" - -namespace content { - -ui::PlatformCursor WebCursor::GetPlatformCursor(const ui::Cursor& cursor) { - if (platform_cursor_) - return platform_cursor_; - - SkBitmap bitmap = GetCursorBitmap(cursor); - - XcursorImage* image = - ui::SkBitmapToXcursorImage(bitmap, GetCursorHotspot(cursor)); - platform_cursor_ = ui::CreateReffedCustomXCursor(image); - return platform_cursor_; -} - -bool WebCursor::IsPlatformDataEqual(const WebCursor& other) const { - return true; -} - -void WebCursor::CleanupPlatformData() { - if (platform_cursor_) { - ui::UnrefCustomXCursor(platform_cursor_); - platform_cursor_ = 0; - } - custom_cursor_.reset(); -} - -void WebCursor::CopyPlatformData(const WebCursor& other) { - if (platform_cursor_) - ui::UnrefCustomXCursor(platform_cursor_); - platform_cursor_ = other.platform_cursor_; - if (platform_cursor_) - ui::RefCustomXCursor(platform_cursor_); - - device_scale_factor_ = other.device_scale_factor_; -} - -} // namespace content diff --git a/chromium/content/common/cursors/webcursor_mac.mm b/chromium/content/common/cursors/webcursor_mac.mm index 06c74d0c4ab..0fd7909e30d 100644 --- a/chromium/content/common/cursors/webcursor_mac.mm +++ b/chromium/content/common/cursors/webcursor_mac.mm @@ -232,11 +232,7 @@ gfx::NativeCursor WebCursor::GetNativeCursor() { return GetCoreCursorWithFallback(kMoveCursor, IDR_MOVE_CURSOR, 7, 7); case ui::mojom::CursorType::kVerticalText: - // IBeamCursorForVerticalLayout is >= 10.7. - if ([NSCursor respondsToSelector:@selector(IBeamCursorForVerticalLayout)]) - return [NSCursor IBeamCursorForVerticalLayout]; - else - return LoadCursor(IDR_VERTICALTEXT_CURSOR, 7, 7); + return [NSCursor IBeamCursorForVerticalLayout]; case ui::mojom::CursorType::kCell: return GetCoreCursorWithFallback(kCellCursor, IDR_CELL_CURSOR, 7, 7); @@ -279,10 +275,6 @@ gfx::NativeCursor WebCursor::GetNativeCursor() { return nil; } -bool WebCursor::IsPlatformDataEqual(const WebCursor& other) const { - return true; -} - void WebCursor::CleanupPlatformData() {} void WebCursor::CopyPlatformData(const WebCursor& other) {} diff --git a/chromium/content/common/cursors/webcursor_ozone.cc b/chromium/content/common/cursors/webcursor_ozone.cc index 1f3644bb1e0..1663960eaa4 100644 --- a/chromium/content/common/cursors/webcursor_ozone.cc +++ b/chromium/content/common/cursors/webcursor_ozone.cc @@ -6,23 +6,26 @@ #include <algorithm> +#include "base/check_op.h" #include "ui/base/cursor/cursor.h" -#include "ui/base/cursor/cursor_lookup.h" -#include "ui/base/cursor/cursor_util.h" -#include "ui/ozone/public/cursor_factory_ozone.h" +#include "ui/base/cursor/cursor_factory.h" +#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" namespace content { ui::PlatformCursor WebCursor::GetPlatformCursor(const ui::Cursor& cursor) { + // The other cursor types are set in CursorLoaderOzone + DCHECK_EQ(cursor.type(), ui::mojom::CursorType::kCustom); + if (!platform_cursor_) { - platform_cursor_ = ui::CursorFactoryOzone::GetInstance()->CreateImageCursor( - GetCursorBitmap(cursor), GetCursorHotspot(cursor), - cursor.image_scale_factor()); + platform_cursor_ = ui::CursorFactory::GetInstance()->CreateImageCursor( + cursor.custom_bitmap(), cursor.custom_hotspot()); } return platform_cursor_; } +#if defined(USE_OZONE) void WebCursor::SetDisplayInfo(const display::Display& display) { if (rotation_ == display.panel_rotation() && device_scale_factor_ == display.device_scale_factor() && @@ -51,14 +54,11 @@ float WebCursor::GetCursorScaleFactor(SkBitmap* bitmap) { static_cast<float>(maximum_cursor_size_.width()) / bitmap->width(), static_cast<float>(maximum_cursor_size_.height()) / bitmap->height()}); } - -bool WebCursor::IsPlatformDataEqual(const WebCursor& other) const { - return true; -} +#endif void WebCursor::CleanupPlatformData() { if (platform_cursor_) { - ui::CursorFactoryOzone::GetInstance()->UnrefImageCursor(platform_cursor_); + ui::CursorFactory::GetInstance()->UnrefImageCursor(platform_cursor_); platform_cursor_ = NULL; } custom_cursor_.reset(); @@ -66,13 +66,15 @@ void WebCursor::CleanupPlatformData() { void WebCursor::CopyPlatformData(const WebCursor& other) { if (platform_cursor_) - ui::CursorFactoryOzone::GetInstance()->UnrefImageCursor(platform_cursor_); + ui::CursorFactory::GetInstance()->UnrefImageCursor(platform_cursor_); platform_cursor_ = other.platform_cursor_; if (platform_cursor_) - ui::CursorFactoryOzone::GetInstance()->RefImageCursor(platform_cursor_); + ui::CursorFactory::GetInstance()->RefImageCursor(platform_cursor_); device_scale_factor_ = other.device_scale_factor_; +#if defined(USE_OZONE) maximum_cursor_size_ = other.maximum_cursor_size_; +#endif } } // namespace content diff --git a/chromium/content/common/cursors/webcursor_unittest.cc b/chromium/content/common/cursors/webcursor_unittest.cc index 7ccdbcc6ae6..5073af765ae 100644 --- a/chromium/content/common/cursors/webcursor_unittest.cc +++ b/chromium/content/common/cursors/webcursor_unittest.cc @@ -9,7 +9,6 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/cursor/cursor.h" -#include "ui/base/cursor/cursor_lookup.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #if defined(OS_WIN) @@ -53,7 +52,7 @@ TEST(WebCursorTest, WebCursorCursorConstructorCustom) { // Test if the custom cursor is correctly cached and updated // on aura platform. gfx::NativeCursor native_cursor = webcursor.GetNativeCursor(); - EXPECT_EQ(gfx::Point(5, 10), GetCursorHotspot(native_cursor)); + EXPECT_EQ(gfx::Point(5, 10), native_cursor.custom_hotspot()); EXPECT_TRUE(webcursor.has_custom_cursor_for_test()); webcursor.SetCursor(cursor); EXPECT_FALSE(webcursor.has_custom_cursor_for_test()); @@ -71,7 +70,7 @@ TEST(WebCursorTest, WebCursorCursorConstructorCustom) { // Hotspot should be scaled & rotated. We're using the icon created for 2.0, // on the display with dsf=1.0, so the host spot should be // ((32 - 20) / 2, 10 / 2) = (6, 5). - EXPECT_EQ(gfx::Point(6, 5), GetCursorHotspot(native_cursor)); + EXPECT_EQ(gfx::Point(6, 5), native_cursor.custom_hotspot()); #endif #endif } diff --git a/chromium/content/common/drag_messages.h b/chromium/content/common/drag_messages.h index b07f4bdd012..3e78d67c58b 100644 --- a/chromium/content/common/drag_messages.h +++ b/chromium/content/common/drag_messages.h @@ -12,7 +12,7 @@ #include "content/common/drag_event_source_info.h" #include "content/public/common/drop_data.h" #include "ipc/ipc_message_macros.h" -#include "third_party/blink/public/platform/web_drag_operation.h" +#include "third_party/blink/public/common/page/web_drag_operation.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/vector2d.h" @@ -28,28 +28,12 @@ IPC_MESSAGE_ROUTED5(DragMsg_TargetDragEnter, blink::WebDragOperationsMask /* ops_allowed */, int /* key_modifiers */) -IPC_MESSAGE_ROUTED4(DragMsg_TargetDragOver, - gfx::PointF /* client_pt */, - gfx::PointF /* screen_pt */, - blink::WebDragOperationsMask /* ops_allowed */, - int /* key_modifiers */) - -IPC_MESSAGE_ROUTED2(DragMsg_TargetDragLeave, - gfx::PointF /* client_point */, - gfx::PointF /* screen_point */) - IPC_MESSAGE_ROUTED4(DragMsg_TargetDrop, content::DropData /* drop_data */, gfx::PointF /* client_pt */, gfx::PointF /* screen_pt */, int /* key_modifiers */) -// Notifies the renderer when and where the mouse-drag ended. -IPC_MESSAGE_ROUTED3(DragMsg_SourceEnded, - gfx::PointF /* client_pt */, - gfx::PointF /* screen_pt */, - blink::WebDragOperation /* drag_operation */) - // Messages sent from the renderer to the browser. // Used to tell the parent the user started dragging in the content area. The diff --git a/chromium/content/common/fetch/fetch_request_type_converters.cc b/chromium/content/common/fetch/fetch_request_type_converters.cc index 9923dd396ac..b4193c138f2 100644 --- a/chromium/content/common/fetch/fetch_request_type_converters.cc +++ b/chromium/content/common/fetch/fetch_request_type_converters.cc @@ -32,8 +32,7 @@ blink::mojom::FetchAPIRequestPtr TypeConverter< input.referrer_policy)); output->mode = input.mode; output->is_main_resource_load = - content::ServiceWorkerUtils::IsMainResourceType( - static_cast<blink::mojom::ResourceType>(input.resource_type)); + content::ServiceWorkerUtils::IsMainRequestDestination(input.destination); output->credentials_mode = input.credentials_mode; output->cache_mode = content::ServiceWorkerUtils::GetCacheModeFromLoadFlags(input.load_flags); diff --git a/chromium/content/common/frame.mojom b/chromium/content/common/frame.mojom index 5dfb74713e4..40821a2c3d7 100644 --- a/chromium/content/common/frame.mojom +++ b/chromium/content/common/frame.mojom @@ -10,10 +10,10 @@ import "content/common/frame_messages.mojom"; import "content/common/native_types.mojom"; import "content/common/navigation_client.mojom"; import "content/common/navigation_params.mojom"; -import "content/common/widget.mojom"; import "content/public/common/browser_controls_state.mojom"; import "content/public/common/transferrable_url_loader.mojom"; import "content/public/common/window_container_type.mojom"; +import "mojo/public/mojom/base/file_path.mojom"; import "mojo/public/mojom/base/string16.mojom"; import "mojo/public/mojom/base/unguessable_token.mojom"; import "mojo/public/mojom/base/values.mojom"; @@ -38,11 +38,12 @@ import "third_party/blink/public/mojom/frame/navigation_initiator.mojom"; import "third_party/blink/public/mojom/loader/resource_load_info.mojom"; import "third_party/blink/public/mojom/loader/url_loader_factory_bundle.mojom"; import "third_party/blink/public/mojom/messaging/transferable_message.mojom"; +import "third_party/blink/public/mojom/page/page.mojom"; import "third_party/blink/public/mojom/page/widget.mojom"; import "third_party/blink/public/mojom/portal/portal.mojom"; import "third_party/blink/public/mojom/referrer.mojom"; import "third_party/blink/public/mojom/service_worker/controller_service_worker.mojom"; -import "third_party/blink/public/mojom/service_worker/service_worker_provider.mojom"; +import "third_party/blink/public/mojom/service_worker/service_worker_container.mojom"; import "third_party/blink/public/mojom/window_features/window_features.mojom"; import "ui/base/mojom/window_open_disposition.mojom"; import "ui/gfx/geometry/mojom/geometry.mojom"; @@ -53,6 +54,19 @@ import "url/mojom/url.mojom"; // frame tree to expose frame-specific interfaces between renderer and browser. const string kNavigation_FrameSpec = "navigation:frame"; +// Provided with each call to Frame::GetSerializedHtmlWithLocalLinks() so that +// the renderer can notify the browser process each time that a chunk of HTML +// data gets serialized, as well as when the entire process is finished. +interface FrameHTMLSerializerHandler { + // Sent by the renderer as a response to GetSerializedHtmlWithLocalLinks() to + // indicate that HTML data has been serialized, included in |data_buffer|. + DidReceiveData(string data_buffer); + + // Reports that the serialization process is finished. It is expected to + // receive this message right after the last time DidReceiveData() is called. + Done(); +}; + // Implemented by the frame provider (e.g. renderer processes). interface Frame { GetInterfaceProvider( @@ -70,9 +84,6 @@ interface Frame { // Cancels blocked requests. BlockRequests must have been called before. CancelBlockedRequests(); - // Set the lifecycle state. - SetLifecycleState(blink.mojom.FrameLifecycleState state); - // Samsung Galaxy Note-specific "smart clip" stylus text getter. // Extracts the data at the given rect. [EnableIf=is_android] @@ -92,6 +103,17 @@ interface Frame { // See ui/accessibility/ax_mode.h for valid values of |ax_mode|. SnapshotAccessibilityTree(uint32 ax_mode) => (ax.mojom.AXContentTreeUpdate snapshot); + + // Get HTML data by serializing the target frame and replacing all resource + // links with a path to the local copy passed in the message payload. In order + // to report progress to the the browser process, a pending remote is passed + // via |callback_remote|, so that direct communication with the SavePackage + // object that initiated the process can be established. + GetSerializedHtmlWithLocalLinks( + map<url.mojom.Url, mojo_base.mojom.FilePath> url_map, + map<mojo_base.mojom.UnguessableToken, mojo_base.mojom.FilePath> + frame_token_map, bool save_with_empty_url, + pending_remote<FrameHTMLSerializerHandler> handler_remote); }; // Implemented by the frame provider and currently must be associated with the @@ -99,52 +121,6 @@ interface Frame { // KEEP THE COMMIT FUNCTIONS IN SYNC in content/common/navigation_client.mojom. // These will eventually be removed from FrameNavigationControl. interface FrameNavigationControl { - // Tells the renderer that a navigation is ready to commit. - // - // The renderer should bind the |url_loader_client_endpoints| to an - // URLLoaderClient implementation to continue loading the document that will - // be the result of the committed navigation. - // - // Note: |url_loader_client_endpoints| will be empty iff the navigation URL - // wasn't handled by the network stack (i.e. about:blank, ...) - // - // When the Network Service is enabled, |subresource_loader_factories| may - // also be provided by the browser as a a means for the renderer to load - // subresources where applicable. - // - // |controller_service_worker_info| may also be provided by the browser if the - // frame that is being navigated is supposed to be controlled by a Service - // Worker. - // |provider_info| may also be provided if the browser has created a - // ServiceWorkerProviderHost for this navigation. - // |prefetch_loader_factory| is populated only when Network Service is - // enabled. The pointer is used to start a prefetch loading via the browser - // process. - // - // For automation driver-initiated navigations over the devtools protocol, - // |devtools_navigation_token_| is used to tag the navigation. This navigation - // token is then sent into the renderer and lands on the DocumentLoader. That - // way subsequent Blink-level frame lifecycle events can be associated with - // the concrete navigation. - // - The value should not be sent back to the browser. - // - The value on DocumentLoader may be generated in the renderer in some - // cases, and thus shouldn't be trusted. - // TODO(crbug.com/783506): Replace devtools navigation token with the generic - // navigation token that can be passed from renderer to the browser. - CommitNavigation( - CommonNavigationParams common_params, - CommitNavigationParams request_params, - network.mojom.URLResponseHead response_head, - handle<data_pipe_consumer>? response_body, - network.mojom.URLLoaderClientEndpoints? url_loader_client_endpoints, - blink.mojom.URLLoaderFactoryBundle? subresource_loader_factories, - array<TransferrableURLLoader>? subresource_overrides, - blink.mojom.ControllerServiceWorkerInfo? controller_service_worker_info, - blink.mojom.ServiceWorkerProviderInfoForClient? provider_info, - pending_remote<network.mojom.URLLoaderFactory>? prefetch_loader_factory, - mojo_base.mojom.UnguessableToken devtools_navigation_token) - => (blink.mojom.CommitResult commit_result); - // Tells the renderer that a same-document navigation should be committed. // The renderer will return a status value indicating whether the commit // could proceed as expected or not. In particular, it might be necessary to @@ -338,6 +314,9 @@ struct CreateNewWindowReply { pending_associated_remote<blink.mojom.WidgetHost> widget_host; pending_associated_receiver<blink.mojom.Widget> widget; + // The communication interfaces for the PageBroadcast. + pending_associated_receiver<blink.mojom.PageBroadcast> page_broadcast; + DocumentScopedInterfaceBundle main_frame_interface_bundle; // Duplicated from CreateNewWindowParams because legacy code. @@ -357,6 +336,35 @@ struct CreateNewWindowReply { bool wait_for_debugger; }; +[Native] +enum TriggeringEventInfo; + +// This struct holds parameters included in the OpenURL method sent by the +// renderer to the browser, |is_history_navigation_in_new_child_frame| is true +// in the case that the browser process should look for an existing history item +// for the frame. +struct OpenURLParams { + // The main URL to open. + url.mojom.Url url; + url.mojom.Origin initiator_origin; + int32 initiator_routing_id; + network.mojom.URLRequestBody? post_body; + string extra_headers; + blink.mojom.Referrer referrer; + + // The window position to open the URL. + ui.mojom.WindowOpenDisposition disposition; + bool should_replace_current_entry; + bool user_gesture; + + // Extra information about the triggering of the OpenURL. + TriggeringEventInfo triggering_event_info; + handle<message_pipe>? blob_url_token; + string href_translate; + Impression? impression; + NavigationDownloadPolicy download_policy; +}; + // An opaque handle that keeps alive the associated render process even after // the frame is detached. Used by resource requests with "keepalive" specified. interface KeepAliveHandle {}; @@ -406,13 +414,13 @@ interface FrameHost { // Similar to CreateNewWindow, except used for sub-widgets, like <select> // dropdowns. - [Sync] CreateNewWidget(pending_remote<Widget> widget, + [Sync] CreateNewWidget( pending_associated_receiver<blink.mojom.WidgetHost> blink_widget_host, pending_associated_remote<blink.mojom.Widget> blink_widget) => (int32 routing_id); // Similar to CreateNewWidget except the widget is a full screen window. - [Sync] CreateNewFullscreenWidget(pending_remote<Widget> widget, + [Sync] CreateNewFullscreenWidget( pending_associated_receiver<blink.mojom.WidgetHost> blink_widget_host, pending_associated_remote<blink.mojom.Widget> blink_widget) => (int32 routing_id); @@ -533,4 +541,10 @@ interface FrameHost { // Requests an overlay routing token. RequestOverlayRoutingToken() => (mojo_base.mojom.UnguessableToken token); + + // Notifies the browser that this frame has new session history information. + UpdateState(PageState state); + + // Requests that the given URL be opened in the specified manner. + OpenURL(OpenURLParams params); }; diff --git a/chromium/content/common/frame_messages.h b/chromium/content/common/frame_messages.h index bec2919abc9..01c30cb7218 100644 --- a/chromium/content/common/frame_messages.h +++ b/chromium/content/common/frame_messages.h @@ -16,6 +16,7 @@ #include <vector> #include "base/optional.h" +#include "base/unguessable_token.h" #include "build/build_config.h" #include "cc/input/touch_action.h" #include "components/viz/common/surfaces/surface_id.h" @@ -28,7 +29,6 @@ #include "content/common/frame_visual_properties.h" #include "content/common/navigation_gesture.h" #include "content/common/navigation_params.h" -#include "content/common/savable_subframe.h" #include "content/public/common/common_param_traits.h" #include "content/public/common/frame_navigate_params.h" #include "content/public/common/impression.h" @@ -50,7 +50,6 @@ #include "third_party/blink/public/common/feature_policy/feature_policy.h" #include "third_party/blink/public/common/frame/frame_policy.h" #include "third_party/blink/public/common/messaging/message_port_channel.h" -#include "third_party/blink/public/common/messaging/transferable_message.h" #include "third_party/blink/public/common/navigation/triggering_event_info.h" #include "third_party/blink/public/mojom/choosers/file_chooser.mojom.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" @@ -65,7 +64,6 @@ #include "third_party/blink/public/mojom/frame/lifecycle.mojom.h" #include "third_party/blink/public/mojom/frame/tree_scope_type.mojom.h" #include "third_party/blink/public/mojom/frame/user_activation_update_types.mojom.h" -#include "third_party/blink/public/mojom/input/focus_type.mojom.h" #include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h" #include "third_party/blink/public/mojom/scroll/scrollbar_mode.mojom.h" #include "third_party/blink/public/mojom/security_context/insecure_request_policy.mojom.h" @@ -85,17 +83,6 @@ #include "content/common/pepper_renderer_instance_data.h" #endif -// Singly-included section for type definitions. -#ifndef INTERNAL_CONTENT_COMMON_FRAME_MESSAGES_H_ -#define INTERNAL_CONTENT_COMMON_FRAME_MESSAGES_H_ - -using FrameMsg_GetSerializedHtmlWithLocalLinks_UrlMap = - std::map<GURL, base::FilePath>; -using FrameMsg_GetSerializedHtmlWithLocalLinks_FrameRoutingIdMap = - std::map<int, base::FilePath>; - -#endif // INTERNAL_CONTENT_COMMON_FRAME_MESSAGES_H_ - #undef IPC_MESSAGE_EXPORT #define IPC_MESSAGE_EXPORT CONTENT_EXPORT @@ -110,8 +97,6 @@ IPC_ENUM_TRAITS_MAX_VALUE(blink::ContextMenuDataMediaType, blink::ContextMenuDataMediaType::kLast) IPC_ENUM_TRAITS_MAX_VALUE(blink::ContextMenuDataInputFieldType, blink::ContextMenuDataInputFieldType::kMaxValue) -IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::FocusType, - blink::mojom::FocusType::kMaxValue) IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::ScrollbarMode, blink::mojom::ScrollbarMode::kMaxValue) IPC_ENUM_TRAITS_MAX_VALUE(content::StopFindAction, @@ -171,7 +156,6 @@ IPC_STRUCT_TRAITS_BEGIN(content::UntrustworthyContextMenuParams) IPC_STRUCT_TRAITS_MEMBER(unfiltered_link_url) IPC_STRUCT_TRAITS_MEMBER(src_url) IPC_STRUCT_TRAITS_MEMBER(has_image_contents) - IPC_STRUCT_TRAITS_MEMBER(properties) IPC_STRUCT_TRAITS_MEMBER(media_flags) IPC_STRUCT_TRAITS_MEMBER(selection_text) IPC_STRUCT_TRAITS_MEMBER(title_text) @@ -219,6 +203,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::FrameVisualProperties) IPC_STRUCT_TRAITS_MEMBER(visible_viewport_size) IPC_STRUCT_TRAITS_MEMBER(min_size_for_auto_resize) IPC_STRUCT_TRAITS_MEMBER(max_size_for_auto_resize) + IPC_STRUCT_TRAITS_MEMBER(root_widget_window_segments) IPC_STRUCT_TRAITS_MEMBER(capture_sequence_number) IPC_STRUCT_TRAITS_MEMBER(zoom_level) IPC_STRUCT_TRAITS_MEMBER(page_scale_factor) @@ -245,7 +230,6 @@ IPC_STRUCT_TRAITS_BEGIN(blink::ViewportIntersectionState) IPC_STRUCT_TRAITS_MEMBER(occlusion_state) IPC_STRUCT_TRAITS_MEMBER(main_frame_viewport_size) IPC_STRUCT_TRAITS_MEMBER(main_frame_scroll_offset) - IPC_STRUCT_TRAITS_MEMBER(can_skip_sticky_frame_tracking) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(content::FrameNavigateParams) @@ -344,29 +328,12 @@ IPC_STRUCT_BEGIN_WITH_PARENT(FrameHostMsg_DidCommitProvisionalLoad_Params, // renderer process to commit the navigation. IPC_STRUCT_MEMBER(base::UnguessableToken, navigation_token) - // An embedding token used to signify the relationship between the frame and - // its parent. This is populated for cross-document navigations in a subframe. + // An embedding token used to signify the relationship between a document and + // its parent. This is populated for cross-document navigations including + // sub-documents and the main document. IPC_STRUCT_MEMBER(base::Optional<base::UnguessableToken>, embedding_token) IPC_STRUCT_END() -IPC_STRUCT_BEGIN(FrameMsg_PostMessage_Params) - // When sent to the browser, this is the routing ID of the source frame in - // the source process. The browser replaces it with the routing ID of the - // equivalent frame proxy in the destination process. - IPC_STRUCT_MEMBER(int, source_routing_id) - - // The origin of the source frame. - IPC_STRUCT_MEMBER(base::string16, source_origin) - - // The origin for the message's target. - IPC_STRUCT_MEMBER(base::string16, target_origin) - - // The encoded data, and any extra properties such as transfered ports or - // blobs. - IPC_STRUCT_MEMBER( - scoped_refptr<base::RefCountedData<blink::TransferableMessage>>, message) -IPC_STRUCT_END() - IPC_STRUCT_TRAITS_BEGIN(network::mojom::SourceLocation) IPC_STRUCT_TRAITS_MEMBER(url) IPC_STRUCT_TRAITS_MEMBER(line) @@ -393,37 +360,12 @@ IPC_STRUCT_TRAITS_BEGIN(content::FrameReplicationState) IPC_STRUCT_TRAITS_MEMBER(insecure_request_policy) IPC_STRUCT_TRAITS_MEMBER(insecure_navigations_set) IPC_STRUCT_TRAITS_MEMBER(has_potentially_trustworthy_unique_origin) - IPC_STRUCT_TRAITS_MEMBER(has_received_user_gesture) + IPC_STRUCT_TRAITS_MEMBER(has_active_user_gesture) IPC_STRUCT_TRAITS_MEMBER(has_received_user_gesture_before_nav) IPC_STRUCT_TRAITS_MEMBER(frame_owner_element_type) IPC_STRUCT_TRAITS_MEMBER(ad_frame_type) IPC_STRUCT_TRAITS_END() -// Parameters included with an OpenURL request. -// |is_history_navigation_in_new_child| is true in the case that the browser -// process should look for an existing history item for the frame. -IPC_STRUCT_BEGIN(FrameHostMsg_OpenURL_Params) - IPC_STRUCT_MEMBER(GURL, url) - IPC_STRUCT_MEMBER(url::Origin, initiator_origin) - IPC_STRUCT_MEMBER(int32_t, initiator_routing_id) - IPC_STRUCT_MEMBER(scoped_refptr<network::ResourceRequestBody>, post_body) - IPC_STRUCT_MEMBER(std::string, extra_headers) - IPC_STRUCT_MEMBER(content::Referrer, referrer) - IPC_STRUCT_MEMBER(WindowOpenDisposition, disposition) - IPC_STRUCT_MEMBER(bool, should_replace_current_entry) - IPC_STRUCT_MEMBER(bool, user_gesture) - IPC_STRUCT_MEMBER(blink::TriggeringEventInfo, triggering_event_info) - IPC_STRUCT_MEMBER(mojo::MessagePipeHandle, blob_url_token) - IPC_STRUCT_MEMBER(std::string, href_translate) - IPC_STRUCT_MEMBER(base::Optional<content::Impression>, impression) - IPC_STRUCT_MEMBER(content::NavigationDownloadPolicy, download_policy) -IPC_STRUCT_END() - -IPC_STRUCT_TRAITS_BEGIN(content::SavableSubframe) - IPC_STRUCT_TRAITS_MEMBER(original_url) - IPC_STRUCT_TRAITS_MEMBER(routing_id) -IPC_STRUCT_TRAITS_END() - IPC_STRUCT_BEGIN(FrameHostMsg_CreateChildFrame_Params) IPC_STRUCT_MEMBER(int32_t, parent_routing_id) IPC_STRUCT_MEMBER(blink::mojom::TreeScopeType, scope) @@ -456,6 +398,7 @@ IPC_STRUCT_BEGIN(FrameMsg_MixedContentFound_Params) IPC_STRUCT_MEMBER(blink::mojom::RequestContextType, request_context_type) IPC_STRUCT_MEMBER(network::mojom::RequestDestination, request_destination) IPC_STRUCT_MEMBER(bool, was_allowed) + IPC_STRUCT_MEMBER(GURL, url_before_redirects) IPC_STRUCT_MEMBER(bool, had_redirect) IPC_STRUCT_MEMBER(network::mojom::SourceLocation, source_location) IPC_STRUCT_END() @@ -483,11 +426,6 @@ IPC_MESSAGE_ROUTED2(FrameMsg_CustomContextMenuAction, content::CustomContextMenuContext /* custom_context */, unsigned /* action */) -// Requests that the RenderFrame or RenderFrameProxy updates its opener to the -// specified frame. The routing ID may be MSG_ROUTING_NONE if the opener was -// disowned. -IPC_MESSAGE_ROUTED1(FrameMsg_UpdateOpener, int /* opener_routing_id */) - // Requests that the RenderFrame send back a response after waiting for the // commit, activation and frame swap of the current DOM tree in blink. IPC_MESSAGE_ROUTED1(FrameMsg_VisualStateRequest, uint64_t /* id */) @@ -502,17 +440,6 @@ IPC_MESSAGE_ROUTED2(FrameMsg_DidUpdateName, std::string /* name */, std::string /* unique_name */) -// Request to enumerate and return links to all savable resources in the frame -// Note: this covers only the immediate frame / doesn't cover subframes. -IPC_MESSAGE_ROUTED0(FrameMsg_GetSavableResourceLinks) - -// Get html data by serializing the target frame and replacing all resource -// links with a path to the local copy passed in the message payload. -IPC_MESSAGE_ROUTED3(FrameMsg_GetSerializedHtmlWithLocalLinks, - FrameMsg_GetSerializedHtmlWithLocalLinks_UrlMap, - FrameMsg_GetSerializedHtmlWithLocalLinks_FrameRoutingIdMap, - bool /* save_with_empty_url */) - #if BUILDFLAG(ENABLE_PLUGINS) // Notifies the renderer of updates to the Plugin Power Saver origin allowlist. IPC_MESSAGE_ROUTED1(FrameMsg_UpdatePluginContentOriginAllowlist, @@ -559,25 +486,6 @@ IPC_MESSAGE_ROUTED0(FrameHostMsg_Detach) // Sent when the renderer is done loading a page. IPC_MESSAGE_ROUTED0(FrameHostMsg_DidStopLoading) -// Notifies the browser that this frame has new session history information. -IPC_MESSAGE_ROUTED1(FrameHostMsg_UpdateState, content::PageState /* state */) - -// Requests that the given URL be opened in the specified manner. -IPC_MESSAGE_ROUTED1(FrameHostMsg_OpenURL, FrameHostMsg_OpenURL_Params) - -// Sent when the RenderFrame or RenderFrameProxy either updates its opener to -// another frame identified by |opener_routing_id|, or, if |opener_routing_id| -// is MSG_ROUTING_NONE, the frame disowns its opener for the lifetime of the -// window. -IPC_MESSAGE_ROUTED1(FrameHostMsg_DidChangeOpener, int /* opener_routing_id */) - -// Notifies the browser that sandbox flags or container policy have changed for -// a subframe of this frame. -IPC_MESSAGE_ROUTED2( - FrameHostMsg_DidChangeFramePolicy, - int32_t /* subframe_routing_id */, - blink::FramePolicy /* updated sandbox flags and container policy */) - #if BUILDFLAG(ENABLE_PLUGINS) // Notification sent from a renderer to the browser that a Pepper plugin // instance is created in the DOM. @@ -734,10 +642,6 @@ IPC_MESSAGE_ROUTED2(FrameHostMsg_SynchronizeVisualProperties, IPC_MESSAGE_ROUTED1(FrameHostMsg_UpdateViewportIntersection, blink::ViewportIntersectionState /* intersection_state */) -// Transfers user activation state from the source frame to the current frame. -IPC_MESSAGE_ROUTED1(FrameMsg_TransferUserActivationFrom, - int /* source_routing_id */) - // Used to tell the parent that the user right clicked on an area of the // content area, and a context menu should be shown for it. The params // object contains information about the node(s) that were selected when the @@ -753,24 +657,10 @@ IPC_MESSAGE_ROUTED3(FrameHostMsg_SelectionChanged, uint32_t /* the offset of the text in the document */, gfx::Range /* selection range in the document */) -// Displays a dialog to confirm that the user wants to navigate away from the -// page. Replies true if yes, and false otherwise. The reply string is ignored, -// but is included so that we can use -// RenderFrameHostImpl::SendJavaScriptDialogReply. -IPC_SYNC_MESSAGE_ROUTED1_2(FrameHostMsg_RunBeforeUnloadConfirm, - bool /* in - is a reload */, - bool /* out - success */, - base::string16 /* out - This is ignored.*/) - // Sent as a response to FrameMsg_VisualStateRequest. // The message is delivered using RenderWidget::QueueMessage. IPC_MESSAGE_ROUTED1(FrameHostMsg_VisualStateResponse, uint64_t /* id */) -// Sent to the browser from a frame proxy to post a message to the frame's -// active renderer. -IPC_MESSAGE_ROUTED1(FrameHostMsg_RouteMessageEvent, - FrameMsg_PostMessage_Params) - // Sent when the renderer runs insecure content in a secure origin. IPC_MESSAGE_ROUTED2(FrameHostMsg_DidRunInsecureContent, GURL /* security_origin */, @@ -784,40 +674,12 @@ IPC_MESSAGE_ROUTED0(FrameHostMsg_DidDisplayContentWithCertificateErrors) // errors. IPC_MESSAGE_ROUTED0(FrameHostMsg_DidRunContentWithCertificateErrors) -// Response to FrameMsg_GetSavableResourceLinks. -IPC_MESSAGE_ROUTED3(FrameHostMsg_SavableResourceLinksResponse, - std::vector<GURL> /* savable resource links */, - content::Referrer /* referrer for all the links above */, - std::vector<content::SavableSubframe> /* subframes */) - -// Response to FrameMsg_GetSavableResourceLinks in case the frame contains -// non-savable content (i.e. from a non-savable scheme) or if there were -// errors gathering the links. -IPC_MESSAGE_ROUTED0(FrameHostMsg_SavableResourceLinksError) - -// Response to FrameMsg_GetSerializedHtmlWithLocalLinks. -IPC_MESSAGE_ROUTED2(FrameHostMsg_SerializedHtmlWithLocalLinksResponse, - std::string /* data buffer */, - bool /* end of data? */) - -// This message is sent from a RenderFrameProxy when sequential focus -// navigation needs to advance into its actual frame. |source_routing_id| -// identifies the frame that issued this request. This is used when pressing -// <tab> or <shift-tab> hits an out-of-process iframe when searching for the -// next focusable element. -IPC_MESSAGE_ROUTED2(FrameHostMsg_AdvanceFocus, - blink::mojom::FocusType /* type */, - int32_t /* source_routing_id */) - // A message from HTML-based UI. When (trusted) Javascript calls // send(message, args), this message is sent to the browser. IPC_MESSAGE_ROUTED2(FrameHostMsg_WebUISend, std::string /* message */, base::ListValue /* args */) -// Sent to notify that a frame called |window.focus()|. -IPC_MESSAGE_ROUTED0(FrameHostMsg_FrameDidCallFocus) - // Ask the frame host to print a cross-process subframe. // The printed content of this subframe belongs to the document specified by // its document cookie. Document cookie is a unique id for a printed document diff --git a/chromium/content/common/frame_proxy.mojom b/chromium/content/common/frame_proxy.mojom index 5b48f28804a..2f7f059af12 100644 --- a/chromium/content/common/frame_proxy.mojom +++ b/chromium/content/common/frame_proxy.mojom @@ -5,6 +5,7 @@ module content.mojom; import "ui/gfx/geometry/mojom/geometry.mojom"; +import "content/common/frame.mojom"; import "content/common/render_frame_metadata.mojom"; import "services/viz/public/mojom/compositing/frame_sink_id.mojom"; @@ -14,6 +15,9 @@ import "services/viz/public/mojom/compositing/frame_sink_id.mojom"; interface RenderFrameProxyHost { // TODO(dtapuska): Keep this interface for now. All methods have moved to // blink::RemoteFrameHost but we might still need this. + + // Requests that the given URL be opened in the specified manner. + OpenURL(OpenURLParams params); }; // Mojo interface for communicating from RenderFrameProxyHost to diff --git a/chromium/content/common/frame_replication_state.cc b/chromium/content/common/frame_replication_state.cc index 91b740a9adf..3c4e20eabc8 100644 --- a/chromium/content/common/frame_replication_state.cc +++ b/chromium/content/common/frame_replication_state.cc @@ -4,20 +4,9 @@ #include "content/common/frame_replication_state.h" -#include "services/network/public/mojom/web_sandbox_flags.mojom-shared.h" -#include "third_party/blink/public/mojom/frame/tree_scope_type.mojom.h" -#include "third_party/blink/public/mojom/security_context/insecure_request_policy.mojom.h" - namespace content { -FrameReplicationState::FrameReplicationState() - : active_sandbox_flags(network::mojom::WebSandboxFlags::kNone), - scope(blink::mojom::TreeScopeType::kDocument), - insecure_request_policy( - blink::mojom::InsecureRequestPolicy::kLeaveInsecureRequestsAlone), - has_potentially_trustworthy_unique_origin(false), - has_received_user_gesture(false), - has_received_user_gesture_before_nav(false) {} +FrameReplicationState::FrameReplicationState() = default; FrameReplicationState::FrameReplicationState( blink::mojom::TreeScopeType scope, @@ -26,7 +15,7 @@ FrameReplicationState::FrameReplicationState( blink::mojom::InsecureRequestPolicy insecure_request_policy, const std::vector<uint32_t>& insecure_navigations_set, bool has_potentially_trustworthy_unique_origin, - bool has_received_user_gesture, + bool has_active_user_gesture, bool has_received_user_gesture_before_nav, blink::mojom::FrameOwnerElementType owner_type) : name(name), @@ -37,15 +26,16 @@ FrameReplicationState::FrameReplicationState( insecure_navigations_set(insecure_navigations_set), has_potentially_trustworthy_unique_origin( has_potentially_trustworthy_unique_origin), - has_received_user_gesture(has_received_user_gesture), + has_active_user_gesture(has_active_user_gesture), has_received_user_gesture_before_nav( has_received_user_gesture_before_nav), frame_owner_element_type(owner_type) {} +FrameReplicationState::~FrameReplicationState() = default; + FrameReplicationState::FrameReplicationState( const FrameReplicationState& other) = default; - -FrameReplicationState::~FrameReplicationState() { -} +FrameReplicationState& FrameReplicationState::operator=( + const FrameReplicationState& other) = default; } // namespace content diff --git a/chromium/content/common/frame_replication_state.h b/chromium/content/common/frame_replication_state.h index 31391e27b13..817594b3e68 100644 --- a/chromium/content/common/frame_replication_state.h +++ b/chromium/content/common/frame_replication_state.h @@ -10,19 +10,15 @@ #include "content/common/content_export.h" #include "services/network/public/mojom/content_security_policy.mojom.h" +#include "services/network/public/mojom/web_sandbox_flags.mojom.h" #include "third_party/blink/public/common/feature_policy/feature_policy.h" #include "third_party/blink/public/common/frame/frame_policy.h" -#include "third_party/blink/public/mojom/ad_tagging/ad_frame.mojom-shared.h" +#include "third_party/blink/public/mojom/ad_tagging/ad_frame.mojom.h" #include "third_party/blink/public/mojom/frame/frame_owner_element_type.mojom.h" -#include "third_party/blink/public/mojom/security_context/insecure_request_policy.mojom-forward.h" +#include "third_party/blink/public/mojom/frame/tree_scope_type.mojom.h" +#include "third_party/blink/public/mojom/security_context/insecure_request_policy.mojom.h" #include "url/origin.h" -namespace blink { -namespace mojom { -enum class TreeScopeType; -} -} - namespace content { // This structure holds information that needs to be replicated between a @@ -36,12 +32,14 @@ struct CONTENT_EXPORT FrameReplicationState { blink::mojom::InsecureRequestPolicy insecure_request_policy, const std::vector<uint32_t>& insecure_navigations_set, bool has_potentially_trustworthy_unique_origin, - bool has_received_user_gesture, + bool has_active_user_gesture, bool has_received_user_gesture_before_nav, blink::mojom::FrameOwnerElementType owner_type); - FrameReplicationState(const FrameReplicationState& other); ~FrameReplicationState(); + FrameReplicationState(const FrameReplicationState& other); + FrameReplicationState& operator=(const FrameReplicationState& other); + // Current origin of the frame. This field is updated whenever a frame // navigation commits. // @@ -87,7 +85,8 @@ struct CONTENT_EXPORT FrameReplicationState { // inherited from parent frames, the currently active flags from the <iframe> // element hosting this frame, as well as any flags set from a // Content-Security-Policy HTTP header. - network::mojom::WebSandboxFlags active_sandbox_flags; + network::mojom::WebSandboxFlags active_sandbox_flags = + network::mojom::WebSandboxFlags::kNone; // Iframe sandbox flags and container policy currently in effect for the // frame. Container policy may be empty if this is the top-level frame. @@ -120,12 +119,13 @@ struct CONTENT_EXPORT FrameReplicationState { // created. However, making it const makes it a pain to embed into IPC message // params: having a const member implicitly deletes the copy assignment // operator. - blink::mojom::TreeScopeType scope; + blink::mojom::TreeScopeType scope = blink::mojom::TreeScopeType::kDocument; // The insecure request policy that a frame's current document is enforcing. // Updates are immediately sent to all frame proxies when frames live in // different processes. - blink::mojom::InsecureRequestPolicy insecure_request_policy; + blink::mojom::InsecureRequestPolicy insecure_request_policy = + blink::mojom::InsecureRequestPolicy::kLeaveInsecureRequestsAlone; // The upgrade insecure navigations set that a frame's current document is // enforcing. Updates are immediately sent to all frame proxies when frames @@ -135,14 +135,14 @@ struct CONTENT_EXPORT FrameReplicationState { // True if a frame's origin is unique and should be considered potentially // trustworthy. - bool has_potentially_trustworthy_unique_origin; + bool has_potentially_trustworthy_unique_origin = false; - // Whether the frame has ever received a user gesture anywhere. - bool has_received_user_gesture; + // Whether the frame has an active transient user gesture. + bool has_active_user_gesture = false; // Whether the frame has received a user gesture in a previous navigation so // long as a the frame has staying on the same eTLD+1. - bool has_received_user_gesture_before_nav; + bool has_received_user_gesture_before_nav = false; // The type of the (local) frame owner for this frame in the parent process. // Note: This should really be const, as it can never change once a frame is diff --git a/chromium/content/common/frame_visual_properties.h b/chromium/content/common/frame_visual_properties.h index 24964d7e766..fc6c7ede2a0 100644 --- a/chromium/content/common/frame_visual_properties.h +++ b/chromium/content/common/frame_visual_properties.h @@ -37,6 +37,7 @@ struct CONTENT_EXPORT FrameVisualProperties { gfx::Size visible_viewport_size; gfx::Size min_size_for_auto_resize; gfx::Size max_size_for_auto_resize; + std::vector<gfx::Rect> root_widget_window_segments; // The size of the compositor viewport, to match the sub-frame's surface. gfx::Rect compositor_viewport; diff --git a/chromium/content/common/input/event_with_latency_info.h b/chromium/content/common/input/event_with_latency_info.h index c90359968a6..edb31dbb8d1 100644 --- a/chromium/content/common/input/event_with_latency_info.h +++ b/chromium/content/common/input/event_with_latency_info.h @@ -5,8 +5,8 @@ #ifndef CONTENT_COMMON_INPUT_EVENT_WITH_LATENCY_INFO_H_ #define CONTENT_COMMON_INPUT_EVENT_WITH_LATENCY_INFO_H_ +#include "base/check_op.h" #include "base/compiler_specific.h" -#include "base/logging.h" #include "content/common/content_export.h" #include "third_party/blink/public/common/input/web_gesture_event.h" #include "third_party/blink/public/common/input/web_mouse_wheel_event.h" diff --git a/chromium/content/common/input/gesture_event_stream_validator_unittest.cc b/chromium/content/common/input/gesture_event_stream_validator_unittest.cc index 46c00da677a..238b31f7cd9 100644 --- a/chromium/content/common/input/gesture_event_stream_validator_unittest.cc +++ b/chromium/content/common/input/gesture_event_stream_validator_unittest.cc @@ -4,8 +4,8 @@ #include "content/common/input/gesture_event_stream_validator.h" -#include "content/common/input/synthetic_web_input_event_builders.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/input/synthetic_web_input_event_builders.h" using blink::WebInputEvent; using blink::WebGestureEvent; @@ -17,8 +17,8 @@ const blink::WebGestureDevice kDefaultGestureDevice = blink::WebGestureDevice::kTouchscreen; blink::WebGestureEvent Build(WebInputEvent::Type type) { - blink::WebGestureEvent event = - SyntheticWebGestureEventBuilder::Build(type, kDefaultGestureDevice); + blink::WebGestureEvent event = blink::SyntheticWebGestureEventBuilder::Build( + type, kDefaultGestureDevice); // Default to providing a (valid) non-zero fling velocity. if (type == WebInputEvent::Type::kGestureFlingStart) event.data.fling_start.velocity_x = 5; diff --git a/chromium/content/common/input/ime_text_span_conversions.cc b/chromium/content/common/input/ime_text_span_conversions.cc deleted file mode 100644 index e8ed1b511ad..00000000000 --- a/chromium/content/common/input/ime_text_span_conversions.cc +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/common/input/ime_text_span_conversions.h" - -#include "base/notreached.h" - -namespace content { - -blink::WebImeTextSpan::Type ConvertUiImeTextSpanTypeToWebType( - ui::ImeTextSpan::Type type) { - switch (type) { - case ui::ImeTextSpan::Type::kComposition: - return blink::WebImeTextSpan::Type::kComposition; - case ui::ImeTextSpan::Type::kSuggestion: - return blink::WebImeTextSpan::Type::kSuggestion; - case ui::ImeTextSpan::Type::kMisspellingSuggestion: - return blink::WebImeTextSpan::Type::kMisspellingSuggestion; - } - - NOTREACHED(); - return blink::WebImeTextSpan::Type::kComposition; -} - -ui::ImeTextSpan::Type ConvertWebImeTextSpanTypeToUiType( - blink::WebImeTextSpan::Type type) { - switch (type) { - case blink::WebImeTextSpan::Type::kComposition: - return ui::ImeTextSpan::Type::kComposition; - case blink::WebImeTextSpan::Type::kSuggestion: - return ui::ImeTextSpan::Type::kSuggestion; - case blink::WebImeTextSpan::Type::kMisspellingSuggestion: - return ui::ImeTextSpan::Type::kMisspellingSuggestion; - } - - NOTREACHED(); - return ui::ImeTextSpan::Type::kComposition; -} - -ui::mojom::ImeTextSpanThickness ConvertUiThicknessToUiImeTextSpanThickness( - ui::ImeTextSpan::Thickness thickness) { - switch (thickness) { - case ui::ImeTextSpan::Thickness::kNone: - return ui::mojom::ImeTextSpanThickness::kNone; - case ui::ImeTextSpan::Thickness::kThin: - return ui::mojom::ImeTextSpanThickness::kThin; - case ui::ImeTextSpan::Thickness::kThick: - return ui::mojom::ImeTextSpanThickness::kThick; - } - - NOTREACHED(); - return ui::mojom::ImeTextSpanThickness::kThin; -} - -ui::ImeTextSpan::Thickness ConvertUiImeTextSpanThicknessToUiThickness( - ui::mojom::ImeTextSpanThickness thickness) { - switch (thickness) { - case ui::mojom::ImeTextSpanThickness::kNone: - return ui::ImeTextSpan::Thickness::kNone; - case ui::mojom::ImeTextSpanThickness::kThin: - return ui::ImeTextSpan::Thickness::kThin; - case ui::mojom::ImeTextSpanThickness::kThick: - return ui::ImeTextSpan::Thickness::kThick; - } - - NOTREACHED(); - return ui::ImeTextSpan::Thickness::kThin; -} - -ui::mojom::ImeTextSpanUnderlineStyle -ConvertUiUnderlineStyleToUiImeTextSpanUnderlineStyle( - ui::ImeTextSpan::UnderlineStyle underline_style) { - switch (underline_style) { - case ui::ImeTextSpan::UnderlineStyle::kNone: - return ui::mojom::ImeTextSpanUnderlineStyle::kNone; - case ui::ImeTextSpan::UnderlineStyle::kSolid: - return ui::mojom::ImeTextSpanUnderlineStyle::kSolid; - case ui::ImeTextSpan::UnderlineStyle::kDot: - return ui::mojom::ImeTextSpanUnderlineStyle::kDot; - case ui::ImeTextSpan::UnderlineStyle::kDash: - return ui::mojom::ImeTextSpanUnderlineStyle::kDash; - case ui::ImeTextSpan::UnderlineStyle::kSquiggle: - return ui::mojom::ImeTextSpanUnderlineStyle::kSquiggle; - } - - NOTREACHED(); - return ui::mojom::ImeTextSpanUnderlineStyle::kSolid; -} - -ui::ImeTextSpan::UnderlineStyle -ConvertUiImeTextSpanUnderlineStyleToUiUnderlineStyle( - ui::mojom::ImeTextSpanUnderlineStyle underline_style) { - switch (underline_style) { - case ui::mojom::ImeTextSpanUnderlineStyle::kNone: - return ui::ImeTextSpan::UnderlineStyle::kNone; - case ui::mojom::ImeTextSpanUnderlineStyle::kSolid: - return ui::ImeTextSpan::UnderlineStyle::kSolid; - case ui::mojom::ImeTextSpanUnderlineStyle::kDot: - return ui::ImeTextSpan::UnderlineStyle::kDot; - case ui::mojom::ImeTextSpanUnderlineStyle::kDash: - return ui::ImeTextSpan::UnderlineStyle::kDash; - case ui::mojom::ImeTextSpanUnderlineStyle::kSquiggle: - return ui::ImeTextSpan::UnderlineStyle::kSquiggle; - } - - NOTREACHED(); - return ui::ImeTextSpan::UnderlineStyle::kSolid; -} - -blink::WebImeTextSpan ConvertUiImeTextSpanToBlinkImeTextSpan( - const ui::ImeTextSpan& ui_ime_text_span) { - blink::WebImeTextSpan blink_ime_text_span = blink::WebImeTextSpan( - ConvertUiImeTextSpanTypeToWebType(ui_ime_text_span.type), - ui_ime_text_span.start_offset, ui_ime_text_span.end_offset, - ConvertUiThicknessToUiImeTextSpanThickness(ui_ime_text_span.thickness), - ConvertUiUnderlineStyleToUiImeTextSpanUnderlineStyle( - ui_ime_text_span.underline_style), - ui_ime_text_span.background_color, - ui_ime_text_span.suggestion_highlight_color, - ui_ime_text_span.suggestions); - blink_ime_text_span.text_color = ui_ime_text_span.text_color; - blink_ime_text_span.underline_color = ui_ime_text_span.underline_color; - blink_ime_text_span.remove_on_finish_composing = - ui_ime_text_span.remove_on_finish_composing; - return blink_ime_text_span; -} - -std::vector<blink::WebImeTextSpan> ConvertUiImeTextSpansToBlinkImeTextSpans( - const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) { - std::vector<blink::WebImeTextSpan> blink_ime_text_spans; - for (const auto& ui_ime_text_span : ui_ime_text_spans) { - blink_ime_text_spans.push_back( - ConvertUiImeTextSpanToBlinkImeTextSpan(ui_ime_text_span)); - } - return blink_ime_text_spans; -} - -ui::ImeTextSpan ConvertBlinkImeTextSpanToUiImeTextSpan( - const blink::WebImeTextSpan& blink_ime_text_span) { - ui::ImeTextSpan ui_ime_text_span = ui::ImeTextSpan( - ConvertWebImeTextSpanTypeToUiType(blink_ime_text_span.type), - blink_ime_text_span.start_offset, blink_ime_text_span.end_offset, - ConvertUiImeTextSpanThicknessToUiThickness(blink_ime_text_span.thickness), - ConvertUiImeTextSpanUnderlineStyleToUiUnderlineStyle( - blink_ime_text_span.underline_style), - blink_ime_text_span.background_color, - blink_ime_text_span.suggestion_highlight_color, - blink_ime_text_span.suggestions); - ui_ime_text_span.text_color = blink_ime_text_span.text_color; - ui_ime_text_span.underline_color = blink_ime_text_span.underline_color; - ui_ime_text_span.remove_on_finish_composing = - blink_ime_text_span.remove_on_finish_composing; - return ui_ime_text_span; -} - -std::vector<ui::ImeTextSpan> ConvertBlinkImeTextSpansToUiImeTextSpans( - const std::vector<blink::WebImeTextSpan>& blink_ime_text_spans) { - std::vector<ui::ImeTextSpan> ui_ime_text_spans; - for (const auto& blink_ime_text_span : blink_ime_text_spans) { - ui_ime_text_spans.push_back( - ConvertBlinkImeTextSpanToUiImeTextSpan(blink_ime_text_span)); - } - return ui_ime_text_spans; -} - -} // namespace content diff --git a/chromium/content/common/input/ime_text_span_conversions.h b/chromium/content/common/input/ime_text_span_conversions.h deleted file mode 100644 index e7dd4fbfc16..00000000000 --- a/chromium/content/common/input/ime_text_span_conversions.h +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_COMMON_INPUT_IME_TEXT_SPAN_CONVERSIONS_H_ -#define CONTENT_COMMON_INPUT_IME_TEXT_SPAN_CONVERSIONS_H_ - -#include "third_party/blink/public/web/web_ime_text_span.h" -#include "ui/base/ime/ime_text_span.h" - -namespace content { - -blink::WebImeTextSpan::Type ConvertUiImeTextSpanTypeToWebType( - ui::ImeTextSpan::Type type); -ui::ImeTextSpan::Type ConvertWebImeTextSpanTypeToUiType( - blink::WebImeTextSpan::Type type); -ui::mojom::ImeTextSpanThickness ConvertUiThicknessToUiImeTextSpanThickness( - ui::ImeTextSpan::Thickness thickness); -ui::ImeTextSpan::Thickness ConvertUiImeTextSpanThicknessToUiThickness( - ui::mojom::ImeTextSpanThickness thickness); -ui::mojom::ImeTextSpanUnderlineStyle -ConvertUiUnderlineStyleToUiImeTextSpanUnderlineStyle( - ui::ImeTextSpan::UnderlineStyle underline_style); -ui::ImeTextSpan::UnderlineStyle -ConvertUiImeTextSpanUnderlineStyleToUiUnderlineStyle( - ui::mojom::ImeTextSpanUnderlineStyle underline_style); -blink::WebImeTextSpan ConvertUiImeTextSpanToBlinkImeTextSpan( - const ui::ImeTextSpan&); -ui::ImeTextSpan ConvertBlinkImeTextSpanToUiImeTextSpan( - const blink::WebImeTextSpan&); -std::vector<blink::WebImeTextSpan> ConvertUiImeTextSpansToBlinkImeTextSpans( - const std::vector<ui::ImeTextSpan>&); -std::vector<ui::ImeTextSpan> ConvertBlinkImeTextSpansToUiImeTextSpans( - const std::vector<blink::WebImeTextSpan>&); - -} // namespace content - -#endif // CONTENT_COMMON_INPUT_IME_TEXT_SPAN_CONVERSIONS_H_ diff --git a/chromium/content/common/input/input_event.cc b/chromium/content/common/input/input_event.cc deleted file mode 100644 index 4e11e69a36a..00000000000 --- a/chromium/content/common/input/input_event.cc +++ /dev/null @@ -1,23 +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 "content/common/input/input_event.h" - -#include "ui/events/blink/web_input_event_traits.h" - -namespace content { - -InputEvent::InputEvent() {} - -InputEvent::InputEvent(ui::WebScopedInputEvent event, - const ui::LatencyInfo& info) - : web_event(std::move(event)), latency_info(info) {} - -InputEvent::InputEvent(const blink::WebInputEvent& web_event, - const ui::LatencyInfo& latency_info) - : web_event(web_event.Clone()), latency_info(latency_info) {} - -InputEvent::~InputEvent() {} - -} // namespace content diff --git a/chromium/content/common/input/input_event.h b/chromium/content/common/input/input_event.h deleted file mode 100644 index 1345731677b..00000000000 --- a/chromium/content/common/input/input_event.h +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_COMMON_INPUT_INPUT_EVENT_H_ -#define CONTENT_COMMON_INPUT_INPUT_EVENT_H_ - -#include <memory> - -#include "base/macros.h" -#include "content/common/content_export.h" -#include "ui/events/blink/web_input_event_traits.h" -#include "ui/latency/latency_info.h" - -namespace blink { -class WebInputEvent; -} - -namespace content { - -// An content-specific wrapper for WebInputEvents and associated metadata. -class CONTENT_EXPORT InputEvent { - public: - InputEvent(); - InputEvent(ui::WebScopedInputEvent web_event, - const ui::LatencyInfo& latency_info); - InputEvent(const blink::WebInputEvent& web_event, - const ui::LatencyInfo& latency_info); - ~InputEvent(); - - ui::WebScopedInputEvent web_event; - ui::LatencyInfo latency_info; - - private: - DISALLOW_COPY_AND_ASSIGN(InputEvent); -}; - -} // namespace content - -#endif // CONTENT_COMMON_INPUT_INPUT_EVENT_H_ diff --git a/chromium/content/common/input/input_event_mojom_traits.cc b/chromium/content/common/input/input_event_mojom_traits.cc deleted file mode 100644 index 9f19111f925..00000000000 --- a/chromium/content/common/input/input_event_mojom_traits.cc +++ /dev/null @@ -1,538 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/common/input/input_event_mojom_traits.h" - -#include "base/i18n/char_iterator.h" -#include "content/common/input_messages.h" -#include "mojo/public/cpp/base/time_mojom_traits.h" -#include "third_party/blink/public/common/input/web_keyboard_event.h" -#include "third_party/blink/public/common/input/web_mouse_wheel_event.h" -#include "ui/latency/mojom/latency_info_mojom_traits.h" - -namespace mojo { -namespace { - -void CopyString(base::char16* dst, const base::string16& text) { - base::i18n::UTF16CharIterator iter(&text); - size_t pos = 0; - while (!iter.end() && pos < blink::WebKeyboardEvent::kTextLengthCap - 1) { - dst[pos++] = iter.get(); - iter.Advance(); - } - dst[pos] = '\0'; -} - -content::mojom::PointerDataPtr PointerDataFromPointerProperties( - const blink::WebPointerProperties& pointer, - content::mojom::MouseDataPtr mouse_data) { - return content::mojom::PointerData::New( - pointer.id, pointer.force, pointer.tilt_x, pointer.tilt_y, - pointer.tangential_pressure, pointer.twist, pointer.button, - pointer.pointer_type, pointer.movement_x, pointer.movement_y, - pointer.is_raw_movement_event, pointer.PositionInWidget(), - pointer.PositionInScreen(), std::move(mouse_data)); -} - -void PointerPropertiesFromPointerData( - const content::mojom::PointerDataPtr& pointer_data, - blink::WebPointerProperties* pointer_properties) { - pointer_properties->id = pointer_data->pointer_id; - pointer_properties->force = pointer_data->force; - pointer_properties->tilt_x = pointer_data->tilt_x; - pointer_properties->tilt_y = pointer_data->tilt_y; - pointer_properties->tangential_pressure = pointer_data->tangential_pressure; - pointer_properties->twist = pointer_data->twist; - pointer_properties->button = pointer_data->button; - pointer_properties->pointer_type = pointer_data->pointer_type; - pointer_properties->movement_x = pointer_data->movement_x; - pointer_properties->movement_y = pointer_data->movement_y; - pointer_properties->is_raw_movement_event = - pointer_data->is_raw_movement_event; -} - -void TouchPointPropertiesFromPointerData( - const content::mojom::TouchPointPtr& mojo_touch_point, - blink::WebTouchPoint* touch_point) { - PointerPropertiesFromPointerData(mojo_touch_point->pointer_data, touch_point); - touch_point->state = mojo_touch_point->state; - touch_point->radius_x = mojo_touch_point->radius_x; - touch_point->radius_y = mojo_touch_point->radius_y; - touch_point->rotation_angle = mojo_touch_point->rotation_angle; - touch_point->SetPositionInWidget( - mojo_touch_point->pointer_data->widget_position.x(), - mojo_touch_point->pointer_data->widget_position.y()); - touch_point->SetPositionInScreen( - mojo_touch_point->pointer_data->screen_position.x(), - mojo_touch_point->pointer_data->screen_position.y()); -} - -// TODO(dtapuska): Remove once SetPositionInXXX moves to WebPointerProperties. -void MouseEventPropertiesFromPointerData( - const content::mojom::PointerDataPtr& pointer_data, - blink::WebMouseEvent* mouse_event) { - PointerPropertiesFromPointerData(pointer_data, mouse_event); - mouse_event->SetPositionInWidget(pointer_data->widget_position.x(), - pointer_data->widget_position.y()); - mouse_event->SetPositionInScreen(pointer_data->screen_position.x(), - pointer_data->screen_position.y()); -} - -} // namespace - -bool StructTraits<content::mojom::EventDataView, InputEventUniquePtr>::Read( - content::mojom::EventDataView event, - InputEventUniquePtr* out) { - DCHECK(!out->get()); - - out->reset(new content::InputEvent()); - - blink::WebInputEvent::Type type; - if (!event.ReadType(&type)) - return false; - - base::TimeTicks timestamp; - if (!event.ReadTimestamp(×tamp)) - return false; - - if (blink::WebInputEvent::IsKeyboardEventType(type)) { - content::mojom::KeyDataPtr key_data; - if (!event.ReadKeyData<content::mojom::KeyDataPtr>(&key_data)) - return false; - - (*out)->web_event.reset( - new blink::WebKeyboardEvent(type, event.modifiers(), timestamp)); - - blink::WebKeyboardEvent* key_event = - static_cast<blink::WebKeyboardEvent*>((*out)->web_event.get()); - key_event->windows_key_code = key_data->windows_key_code; - key_event->native_key_code = key_data->native_key_code; - key_event->dom_code = key_data->dom_code; - key_event->dom_key = key_data->dom_key; - key_event->is_system_key = key_data->is_system_key; - key_event->is_browser_shortcut = key_data->is_browser_shortcut; - CopyString(key_event->text, key_data->text); - CopyString(key_event->unmodified_text, key_data->unmodified_text); - } else if (blink::WebInputEvent::IsGestureEventType(type)) { - content::mojom::GestureDataPtr gesture_data; - if (!event.ReadGestureData<content::mojom::GestureDataPtr>(&gesture_data)) - return false; - (*out)->web_event.reset(new blink::WebGestureEvent( - type, event.modifiers(), timestamp, gesture_data->source_device)); - - blink::WebGestureEvent* gesture_event = - static_cast<blink::WebGestureEvent*>((*out)->web_event.get()); - gesture_event->SetPositionInWidget(gesture_data->widget_position); - gesture_event->SetPositionInScreen(gesture_data->screen_position); - gesture_event->is_source_touch_event_set_non_blocking = - gesture_data->is_source_touch_event_set_non_blocking; - gesture_event->primary_pointer_type = gesture_data->primary_pointer_type; - gesture_event->SetSourceDevice(gesture_data->source_device); - gesture_event->unique_touch_event_id = gesture_data->unique_touch_event_id; - - if (gesture_data->contact_size) { - switch (type) { - default: - break; - case blink::WebInputEvent::Type::kGestureTapDown: - gesture_event->data.tap_down.width = - gesture_data->contact_size->width(); - gesture_event->data.tap_down.height = - gesture_data->contact_size->height(); - break; - case blink::WebInputEvent::Type::kGestureShowPress: - gesture_event->data.show_press.width = - gesture_data->contact_size->width(); - gesture_event->data.show_press.height = - gesture_data->contact_size->height(); - break; - case blink::WebInputEvent::Type::kGestureTap: - case blink::WebInputEvent::Type::kGestureTapUnconfirmed: - case blink::WebInputEvent::Type::kGestureDoubleTap: - gesture_event->data.tap.width = gesture_data->contact_size->width(); - gesture_event->data.tap.height = gesture_data->contact_size->height(); - break; - case blink::WebInputEvent::Type::kGestureLongPress: - case blink::WebInputEvent::Type::kGestureLongTap: - gesture_event->data.long_press.width = - gesture_data->contact_size->width(); - gesture_event->data.long_press.height = - gesture_data->contact_size->height(); - break; - case blink::WebInputEvent::Type::kGestureTwoFingerTap: - gesture_event->data.two_finger_tap.first_finger_width = - gesture_data->contact_size->width(); - gesture_event->data.two_finger_tap.first_finger_height = - gesture_data->contact_size->height(); - break; - } - } - - if (gesture_data->scroll_data) { - switch (type) { - default: - break; - case blink::WebInputEvent::Type::kGestureScrollBegin: - gesture_event->data.scroll_begin.delta_x_hint = - gesture_data->scroll_data->delta_x; - gesture_event->data.scroll_begin.delta_y_hint = - gesture_data->scroll_data->delta_y; - gesture_event->data.scroll_begin.delta_hint_units = - gesture_data->scroll_data->delta_units; - gesture_event->data.scroll_begin.target_viewport = - gesture_data->scroll_data->target_viewport; - gesture_event->data.scroll_begin.inertial_phase = - gesture_data->scroll_data->inertial_phase; - gesture_event->data.scroll_begin.synthetic = - gesture_data->scroll_data->synthetic; - gesture_event->data.scroll_begin.pointer_count = - gesture_data->scroll_data->pointer_count; - break; - case blink::WebInputEvent::Type::kGestureScrollEnd: - gesture_event->data.scroll_end.delta_units = - gesture_data->scroll_data->delta_units; - gesture_event->data.scroll_end.inertial_phase = - gesture_data->scroll_data->inertial_phase; - gesture_event->data.scroll_end.synthetic = - gesture_data->scroll_data->synthetic; - break; - case blink::WebInputEvent::Type::kGestureScrollUpdate: - gesture_event->data.scroll_update.delta_x = - gesture_data->scroll_data->delta_x; - gesture_event->data.scroll_update.delta_y = - gesture_data->scroll_data->delta_y; - gesture_event->data.scroll_update.delta_units = - gesture_data->scroll_data->delta_units; - gesture_event->data.scroll_update.inertial_phase = - gesture_data->scroll_data->inertial_phase; - if (gesture_data->scroll_data->update_details) { - gesture_event->data.scroll_update.velocity_x = - gesture_data->scroll_data->update_details->velocity_x; - gesture_event->data.scroll_update.velocity_y = - gesture_data->scroll_data->update_details->velocity_y; - } - break; - } - } - - if (gesture_data->pinch_begin_data && - type == blink::WebInputEvent::Type::kGesturePinchBegin) { - gesture_event->data.pinch_begin.needs_wheel_event = - gesture_data->pinch_begin_data->needs_wheel_event; - } - - if (gesture_data->pinch_update_data && - type == blink::WebInputEvent::Type::kGesturePinchUpdate) { - gesture_event->data.pinch_update.zoom_disabled = - gesture_data->pinch_update_data->zoom_disabled; - gesture_event->data.pinch_update.scale = - gesture_data->pinch_update_data->scale; - gesture_event->data.pinch_update.needs_wheel_event = - gesture_data->pinch_update_data->needs_wheel_event; - } - - if (gesture_data->pinch_end_data && - type == blink::WebInputEvent::Type::kGesturePinchEnd) { - gesture_event->data.pinch_end.needs_wheel_event = - gesture_data->pinch_end_data->needs_wheel_event; - } - - if (gesture_data->tap_data) { - switch (type) { - default: - break; - case blink::WebInputEvent::Type::kGestureTap: - case blink::WebInputEvent::Type::kGestureTapUnconfirmed: - case blink::WebInputEvent::Type::kGestureDoubleTap: - gesture_event->data.tap.tap_count = gesture_data->tap_data->tap_count; - gesture_event->data.tap.needs_wheel_event = - gesture_data->tap_data->needs_wheel_event; - break; - } - } - - if (gesture_data->fling_data) { - switch (type) { - default: - break; - case blink::WebInputEvent::Type::kGestureFlingStart: - gesture_event->data.fling_start.velocity_x = - gesture_data->fling_data->velocity_x; - gesture_event->data.fling_start.velocity_y = - gesture_data->fling_data->velocity_y; - gesture_event->data.fling_start.target_viewport = - gesture_data->fling_data->target_viewport; - break; - case blink::WebInputEvent::Type::kGestureFlingCancel: - gesture_event->data.fling_cancel.target_viewport = - gesture_data->fling_data->target_viewport; - gesture_event->data.fling_cancel.prevent_boosting = - gesture_data->fling_data->prevent_boosting; - break; - } - } - - } else if (blink::WebInputEvent::IsTouchEventType(type)) { - content::mojom::TouchDataPtr touch_data; - if (!event.ReadTouchData<content::mojom::TouchDataPtr>(&touch_data)) - return false; - - (*out)->web_event.reset( - new blink::WebTouchEvent(type, event.modifiers(), timestamp)); - - blink::WebTouchEvent* touch_event = - static_cast<blink::WebTouchEvent*>((*out)->web_event.get()); - std::vector<content::mojom::TouchPointPtr> touches; - unsigned i; - for (i = 0; i < touch_data->touches.size() && - i < blink::WebTouchEvent::kTouchesLengthCap; - ++i) { - blink::WebTouchPoint& touch_point = touch_event->touches[i]; - TouchPointPropertiesFromPointerData(touch_data->touches[i], &touch_point); - } - - touch_event->touches_length = i; - touch_event->dispatch_type = touch_data->cancelable; - touch_event->moved_beyond_slop_region = - touch_data->moved_beyond_slop_region; - touch_event->hovering = touch_data->hovering; - touch_event->touch_start_or_first_touch_move = - touch_data->touch_start_or_first_move; - touch_event->unique_touch_event_id = touch_data->unique_touch_event_id; - } else if (blink::WebInputEvent::IsMouseEventType(type) || - type == blink::WebInputEvent::Type::kMouseWheel) { - content::mojom::PointerDataPtr pointer_data; - if (!event.ReadPointerData<content::mojom::PointerDataPtr>(&pointer_data)) - return false; - - if (blink::WebInputEvent::IsMouseEventType(type)) { - (*out)->web_event.reset( - new blink::WebMouseEvent(type, event.modifiers(), timestamp)); - } else { - (*out)->web_event.reset( - new blink::WebMouseWheelEvent(type, event.modifiers(), timestamp)); - } - - blink::WebMouseEvent* mouse_event = - static_cast<blink::WebMouseEvent*>((*out)->web_event.get()); - - MouseEventPropertiesFromPointerData(pointer_data, mouse_event); - if (pointer_data->mouse_data) { - mouse_event->click_count = pointer_data->mouse_data->click_count; - - if (type == blink::WebInputEvent::Type::kMouseWheel && - pointer_data->mouse_data->wheel_data) { - blink::WebMouseWheelEvent* wheel_event = - static_cast<blink::WebMouseWheelEvent*>(mouse_event); - content::mojom::WheelDataPtr& wheel_data = - pointer_data->mouse_data->wheel_data; - wheel_event->delta_x = wheel_data->delta_x; - wheel_event->delta_y = wheel_data->delta_y; - wheel_event->wheel_ticks_x = wheel_data->wheel_ticks_x; - wheel_event->wheel_ticks_y = wheel_data->wheel_ticks_y; - wheel_event->acceleration_ratio_x = wheel_data->acceleration_ratio_x; - wheel_event->acceleration_ratio_y = wheel_data->acceleration_ratio_y; - wheel_event->phase = - static_cast<blink::WebMouseWheelEvent::Phase>(wheel_data->phase); - wheel_event->momentum_phase = - static_cast<blink::WebMouseWheelEvent::Phase>( - wheel_data->momentum_phase); - wheel_event->dispatch_type = wheel_data->cancelable; - wheel_event->event_action = - static_cast<blink::WebMouseWheelEvent::EventAction>( - wheel_data->event_action); - wheel_event->delta_units = - static_cast<ui::ScrollGranularity>(wheel_data->delta_units); - } - } - - } else { - return false; - } - - return event.ReadLatency(&((*out)->latency_info)); -} - -// static -content::mojom::KeyDataPtr -StructTraits<content::mojom::EventDataView, InputEventUniquePtr>::key_data( - const InputEventUniquePtr& event) { - if (!event->web_event || - !blink::WebInputEvent::IsKeyboardEventType(event->web_event->GetType())) - return nullptr; - const blink::WebKeyboardEvent* key_event = - static_cast<const blink::WebKeyboardEvent*>(event->web_event.get()); - return content::mojom::KeyData::New( - key_event->dom_key, key_event->dom_code, key_event->windows_key_code, - key_event->native_key_code, key_event->is_system_key, - key_event->is_browser_shortcut, key_event->text, - key_event->unmodified_text); -} - -// static -content::mojom::PointerDataPtr -StructTraits<content::mojom::EventDataView, InputEventUniquePtr>::pointer_data( - const InputEventUniquePtr& event) { - if (!event->web_event) - return nullptr; - bool is_wheel_event = - event->web_event->GetType() == blink::WebInputEvent::Type::kMouseWheel; - if (!blink::WebInputEvent::IsMouseEventType(event->web_event->GetType()) && - !is_wheel_event) { - return nullptr; - } - const blink::WebMouseEvent* mouse_event = - static_cast<const blink::WebMouseEvent*>(event->web_event.get()); - - content::mojom::WheelDataPtr wheel_data; - if (is_wheel_event) { - const blink::WebMouseWheelEvent* wheel_event = - static_cast<const blink::WebMouseWheelEvent*>(mouse_event); - wheel_data = content::mojom::WheelData::New( - wheel_event->delta_x, wheel_event->delta_y, wheel_event->wheel_ticks_x, - wheel_event->wheel_ticks_y, wheel_event->acceleration_ratio_x, - wheel_event->acceleration_ratio_y, wheel_event->phase, - wheel_event->momentum_phase, wheel_event->dispatch_type, - static_cast<uint8_t>(wheel_event->event_action), - static_cast<uint8_t>(wheel_event->delta_units)); - } - - return PointerDataFromPointerProperties( - *mouse_event, content::mojom::MouseData::New(mouse_event->click_count, - std::move(wheel_data))); -} - -// static -content::mojom::GestureDataPtr -StructTraits<content::mojom::EventDataView, InputEventUniquePtr>::gesture_data( - const InputEventUniquePtr& event) { - if (!event->web_event || - !blink::WebInputEvent::IsGestureEventType(event->web_event->GetType())) - return nullptr; - const blink::WebGestureEvent* gesture_event = - static_cast<const blink::WebGestureEvent*>(event->web_event.get()); - auto gesture_data = content::mojom::GestureData::New(); - gesture_data->screen_position = gesture_event->PositionInScreen(); - gesture_data->widget_position = gesture_event->PositionInWidget(); - gesture_data->source_device = gesture_event->SourceDevice(); - gesture_data->is_source_touch_event_set_non_blocking = - gesture_event->is_source_touch_event_set_non_blocking; - gesture_data->primary_pointer_type = gesture_event->primary_pointer_type; - gesture_data->unique_touch_event_id = gesture_event->unique_touch_event_id; - switch (gesture_event->GetType()) { - default: - break; - case blink::WebInputEvent::Type::kGestureTapDown: - gesture_data->contact_size = - gfx::Size(gesture_event->data.tap_down.width, - gesture_event->data.tap_down.height); - break; - case blink::WebInputEvent::Type::kGestureShowPress: - gesture_data->contact_size = - gfx::Size(gesture_event->data.show_press.width, - gesture_event->data.show_press.height); - break; - case blink::WebInputEvent::Type::kGestureTap: - case blink::WebInputEvent::Type::kGestureTapUnconfirmed: - case blink::WebInputEvent::Type::kGestureDoubleTap: - gesture_data->contact_size = gfx::Size(gesture_event->data.tap.width, - gesture_event->data.tap.height); - gesture_data->tap_data = content::mojom::TapData::New( - gesture_event->data.tap.tap_count, - gesture_event->data.tap.needs_wheel_event); - break; - case blink::WebInputEvent::Type::kGestureLongPress: - case blink::WebInputEvent::Type::kGestureLongTap: - gesture_data->contact_size = - gfx::Size(gesture_event->data.long_press.width, - gesture_event->data.long_press.height); - break; - - case blink::WebInputEvent::Type::kGestureTwoFingerTap: - gesture_data->contact_size = - gfx::Size(gesture_event->data.two_finger_tap.first_finger_width, - gesture_event->data.two_finger_tap.first_finger_height); - break; - case blink::WebInputEvent::Type::kGestureScrollBegin: - gesture_data->scroll_data = content::mojom::ScrollData::New( - gesture_event->data.scroll_begin.delta_x_hint, - gesture_event->data.scroll_begin.delta_y_hint, - gesture_event->data.scroll_begin.delta_hint_units, - gesture_event->data.scroll_begin.target_viewport, - gesture_event->data.scroll_begin.inertial_phase, - gesture_event->data.scroll_begin.synthetic, - gesture_event->data.scroll_begin.pointer_count, nullptr); - break; - case blink::WebInputEvent::Type::kGestureScrollEnd: - gesture_data->scroll_data = content::mojom::ScrollData::New( - 0, 0, gesture_event->data.scroll_end.delta_units, false, - gesture_event->data.scroll_end.inertial_phase, - gesture_event->data.scroll_end.synthetic, 0, nullptr); - break; - case blink::WebInputEvent::Type::kGestureScrollUpdate: - gesture_data->scroll_data = content::mojom::ScrollData::New( - gesture_event->data.scroll_update.delta_x, - gesture_event->data.scroll_update.delta_y, - gesture_event->data.scroll_update.delta_units, false, - gesture_event->data.scroll_update.inertial_phase, false, 0, - content::mojom::ScrollUpdate::New( - gesture_event->data.scroll_update.velocity_x, - gesture_event->data.scroll_update.velocity_y)); - break; - case blink::WebInputEvent::Type::kGestureFlingStart: - gesture_data->fling_data = content::mojom::FlingData::New( - gesture_event->data.fling_start.velocity_x, - gesture_event->data.fling_start.velocity_y, - gesture_event->data.fling_start.target_viewport, false); - break; - case blink::WebInputEvent::Type::kGestureFlingCancel: - gesture_data->fling_data = content::mojom::FlingData::New( - 0, 0, gesture_event->data.fling_cancel.target_viewport, - gesture_event->data.fling_cancel.prevent_boosting); - break; - case blink::WebInputEvent::Type::kGesturePinchBegin: - gesture_data->pinch_begin_data = content::mojom::PinchBeginData::New( - gesture_event->data.pinch_begin.needs_wheel_event); - break; - case blink::WebInputEvent::Type::kGesturePinchUpdate: - gesture_data->pinch_update_data = content::mojom::PinchUpdateData::New( - gesture_event->data.pinch_update.scale, - gesture_event->data.pinch_update.zoom_disabled, - gesture_event->data.pinch_update.needs_wheel_event); - break; - case blink::WebInputEvent::Type::kGesturePinchEnd: - gesture_data->pinch_end_data = content::mojom::PinchEndData::New( - gesture_event->data.pinch_end.needs_wheel_event); - break; - } - return gesture_data; -} - -// static -content::mojom::TouchDataPtr -StructTraits<content::mojom::EventDataView, InputEventUniquePtr>::touch_data( - const InputEventUniquePtr& event) { - if (!event->web_event || - !blink::WebInputEvent::IsTouchEventType(event->web_event->GetType())) - return nullptr; - - const blink::WebTouchEvent* touch_event = - static_cast<const blink::WebTouchEvent*>(event->web_event.get()); - auto touch_data = content::mojom::TouchData::New( - touch_event->dispatch_type, touch_event->moved_beyond_slop_region, - touch_event->touch_start_or_first_touch_move, touch_event->hovering, - touch_event->unique_touch_event_id, - std::vector<content::mojom::TouchPointPtr>()); - for (unsigned i = 0; i < touch_event->touches_length; ++i) { - content::mojom::PointerDataPtr pointer_data = - PointerDataFromPointerProperties(touch_event->touches[i], nullptr); - touch_data->touches.emplace_back(content::mojom::TouchPoint::New( - touch_event->touches[i].state, touch_event->touches[i].radius_x, - touch_event->touches[i].radius_y, - touch_event->touches[i].rotation_angle, std::move(pointer_data))); - } - return touch_data; -} - -} // namespace mojo diff --git a/chromium/content/common/input/input_event_mojom_traits.h b/chromium/content/common/input/input_event_mojom_traits.h deleted file mode 100644 index 6d453a672bd..00000000000 --- a/chromium/content/common/input/input_event_mojom_traits.h +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_COMMON_INPUT_INPUT_EVENT_MOJOM_TRAITS_H_ -#define CONTENT_COMMON_INPUT_INPUT_EVENT_MOJOM_TRAITS_H_ - -#include "content/common/input/input_handler.mojom.h" - -namespace content { -class InputEvent; -} - -namespace mojo { - -using InputEventUniquePtr = std::unique_ptr<content::InputEvent>; - -template <> -struct StructTraits<content::mojom::EventDataView, InputEventUniquePtr> { - static blink::WebInputEvent::Type type(const InputEventUniquePtr& event) { - return event->web_event->GetType(); - } - - static int32_t modifiers(const InputEventUniquePtr& event) { - return event->web_event->GetModifiers(); - } - - static base::TimeTicks timestamp(const InputEventUniquePtr& event) { - return event->web_event->TimeStamp(); - } - - static const ui::LatencyInfo& latency(const InputEventUniquePtr& event) { - return event->latency_info; - } - - static content::mojom::KeyDataPtr key_data(const InputEventUniquePtr& event); - static content::mojom::PointerDataPtr pointer_data( - const InputEventUniquePtr& event); - static content::mojom::GestureDataPtr gesture_data( - const InputEventUniquePtr& event); - static content::mojom::TouchDataPtr touch_data( - const InputEventUniquePtr& event); - - static bool Read(content::mojom::EventDataView r, InputEventUniquePtr* out); -}; - -} // namespace mojo - -#endif // CONTENT_COMMON_INPUT_INPUT_EVENT_MOJOM_TRAITS_H_ diff --git a/chromium/content/common/input/input_handler.mojom b/chromium/content/common/input/input_handler.mojom deleted file mode 100644 index 6ae8d0bf969..00000000000 --- a/chromium/content/common/input/input_handler.mojom +++ /dev/null @@ -1,398 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module content.mojom; - -import "cc/mojom/touch_action.mojom"; -import "content/common/input/synchronous_compositor.mojom"; -import "content/common/native_types.mojom"; -import "mojo/public/mojom/base/string16.mojom"; -import "mojo/public/mojom/base/time.mojom"; -import "third_party/blink/public/mojom/input/gesture_event.mojom"; -import "third_party/blink/public/mojom/input/input_event.mojom"; -import "third_party/blink/public/mojom/input/input_handler.mojom"; -import "third_party/blink/public/mojom/input/input_event_result.mojom"; -import "third_party/blink/public/mojom/input/pointer_lock_result.mojom"; -import "third_party/blink/public/mojom/input/touch_event.mojom"; -import "third_party/blink/public/mojom/input/pointer_lock_context.mojom"; -import "third_party/blink/public/mojom/selection_menu/selection_menu_behavior.mojom"; -import "ui/base/ime/mojom/ime_types.mojom"; -import "ui/events/mojom/event.mojom"; -import "ui/events/mojom/event_constants.mojom"; -import "ui/events/mojom/scroll_granularity.mojom"; -import "ui/gfx/geometry/mojom/geometry.mojom"; -import "ui/gfx/range/mojom/range.mojom"; -import "ui/latency/mojom/latency_info.mojom"; - - -// These structs are purposely duplicated from ui/events/mojom/event.mojom. -// They map WebInputEvent <-> WebInputEvent across mojo. -// We have to work at unifying them. The current problem is that the browser -// uses WebInputEvents inside the render widget host and input router. Once -// we move these to ui::Event's then we can get rid of these duplicated -// mojom structs. Ideally the browser would use ui::Event up until we -// pass the events into the renderer and just use a StructTraits to perform -// conversion from ui::mojom::Event --> blink::WebInputEvent. -struct KeyData { - int32 dom_key; - int32 dom_code; - int32 windows_key_code; - int32 native_key_code; - bool is_system_key; - bool is_browser_shortcut; - mojo_base.mojom.String16 text; - mojo_base.mojom.String16 unmodified_text; -}; - -struct PointerData { - int32 pointer_id; - float force; - int32 tilt_x; - int32 tilt_y; - float tangential_pressure; - int32 twist; - blink.mojom.Button button; - ui.mojom.EventPointerType pointer_type; - int32 movement_x; - int32 movement_y; - bool is_raw_movement_event; - gfx.mojom.PointF widget_position; - gfx.mojom.PointF screen_position; - MouseData? mouse_data; -}; - -struct WheelData { - float delta_x; - float delta_y; - float wheel_ticks_x; - float wheel_ticks_y; - float acceleration_ratio_x; - float acceleration_ratio_y; - uint8 phase; - uint8 momentum_phase; - blink.mojom.DispatchType cancelable; - uint8 event_action; - uint8 delta_units; -}; - -struct MouseData { - int32 click_count; - WheelData? wheel_data; -}; - -struct ScrollUpdate { - float velocity_x; - float velocity_y; -}; - -struct ScrollData { - float delta_x; - float delta_y; - ui.mojom.ScrollGranularity delta_units; - bool target_viewport; - blink.mojom.InertialPhaseState inertial_phase; - bool synthetic; - int32 pointer_count; - ScrollUpdate? update_details; -}; - -struct PinchBeginData { - bool needs_wheel_event; -}; - -struct PinchUpdateData { - float scale; - bool zoom_disabled; - bool needs_wheel_event; -}; - -struct PinchEndData { - bool needs_wheel_event; -}; - -struct FlingData { - float velocity_x; - float velocity_y; - bool target_viewport; - bool prevent_boosting; -}; - -struct TapData { - int32 tap_count; - bool needs_wheel_event; -}; - -struct GestureData { - gfx.mojom.PointF screen_position; - gfx.mojom.PointF widget_position; - blink.mojom.GestureDevice source_device; - bool is_source_touch_event_set_non_blocking; - ui.mojom.EventPointerType primary_pointer_type; - int32 unique_touch_event_id; - gfx.mojom.Size? contact_size; - ScrollData? scroll_data; - PinchBeginData? pinch_begin_data; - PinchUpdateData? pinch_update_data; - PinchEndData? pinch_end_data; - TapData? tap_data; - FlingData? fling_data; -}; - -struct TouchPoint { - blink.mojom.TouchState state; - float radius_x; - float radius_y; - float rotation_angle; - PointerData pointer_data; -}; - -struct TouchData { - blink.mojom.DispatchType cancelable; - bool moved_beyond_slop_region; - bool touch_start_or_first_move; - bool hovering; - uint32 unique_touch_event_id; - array<TouchPoint> touches; -}; - -struct Event { - blink.mojom.EventType type; - int32 modifiers; - mojo_base.mojom.TimeTicks timestamp; - ui.mojom.LatencyInfo latency; - KeyData? key_data; - PointerData? pointer_data; - GestureData? gesture_data; - TouchData? touch_data; -}; - -// Interface exposed by the browser to the renderer. -interface WidgetInputHandlerHost { - // When the renderer's main thread computes the touch action, send this to the - // browser. - SetTouchActionFromMain(cc.mojom.TouchAction touch_action); - - // Sent by the compositor when input scroll events are dropped due to bounds - // restrictions on the root scroll offset. - DidOverscroll(blink.mojom.DidOverscrollParams params); - - // Sent by the compositor when a GSB has started scrolling the viewport. - DidStartScrollingViewport(); - - // Required for cancelling an ongoing input method composition. - ImeCancelComposition(); - - // Sends the character bounds after every composition change - // to always have correct bound info. - ImeCompositionRangeChanged(gfx.mojom.Range range, - array<gfx.mojom.Rect> bounds); - - // Updates the mouse capture state of this widget. While capture is enabled, - // all mouse events, including those that don't hittest to this widget, will - // be targeted to this widget. This enables Blink to behave correctly when - // a scrollbar is being dragged, or text is being drag-highlighted, even - // when the mouse passes across different RenderWidget areas. - SetMouseCapture(bool capture); - - // Requests locking the target of mouse events to a single element and - // removing the cursor from view. Mostly used by the Pointer Lock API. - // See https://www.w3.org/TR/pointerlock/ for more info. This call is - // also used by Pepper Flash. - // |from_user_gesture| indicates whether this request came from a user - // gesture or not. - // |privileged| is used by Pepper Flash. Privileged mouse lock is only - // allowed for fullscreen render widget, which is used to implement Pepper - // Flash fullscreen. If privileged is allowed and set to true, we - // won't pop up a bubble to ask for user permission or take mouse lock - // content into account. The mouse lock will be directly approved. - // |unadjusted_movement| indicates whether the request asked for raw mouse - // movement data or just what the operating system returns (often accelerated - // mouse movement). - // |result| kSuccess if the mouse has been locked or the appropriate error - // reason if not. - // |context| is one end of a mojo pipe that will stay connected as long as - // the mouse is locked. Is a NullRemote if |result| is not kSuccess. - RequestMouseLock(bool from_user_gesture, - bool privileged, - bool unadjusted_movement) - => (blink.mojom.PointerLockResult result, - pending_remote<blink.mojom.PointerLockContext>? context); -}; - -// Interface exposed by the renderer to the browser. This class represents -// an input interface for an associated Widget object. See FrameInputHandler -// for an interface at the frame level. -interface WidgetInputHandler { - // Tells widget focus has been changed. - SetFocus(bool focused); - - // Tells widget mouse capture has been lost. - MouseCaptureLost(); - - // This message notifies the renderer that the next key event is bound to one - // or more pre-defined edit commands. If the next key event is not handled - // by blink, the specified edit commands shall be executed against current - // focused frame. - // Parameters - // * edit_commands - // See t_p/b/renderer/core/editing/commands/editing_command_type.h - // Contains one or more edit commands. - // See t_p/b/renderer/core/editing/commands/editor_command.cc for - // detailed definition of webkit edit commands. - // - // This message must be sent just before sending a key event. - SetEditCommandsForNextKeyEvent(array<blink.mojom.EditCommand> edit_commands); - - // Sends the cursor visibility state to the render widget. - CursorVisibilityChanged(bool visible); - - // This message sends a string being composed with an input method. - ImeSetComposition(mojo_base.mojom.String16 text, - array<ui.mojom.ImeTextSpan> ime_text_spans, - gfx.mojom.Range range, int32 start, int32 end); - - // This message deletes the current composition, inserts specified text, and - // moves the cursor. - ImeCommitText(mojo_base.mojom.String16 text, - array<ui.mojom.ImeTextSpan> ime_text_spans, - gfx.mojom.Range range, int32 relative_cursor_position) => (); - - // This message inserts the ongoing composition. - ImeFinishComposingText(bool keep_selection); - - // Request from browser to update text input state. - RequestTextInputStateUpdate(); - - // Request from browser to update the cursor and composition information which - // will be sent through ImeCompositionRangeChanged. Setting - // |immediate_request| to true will lead to an immediate update. If - // |monitor_updates| is set to true then changes to text selection or regular - // updates in each compositor frame (when there is a change in composition - // info) will lead to updates being sent to the browser. - RequestCompositionUpdates(bool immediate_request, bool monitor_request); - - // Sends an input event to the render widget. The browser should use this - // API if it wants to know about the result of the rendering handling - // the event. The callback may be delayed based on the event running on - // the main thread so DispatchNonBlockingEvent is always preferred if - // you don't require notification. - DispatchEvent(Event event) - => (blink.mojom.InputEventResultSource source, - ui.mojom.LatencyInfo updated_latency, - blink.mojom.InputEventResultState state, - blink.mojom.DidOverscrollParams? overscroll, - blink.mojom.TouchActionOptional? touch_action); - - // Sends a non-blocking input event to the render widget. The behaviour - // of this API is the same as DispatchEvent just that there is no callback - // after the event is processed. - DispatchNonBlockingEvent(Event event); - - // Forces input to be flushed and resolves the callback only once the input - // has been fully processed, meaning its effects are visible to the full - // system. In practice, this will force a redraw and wait until the new - // CompositorFrame (containing all changes caused by prior input) has been - // displayed. - WaitForInputProcessed() => (); - - // Attach the synchronous compositor interface. This method only - // should be called for Android WebView. - AttachSynchronousCompositor( - pending_remote<SynchronousCompositorControlHost> control_host, - pending_associated_remote<SynchronousCompositorHost> host, - pending_associated_receiver<SynchronousCompositor> compositor_request); -}; - -// This interface provides the input actions associated with the RenderFrame. -// Other input actions may also be dispatched via the WidgetInputHandler -// interface. If frame input actions are dispatched the WidgetInputHandler -// should be fetched via the associated interface request so that input calls -// remain in order. See https://goo.gl/x4ee8A for more details. -interface FrameInputHandler { - // Sets the text composition to be between the given start and end offsets in - // the currently focused editable field. - SetCompositionFromExistingText( - int32 start, int32 end, array<ui.mojom.ImeTextSpan> ime_text_spans); - - // Deletes the current selection plus the specified number of characters - // before and after the selection or caret. - ExtendSelectionAndDelete(int32 before, int32 after); - - // Deletes text before and after the current cursor position, excluding the - // selection. The lengths are supplied in Java chars (UTF-16 Code Unit), - // not in code points or in glyphs. - DeleteSurroundingText(int32 before, int32 after); - - // Deletes text before and after the current cursor position, excluding the - // selection. The lengths are supplied in code points, not in Java chars - // (UTF-16 Code Unit) or in glyphs. Does nothing if there are one or more - // invalid surrogate pairs in the requested range - DeleteSurroundingTextInCodePoints(int32 before, int32 after); - - // Selects between the given start and end offsets in the currently focused - // editable field. - SetEditableSelectionOffsets(int32 start, int32 end); - - // Message payload is the name/value of a WebCore edit command to execute. - ExecuteEditCommand(string command, mojo_base.mojom.String16? value); - - // These messages are typically generated from context menus and request the - // renderer to apply the specified operation to the current selection. - Undo(); - Redo(); - Cut(); - Copy(); - CopyToFindPboard(); - Paste(); - PasteAndMatchStyle(); - Delete(); - SelectAll(); - CollapseSelection(); - - // Replaces the selected region or a word around the cursor with the - // specified string. - Replace(mojo_base.mojom.String16 word); - - // Replaces the misspelling in the selected region with the specified string. - ReplaceMisspelling(mojo_base.mojom.String16 word); - - // Requests the renderer to select the region between two points. - // Expects a SelectRange_ACK message when finished. - SelectRange(gfx.mojom.Point base, gfx.mojom.Point extent); - - // Sent by the browser to ask the renderer to adjust the selection start and - // end points by the given amounts. A negative amount moves the selection - // towards the beginning of the document, a positive amount moves the - // selection towards the end of the document. Will send show selection menu - // event when needed. - AdjustSelectionByCharacterOffset( - int32 start, int32 end, blink.mojom.SelectionMenuBehavior behavior); - - // Requests the renderer to select word around caret. - // Expects ack with new selection information when finished. |start_adjust| - // and |end_adjust| are the start and end offset difference between the - // current selection and the previous selection (which is a caret). - [EnableIf=is_android] - SelectWordAroundCaret() - => (bool did_select, int32 start_adjust, int32 end_adjust); - - // Requests the renderer to move the selection extent point to a new position. - // Expects a MoveRangeSelectionExtent_ACK message when finished. - MoveRangeSelectionExtent(gfx.mojom.Point extent); - - // Tells the renderer to scroll the currently focused node into rect only if - // the currently focused node is a Text node (textfield, text area or content - // editable divs). - ScrollFocusedEditableNodeIntoRect(gfx.mojom.Rect rect); - - // Requests the renderer to move the caret selection toward the point. - MoveCaret(gfx.mojom.Point point); - - // Return an associated WidgetInputHandler interface so that input - // messages to the widget associated with this frame can be sent - // serially. - GetWidgetInputHandler( - pending_associated_receiver<WidgetInputHandler> interface_request, - pending_remote<WidgetInputHandlerHost> host); -}; diff --git a/chromium/content/common/input/synchronous_compositor.mojom b/chromium/content/common/input/synchronous_compositor.mojom deleted file mode 100644 index 7af71ab1812..00000000000 --- a/chromium/content/common/input/synchronous_compositor.mojom +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module content.mojom; - -import "mojo/public/mojom/base/shared_memory.mojom"; -import "mojo/public/mojom/base/time.mojom"; -import "services/viz/public/mojom/compositing/begin_frame_args.mojom"; -import "services/viz/public/mojom/compositing/compositor_frame.mojom"; -import "services/viz/public/mojom/compositing/compositor_frame_metadata.mojom"; -import "services/viz/public/mojom/compositing/frame_timing_details.mojom"; -import "services/viz/public/mojom/compositing/returned_resource.mojom"; -import "services/viz/public/mojom/hit_test/hit_test_region_list.mojom"; -import "ui/gfx/geometry/mojom/geometry.mojom"; -import "ui/gfx/mojom/transform.mojom"; - -struct SyncCompositorDemandDrawHwParams { - gfx.mojom.Size viewport_size; - gfx.mojom.Rect viewport_rect_for_tile_priority; - gfx.mojom.Transform transform_for_tile_priority; -}; - -struct SyncCompositorDemandDrawSwParams { - gfx.mojom.Size size; - gfx.mojom.Rect clip; - gfx.mojom.Transform transform; -}; - -struct SyncCompositorCommonRendererParams { - uint32 version = 0; - gfx.mojom.ScrollOffset total_scroll_offset; - gfx.mojom.ScrollOffset max_scroll_offset; - gfx.mojom.SizeF scrollable_size; - float page_scale_factor = 0; - float min_page_scale_factor = 0; - float max_page_scale_factor = 0; - uint32 need_invalidate_count = 0; - bool invalidate_needs_draw = true; - uint32 did_activate_pending_tree_count = 0; -}; - -// The SynchronousCompositor is an interface that is used by Android Webview -// which must control the compositor synchronously. It does this so that -// java UI is drawn in lock step with content renderer by the webview. -// The SynchronousCompositor is an associated interface with WidgetInputHandler -// because input must be delivered in order with the compositing events. -interface SynchronousCompositor { - // Hardware draw asynchronously, ReturnFrame will return the result on - // the associated SynchronousCompositorControlHost. - DemandDrawHwAsync(SyncCompositorDemandDrawHwParams draw_params); - - // Synchronously hardware draws. - [Sync] - DemandDrawHw(SyncCompositorDemandDrawHwParams draw_params) => - (SyncCompositorCommonRendererParams result, - uint32 layer_tree_frame_sink_id, - uint32 metadata_version, - viz.mojom.CompositorFrame? frame, - viz.mojom.HitTestRegionList? hit_test_region_list); - - // Synchronously sets the shared memory used for resourceless software - // drawing. This mode just has the renderer send over a single bitmap of the - // final frame, rather than sending over individual tiles (ie. resources) - // that are then composited by the browser. - [Sync] - SetSharedMemory(mojo_base.mojom.WritableSharedMemoryRegion shm_region) => - (bool success, SyncCompositorCommonRendererParams result); - - // Synchronously does a software based draw. - [Sync] DemandDrawSw(SyncCompositorDemandDrawSwParams draw_params) => - (SyncCompositorCommonRendererParams result, - uint32 metadata_version, - viz.mojom.CompositorFrameMetadata? meta_data); - - // Instead of drawing, allow the compositor to finish the frame and update - // tiles if needed. - WillSkipDraw(); - - // Zero out the shared memory. This is necessary since most of the time, - // viewport size doesn't change between draws, it's cheaper to zero out - // and reuse the shared memory, instead of allocating and mapping a new - // one each frame. - ZeroSharedMemory(); - - // Synchronously zoom by adjusting the page scale factor by delta around - // the anchor point. - [Sync] ZoomBy(float delta, gfx.mojom.Point anchor) => - (SyncCompositorCommonRendererParams result); - - // Adjust the memory policy of the compositor. Explicitly how much the - // compositor can use without changing visibility. ie. The limit on - // amount of memory used for caching tiles. - SetMemoryPolicy(uint32 bytes_limit); - - // Attempt to reclaim resources. - ReclaimResources(uint32 layer_tree_frame_sink_id, - array<viz.mojom.ReturnedResource> resources); - - // Adjust the scroll to the given offset. - SetScroll(gfx.mojom.ScrollOffset offset); - - // BeginFrame, update will be pushed via SynchronousCompositorControlHost - // BeginFrameResponse. - // |timing_details| is a map from frame token to FrameTimingDetails. - // Frame token is an incrementing id generated by untrusted viz client - // (renderer) and sent to viz service (browser) in a frame (see - // CompositorFrameMetadata). FrameTimingDetails contains info of viz server - // displaying frames, such as time of display. The index of the map is the - // frame token of the previously submitted frame that has been displayed. - // Note that the viz server might choose to skip display some of the - // previously submitted frames; however, feedback about all previously - // submitted frames will be sent back once a new frame is displayed. - BeginFrame(viz.mojom.BeginFrameArgs args, - map<uint32, viz.mojom.FrameTimingDetails> timing_details); - - // Indicates BeginFrame messages are paused. - SetBeginFrameSourcePaused(bool paused); -}; - -// Interface that runs on the UI thread of the browser. To be used -// for responses to most messages. -interface SynchronousCompositorHost { - // Indicates the layer tree was created. - LayerTreeFrameSinkCreated(); - - // Notification of new compositor information. - UpdateState(SyncCompositorCommonRendererParams params); - - // Notifies the that a begin frame is needed or not. - SetNeedsBeginFrames(bool needs_begin_frames); -}; - -// Interface that runs on the IO thread of the browser. To be used for responses -// to messages that need to wait for the response to be available before -// execution continues. Typically the browser UI thread will dispatch some -// messages asynchronously via the SynchronousCompositor interface but then -// reach a point at which a response must be available. For example the -// BeginFrame is sent to all attached WebViews but before the Android VSync -// execution flow (from java) returns the responses from BeginFrames must be -// received. -interface SynchronousCompositorControlHost { - // Response from DrawHwAsync. - ReturnFrame(uint32 layer_tree_frame_sink_id, - uint32 metadata_version, - viz.mojom.CompositorFrame? frame, - viz.mojom.HitTestRegionList? hit_test_region_list); - - // Response from BeginFrame. - BeginFrameResponse(SyncCompositorCommonRendererParams params); -}; diff --git a/chromium/content/common/input/synthetic_pointer_action_params.h b/chromium/content/common/input/synthetic_pointer_action_params.h index 87586800850..936c80e1815 100644 --- a/chromium/content/common/input/synthetic_pointer_action_params.h +++ b/chromium/content/common/input/synthetic_pointer_action_params.h @@ -5,11 +5,11 @@ #ifndef CONTENT_COMMON_INPUT_SYNTHETIC_POINTER_ACTION_PARAMS_H_ #define CONTENT_COMMON_INPUT_SYNTHETIC_POINTER_ACTION_PARAMS_H_ -#include "base/logging.h" +#include "base/check_op.h" #include "content/common/content_export.h" #include "content/common/content_param_traits_macros.h" #include "content/common/input/synthetic_gesture_params.h" -#include "content/common/input/synthetic_web_input_event_builders.h" +#include "third_party/blink/public/common/input/web_mouse_event.h" #include "third_party/blink/public/common/input/web_touch_event.h" #include "ui/gfx/geometry/point_f.h" diff --git a/chromium/content/common/input/synthetic_web_input_event_builders.cc b/chromium/content/common/input/synthetic_web_input_event_builders.cc deleted file mode 100644 index 785640f90b7..00000000000 --- a/chromium/content/common/input/synthetic_web_input_event_builders.cc +++ /dev/null @@ -1,282 +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 "content/common/input/synthetic_web_input_event_builders.h" - -#include "base/check_op.h" -#include "content/common/input/web_mouse_wheel_event_traits.h" -#include "content/common/input/web_touch_event_traits.h" -#include "ui/events/base_event_utils.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" - -namespace content { - -using blink::WebInputEvent; -using blink::WebKeyboardEvent; -using blink::WebGestureEvent; -using blink::WebMouseEvent; -using blink::WebMouseWheelEvent; -using blink::WebTouchEvent; -using blink::WebTouchPoint; - -WebMouseEvent SyntheticWebMouseEventBuilder::Build( - blink::WebInputEvent::Type type) { - return WebMouseEvent(type, WebInputEvent::kNoModifiers, - ui::EventTimeForNow()); -} - -WebMouseEvent SyntheticWebMouseEventBuilder::Build( - blink::WebInputEvent::Type type, - float window_x, - float window_y, - int modifiers, - blink::WebPointerProperties::PointerType pointer_type) { - DCHECK(WebInputEvent::IsMouseEventType(type)); - WebMouseEvent result(type, modifiers, ui::EventTimeForNow()); - result.SetPositionInWidget(window_x, window_y); - result.SetPositionInScreen(window_x, window_y); - result.SetModifiers(modifiers); - result.pointer_type = pointer_type; - result.id = ui::kPointerIdMouse; - return result; -} - -WebMouseWheelEvent SyntheticWebMouseWheelEventBuilder::Build( - WebMouseWheelEvent::Phase phase) { - WebMouseWheelEvent result(WebInputEvent::Type::kMouseWheel, - WebInputEvent::kNoModifiers, ui::EventTimeForNow()); - result.phase = phase; - result.event_action = WebMouseWheelEventTraits::GetEventAction(result); - return result; -} - -WebMouseWheelEvent SyntheticWebMouseWheelEventBuilder::Build( - float x, - float y, - float dx, - float dy, - int modifiers, - ui::ScrollGranularity delta_units) { - return Build(x, y, 0, 0, dx, dy, modifiers, delta_units); -} - -WebMouseWheelEvent SyntheticWebMouseWheelEventBuilder::Build( - float x, - float y, - float global_x, - float global_y, - float dx, - float dy, - int modifiers, - ui::ScrollGranularity delta_units) { - WebMouseWheelEvent result(WebInputEvent::Type::kMouseWheel, modifiers, - ui::EventTimeForNow()); - result.SetPositionInScreen(global_x, global_y); - result.SetPositionInWidget(x, y); - result.delta_units = delta_units; - result.delta_x = dx; - result.delta_y = dy; - if (dx) - result.wheel_ticks_x = dx > 0.0f ? 1.0f : -1.0f; - if (dy) - result.wheel_ticks_y = dy > 0.0f ? 1.0f : -1.0f; - - result.event_action = WebMouseWheelEventTraits::GetEventAction(result); - return result; -} - -WebKeyboardEvent SyntheticWebKeyboardEventBuilder::Build( - WebInputEvent::Type type) { - DCHECK(WebInputEvent::IsKeyboardEventType(type)); - WebKeyboardEvent result(type, WebInputEvent::kNoModifiers, - ui::EventTimeForNow()); - result.windows_key_code = ui::VKEY_L; // non-null made up value. - return result; -} - -WebGestureEvent SyntheticWebGestureEventBuilder::Build( - WebInputEvent::Type type, - blink::WebGestureDevice source_device, - int modifiers) { - DCHECK(WebInputEvent::IsGestureEventType(type)); - WebGestureEvent result(type, modifiers, ui::EventTimeForNow(), source_device); - if (type == WebInputEvent::Type::kGestureTap || - type == WebInputEvent::Type::kGestureTapUnconfirmed || - type == WebInputEvent::Type::kGestureDoubleTap) { - result.data.tap.tap_count = 1; - result.data.tap.width = 10; - result.data.tap.height = 10; - } - - result.SetNeedsWheelEvent(result.IsTouchpadZoomEvent()); - - return result; -} - -WebGestureEvent SyntheticWebGestureEventBuilder::BuildScrollBegin( - float dx_hint, - float dy_hint, - blink::WebGestureDevice source_device, - int pointer_count) { - WebGestureEvent result = - Build(WebInputEvent::Type::kGestureScrollBegin, source_device); - result.data.scroll_begin.delta_x_hint = dx_hint; - result.data.scroll_begin.delta_y_hint = dy_hint; - result.data.scroll_begin.pointer_count = pointer_count; - return result; -} - -WebGestureEvent SyntheticWebGestureEventBuilder::BuildScrollUpdate( - float dx, - float dy, - int modifiers, - blink::WebGestureDevice source_device) { - WebGestureEvent result = Build(WebInputEvent::Type::kGestureScrollUpdate, - source_device, modifiers); - result.data.scroll_update.delta_x = dx; - result.data.scroll_update.delta_y = dy; - return result; -} - -WebGestureEvent SyntheticWebGestureEventBuilder::BuildPinchUpdate( - float scale, - float anchor_x, - float anchor_y, - int modifiers, - blink::WebGestureDevice source_device) { - WebGestureEvent result = - Build(WebInputEvent::Type::kGesturePinchUpdate, source_device, modifiers); - result.data.pinch_update.scale = scale; - result.SetPositionInWidget(gfx::PointF(anchor_x, anchor_y)); - result.SetPositionInScreen(gfx::PointF(anchor_x, anchor_y)); - return result; -} - -WebGestureEvent SyntheticWebGestureEventBuilder::BuildFling( - float velocity_x, - float velocity_y, - blink::WebGestureDevice source_device) { - WebGestureEvent result = - Build(WebInputEvent::Type::kGestureFlingStart, source_device); - result.data.fling_start.velocity_x = velocity_x; - result.data.fling_start.velocity_y = velocity_y; - return result; -} - -SyntheticWebTouchEvent::SyntheticWebTouchEvent() : WebTouchEvent() { - unique_touch_event_id = ui::GetNextTouchEventId(); - SetTimestamp(ui::EventTimeForNow()); - pointer_id_ = 0; -} - -void SyntheticWebTouchEvent::ResetPoints() { - int activePointCount = 0; - unsigned count = 0; - for (unsigned int i = 0; i < kTouchesLengthCap; ++i) { - switch (touches[i].state) { - case WebTouchPoint::State::kStatePressed: - case WebTouchPoint::State::kStateMoved: - case WebTouchPoint::State::kStateStationary: - touches[i].state = WebTouchPoint::State::kStateStationary; - ++activePointCount; - ++count; - break; - case WebTouchPoint::State::kStateReleased: - case WebTouchPoint::State::kStateCancelled: - touches[i] = WebTouchPoint(); - ++count; - break; - case WebTouchPoint::State::kStateUndefined: - break; - } - if (count >= touches_length) - break; - } - touches_length = activePointCount; - type_ = WebInputEvent::Type::kUndefined; - moved_beyond_slop_region = false; - unique_touch_event_id = ui::GetNextTouchEventId(); -} - -int SyntheticWebTouchEvent::PressPoint(float x, - float y, - float radius_x, - float radius_y, - float rotation_angle, - float force) { - int index = FirstFreeIndex(); - if (index == -1) - return -1; - WebTouchPoint& point = touches[index]; - point.id = pointer_id_++; - point.SetPositionInWidget(x, y); - point.SetPositionInScreen(x, y); - point.state = WebTouchPoint::State::kStatePressed; - point.radius_x = radius_x; - point.radius_y = radius_y; - point.rotation_angle = rotation_angle; - point.force = force; - point.tilt_x = point.tilt_y = 0; - point.pointer_type = blink::WebPointerProperties::PointerType::kTouch; - ++touches_length; - WebTouchEventTraits::ResetType(WebInputEvent::Type::kTouchStart, TimeStamp(), - this); - return index; -} - -void SyntheticWebTouchEvent::MovePoint(int index, - float x, - float y, - float radius_x, - float radius_y, - float rotation_angle, - float force) { - CHECK_GE(index, 0); - CHECK_LT(index, kTouchesLengthCap); - // Always set this bit to avoid otherwise unexpected touchmove suppression. - // The caller can opt-out explicitly, if necessary. - moved_beyond_slop_region = true; - WebTouchPoint& point = touches[index]; - point.SetPositionInWidget(x, y); - point.SetPositionInScreen(x, y); - point.state = WebTouchPoint::State::kStateMoved; - point.radius_x = radius_x; - point.radius_y = radius_y; - point.rotation_angle = rotation_angle; - point.force = force; - WebTouchEventTraits::ResetType(WebInputEvent::Type::kTouchMove, TimeStamp(), - this); -} - -void SyntheticWebTouchEvent::ReleasePoint(int index) { - CHECK_GE(index, 0); - CHECK_LT(index, kTouchesLengthCap); - touches[index].state = WebTouchPoint::State::kStateReleased; - touches[index].force = 0.f; - WebTouchEventTraits::ResetType(WebInputEvent::Type::kTouchEnd, TimeStamp(), - this); -} - -void SyntheticWebTouchEvent::CancelPoint(int index) { - CHECK_GE(index, 0); - CHECK_LT(index, kTouchesLengthCap); - touches[index].state = WebTouchPoint::State::kStateCancelled; - WebTouchEventTraits::ResetType(WebInputEvent::Type::kTouchCancel, TimeStamp(), - this); -} - -void SyntheticWebTouchEvent::SetTimestamp(base::TimeTicks timestamp) { - SetTimeStamp(timestamp); -} - -int SyntheticWebTouchEvent::FirstFreeIndex() { - for (size_t i = 0; i < kTouchesLengthCap; ++i) { - if (touches[i].state == WebTouchPoint::State::kStateUndefined) - return i; - } - return -1; -} - -} // namespace content diff --git a/chromium/content/common/input/synthetic_web_input_event_builders.h b/chromium/content/common/input/synthetic_web_input_event_builders.h deleted file mode 100644 index 42e46d3f4b2..00000000000 --- a/chromium/content/common/input/synthetic_web_input_event_builders.h +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_COMMON_INPUT_SYNTHETIC_WEB_INPUT_EVENT_BUILDERS_H_ -#define CONTENT_COMMON_INPUT_SYNTHETIC_WEB_INPUT_EVENT_BUILDERS_H_ - -#include "base/time/time.h" -#include "content/common/content_export.h" -#include "third_party/blink/public/common/input/web_gesture_event.h" -#include "third_party/blink/public/common/input/web_input_event.h" -#include "third_party/blink/public/common/input/web_keyboard_event.h" -#include "third_party/blink/public/common/input/web_mouse_wheel_event.h" -#include "third_party/blink/public/common/input/web_touch_event.h" -#include "ui/events/types/scroll_types.h" - -// Provides sensible creation of default WebInputEvents for testing purposes. - -namespace content { - -class CONTENT_EXPORT SyntheticWebMouseEventBuilder { - public: - static blink::WebMouseEvent Build(blink::WebInputEvent::Type type); - static blink::WebMouseEvent Build( - blink::WebInputEvent::Type type, - float window_x, - float window_y, - int modifiers, - blink::WebPointerProperties::PointerType pointer_type = - blink::WebPointerProperties::PointerType::kMouse); -}; - -class CONTENT_EXPORT SyntheticWebMouseWheelEventBuilder { - public: - static blink::WebMouseWheelEvent Build( - blink::WebMouseWheelEvent::Phase phase); - static blink::WebMouseWheelEvent Build(float x, - float y, - float dx, - float dy, - int modifiers, - ui::ScrollGranularity delta_units); - static blink::WebMouseWheelEvent Build(float x, - float y, - float global_x, - float global_y, - float dx, - float dy, - int modifiers, - ui::ScrollGranularity delta_units); -}; - -class CONTENT_EXPORT SyntheticWebKeyboardEventBuilder { - public: - static blink::WebKeyboardEvent Build(blink::WebInputEvent::Type type); -}; - -class CONTENT_EXPORT SyntheticWebGestureEventBuilder { - public: - static blink::WebGestureEvent Build(blink::WebInputEvent::Type type, - blink::WebGestureDevice source_device, - int modifiers = 0); - static blink::WebGestureEvent BuildScrollBegin( - float dx_hint, - float dy_hint, - blink::WebGestureDevice source_device, - int pointer_count = 1); - static blink::WebGestureEvent BuildScrollUpdate( - float dx, - float dy, - int modifiers, - blink::WebGestureDevice source_device); - static blink::WebGestureEvent BuildPinchUpdate( - float scale, - float anchor_x, - float anchor_y, - int modifiers, - blink::WebGestureDevice source_device); - static blink::WebGestureEvent BuildFling( - float velocity_x, - float velocity_y, - blink::WebGestureDevice source_device); -}; - -class CONTENT_EXPORT SyntheticWebTouchEvent : public blink::WebTouchEvent { - public: - SyntheticWebTouchEvent(); - - // Mark all the points as stationary, and remove any released points. - void ResetPoints(); - - // Adds an additional point to the touch list, returning the point's index. - int PressPoint(float x, - float y, - float radius_x = 20.f, - float radius_y = 20.f, - float rotation_angle = 0.f, - float force = 1.f); - void MovePoint(int index, - float x, - float y, - float radius_x = 20.f, - float radius_y = 20.f, - float rotation_angle = 0.f, - float force = 1.f); - void ReleasePoint(int index); - void CancelPoint(int index); - - void SetTimestamp(base::TimeTicks timestamp); - - int FirstFreeIndex(); - - private: - // A pointer id of each touch pointer. Every time when a pointer is pressed - // the screen, it will be assigned to a new pointer id. - unsigned pointer_id_; -}; - -} // namespace content - -#endif // CONTENT_COMMON_INPUT_SYNTHETIC_WEB_INPUT_EVENT_BUILDERS_H_ diff --git a/chromium/content/common/input/synthetic_web_input_event_builders_unittest.cc b/chromium/content/common/input/synthetic_web_input_event_builders_unittest.cc deleted file mode 100644 index 49a034c65e1..00000000000 --- a/chromium/content/common/input/synthetic_web_input_event_builders_unittest.cc +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2018 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 "content/common/input/synthetic_web_input_event_builders.h" -#include "content/common/input/web_touch_event_traits.h" -#include "testing/gtest/include/gtest/gtest.h" - -using blink::WebInputEvent; -using blink::WebTouchEvent; -using blink::WebTouchPoint; - -namespace content { - -TEST(SyntheticWebInputEventBuilders, BuildWebTouchEvent) { - SyntheticWebTouchEvent event; - - event.PressPoint(1, 2); - EXPECT_EQ(1U, event.touches_length); - EXPECT_EQ(0, event.touches[0].id); - EXPECT_EQ(WebTouchPoint::State::kStatePressed, event.touches[0].state); - EXPECT_EQ(gfx::PointF(1, 2), event.touches[0].PositionInWidget()); - event.ResetPoints(); - - event.PressPoint(3, 4); - EXPECT_EQ(2U, event.touches_length); - EXPECT_EQ(1, event.touches[1].id); - EXPECT_EQ(WebTouchPoint::State::kStatePressed, event.touches[1].state); - EXPECT_EQ(gfx::PointF(3, 4), event.touches[1].PositionInWidget()); - event.ResetPoints(); - - event.MovePoint(1, 5, 6); - EXPECT_EQ(2U, event.touches_length); - EXPECT_EQ(1, event.touches[1].id); - EXPECT_EQ(WebTouchPoint::State::kStateMoved, event.touches[1].state); - EXPECT_EQ(gfx::PointF(5, 6), event.touches[1].PositionInWidget()); - event.ResetPoints(); - - event.ReleasePoint(0); - EXPECT_EQ(2U, event.touches_length); - EXPECT_EQ(0, event.touches[0].id); - EXPECT_EQ(WebTouchPoint::State::kStateReleased, event.touches[0].state); - event.ResetPoints(); - - event.MovePoint(1, 7, 8); - EXPECT_EQ(1U, event.touches_length); - EXPECT_EQ(1, event.touches[1].id); - EXPECT_EQ(WebTouchPoint::State::kStateMoved, event.touches[1].state); - EXPECT_EQ(gfx::PointF(7, 8), event.touches[1].PositionInWidget()); - EXPECT_EQ(WebTouchPoint::State::kStateUndefined, event.touches[0].state); - event.ResetPoints(); - - event.PressPoint(9, 10); - EXPECT_EQ(2U, event.touches_length); - EXPECT_EQ(2, event.touches[0].id); - EXPECT_EQ(WebTouchPoint::State::kStatePressed, event.touches[0].state); - EXPECT_EQ(gfx::PointF(9, 10), event.touches[0].PositionInWidget()); -} - -} // namespace content diff --git a/chromium/content/common/input/touch_event_stream_validator_unittest.cc b/chromium/content/common/input/touch_event_stream_validator_unittest.cc index d8ce67bd0b9..647aef72225 100644 --- a/chromium/content/common/input/touch_event_stream_validator_unittest.cc +++ b/chromium/content/common/input/touch_event_stream_validator_unittest.cc @@ -6,9 +6,9 @@ #include <stddef.h> -#include "content/common/input/synthetic_web_input_event_builders.h" #include "content/common/input/web_touch_event_traits.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/input/synthetic_web_input_event_builders.h" using blink::WebInputEvent; using blink::WebTouchEvent; @@ -18,7 +18,7 @@ namespace content { TEST(TouchEventStreamValidator, ValidTouchStream) { TouchEventStreamValidator validator; - SyntheticWebTouchEvent event; + blink::SyntheticWebTouchEvent event; std::string error_msg; event.PressPoint(0, 1); @@ -58,7 +58,7 @@ TEST(TouchEventStreamValidator, ValidTouchStream) { TEST(TouchEventStreamValidator, ResetOnNewTouchStream) { TouchEventStreamValidator validator; - SyntheticWebTouchEvent event; + blink::SyntheticWebTouchEvent event; std::string error_msg; event.PressPoint(0, 1); @@ -75,7 +75,7 @@ TEST(TouchEventStreamValidator, ResetOnNewTouchStream) { TEST(TouchEventStreamValidator, MissedTouchStart) { TouchEventStreamValidator validator; - SyntheticWebTouchEvent event; + blink::SyntheticWebTouchEvent event; std::string error_msg; event.PressPoint(0, 1); @@ -91,7 +91,7 @@ TEST(TouchEventStreamValidator, MissedTouchStart) { TEST(TouchEventStreamValidator, MissedTouchEnd) { TouchEventStreamValidator validator; - SyntheticWebTouchEvent event; + blink::SyntheticWebTouchEvent event; std::string error_msg; event.PressPoint(0, 1); @@ -152,7 +152,7 @@ TEST(TouchEventStreamValidator, InvalidPointStates) { WebTouchPoint::State::kStateCancelled, }; - SyntheticWebTouchEvent start; + blink::SyntheticWebTouchEvent start; start.PressPoint(0, 0); for (size_t i = 0; i < 4; ++i) { // Always start with a touchstart to reset the stream validation. diff --git a/chromium/content/common/input/web_mouse_wheel_event_traits.cc b/chromium/content/common/input/web_mouse_wheel_event_traits.cc deleted file mode 100644 index 73d1c4eb87a..00000000000 --- a/chromium/content/common/input/web_mouse_wheel_event_traits.cc +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2018 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 "content/common/input/web_mouse_wheel_event_traits.h" - -#include "third_party/blink/public/common/input/web_input_event.h" - -namespace content { - -using blink::WebInputEvent; - -// static -blink::WebMouseWheelEvent::EventAction WebMouseWheelEventTraits::GetEventAction( - const blink::WebMouseWheelEvent& event) { -#if defined(USE_AURA) - // Scroll events generated from the mouse wheel when the control key is held - // don't trigger scrolling. Instead, they may cause zooming. - if (event.delta_units != ui::ScrollGranularity::kScrollByPrecisePixel && - (event.GetModifiers() & WebInputEvent::kControlKey)) { - return blink::WebMouseWheelEvent::EventAction::kPageZoom; - } - - if (event.delta_x == 0 && (event.GetModifiers() & WebInputEvent::kShiftKey)) - return blink::WebMouseWheelEvent::EventAction::kScrollHorizontal; -#endif - if (event.rails_mode == WebInputEvent::kRailsModeHorizontal || - (event.delta_x != 0 && event.delta_y == 0)) { - return blink::WebMouseWheelEvent::EventAction::kScrollHorizontal; - } - - if (event.rails_mode == WebInputEvent::kRailsModeVertical || - (event.delta_x == 0 && event.delta_y != 0)) { - return blink::WebMouseWheelEvent::EventAction::kScrollVertical; - } - - return blink::WebMouseWheelEvent::EventAction::kScroll; -} - -} // namespace content diff --git a/chromium/content/common/input/web_mouse_wheel_event_traits.h b/chromium/content/common/input/web_mouse_wheel_event_traits.h deleted file mode 100644 index 45fe2a8e6ad..00000000000 --- a/chromium/content/common/input/web_mouse_wheel_event_traits.h +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2018 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 CONTENT_COMMON_INPUT_WEB_MOUSE_WHEEL_EVENT_TRAITS_H_ -#define CONTENT_COMMON_INPUT_WEB_MOUSE_WHEEL_EVENT_TRAITS_H_ - -#include "base/macros.h" -#include "content/common/content_export.h" -#include "third_party/blink/public/common/input/web_mouse_wheel_event.h" - -namespace content { - -// Utility class for performing operations on and with WebMouseWheelEvent. -class CONTENT_EXPORT WebMouseWheelEventTraits { - public: - // Returns the *platform specific* event action corresponding with the wheel - // event. - static blink::WebMouseWheelEvent::EventAction GetEventAction( - const blink::WebMouseWheelEvent& event); - - private: - DISALLOW_IMPLICIT_CONSTRUCTORS(WebMouseWheelEventTraits); -}; - -} // namespace content - -#endif // CONTENT_COMMON_INPUT_WEB_MOUSE_WHEEL_EVENT_TRAITS_H_ diff --git a/chromium/content/common/input_messages.h b/chromium/content/common/input_messages.h index 7f88de656cb..5d4704b2867 100644 --- a/chromium/content/common/input_messages.h +++ b/chromium/content/common/input_messages.h @@ -13,7 +13,6 @@ #include "cc/input/overscroll_behavior.h" #include "content/common/content_export.h" #include "content/common/content_param_traits.h" -#include "content/common/input/input_event.h" #include "content/common/input/input_event_dispatch_type.h" #include "content/common/input/synthetic_gesture_params.h" #include "content/common/input/synthetic_pinch_gesture_params.h" diff --git a/chromium/content/common/mac/OWNERS b/chromium/content/common/mac/OWNERS new file mode 100644 index 00000000000..a1660982293 --- /dev/null +++ b/chromium/content/common/mac/OWNERS @@ -0,0 +1,2 @@ +per-file *_type_converter*.*=set noparent +per-file *_type_converter*.*=file://ipc/SECURITY_OWNERS diff --git a/chromium/content/common/mac/attributed_string_coder.h b/chromium/content/common/mac/attributed_string_coder.h deleted file mode 100644 index 7100793b51d..00000000000 --- a/chromium/content/common/mac/attributed_string_coder.h +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright (c) 2012 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 CONTENT_COMMON_MAC_ATTRIBUTED_STRING_CODER_H_ -#define CONTENT_COMMON_MAC_ATTRIBUTED_STRING_CODER_H_ - -#include <set> - -#include "base/strings/string16.h" -#include "content/common/content_export.h" -#include "ipc/ipc_message_utils.h" -#include "ui/gfx/range/range.h" - -#if __OBJC__ -@class NSAttributedString; -@class NSDictionary; -#else -class NSAttributedString; -class NSDictionary; -#endif - -namespace base { -class Pickle; -class PickleIterator; -} - -namespace mac { - -// This class will serialize the font information of an NSAttributedString so -// that it can be sent over IPC. This class only stores the information of the -// NSFontAttributeName. The motive is that of security: using NSArchiver and -// friends to send objects from the renderer to the browser could lead to -// deserialization of arbitrary objects. This class restricts serialization to -// a specific object class and specific attributes of that object. -class CONTENT_EXPORT AttributedStringCoder { - public: - // A C++ IPC-friendly representation of the NSFontAttributeName attribute - // set. - class FontAttribute { - public: - FontAttribute(NSDictionary* ns_attributes, gfx::Range effective_range); - FontAttribute(const base::string16& font_name, - float font_point_size, - const gfx::Range& range); - FontAttribute(); - ~FontAttribute(); - - // Creates an autoreleased NSDictionary that can be attached to an - // NSAttributedString. - NSDictionary* ToAttributesDictionary() const; - - // Whether or not the attribute should be placed in the EncodedString. This - // can return false, e.g. if the Cocoa-based constructor can't find any - // information to encode. - bool ShouldEncode() const; - - // Accessors: - const base::string16& font_name() const { return font_name_; } - float font_point_size() const { return font_point_size_; } - const gfx::Range& effective_range() const { return effective_range_; } - - private: - base::string16 font_name_; - float font_point_size_; - gfx::Range effective_range_; - }; - - // A class that contains the pertinent information from an NSAttributedString, - // which can be serialized over IPC. - class EncodedString { - public: - explicit EncodedString(base::string16 string); - EncodedString(); - EncodedString(const EncodedString& other); - EncodedString& operator=(const EncodedString& other); - ~EncodedString(); - - // Accessors: - base::string16 string() const { return string_; } - const std::vector<FontAttribute>& attributes() const { - return attributes_; - } - std::vector<FontAttribute>* attributes() { return &attributes_; } - - private: - // The plain-text string. - base::string16 string_; - // The set of attributes that style |string_|. - std::vector<FontAttribute> attributes_; - }; - - // Takes an NSAttributedString, extracts the pertinent attributes, and returns - // an object that represents it. Caller owns the result. - static const EncodedString* Encode(NSAttributedString* str); - - // Returns an autoreleased NSAttributedString from an encoded representation. - static NSAttributedString* Decode(const EncodedString* str); - - private: - AttributedStringCoder(); -}; - -} // namespace mac - -// IPC ParamTraits specialization ////////////////////////////////////////////// - -namespace IPC { - -template <> -struct ParamTraits<mac::AttributedStringCoder::EncodedString> { - typedef mac::AttributedStringCoder::EncodedString param_type; - static void Write(base::Pickle* m, const param_type& p); - static bool Read(const base::Pickle* m, - base::PickleIterator* iter, - param_type* r); - static void Log(const param_type& p, std::string* l); -}; - -template <> -struct ParamTraits<mac::AttributedStringCoder::FontAttribute> { - typedef mac::AttributedStringCoder::FontAttribute param_type; - static void Write(base::Pickle* m, const param_type& p); - static bool Read(const base::Pickle* m, - base::PickleIterator* iter, - param_type* r); - static void Log(const param_type& p, std::string* l); -}; - -} // namespace IPC - -#endif // CONTENT_COMMON_MAC_ATTRIBUTED_STRING_CODER_H_ diff --git a/chromium/content/common/mac/attributed_string_coder.mm b/chromium/content/common/mac/attributed_string_coder.mm deleted file mode 100644 index 7cb5f404f2c..00000000000 --- a/chromium/content/common/mac/attributed_string_coder.mm +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright (c) 2012 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 "content/common/mac/attributed_string_coder.h" - -#include <AppKit/AppKit.h> - -#include "base/check.h" -#include "base/mac/scoped_nsobject.h" -#include "base/strings/sys_string_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "content/public/common/common_param_traits.h" -#include "ipc/ipc_message_utils.h" - -namespace mac { - -// static -const AttributedStringCoder::EncodedString* AttributedStringCoder::Encode( - NSAttributedString* str) { - // Create the return value. - EncodedString* encoded_string = - new EncodedString(base::SysNSStringToUTF16([str string])); - // Iterate over all the attributes in the string. - NSUInteger length = [str length]; - for (NSUInteger i = 0; i < length; ) { - NSRange effective_range; - NSDictionary* ns_attributes = [str attributesAtIndex:i - effectiveRange:&effective_range]; - // Convert the attributes to IPC-friendly types. - FontAttribute attrs(ns_attributes, gfx::Range(effective_range)); - // Only encode the attributes if the filtered set contains font information. - if (attrs.ShouldEncode()) { - encoded_string->attributes()->push_back(attrs); - } - // Advance the iterator to the position outside of the effective range. - i = NSMaxRange(effective_range); - } - return encoded_string; -} - -// static -NSAttributedString* AttributedStringCoder::Decode( - const AttributedStringCoder::EncodedString* str) { - // Create the return value. - NSString* plain_text = base::SysUTF16ToNSString(str->string()); - base::scoped_nsobject<NSMutableAttributedString> decoded_string( - [[NSMutableAttributedString alloc] initWithString:plain_text]); - // Iterate over all the encoded attributes, attaching each to the string. - const std::vector<FontAttribute> attributes = str->attributes(); - for (std::vector<FontAttribute>::const_iterator it = attributes.begin(); - it != attributes.end(); ++it) { - // Protect against ranges that are outside the range of the string. - const gfx::Range& range = it->effective_range(); - if (range.GetMin() > [plain_text length] || - range.GetMax() > [plain_text length]) { - continue; - } - [decoded_string addAttributes:it->ToAttributesDictionary() - range:range.ToNSRange()]; - } - return [decoded_string.release() autorelease]; -} - -// Data Types ////////////////////////////////////////////////////////////////// - -AttributedStringCoder::EncodedString::EncodedString(base::string16 string) - : string_(string) { -} - -AttributedStringCoder::EncodedString::EncodedString() - : string_() { -} - -AttributedStringCoder::EncodedString::EncodedString( - const EncodedString& other) = default; - -AttributedStringCoder::EncodedString& AttributedStringCoder::EncodedString:: -operator=(const EncodedString& other) = default; - -AttributedStringCoder::EncodedString::~EncodedString() { -} - -AttributedStringCoder::FontAttribute::FontAttribute(NSDictionary* dict, - gfx::Range effective_range) - : font_name_(), font_point_size_(0), effective_range_(effective_range) { - NSFont* font = [dict objectForKey:NSFontAttributeName]; - if (font) { - font_name_ = base::SysNSStringToUTF16([font fontName]); - font_point_size_ = [font pointSize]; - } -} - -AttributedStringCoder::FontAttribute::FontAttribute( - const base::string16& font_name, - float font_point_size, - const gfx::Range& range) - : font_name_(std::move(font_name)), - font_point_size_(font_point_size), - effective_range_(range) {} - -AttributedStringCoder::FontAttribute::FontAttribute() - : font_name_(), font_point_size_(0), effective_range_() {} - -AttributedStringCoder::FontAttribute::~FontAttribute() { -} - -NSDictionary* -AttributedStringCoder::FontAttribute::ToAttributesDictionary() const { - DCHECK(ShouldEncode()); - NSString* font_name_ns = base::SysUTF16ToNSString(font_name_); - NSFont* font = [NSFont fontWithName:font_name_ns size:font_point_size_]; - if (!font) - return [NSDictionary dictionary]; - return [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName]; -} - -bool AttributedStringCoder::FontAttribute::ShouldEncode() const { - return !font_name_.empty(); -} - -} // namespace mac - -// IPC ParamTraits specialization ////////////////////////////////////////////// - -namespace IPC { - -using mac::AttributedStringCoder; - -void ParamTraits<AttributedStringCoder::EncodedString>::Write( - base::Pickle* m, - const param_type& p) { - WriteParam(m, p.string()); - WriteParam(m, p.attributes()); -} - -bool ParamTraits<AttributedStringCoder::EncodedString>::Read( - const base::Pickle* m, - base::PickleIterator* iter, - param_type* p) { - bool success = true; - - base::string16 result; - success &= ReadParam(m, iter, &result); - *p = AttributedStringCoder::EncodedString(result); - - success &= ReadParam(m, iter, p->attributes()); - return success; -} - -void ParamTraits<AttributedStringCoder::EncodedString>::Log( - const param_type& p, std::string* l) { - l->append(base::UTF16ToUTF8(p.string())); -} - -void ParamTraits<AttributedStringCoder::FontAttribute>::Write( - base::Pickle* m, - const param_type& p) { - WriteParam(m, p.font_name()); - WriteParam(m, p.font_point_size()); - WriteParam(m, p.effective_range()); -} - -bool ParamTraits<AttributedStringCoder::FontAttribute>::Read( - const base::Pickle* m, - base::PickleIterator* iter, - param_type* p) { - bool success = true; - - base::string16 font_name; - success &= ReadParam(m, iter, &font_name); - - float font_point_size; - success &= ReadParam(m, iter, &font_point_size); - - gfx::Range range; - success &= ReadParam(m, iter, &range); - - if (success) { - *p = AttributedStringCoder::FontAttribute(std::move(font_name), - font_point_size, range); - } - return success; -} - -void ParamTraits<AttributedStringCoder::FontAttribute>::Log( - const param_type& p, std::string* l) { -} - -} // namespace IPC diff --git a/chromium/content/common/mac/attributed_string_type_converters.h b/chromium/content/common/mac/attributed_string_type_converters.h new file mode 100644 index 00000000000..1fa044d305f --- /dev/null +++ b/chromium/content/common/mac/attributed_string_type_converters.h @@ -0,0 +1,59 @@ +// Copyright (c) 2012 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 CONTENT_COMMON_MAC_ATTRIBUTED_STRING_TYPE_CONVERTERS_H_ +#define CONTENT_COMMON_MAC_ATTRIBUTED_STRING_TYPE_CONVERTERS_H_ + +#include "base/strings/string16.h" +#include "content/common/content_export.h" +#include "ipc/ipc_message_utils.h" +#include "ui/base/mojom/attributed_string.mojom.h" +#include "ui/gfx/range/range.h" + +#if __OBJC__ +@class NSAttributedString; +#else +class NSAttributedString; +#endif + +namespace base { +class Pickle; +class PickleIterator; +} + +namespace mojo { + +template <> +struct CONTENT_EXPORT + TypeConverter<NSAttributedString*, ui::mojom::AttributedStringPtr> { + static NSAttributedString* Convert( + const ui::mojom::AttributedStringPtr& mojo_attributed_string); +}; + +template <> +struct CONTENT_EXPORT + TypeConverter<ui::mojom::AttributedStringPtr, NSAttributedString*> { + static ui::mojom::AttributedStringPtr Convert( + const NSAttributedString* ns_attributed_string); +}; + +} // namespace mojo + +// IPC ParamTraits specialization ////////////////////////////////////////////// + +namespace IPC { + +template <> +struct ParamTraits<ui::mojom::FontAttributePtr> { + typedef ui::mojom::FontAttributePtr param_type; + static void Write(base::Pickle* m, const param_type& p); + static bool Read(const base::Pickle* m, + base::PickleIterator* iter, + param_type* r); + static void Log(const param_type& p, std::string* l); +}; + +} // namespace IPC + +#endif // CONTENT_COMMON_MAC_ATTRIBUTED_STRING_TYPE_CONVERTERS_H_ diff --git a/chromium/content/common/mac/attributed_string_type_converters.mm b/chromium/content/common/mac/attributed_string_type_converters.mm new file mode 100644 index 00000000000..eb67745731a --- /dev/null +++ b/chromium/content/common/mac/attributed_string_type_converters.mm @@ -0,0 +1,133 @@ +// Copyright (c) 2012 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 "content/common/mac/attributed_string_type_converters.h" + +#include <AppKit/AppKit.h> + +#include "base/check.h" +#include "base/mac/scoped_nsobject.h" +#include "base/strings/sys_string_conversions.h" +#include "base/strings/utf_string_conversions.h" +#include "content/public/common/common_param_traits.h" + +namespace mojo { + +namespace { + +NSDictionary* ToAttributesDictionary(base::string16 name, float font_size) { + DCHECK(!name.empty()); + NSString* font_name_ns = base::SysUTF16ToNSString(name); + NSFont* font = [NSFont fontWithName:font_name_ns size:font_size]; + if (!font) + return [NSDictionary dictionary]; + return [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName]; +} + +} // namespace + +NSAttributedString* +TypeConverter<NSAttributedString*, ui::mojom::AttributedStringPtr>::Convert( + const ui::mojom::AttributedStringPtr& mojo_attributed_string) { + // Create the return value. + NSString* plain_text = + base::SysUTF16ToNSString(mojo_attributed_string->string); + base::scoped_nsobject<NSMutableAttributedString> decoded_string( + [[NSMutableAttributedString alloc] initWithString:plain_text]); + // Iterate over all the encoded attributes, attaching each to the string. + const std::vector<ui::mojom::FontAttributePtr>& attributes = + mojo_attributed_string->attributes; + for (std::vector<ui::mojom::FontAttributePtr>::const_iterator it = + attributes.begin(); + it != attributes.end(); ++it) { + // Protect against ranges that are outside the range of the string. + const gfx::Range& range = it->get()->effective_range; + if (range.GetMin() > [plain_text length] || + range.GetMax() > [plain_text length]) { + continue; + } + [decoded_string + addAttributes:ToAttributesDictionary(it->get()->font_name, + it->get()->font_point_size) + range:range.ToNSRange()]; + } + return [decoded_string.release() autorelease]; +} + +ui::mojom::AttributedStringPtr +TypeConverter<ui::mojom::AttributedStringPtr, NSAttributedString*>::Convert( + const NSAttributedString* ns_attributed_string) { + // Create the return value. + ui::mojom::AttributedStringPtr attributed_string = + ui::mojom::AttributedString::New(); + attributed_string->string = + base::SysNSStringToUTF16([ns_attributed_string string]); + + // Iterate over all the attributes in the string. + NSUInteger length = [ns_attributed_string length]; + for (NSUInteger i = 0; i < length;) { + NSRange effective_range; + NSDictionary* ns_attributes = + [ns_attributed_string attributesAtIndex:i + effectiveRange:&effective_range]; + + NSFont* font = [ns_attributes objectForKey:NSFontAttributeName]; + base::string16 font_name; + float font_point_size; + // Only encode the attributes if the filtered set contains font information. + if (font) { + font_name = base::SysNSStringToUTF16([font fontName]); + font_point_size = [font pointSize]; + if (!font_name.empty()) { + // Convert the attributes. + ui::mojom::FontAttributePtr attrs = ui::mojom::FontAttribute::New( + font_name, font_point_size, gfx::Range(effective_range)); + attributed_string->attributes.push_back(std::move(attrs)); + } + } + // Advance the iterator to the position outside of the effective range. + i = NSMaxRange(effective_range); + } + return attributed_string; +} + +} // namespace mojo + +// IPC ParamTraits specialization ////////////////////////////////////////////// + +namespace IPC { + +using ui::mojom::FontAttributePtr; + +void ParamTraits<FontAttributePtr>::Write(base::Pickle* m, + const param_type& p) { + WriteParam(m, p->font_name); + WriteParam(m, p->font_point_size); + WriteParam(m, p->effective_range); +} + +bool ParamTraits<FontAttributePtr>::Read(const base::Pickle* m, + base::PickleIterator* iter, + param_type* p) { + bool success = true; + + base::string16 font_name; + success &= ReadParam(m, iter, &font_name); + + float font_point_size; + success &= ReadParam(m, iter, &font_point_size); + + gfx::Range range; + success &= ReadParam(m, iter, &range); + + if (success) { + *p = ui::mojom::FontAttribute::New(std::move(font_name), font_point_size, + range); + } + return success; +} + +void ParamTraits<FontAttributePtr>::Log(const param_type& p, std::string* l) {} + +} // namespace IPC diff --git a/chromium/content/common/mac/attributed_string_coder_unittest.mm b/chromium/content/common/mac/attributed_string_type_converters_unittest.mm index bc4991bb3fa..38485ff3834 100644 --- a/chromium/content/common/mac/attributed_string_coder_unittest.mm +++ b/chromium/content/common/mac/attributed_string_type_converters_unittest.mm @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import "content/common/mac/attributed_string_coder.h" +#import "content/common/mac/attributed_string_type_converters.h" #include <AppKit/AppKit.h> @@ -14,9 +14,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest_mac.h" -using mac::AttributedStringCoder; - -class AttributedStringCoderTest : public testing::Test { +class AttributedStringConverterTest : public testing::Test { public: NSMutableAttributedString* NewAttrString() { NSString* str = @"The quick brown fox jumped over the lazy dog."; @@ -28,29 +26,29 @@ class AttributedStringCoderTest : public testing::Test { return [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName]; } - NSAttributedString* EncodeAndDecode(NSAttributedString* str) { - std::unique_ptr<const AttributedStringCoder::EncodedString> encoded_str( - AttributedStringCoder::Encode(str)); - return AttributedStringCoder::Decode(encoded_str.get()); + NSAttributedString* ConvertAndRestore(NSAttributedString* str) { + ui::mojom::AttributedStringPtr attributed_str = + ui::mojom::AttributedString::From(str); + return attributed_str.To<NSAttributedString*>(); } }; -TEST_F(AttributedStringCoderTest, SimpleString) { +TEST_F(AttributedStringConverterTest, SimpleString) { base::scoped_nsobject<NSMutableAttributedString> attr_str(NewAttrString()); [attr_str addAttributes:FontAttribute(@"Helvetica", 12.5) range:NSMakeRange(0, [attr_str length])]; - NSAttributedString* decoded = EncodeAndDecode(attr_str.get()); - EXPECT_NSEQ(attr_str.get(), decoded); + NSAttributedString* ns_attributed_string = ConvertAndRestore(attr_str.get()); + EXPECT_NSEQ(attr_str.get(), ns_attributed_string); } -TEST_F(AttributedStringCoderTest, NoAttributes) { +TEST_F(AttributedStringConverterTest, NoAttributes) { base::scoped_nsobject<NSAttributedString> attr_str(NewAttrString()); - NSAttributedString* decoded = EncodeAndDecode(attr_str.get()); - EXPECT_NSEQ(attr_str.get(), decoded); + NSAttributedString* ns_attributed_string = ConvertAndRestore(attr_str.get()); + EXPECT_NSEQ(attr_str.get(), ns_attributed_string); } -TEST_F(AttributedStringCoderTest, StripColor) { +TEST_F(AttributedStringConverterTest, StripColor) { base::scoped_nsobject<NSMutableAttributedString> attr_str(NewAttrString()); const NSUInteger kStringLength = [attr_str length]; [attr_str addAttribute:NSFontAttributeName @@ -60,17 +58,18 @@ TEST_F(AttributedStringCoderTest, StripColor) { value:[NSColor redColor] range:NSMakeRange(0, kStringLength)]; - NSAttributedString* decoded = EncodeAndDecode(attr_str.get()); + NSAttributedString* ns_attributed_string = ConvertAndRestore(attr_str.get()); NSRange range; - NSDictionary* attrs = [decoded attributesAtIndex:0 effectiveRange:&range]; + NSDictionary* attrs = [ns_attributed_string attributesAtIndex:0 + effectiveRange:&range]; EXPECT_TRUE(NSEqualRanges(NSMakeRange(0, kStringLength), range)); EXPECT_NSEQ([NSFont systemFontOfSize:26], [attrs objectForKey:NSFontAttributeName]); EXPECT_FALSE([attrs objectForKey:NSForegroundColorAttributeName]); } -TEST_F(AttributedStringCoderTest, MultipleFonts) { +TEST_F(AttributedStringConverterTest, MultipleFonts) { base::scoped_nsobject<NSMutableAttributedString> attr_str(NewAttrString()); [attr_str setAttributes:FontAttribute(@"Courier", 12) range:NSMakeRange(0, 10)]; @@ -79,12 +78,12 @@ TEST_F(AttributedStringCoderTest, MultipleFonts) { [attr_str addAttributes:FontAttribute(@"Helvetica", 14) range:NSMakeRange(15, 5)]; - NSAttributedString* decoded = EncodeAndDecode(attr_str); + NSAttributedString* ns_attributed_string = ConvertAndRestore(attr_str); - EXPECT_NSEQ(attr_str.get(), decoded); + EXPECT_NSEQ(attr_str.get(), ns_attributed_string); } -TEST_F(AttributedStringCoderTest, NoPertinentAttributes) { +TEST_F(AttributedStringConverterTest, NoPertinentAttributes) { base::scoped_nsobject<NSMutableAttributedString> attr_str(NewAttrString()); [attr_str addAttribute:NSForegroundColorAttributeName value:[NSColor blueColor] @@ -96,40 +95,43 @@ TEST_F(AttributedStringCoderTest, NoPertinentAttributes) { value:[NSNumber numberWithFloat:2.6] range:NSMakeRange(11, 3)]; - NSAttributedString* decoded = EncodeAndDecode(attr_str.get()); + NSAttributedString* ns_attributed_string = ConvertAndRestore(attr_str.get()); base::scoped_nsobject<NSAttributedString> expected(NewAttrString()); - EXPECT_NSEQ(expected.get(), decoded); + EXPECT_NSEQ(expected.get(), ns_attributed_string); } -TEST_F(AttributedStringCoderTest, NilString) { - NSAttributedString* decoded = EncodeAndDecode(nil); - EXPECT_TRUE(decoded); - EXPECT_EQ(0U, [decoded length]); +TEST_F(AttributedStringConverterTest, NilString) { + NSAttributedString* ns_attributed_string = ConvertAndRestore(nil); + EXPECT_TRUE(ns_attributed_string); + EXPECT_EQ(0U, [ns_attributed_string length]); } -TEST_F(AttributedStringCoderTest, OutOfRange) { +TEST_F(AttributedStringConverterTest, OutOfRange) { NSFont* system_font = [NSFont systemFontOfSize:10]; base::string16 font_name = base::SysNSStringToUTF16([system_font fontName]); - AttributedStringCoder::EncodedString encoded( - base::ASCIIToUTF16("Hello World")); - encoded.attributes()->push_back( - AttributedStringCoder::FontAttribute(font_name, 12, gfx::Range(0, 5))); - encoded.attributes()->push_back( - AttributedStringCoder::FontAttribute(font_name, 14, gfx::Range(5, 100))); - encoded.attributes()->push_back( - AttributedStringCoder::FontAttribute(font_name, 16, gfx::Range(100, 5))); - - NSAttributedString* decoded = AttributedStringCoder::Decode(&encoded); - EXPECT_TRUE(decoded); + ui::mojom::AttributedStringPtr attributed_string = + ui::mojom::AttributedString::New(); + attributed_string->string = base::ASCIIToUTF16("Hello World"); + attributed_string->attributes.push_back( + ui::mojom::FontAttribute::New(font_name, 12, gfx::Range(0, 5))); + attributed_string->attributes.push_back( + ui::mojom::FontAttribute::New(font_name, 14, gfx::Range(5, 100))); + attributed_string->attributes.push_back( + ui::mojom::FontAttribute::New(font_name, 16, gfx::Range(100, 5))); + + NSAttributedString* ns_attributed_string = + attributed_string.To<NSAttributedString*>(); + EXPECT_TRUE(ns_attributed_string); NSRange range; - NSDictionary* attrs = [decoded attributesAtIndex:0 effectiveRange:&range]; + NSDictionary* attrs = [ns_attributed_string attributesAtIndex:0 + effectiveRange:&range]; EXPECT_NSEQ([NSFont systemFontOfSize:12], [attrs objectForKey:NSFontAttributeName]); EXPECT_TRUE(NSEqualRanges(range, NSMakeRange(0, 5))); - attrs = [decoded attributesAtIndex:5 effectiveRange:&range]; + attrs = [ns_attributed_string attributesAtIndex:5 effectiveRange:&range]; EXPECT_FALSE([attrs objectForKey:NSFontAttributeName]); EXPECT_EQ(0U, [attrs count]); } diff --git a/chromium/content/common/mac/font_loader.h b/chromium/content/common/mac/font_loader.h index c3f9d96c895..1ca8887cc67 100644 --- a/chromium/content/common/mac/font_loader.h +++ b/chromium/content/common/mac/font_loader.h @@ -12,6 +12,7 @@ #include "base/callback_forward.h" #include "base/mac/scoped_cftyperef.h" +#include "base/strings/string16.h" #include "content/common/content_export.h" #include "mojo/public/cpp/system/buffer.h" diff --git a/chromium/content/common/mac/font_loader.mm b/chromium/content/common/mac/font_loader.mm index ce391bb8b57..f0af36a630a 100644 --- a/chromium/content/common/mac/font_loader.mm +++ b/chromium/content/common/mac/font_loader.mm @@ -17,6 +17,7 @@ #import "base/mac/foundation_util.h" #include "base/mac/scoped_cftyperef.h" #import "base/mac/scoped_nsobject.h" +#include "base/strings/string16.h" #include "base/strings/sys_string_conversions.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" diff --git a/chromium/content/common/media/media_player_delegate_messages.h b/chromium/content/common/media/media_player_delegate_messages.h index 80fcfb4b270..2ee460cf5c2 100644 --- a/chromium/content/common/media/media_player_delegate_messages.h +++ b/chromium/content/common/media/media_player_delegate_messages.h @@ -118,4 +118,7 @@ IPC_MESSAGE_ROUTED2( int /* delegate_id, distinguishes instances */, bool /* picture-in-picture availability */) +IPC_MESSAGE_ROUTED1(MediaPlayerDelegateHostMsg_OnBufferUnderflow, + int /* delegate_id, distinguishes instances */) + #endif // CONTENT_COMMON_MEDIA_MEDIA_PLAYER_DELEGATE_MESSAGES_H_ diff --git a/chromium/content/common/mojo_core_library_support.cc b/chromium/content/common/mojo_core_library_support.cc new file mode 100644 index 00000000000..ed6c31b5910 --- /dev/null +++ b/chromium/content/common/mojo_core_library_support.cc @@ -0,0 +1,31 @@ +// Copyright 2020 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 "content/common/mojo_core_library_support.h" + +#include "base/command_line.h" +#include "build/build_config.h" +#include "content/public/common/content_switches.h" + +namespace content { + +bool IsMojoCoreSharedLibraryEnabled() { + return GetMojoCoreSharedLibraryPath() != base::nullopt; +} + +base::Optional<base::FilePath> GetMojoCoreSharedLibraryPath() { +#if defined(OS_LINUX) + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + if (!command_line.HasSwitch(switches::kMojoCoreLibraryPath)) + return base::nullopt; + return command_line.GetSwitchValuePath(switches::kMojoCoreLibraryPath); +#else + // Content does not yet properly support dynamic Mojo Core on platforms other + // than Linux and Chrome OS. + return base::nullopt; +#endif +} + +} // namespace content diff --git a/chromium/content/common/mojo_core_library_support.h b/chromium/content/common/mojo_core_library_support.h new file mode 100644 index 00000000000..73ec4ff858c --- /dev/null +++ b/chromium/content/common/mojo_core_library_support.h @@ -0,0 +1,26 @@ +// Copyright 2020 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 CONTENT_COMMON_MOJO_CORE_LIBRARY_SUPPORT_H_ +#define CONTENT_COMMON_MOJO_CORE_LIBRARY_SUPPORT_H_ + +#include "base/files/file_path.h" +#include "base/optional.h" +#include "content/common/content_export.h" + +namespace content { + +// Indicates whether the calling process was launched with the option to +// initialize Mojo Core from a shared library rather than the statically linked +// implementation. +CONTENT_EXPORT bool IsMojoCoreSharedLibraryEnabled(); + +// Returns the path to the Mojo Core shared library passed in on the command +// line for the calling process, or null if the process was launched without a +// Mojo Core library path on the command line. +CONTENT_EXPORT base::Optional<base::FilePath> GetMojoCoreSharedLibraryPath(); + +} // namespace content + +#endif // CONTENT_COMMON_MOJO_CORE_LIBRARY_SUPPORT_H_ diff --git a/chromium/content/common/native_types.mojom b/chromium/content/common/native_types.mojom index 9882968f03c..f26cfe9a10f 100644 --- a/chromium/content/common/native_types.mojom +++ b/chromium/content/common/native_types.mojom @@ -8,10 +8,6 @@ module content.mojom; // ParamTraits for serialization. All of these should eventually be converted to // proper mojom definitions. -// NOTE: This type is only mapped and usable on Mac. -[Native] -struct EncodedAttributedString; - [Native] struct FrameOwnerProperties; diff --git a/chromium/content/common/navigation_client.mojom b/chromium/content/common/navigation_client.mojom index bd561f899ae..fe7852700b2 100644 --- a/chromium/content/common/navigation_client.mojom +++ b/chromium/content/common/navigation_client.mojom @@ -15,7 +15,7 @@ import "mojo/public/mojom/base/unguessable_token.mojom"; import "url/mojom/url.mojom"; import "third_party/blink/public/mojom/loader/url_loader_factory_bundle.mojom"; import "third_party/blink/public/mojom/service_worker/controller_service_worker.mojom"; -import "third_party/blink/public/mojom/service_worker/service_worker_provider.mojom"; +import "third_party/blink/public/mojom/service_worker/service_worker_container.mojom"; import "third_party/blink/public/mojom/commit_result/commit_result.mojom"; interface NavigationClient { @@ -38,8 +38,8 @@ interface NavigationClient { // |controller_service_worker_info| may also be provided by the browser if the // frame that is being navigated is supposed to be controlled by a Service // Worker. - // |provider_info| may also be provided if the browser has created a - // ServiceWorkerProviderHost for this navigation. + // |container_info| may also be provided if the browser has created a + // ServiceWorkerContainerHost for this navigation. // |prefetch_loader_factory| is populated only when Network Service is // enabled. The pointer is used to start a prefetch loading via the browser // process. @@ -63,7 +63,7 @@ interface NavigationClient { blink.mojom.URLLoaderFactoryBundle? subresource_loader_factories, array<TransferrableURLLoader>? subresource_overrides, blink.mojom.ControllerServiceWorkerInfo? controller_service_worker_info, - blink.mojom.ServiceWorkerProviderInfoForClient? provider_info, + blink.mojom.ServiceWorkerContainerInfoForClient? container_info, pending_remote<network.mojom.URLLoaderFactory>? prefetch_loader_factory, mojo_base.mojom.UnguessableToken devtools_navigation_token) => (DidCommitProvisionalLoadParams params, diff --git a/chromium/content/common/navigation_params.mojom b/chromium/content/common/navigation_params.mojom index f218c7ad9e9..872d11d8fda 100644 --- a/chromium/content/common/navigation_params.mojom +++ b/chromium/content/common/navigation_params.mojom @@ -296,7 +296,7 @@ struct CommitNavigationParams { // resources. bool can_load_local_resources = false; - // Opaque history state (received by FrameHostMsg_UpdateState). + // Opaque history state (received by UpdateState Mojo message). PageState page_state; // For browser-initiated navigations, this is the unique id of the @@ -414,4 +414,7 @@ struct CommitNavigationParams { // The names of origin trials to be force enabled for this navigation. array<string> force_enabled_origin_trials; + + // Whether origin isolation is restricting certain cross-origin web APIs. + bool origin_isolation_restricted = false; }; diff --git a/chromium/content/common/page_messages.h b/chromium/content/common/page_messages.h index feb245f47a1..ad73d342756 100644 --- a/chromium/content/common/page_messages.h +++ b/chromium/content/common/page_messages.h @@ -31,20 +31,6 @@ IPC_MESSAGE_ROUTED2(PageMsg_SetHistoryOffsetAndLength, IPC_MESSAGE_ROUTED1(PageMsg_AudioStateChanged, bool /* is_audio_playing */) -// Sent to all renderers, instructing them to freeze or unfreeze all frames that -// belongs to this page. -IPC_MESSAGE_ROUTED1(PageMsg_SetPageFrozen, bool /* frozen */) - -// Sent to all renderers to freeze all frames and dispatch page visibility -// events for bfcache. -IPC_MESSAGE_ROUTED0(PageMsg_PutPageIntoBackForwardCache) - -// Sent to all renderers to resume all frames and dispatch page visibility -// events for bfcache. -IPC_MESSAGE_ROUTED1(PageMsg_RestorePageFromBackForwardCache, - base::TimeTicks /* navigation_start */) - -// Sent to all renderers when the mainframe state required by // blink::TextAutosizer changes in the main frame's renderer. IPC_MESSAGE_ROUTED1(PageMsg_UpdateTextAutosizerPageInfoForRemoteMainFrames, blink::WebTextAutosizerPageInfo /* page_info */) diff --git a/chromium/content/common/page_state.mojom b/chromium/content/common/page_state.mojom index e4f2abcd424..ef6e9e5ba7a 100644 --- a/chromium/content/common/page_state.mojom +++ b/chromium/content/common/page_state.mojom @@ -15,17 +15,16 @@ import "ui/gfx/geometry/mojom/geometry.mojom"; // parts. The resultant generated code is used to serialize and deserialize // PageState for the purpose of history restore. // -// When adding fields: +// All structures here must maintain backward-compatibility (and hence must be +// marked [Stable]) according to mojom backward-compatibility rules. Namely, +// when adding new fields: // - Assign your new field an explicit ordinal(@n) and prefer to add fields to // the end of the struct to simplify finding the latest ordinal. -// - For backwards compatibility purposes: -// - New fields must be tagged with a [MinVersion=x] attribute; x is -// specified at the bottom of this comment block. -// - Only types with frozen/unchanging Mojo serialization may be used; -// for example, |string| is okay, but |url.mojom.Origin| is not. -// (note that if serialization of any of the types used in PageState -// changes in a backwards-incompatible way then it should be caught by -// one of PageStateSerializationTest, BackwardsCompat_vXX tests). +// - New fields must be tagged with a [MinVersion=x] attribute where x is larger +// than the MinVersion for any existing fields. The next available MinVersion +// value is specified at the bottom of this comment block for convenience. +// - Only builtin mojom types or other user-defined [Stable] types are allowed +// as transitive dependencies here. This is enforced at build time. // - You'll also need to read/write the new field's value when decoding and // encoding PageState, update PageStateSerializationTest to check that your // new field is preserved across serialization, and add a BackwardsCompat @@ -37,11 +36,15 @@ import "ui/gfx/geometry/mojom/geometry.mojom"; // compatibility. If re-ordering fields, make sure to retain the original // ordinal value. // +// Finally, note that any backward-incomptable changes will be caught by a +// presubmit check. +// // Update the below value if your change introduces fields using it. // Next MinVersion: 3 // Next Ordinal: 4 // FileSystemFile is no longer supported. +[Stable] struct DEPRECATED_FileSystemFile { url.mojom.Url filesystem_url@0; uint64 offset@1; @@ -50,6 +53,7 @@ struct DEPRECATED_FileSystemFile { }; // Next Ordinal: 4 +[Stable] struct File { mojo_base.mojom.String16 path@0; uint64 offset@1; @@ -58,6 +62,7 @@ struct File { }; // Next Ordinal: 4 +[Stable] union Element { string blob_uuid@0; array<uint8> bytes@1; @@ -67,6 +72,7 @@ union Element { }; // Next Ordinal: 3 +[Stable] struct RequestBody { array<Element> elements@0; int64 identifier@1; @@ -74,6 +80,7 @@ struct RequestBody { }; // Next Ordinal: 3 +[Stable] struct HttpBody { mojo_base.mojom.String16? http_content_type@0; RequestBody? request_body@1; @@ -82,13 +89,14 @@ struct HttpBody { // This enum's values must match blink::WebHistoryScrollRestorationType. This // is enforced with static asserts in page_state_serialization.cc. -[Extensible] +[Stable, Extensible] enum ScrollRestorationType { kAuto = 0, kManual = 1 }; // Next Ordinal: 6 +[Stable] struct ViewState { gfx.mojom.PointF visual_viewport_scroll_offset@0; gfx.mojom.Point scroll_offset@1; @@ -100,6 +108,7 @@ struct ViewState { }; // Next Ordinal: 13 +[Stable] struct FrameState { mojo_base.mojom.String16? url_string@0; mojo_base.mojom.String16? referrer@1; @@ -117,6 +126,7 @@ struct FrameState { }; // Next Ordinal: 2 +[Stable] struct PageState { array<mojo_base.mojom.String16?> referenced_files@0; FrameState top@1; diff --git a/chromium/content/common/render_accessibility.mojom b/chromium/content/common/render_accessibility.mojom index 4bfa3eee09c..19ec49f79f4 100644 --- a/chromium/content/common/render_accessibility.mojom +++ b/chromium/content/common/render_accessibility.mojom @@ -10,6 +10,7 @@ import "ui/accessibility/mojom/ax_action_data.mojom"; import "ui/accessibility/mojom/ax_event.mojom"; import "ui/accessibility/mojom/ax_relative_bounds.mojom"; import "ui/gfx/geometry/mojom/geometry.mojom"; +import "mojo/public/mojom/base/unguessable_token.mojom"; struct LocationChanges { // ID of the object whose location is changing. @@ -19,16 +20,19 @@ struct LocationChanges { ax.mojom.AXRelativeBounds new_location; }; -struct ChildFrameHitTestInfo { - // The routing ID of the child frame to request a hit test for. - int32 child_frame_routing_id; +struct HitTestResponse { + // The frame token of the frame that got hit. If this is not equal to the + // frame that the original hit test was called on, the client should do + // another hit test on this frame. + mojo_base.mojom.UnguessableToken hit_frame_token; // The coordinates that should be used for the hit test on the child frame - // indicated by |child_frame_routing_id|, accounting for the viewport. - gfx.mojom.Point transformed_point; + // indicated by |hit_frame_token|, accounting for the viewport. This is only + // needed if |hit_frame_token| is not the same as the current frame's token. + gfx.mojom.Point hit_frame_transformed_point; - // The accessibility event that should be fired. - ax.mojom.Event event_to_fire; + // The AXID of the accessibility node that got hit. + int32 hit_node_id; }; // Interface for accessibility messages sent from the renderer to the browser, @@ -71,15 +75,18 @@ interface RenderAccessibility { FatalError(); // Relays a request from assistive technology to perform a hit test over the - // accessibility object at the point passed via |action_data.target_point|. + // accessibility object at the point passed via |point| in frame pixels. // - // If the object hit doesn't have a child frame, the accessibility event - // indicated via |action_data.hit_test_event_to_fire| will be emitted by the - // renderer and no |child_frame_hit_test_info| should be returned. Otherwise, - // |child_frame_hit_test_info| will provide the necessary information for the - // browser process to request another hit test over the child frame found. - HitTest(ax.mojom.AXActionData action_data) - => (ChildFrameHitTestInfo? child_frame_hit_test_info); + // If the object hit doesn't have a child frame, and if |event_to_fire| is + // set, the accessibility event will be emitted on the hit node with the + // given request ID. + // + // Either way, the response contains the routing ID of the hit frame, + // and the transformed point if the hit frame is a child frame. + HitTest(gfx.mojom.Point point, + ax.mojom.Event event_to_fire, + int32 request_id) + => (HitTestResponse? hit_test_response); // Relay a request from assistive technology to perform an action, such as // focusing or clicking on a node. diff --git a/chromium/content/common/render_frame_metadata.mojom b/chromium/content/common/render_frame_metadata.mojom index fccbceb8034..badccc73abe 100644 --- a/chromium/content/common/render_frame_metadata.mojom +++ b/chromium/content/common/render_frame_metadata.mojom @@ -36,6 +36,11 @@ struct RenderFrameMetadata { // are the same). bool is_mobile_optimized; + // Flag used to notify the browser process to start or stop forwarding points + // to viz for use in a delegated ink trail. True the entire time points should + // be forwarded, and forwarding stops as soon as it is false again. + bool has_delegated_ink_metadata; + // The device scale factor used to generate CompositorFrame. float device_scale_factor; @@ -98,11 +103,18 @@ struct RenderFrameMetadata { // which a fully populated RenderFrameMetadata object (above) is delivered to // the RenderFrameMetadataObserverClient. interface RenderFrameMetadataObserver { - // When |enabled| is set to true, this will send RenderFrameMetadata to - // the RenderFrameMetadataObserverClient for any frame in which the root - // scroll changes. Used only on Android for accessibility cases. + // When |enabled| is set to true this notifies the client of any change to the + // root scroll offset. The client is notified in two ways: + // . OnRenderFrameMetadataChanged(), is sent if the client would normally be + // notified of the frame (for example, the viewport changed). + // . OnRootScrollOffsetChanged() if the client is not notified of the frame + // change, but the root scroll offset has changed. In other words, if this + // is sent, *only* the root-scroll-offset has changed and the client is not + // sent a OnRenderFrameMetadataChanged() for the frame. + // Used on Android for acessibility and GestureListenerManager. [EnableIf=is_android] - ReportAllRootScrollsForAccessibility(bool enabled); + ReportAllRootScrolls(bool enabled); + // When |enabled| is set to true, this will send RenderFrameMetadata to // the RenderFrameMetadataObserverClient for all frames. Only used for // tests. @@ -113,11 +125,16 @@ interface RenderFrameMetadataObserver { // RenderFrameMetadata. It can be notified of all frame submissions, via // RenderFrameMetadataObserver::ReportAllFrameSubmissionsForTesting, or of // additional frames with root scroll offset changes via -// RenderFrameMetadataObserver::ReportAllRootScrollsForAccessibility. +// RenderFrameMetadataObserver::ReportAllRootScrolls. interface RenderFrameMetadataObserverClient { // Notified when RenderFrameMetadata has changed. OnRenderFrameMetadataChanged(uint32 frame_token, RenderFrameMetadata metadata); // Notified on all frame submissions. OnFrameSubmissionForTesting(uint32 frame_token); + + // Only called if ReportAllRootScrolls(true) has been called. See + // ReportAllRootScrolls() for details. + [EnableIf=is_android] + OnRootScrollOffsetChanged(gfx.mojom.Vector2dF root_scroll_offset); }; diff --git a/chromium/content/common/render_frame_metadata_mojom_traits.cc b/chromium/content/common/render_frame_metadata_mojom_traits.cc index 065f06fc64f..eefa6594444 100644 --- a/chromium/content/common/render_frame_metadata_mojom_traits.cc +++ b/chromium/content/common/render_frame_metadata_mojom_traits.cc @@ -21,6 +21,7 @@ bool StructTraits<content::mojom::RenderFrameMetadataDataView, out->root_background_color = data.root_background_color(); out->is_scroll_offset_at_top = data.is_scroll_offset_at_top(); out->is_mobile_optimized = data.is_mobile_optimized(); + out->has_delegated_ink_metadata = data.has_delegated_ink_metadata(); out->device_scale_factor = data.device_scale_factor(); out->page_scale_factor = data.page_scale_factor(); out->external_page_scale_factor = data.external_page_scale_factor(); diff --git a/chromium/content/common/render_frame_metadata_mojom_traits.h b/chromium/content/common/render_frame_metadata_mojom_traits.h index b998ec4e963..3e0d9d3e5c4 100644 --- a/chromium/content/common/render_frame_metadata_mojom_traits.h +++ b/chromium/content/common/render_frame_metadata_mojom_traits.h @@ -40,6 +40,11 @@ struct StructTraits<content::mojom::RenderFrameMetadataDataView, return metadata.is_mobile_optimized; } + static bool has_delegated_ink_metadata( + const cc::RenderFrameMetadata& metadata) { + return metadata.has_delegated_ink_metadata; + } + static float device_scale_factor(const cc::RenderFrameMetadata& metadata) { return metadata.device_scale_factor; } diff --git a/chromium/content/common/render_widget_host_ns_view.mojom b/chromium/content/common/render_widget_host_ns_view.mojom index 8a5b18a4261..a8c3582a4fb 100644 --- a/chromium/content/common/render_widget_host_ns_view.mojom +++ b/chromium/content/common/render_widget_host_ns_view.mojom @@ -5,10 +5,10 @@ module remote_cocoa.mojom; import "content/common/native_types.mojom"; -import "content/common/input/input_handler.mojom"; import "mojo/public/mojom/base/string16.mojom"; -import "ui/base/ime/mojom/ime_types.mojom"; import "third_party/blink/public/mojom/input/input_handler.mojom"; +import "ui/base/mojom/attributed_string.mojom"; +import "ui/base/ime/mojom/ime_types.mojom"; import "ui/display/mojom/display.mojom"; import "ui/events/mojom/event.mojom"; import "ui/gfx/geometry/mojom/geometry.mojom"; @@ -80,7 +80,7 @@ interface RenderWidgetHostNSView { // Open the dictionary overlay for the specified string at the specified // point. - ShowDictionaryOverlay(content.mojom.EncodedAttributedString attributed_string, + ShowDictionaryOverlay(ui.mojom.AttributedString attributed_string, gfx.mojom.Point baseline_point); // Start intercepting keyboard events for the specified codes. @@ -138,28 +138,28 @@ interface RenderWidgetHostNSViewHost { // Forward a keyboard event to the RenderWidgetHost that is currently handling // the key-down event. ForwardKeyboardEventWithCommands( - content.mojom.Event event, + blink.mojom.Event event, array<uint8> native_event_data, bool skip_in_browser, array<blink.mojom.EditCommand> commands); // Forward events to the renderer or the input router, as appropriate. - RouteOrProcessMouseEvent(content.mojom.Event event); - RouteOrProcessTouchEvent(content.mojom.Event event); - RouteOrProcessWheelEvent(content.mojom.Event event); + RouteOrProcessMouseEvent(blink.mojom.Event event); + RouteOrProcessTouchEvent(blink.mojom.Event event); + RouteOrProcessWheelEvent(blink.mojom.Event event); // Special case forwarding of synthetic events to the renderer. - ForwardMouseEvent(content.mojom.Event event); - ForwardWheelEvent(content.mojom.Event event); + ForwardMouseEvent(blink.mojom.Event event); + ForwardWheelEvent(blink.mojom.Event event); // Handling pinch gesture events. Note that for GestureBegin, the type of the // event is ignored, and is inferred from subsequent GestureUpdate calls. - GestureBegin(content.mojom.Event event, bool is_synthetically_injected); - GestureUpdate(content.mojom.Event event); - GestureEnd(content.mojom.Event event); + GestureBegin(blink.mojom.Event event, bool is_synthetically_injected); + GestureUpdate(blink.mojom.Event event); + GestureEnd(blink.mojom.Event event); // Handle a double-tap magnify event. - SmartMagnify(content.mojom.Event event); + SmartMagnify(blink.mojom.Event event); // Forward the corresponding Ime commands to the appropriate RenderWidgetHost. // Appropriate, has two meanings here. If this is during a key-down event, diff --git a/chromium/content/common/renderer.mojom b/chromium/content/common/renderer.mojom index 309746baa6e..39a399c3064 100644 --- a/chromium/content/common/renderer.mojom +++ b/chromium/content/common/renderer.mojom @@ -54,9 +54,9 @@ struct CreateViewParams { // The session storage namespace ID this view should use. string session_storage_namespace_id; - // The route ID of the opener RenderFrame or RenderFrameProxy, if we need to - // set one (MSG_ROUTING_NONE otherwise). - int32 opener_frame_route_id = IPC.mojom.kRoutingIdNone; + // The frame token of the opener RenderFrame or RenderFrameProxy, if we need + // to set one (base::nullopt otherwise). + mojo_base.mojom.UnguessableToken? opener_frame_token; // Carries replicated information, such as frame name and sandbox flags, for // this view's main frame, which will be a proxy when |main_frame_routing_id| @@ -144,8 +144,8 @@ struct CreateFrameParams { mojo_base.mojom.UnguessableToken frame_token; // Specifies the new frame's opener. The opener will be null if this is - // MSG_ROUTING_NONE. - int32 opener_routing_id; + // base::nullopt. + mojo_base.mojom.UnguessableToken? opener_frame_token; // The new frame should be created as a child of the object // identified by |parent_routing_id| or as top level if that is @@ -246,9 +246,9 @@ interface Renderer { // Tells the renderer to create a new RenderFrameProxy object with // |routing_id|. |render_view_routing_id| identifies the - // RenderView to be associated with this proxy. The new proxy's opener should - // be set to the object identified by |opener_routing_id|, or to null if that - // is MSG_ROUTING_NONE. The new proxy should be created as a child of the + // RenderView to be associated with this proxy. The new proxy's opener should + // be set to the object identified by |opener_frame_token|, or to null if that + // is base::nullopt. The new proxy should be created as a child of the // object identified by |parent_routing_id| or as top level if that is // MSG_ROUTING_NONE. // |proxy_frame_token| is used uniquely identify the @@ -257,7 +257,8 @@ interface Renderer { // and trace-ability. It is defined by the browser and is never // sent back from the renderer in the control calls. CreateFrameProxy(int32 routing_id, int32 render_view_routing_id, - int32 opener_routing_id, int32 parent_routing_id, + mojo_base.mojom.UnguessableToken? opener_frame_token, + int32 parent_routing_id, FrameReplicationState replication_state, mojo_base.mojom.UnguessableToken proxy_frame_token, mojo_base.mojom.UnguessableToken devtools_frame_token); @@ -294,6 +295,9 @@ interface Renderer { // decide to ship https://github.com/WICG/ua-client-hints. SetUserAgentMetadata(blink.mojom.UserAgentMetadata metadata); + // Sets the CORS exempt header list for sanity checking (e.g. DCHECKs). + SetCorsExemptHeaderList(array<string> list); + // Tells the renderer about a scrollbar appearance change. Only for use on // OS X. UpdateScrollbarTheme(UpdateScrollbarThemeParams params); @@ -324,15 +328,17 @@ interface Renderer { // origin. SetIsLockedToSite(); - // Tells the renderer to enable V8's memory saving mode when possible. - // This is only used when site-per-process is enabled. If the process - // only contains subframes, V8's low memory mode will be enabled. - // If a main frame exists or is created, the low memory mode will - // be disabled. - EnableV8LowMemoryMode(); - // Write out the accumulated code profiling profile to the configured file. // The callback is invoked once the profile has been flushed to disk. [EnableIf=clang_profiling_inside_sandbox] WriteClangProfilingProfile() => (); + + // Set whether this renderer process is "cross-origin isolated". This + // corresponds to agent cluster's "cross-origin isolated" concept. + // TODO(yhirano): Have the spec URL. + // This property is process global because we ensure that a renderer process + // host only cross-origin isolated agents or only non-cross-origin isolated + // agents, not both. + // This is called at most once. This is called earlier than any frame commit. + SetIsCrossOriginIsolated(bool value); }; diff --git a/chromium/content/common/savable_subframe.h b/chromium/content/common/savable_subframe.h deleted file mode 100644 index ec7f572b642..00000000000 --- a/chromium/content/common/savable_subframe.h +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_COMMON_SAVABLE_SUBFRAME_H_ -#define CONTENT_COMMON_SAVABLE_SUBFRAME_H_ - -#include "url/gurl.h" - -namespace content { - -// Information about a subframe being saved as "complete html". -struct SavableSubframe { - // Original url of the subframe (i.e. based the parent's html sources). - GURL original_url; - - // Routing ID of the RenderFrame or RenderFrameProxy for the subframe. - int routing_id; -}; - -} // namespace content - -#endif // CONTENT_COMMON_SAVABLE_SUBFRAME_H_ diff --git a/chromium/content/common/service_worker/service_worker_loader_helpers.cc b/chromium/content/common/service_worker/service_worker_loader_helpers.cc index 8f2ac0aff55..b09fd3dc98b 100644 --- a/chromium/content/common/service_worker/service_worker_loader_helpers.cc +++ b/chromium/content/common/service_worker/service_worker_loader_helpers.cc @@ -96,10 +96,19 @@ void ServiceWorkerLoaderHelpers::SaveResponseInfo( out_head->was_fallback_required_by_service_worker = false; out_head->url_list_via_service_worker = response.url_list; out_head->response_type = response.response_type; + if (response.mime_type.has_value()) { + std::string charset; + bool had_charset = false; + // The mime type set on |response| may have a charset included. The + // loading stack, however, expects the charset to already have been + // stripped. Parse out the mime type essence without any charset and + // store the result on |out_head|. + net::HttpUtil::ParseContentType(response.mime_type.value(), + &out_head->mime_type, &charset, + &had_charset, nullptr); + } out_head->response_time = response.response_time; - out_head->is_in_cache_storage = - response.response_source == - network::mojom::FetchResponseSource::kCacheStorage; + out_head->service_worker_response_source = response.response_source; if (response.cache_storage_cache_name) out_head->cache_storage_cache_name = *(response.cache_storage_cache_name); else @@ -107,6 +116,9 @@ void ServiceWorkerLoaderHelpers::SaveResponseInfo( out_head->cors_exposed_header_names = response.cors_exposed_header_names; out_head->did_service_worker_navigation_preload = false; out_head->parsed_headers = mojo::Clone(response.parsed_headers); + out_head->connection_info = response.connection_info; + out_head->alpn_negotiated_protocol = response.alpn_negotiated_protocol; + out_head->was_fetched_via_spdy = response.was_fetched_via_spdy; } // static diff --git a/chromium/content/common/service_worker/service_worker_loader_helpers.h b/chromium/content/common/service_worker/service_worker_loader_helpers.h index c90564e3b3a..8d82271bb85 100644 --- a/chromium/content/common/service_worker/service_worker_loader_helpers.h +++ b/chromium/content/common/service_worker/service_worker_loader_helpers.h @@ -21,7 +21,7 @@ struct ResourceRequest; namespace content { // Helper functions for service worker classes that use URLLoader -//(e.g., ServiceWorkerNavigationLoader and ServiceWorkerSubresourceLoader). +//(e.g., ServiceWorkerMainResourceLoader and ServiceWorkerSubresourceLoader). class ServiceWorkerLoaderHelpers { public: // Populates |out_head->headers| with the given |status_code|, |status_text|, diff --git a/chromium/content/common/service_worker/service_worker_utils.cc b/chromium/content/common/service_worker/service_worker_utils.cc index 91f1a64250b..eb8dd0ecf59 100644 --- a/chromium/content/common/service_worker/service_worker_utils.cc +++ b/chromium/content/common/service_worker/service_worker_utils.cc @@ -56,6 +56,17 @@ bool ServiceWorkerUtils::IsMainResourceType(blink::mojom::ResourceType type) { } // static +bool ServiceWorkerUtils::IsMainRequestDestination( + network::mojom::RequestDestination destination) { + // When PlzDedicatedWorker is enabled, a dedicated worker script is considered + // to be a main resource. + if (destination == network::mojom::RequestDestination::kWorker) + return base::FeatureList::IsEnabled(blink::features::kPlzDedicatedWorker); + return blink::IsRequestDestinationFrame(destination) || + destination == network::mojom::RequestDestination::kSharedWorker; +} + +// static bool ServiceWorkerUtils::ScopeMatches(const GURL& scope, const GURL& url) { DCHECK(!scope.has_ref()); return base::StartsWith(url.spec(), scope.spec(), diff --git a/chromium/content/common/service_worker/service_worker_utils.h b/chromium/content/common/service_worker/service_worker_utils.h index 36955b209cc..1ea5f93e362 100644 --- a/chromium/content/common/service_worker/service_worker_utils.h +++ b/chromium/content/common/service_worker/service_worker_utils.h @@ -28,6 +28,9 @@ class ServiceWorkerUtils { public: static bool IsMainResourceType(blink::mojom::ResourceType type); + static bool IsMainRequestDestination( + network::mojom::RequestDestination destination); + // Returns true if |scope| matches |url|. CONTENT_EXPORT static bool ScopeMatches(const GURL& scope, const GURL& url); diff --git a/chromium/content/common/state_transitions.h b/chromium/content/common/state_transitions.h new file mode 100644 index 00000000000..31178988e26 --- /dev/null +++ b/chromium/content/common/state_transitions.h @@ -0,0 +1,100 @@ +// Copyright 2020 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 CONTENT_COMMON_STATE_TRANSITIONS_H_ +#define CONTENT_COMMON_STATE_TRANSITIONS_H_ + +#include <vector> + +#include "base/check_op.h" +#include "base/no_destructor.h" +#include "base/stl_util.h" + +namespace content { + +// This class represents a set of state transitions where each state is a value +// that supports copy, << and == (e.g. an enum element). It's intended to be +// used in DCHECK-enabled builds to check that only valid transitions occur. Its +// implementation favours convenience and simplicity over performance. To use it +// follow this example: + +// In foo.h +// --------- +// enum class State { +// kState1, +// kState2, +// kState3, +// }; +// +// // This may require exporting the symbol (e.g. CONTENT_EXPORT) if it will be +// // used by any other components: one common way this can happen is if the +// // enum is logged in tests (e.g. via gtest's EXPECT_* macros). +// std::ostream& operator<<(std::ostream& o, const State& s); +// --------- +// +// In foo.cc +// --------- +// #include "base/no_destructor.h" +// #include "content/common/state_transitions.h" +// +// std::ostream& operator<<(std::ostream& o, const State& s) { +// return o << static_cast<int>(s); +// } +// +// void DCheckStateTransition(State old_state, State new_state) { +// #if DCHECK_IS_ON() +// static const base::NoDestructor<StateTransitions<State>> transitions( +// StateTransitions<State>({ +// {kState1, {kState2, kState3}}, +// {kState2, {kState3}}, +// {kState3, {}}, +// })); +// DCHECK_STATE_TRANSITION(transitions, old_state, new_state); +// #endif // DCHECK_IS_ON() +// } +// --------- + +template <typename State> +struct StateTransitions { + public: + // Represents a state and all of the states that are valid transitions from + // it. + struct StateTransition { + StateTransition(State source, std::vector<State> destinations) + : source(std::move(source)), destinations(std::move(destinations)) {} + + const State source; + const std::vector<State> destinations; + }; + + explicit StateTransitions(std::vector<StateTransition> state_transitions) + : state_transitions(std::move(state_transitions)) {} + + // Returns a list of states that are valid to transition to from |source|. + const std::vector<State>& GetValidTransitions(const State& source) const { + for (const StateTransition& state_transition : state_transitions) { + if (state_transition.source == source) + return state_transition.destinations; + } + static const base::NoDestructor<std::vector<State>> no_transitions; + return *no_transitions; + } + + // Tests whether transitioning from |source| to |destination| is valid. + bool IsTransitionValid(const State& source, const State& destination) const { + return base::Contains(GetValidTransitions(source), destination); + } + + const std::vector<StateTransition> state_transitions; +}; + +// DCHECK if transitioning from |old_state| to |new_state| is not valid +// according to |transitions|. +#define DCHECK_STATE_TRANSITION(transitions, old_state, new_state) \ + DCHECK((transitions)->IsTransitionValid((old_state), (new_state))) \ + << "Invalid transition: " << old_state << " -> " << new_state + +} // namespace content + +#endif // CONTENT_COMMON_STATE_TRANSITIONS_H_ diff --git a/chromium/content/common/state_transitions_unittest.cc b/chromium/content/common/state_transitions_unittest.cc new file mode 100644 index 00000000000..e7edee2953f --- /dev/null +++ b/chromium/content/common/state_transitions_unittest.cc @@ -0,0 +1,100 @@ +// Copyright (c) 2020 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 "content/common/state_transitions.h" + +#include <ostream> +#include <string> + +#include "base/test/gtest_util.h" +#include "build/build_config.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace content { + +enum class State { kState1 = 0, kState2, kState3, kState4 }; + +std::ostream& operator<<(std::ostream& o, const State& s) { + return o << static_cast<int>(s); +} + +TEST(StateTransitionsTest, Constructor) { + // No expectations, just make sure the constructor works. + const StateTransitions<State> transitions({ + {State::kState1, {State::kState2, State::kState3}}, + {State::kState2, {State::kState3, State::kState4}}, + }); +} + +TEST(StateTransitionsTest, GetValidTransitions) { + const StateTransitions<State> transitions({ + {State::kState1, {State::kState2, State::kState3}}, + {State::kState2, {State::kState3, State::kState4}}, + }); + EXPECT_THAT(transitions.GetValidTransitions(State::kState1), + testing::ElementsAre(State::kState2, State::kState3)); + EXPECT_THAT(transitions.GetValidTransitions(State::kState2), + testing::ElementsAre(State::kState3, State::kState4)); + EXPECT_THAT(transitions.GetValidTransitions(State::kState3), + testing::ElementsAre()); + EXPECT_THAT(transitions.GetValidTransitions(State::kState4), + testing::ElementsAre()); +} + +TEST(StateTransitionsTest, IsTransitionValid) { + const StateTransitions<State> transitions({ + {State::kState1, {State::kState2, State::kState3}}, + {State::kState2, {State::kState3, State::kState4}}, + }); + ASSERT_TRUE(transitions.IsTransitionValid(State::kState1, State::kState2)); + ASSERT_TRUE(transitions.IsTransitionValid(State::kState2, State::kState3)); + ASSERT_FALSE(transitions.IsTransitionValid(State::kState1, State::kState4)); + // kState3 was omitted from the definition. + ASSERT_FALSE(transitions.IsTransitionValid(State::kState3, State::kState4)); +} + +TEST(StateTransitionsTest, DCHECK_STATE_TRANSITION) { + const StateTransitions<State> transitions({ + {State::kState1, {State::kState2, State::kState3}}, + {State::kState2, {State::kState3, State::kState4}}, + }); + DCHECK_STATE_TRANSITION(&transitions, State::kState1, State::kState2); + DCHECK_STATE_TRANSITION(&transitions, State::kState2, State::kState3); + +#if DCHECK_IS_ON() + // EXPECT_DEATH is not defined on IOS. +#ifndef OS_IOS + EXPECT_DEATH( + DCHECK_STATE_TRANSITION(&transitions, State::kState1, State::kState4), + "Check failed.*Invalid transition: 0 -> 3"); + // kState3 was omitted from the definition. + EXPECT_DEATH( + DCHECK_STATE_TRANSITION(&transitions, State::kState3, State::kState4), + "Check failed.*Invalid transition: 2 -> 3"); +#endif // !OS_IOS +#endif // DCHECK_IS_ON() +} + +// Test that everything works OK with some other data type. +TEST(StateTransitionsTest, NonEnum) { + const StateTransitions<std::string> transitions({ + {"state1", {"state2", "state3"}}, + {"state2", {"state3", "state4"}}, + }); + ASSERT_TRUE(transitions.IsTransitionValid("state1", "state2")); + ASSERT_TRUE(transitions.IsTransitionValid("state2", "state3")); + ASSERT_FALSE(transitions.IsTransitionValid("state1", "state4")); + // kState3 was omitted from the definition. + ASSERT_FALSE(transitions.IsTransitionValid("state3", "state4")); + DCHECK_STATE_TRANSITION(&transitions, "state1", "state2"); + DCHECK_STATE_TRANSITION(&transitions, "state2", "state3"); + + // Try some states that are not in the specification at all. + ASSERT_FALSE(transitions.IsTransitionValid("foo", "state2")); + ASSERT_FALSE(transitions.IsTransitionValid("state1", "foo")); + ASSERT_FALSE(transitions.IsTransitionValid("foo", "bar")); +} + +} // namespace content diff --git a/chromium/content/common/tab_switch_time_recorder_unittest.cc b/chromium/content/common/tab_switch_time_recorder_unittest.cc index e8dfadb2cfa..46264244ba3 100644 --- a/chromium/content/common/tab_switch_time_recorder_unittest.cc +++ b/chromium/content/common/tab_switch_time_recorder_unittest.cc @@ -19,10 +19,6 @@ constexpr char kDurationWithSavedFramesHistogram[] = "Browser.Tabs.TotalSwitchDuration.WithSavedFrames"; constexpr char kDurationNoSavedFramesHistogram[] = "Browser.Tabs.TotalSwitchDuration.NoSavedFrames_Loaded"; -constexpr char kDurationNoSavedFramesNotFrozenHistogram[] = - "Browser.Tabs.TotalSwitchDuration.NoSavedFrames_Loaded_NotFrozen"; -constexpr char kDurationNoSavedFramesFrozenHistogram[] = - "Browser.Tabs.TotalSwitchDuration.NoSavedFrames_Loaded_Frozen"; constexpr char kDurationNoSavedFramesUnloadedHistogram[] = "Browser.Tabs.TotalSwitchDuration.NoSavedFrames_NotLoaded"; @@ -30,10 +26,6 @@ constexpr char kIncompleteDurationWithSavedFramesHistogram[] = "Browser.Tabs.TotalIncompleteSwitchDuration.WithSavedFrames"; constexpr char kIncompleteDurationNoSavedFramesHistogram[] = "Browser.Tabs.TotalIncompleteSwitchDuration.NoSavedFrames_Loaded"; -constexpr char kIncompleteDurationNoSavedFramesNotFrozenHistogram[] = - "Browser.Tabs.TotalIncompleteSwitchDuration.NoSavedFrames_Loaded_NotFrozen"; -constexpr char kIncompleteDurationNoSavedFramesFrozenHistogram[] = - "Browser.Tabs.TotalIncompleteSwitchDuration.NoSavedFrames_Loaded_Frozen"; constexpr char kIncompleteDurationNoSavedFramesUnloadedHistogram[] = "Browser.Tabs.TotalIncompleteSwitchDuration.NoSavedFrames_NotLoaded"; @@ -41,10 +33,6 @@ constexpr char kResultWithSavedFramesHistogram[] = "Browser.Tabs.TabSwitchResult.WithSavedFrames"; constexpr char kResultNoSavedFramesHistogram[] = "Browser.Tabs.TabSwitchResult.NoSavedFrames_Loaded"; -constexpr char kResultNoSavedFramesNotFrozenHistogram[] = - "Browser.Tabs.TabSwitchResult.NoSavedFrames_Loaded_NotFrozen"; -constexpr char kResultNoSavedFramesFrozenHistogram[] = - "Browser.Tabs.TabSwitchResult.NoSavedFrames_Loaded_Frozen"; constexpr char kResultNoSavedFramesUnloadedHistogram[] = "Browser.Tabs.TabSwitchResult.NoSavedFrames_NotLoaded"; constexpr char kWebContentsUnOccludedHistogram[] = @@ -68,18 +56,12 @@ class ContentToVisibleTimeReporterTest : public testing::Test { constexpr const char* kAllHistograms[] = { kDurationWithSavedFramesHistogram, kDurationNoSavedFramesHistogram, - kDurationNoSavedFramesNotFrozenHistogram, - kDurationNoSavedFramesFrozenHistogram, kDurationNoSavedFramesUnloadedHistogram, kIncompleteDurationWithSavedFramesHistogram, kIncompleteDurationNoSavedFramesHistogram, - kIncompleteDurationNoSavedFramesNotFrozenHistogram, - kIncompleteDurationNoSavedFramesFrozenHistogram, kIncompleteDurationNoSavedFramesUnloadedHistogram, kResultWithSavedFramesHistogram, kResultNoSavedFramesHistogram, - kResultNoSavedFramesNotFrozenHistogram, - kResultNoSavedFramesFrozenHistogram, kResultNoSavedFramesUnloadedHistogram, kWebContentsUnOccludedHistogram}; for (const char* histogram : kAllHistograms) { @@ -122,7 +104,7 @@ TEST_F(ContentToVisibleTimeReporterTest, TimeIsRecordedWithSavedFrames) { auto callback = tab_switch_time_recorder_.TabWasShown( true /* has_saved_frames */, {start, /* destination_is_loaded */ true, - /* destination_is_frozen */ false, /* show_reason_tab_switching */ true, + /* show_reason_tab_switching */ true, /* show_reason_unoccluded */ false, /* show_reason_bfcache_restore */ false}, start); @@ -147,49 +129,12 @@ TEST_F(ContentToVisibleTimeReporterTest, TimeIsRecordedWithSavedFrames) { // Time is properly recorded to histogram when we have no saved frame and if we // have a proper matching TabWasShown and callback execution. -TEST_F(ContentToVisibleTimeReporterTest, TimeIsRecordedNoSavedFrameNotFrozen) { +TEST_F(ContentToVisibleTimeReporterTest, TimeIsRecordedNoSavedFrame) { const auto start = base::TimeTicks::Now(); auto callback = tab_switch_time_recorder_.TabWasShown( false /* has_saved_frames */, {start, /* destination_is_loaded */ true, - /* destination_is_frozen */ false, /* show_reason_tab_switching */ true, - /* show_reason_unoccluded */ false, - /* show_reason_bfcache_restore */ false}, - start); - const auto end = start + kDuration; - auto presentation_feedback = gfx::PresentationFeedback( - end, end - start, gfx::PresentationFeedback::Flags::kHWCompletion); - std::move(callback).Run(presentation_feedback); - - ExpectHistogramsEmptyExcept({kDurationNoSavedFramesHistogram, - kDurationNoSavedFramesNotFrozenHistogram, - kResultNoSavedFramesHistogram, - kResultNoSavedFramesNotFrozenHistogram}); - - // Duration. - ExpectTotalSamples(kDurationNoSavedFramesHistogram, 1); - ExpectTimeBucketCount(kDurationNoSavedFramesHistogram, kDuration, 1); - ExpectTotalSamples(kDurationNoSavedFramesNotFrozenHistogram, 1); - ExpectTimeBucketCount(kDurationNoSavedFramesNotFrozenHistogram, kDuration, 1); - - // Result. - ExpectTotalSamples(kResultNoSavedFramesHistogram, 1); - ExpectResultBucketCount( - kResultNoSavedFramesHistogram, - ContentToVisibleTimeReporter::TabSwitchResult::kSuccess, 1); - ExpectTotalSamples(kResultNoSavedFramesNotFrozenHistogram, 1); - ExpectResultBucketCount( - kResultNoSavedFramesNotFrozenHistogram, - ContentToVisibleTimeReporter::TabSwitchResult::kSuccess, 1); -} - -// Same as TimeIsRecordedNoSavedFrame but with the destination frame frozen. -TEST_F(ContentToVisibleTimeReporterTest, TimeIsRecordedNoSavedFrameFrozen) { - const auto start = base::TimeTicks::Now(); - auto callback = tab_switch_time_recorder_.TabWasShown( - false /* has_saved_frames */, - {start, /* destination_is_loaded */ true, - /* destination_is_frozen */ true, /* show_reason_tab_switching */ true, + /* show_reason_tab_switching */ true, /* show_reason_unoccluded */ false, /* show_reason_bfcache_restore */ false}, start); @@ -199,24 +144,17 @@ TEST_F(ContentToVisibleTimeReporterTest, TimeIsRecordedNoSavedFrameFrozen) { std::move(callback).Run(presentation_feedback); ExpectHistogramsEmptyExcept( - {kDurationNoSavedFramesHistogram, kDurationNoSavedFramesFrozenHistogram, - kResultNoSavedFramesHistogram, kResultNoSavedFramesFrozenHistogram}); + {kDurationNoSavedFramesHistogram, kResultNoSavedFramesHistogram}); // Duration. ExpectTotalSamples(kDurationNoSavedFramesHistogram, 1); ExpectTimeBucketCount(kDurationNoSavedFramesHistogram, kDuration, 1); - ExpectTotalSamples(kDurationNoSavedFramesFrozenHistogram, 1); - ExpectTimeBucketCount(kDurationNoSavedFramesFrozenHistogram, kDuration, 1); // Result. ExpectTotalSamples(kResultNoSavedFramesHistogram, 1); ExpectResultBucketCount( kResultNoSavedFramesHistogram, ContentToVisibleTimeReporter::TabSwitchResult::kSuccess, 1); - ExpectTotalSamples(kResultNoSavedFramesFrozenHistogram, 1); - ExpectResultBucketCount( - kResultNoSavedFramesFrozenHistogram, - ContentToVisibleTimeReporter::TabSwitchResult::kSuccess, 1); } // Same as TimeIsRecordedNoSavedFrame but with the destination frame unloaded. @@ -225,7 +163,7 @@ TEST_F(ContentToVisibleTimeReporterTest, TimeIsRecordedNoSavedFrameUnloaded) { auto callback = tab_switch_time_recorder_.TabWasShown( false /* has_saved_frames */, {start, /* destination_is_loaded */ false, - /* destination_is_frozen */ false, /* show_reason_tab_switching */ true, + /* show_reason_tab_switching */ true, /* show_reason_unoccluded */ false, /* show_reason_bfcache_restore */ false}, start); @@ -255,7 +193,7 @@ TEST_F(ContentToVisibleTimeReporterTest, PresentationFailureWithSavedFrames) { auto callback = tab_switch_time_recorder_.TabWasShown( true /* has_saved_frames */, {start, /* destination_is_loaded */ true, - /* destination_is_frozen */ false, /* show_reason_tab_switching */ true, + /* show_reason_tab_switching */ true, /* show_reason_unoccluded */ false, /* show_reason_bfcache_restore */ false}, start); @@ -277,24 +215,17 @@ TEST_F(ContentToVisibleTimeReporterTest, PresentationFailureNoSavedFrames) { auto callback = tab_switch_time_recorder_.TabWasShown( false /* has_saved_frames */, {start, /* destination_is_loaded */ true, - /* destination_is_frozen */ false, /* show_reason_tab_switching */ true, + /* show_reason_tab_switching */ true, /* show_reason_unoccluded */ false, /* show_reason_bfcache_restore */ false}, start); std::move(callback).Run(gfx::PresentationFeedback::Failure()); - ExpectHistogramsEmptyExcept( - {kResultNoSavedFramesHistogram, kResultNoSavedFramesNotFrozenHistogram}); - // Result (no duration is recorded on presentation failure). ExpectTotalSamples(kResultNoSavedFramesHistogram, 1); ExpectResultBucketCount( kResultNoSavedFramesHistogram, ContentToVisibleTimeReporter::TabSwitchResult::kPresentationFailure, 1); - ExpectTotalSamples(kResultNoSavedFramesNotFrozenHistogram, 1); - ExpectResultBucketCount( - kResultNoSavedFramesNotFrozenHistogram, - ContentToVisibleTimeReporter::TabSwitchResult::kPresentationFailure, 1); } // An incomplete tab switch is reported when no frame is shown before a tab is @@ -305,7 +236,7 @@ TEST_F(ContentToVisibleTimeReporterTest, auto callback1 = tab_switch_time_recorder_.TabWasShown( true /* has_saved_frames */, {start1, /* destination_is_loaded */ true, - /* destination_is_frozen */ false, /* show_reason_tab_switching */ true, + /* show_reason_tab_switching */ true, /* show_reason_unoccluded */ false, /* show_reason_bfcache_restore */ false}, start1); @@ -331,7 +262,7 @@ TEST_F(ContentToVisibleTimeReporterTest, auto callback2 = tab_switch_time_recorder_.TabWasShown( true /* has_saved_frames */, {start2, /* destination_is_loaded */ true, - /* destination_is_frozen */ false, /* show_reason_tab_switching */ true, + /* show_reason_tab_switching */ true, /* show_reason_unoccluded */ false, /* show_reason_bfcache_restore */ false}, start2); @@ -366,7 +297,7 @@ TEST_F(ContentToVisibleTimeReporterTest, HideBeforePresentFrameNoSavedFrames) { auto callback1 = tab_switch_time_recorder_.TabWasShown( false /* has_saved_frames */, {start1, /* destination_is_loaded */ true, - /* destination_is_frozen */ false, /* show_reason_tab_switching */ true, + /* show_reason_tab_switching */ true, /* show_reason_unoccluded */ false, /* show_reason_bfcache_restore */ false}, start1); @@ -374,34 +305,22 @@ TEST_F(ContentToVisibleTimeReporterTest, HideBeforePresentFrameNoSavedFrames) { task_environment_.FastForwardBy(kDuration); tab_switch_time_recorder_.TabWasHidden(); - ExpectHistogramsEmptyExcept( - {kIncompleteDurationNoSavedFramesHistogram, - kIncompleteDurationNoSavedFramesNotFrozenHistogram, - kResultNoSavedFramesHistogram, kResultNoSavedFramesNotFrozenHistogram}); - // Duration. ExpectTotalSamples(kIncompleteDurationNoSavedFramesHistogram, 1); ExpectTimeBucketCount(kIncompleteDurationNoSavedFramesHistogram, kDuration, 1); - ExpectTotalSamples(kIncompleteDurationNoSavedFramesNotFrozenHistogram, 1); - ExpectTimeBucketCount(kIncompleteDurationNoSavedFramesNotFrozenHistogram, - kDuration, 1); // Result. ExpectTotalSamples(kResultNoSavedFramesHistogram, 1); ExpectResultBucketCount( kResultNoSavedFramesHistogram, ContentToVisibleTimeReporter::TabSwitchResult::kIncomplete, 1); - ExpectTotalSamples(kResultNoSavedFramesNotFrozenHistogram, 1); - ExpectResultBucketCount( - kResultNoSavedFramesNotFrozenHistogram, - ContentToVisibleTimeReporter::TabSwitchResult::kIncomplete, 1); const auto start2 = base::TimeTicks::Now(); auto callback2 = tab_switch_time_recorder_.TabWasShown( false /* has_saved_frames */, {start2, /* destination_is_loaded */ true, - /* destination_is_frozen */ false, /* show_reason_tab_switching */ true, + /* show_reason_tab_switching */ true, /* show_reason_unoccluded */ false, /* show_reason_bfcache_restore */ false}, start2); @@ -411,26 +330,17 @@ TEST_F(ContentToVisibleTimeReporterTest, HideBeforePresentFrameNoSavedFrames) { end2, end2 - start2, gfx::PresentationFeedback::Flags::kHWCompletion); std::move(callback2).Run(presentation_feedback); - ExpectHistogramsEmptyExcept( - {kIncompleteDurationNoSavedFramesHistogram, - kIncompleteDurationNoSavedFramesNotFrozenHistogram, - kDurationNoSavedFramesHistogram, - kDurationNoSavedFramesNotFrozenHistogram, kResultNoSavedFramesHistogram, - kResultNoSavedFramesNotFrozenHistogram}); + ExpectHistogramsEmptyExcept({kIncompleteDurationNoSavedFramesHistogram, + kDurationNoSavedFramesHistogram, + kResultNoSavedFramesHistogram}); // Duration. ExpectTotalSamples(kIncompleteDurationNoSavedFramesHistogram, 1); ExpectTimeBucketCount(kIncompleteDurationNoSavedFramesHistogram, kDuration, 1); - ExpectTotalSamples(kIncompleteDurationNoSavedFramesNotFrozenHistogram, 1); - ExpectTimeBucketCount(kIncompleteDurationNoSavedFramesNotFrozenHistogram, - kDuration, 1); ExpectTotalSamples(kDurationNoSavedFramesHistogram, 1); ExpectTimeBucketCount(kDurationNoSavedFramesHistogram, kOtherDuration, 1); - ExpectTotalSamples(kDurationNoSavedFramesNotFrozenHistogram, 1); - ExpectTimeBucketCount(kDurationNoSavedFramesNotFrozenHistogram, - kOtherDuration, 1); // Result. ExpectTotalSamples(kResultNoSavedFramesHistogram, 2); @@ -440,13 +350,6 @@ TEST_F(ContentToVisibleTimeReporterTest, HideBeforePresentFrameNoSavedFrames) { ExpectResultBucketCount( kResultNoSavedFramesHistogram, ContentToVisibleTimeReporter::TabSwitchResult::kSuccess, 1); - ExpectTotalSamples(kResultNoSavedFramesNotFrozenHistogram, 2); - ExpectResultBucketCount( - kResultNoSavedFramesNotFrozenHistogram, - ContentToVisibleTimeReporter::TabSwitchResult::kIncomplete, 1); - ExpectResultBucketCount( - kResultNoSavedFramesNotFrozenHistogram, - ContentToVisibleTimeReporter::TabSwitchResult::kSuccess, 1); } // Time is properly recorded to histogram when we have unoccluded event. @@ -455,7 +358,6 @@ TEST_F(ContentToVisibleTimeReporterTest, UnoccludedTimeIsRecorded) { auto callback = tab_switch_time_recorder_.TabWasShown( true /* has_saved_frames */, {start, base::Optional<bool>() /* destination_is_loaded */, - base::Optional<bool>() /* destination_is_frozen */, /* show_reason_tab_switching */ false, /* show_reason_unoccluded */ true, /* show_reason_bfcache_restore */ false}, @@ -480,7 +382,7 @@ TEST_F(ContentToVisibleTimeReporterTest, auto callback = tab_switch_time_recorder_.TabWasShown( true /* has_saved_frames */, {start, /* destination_is_loaded */ true, - /* destination_is_frozen */ false, /* show_reason_tab_switching */ true, + /* show_reason_tab_switching */ true, /* show_reason_unoccluded */ true, /* show_reason_bfcache_restore */ false}, start); @@ -514,7 +416,6 @@ TEST_F(ContentToVisibleTimeReporterTest, BfcacheRestoreTimeIsRecorded) { auto callback = tab_switch_time_recorder_.TabWasShown( false /* has_saved_frames */, {start, base::Optional<bool>() /* destination_is_loaded */, - base::Optional<bool>() /* destination_is_frozen */, /* show_reason_tab_switching */ false, /* show_reason_unoccluded */ false, /* show_reason_bfcache_restore */ true}, @@ -540,7 +441,6 @@ class RecordContentToVisibleTimeRequestTest : public testing::Test { const std::string& msg) const { EXPECT_EQ(left.event_start_time, right.event_start_time) << msg; EXPECT_EQ(left.destination_is_loaded, right.destination_is_loaded); - EXPECT_EQ(left.destination_is_frozen, right.destination_is_frozen); EXPECT_EQ(left.show_reason_tab_switching, right.show_reason_tab_switching); EXPECT_EQ(left.show_reason_unoccluded, right.show_reason_unoccluded); EXPECT_EQ(left.show_reason_bfcache_restore, @@ -565,8 +465,6 @@ class RecordContentToVisibleTimeRequest_MergeRequestTest bool, bool, bool, - bool, - bool, bool>> { protected: RecordContentToVisibleTimeRequest GetRequest1() const { @@ -576,27 +474,21 @@ class RecordContentToVisibleTimeRequest_MergeRequestTest std::get<0>(GetParam()) ? base::Optional<bool>(true) : base::Optional<bool>() /* destination_is_loaded */, - std::get<1>(GetParam()) - ? base::Optional<bool>(true) - : base::Optional<bool>() /* destination_is_frozen */, - std::get<2>(GetParam()) /* show_reason_tab_switching */, - std::get<3>(GetParam()) /* show_reason_unoccluded */, - std::get<4>(GetParam()) /* show_reason_bfcache_restore */); + std::get<1>(GetParam()) /* show_reason_tab_switching */, + std::get<2>(GetParam()) /* show_reason_unoccluded */, + std::get<3>(GetParam()) /* show_reason_bfcache_restore */); } RecordContentToVisibleTimeRequest GetRequest2() const { const base::TimeTicks timestamp = RandomRequestTimeTicks(); return RecordContentToVisibleTimeRequest( timestamp, - std::get<5>(GetParam()) + std::get<4>(GetParam()) ? base::Optional<bool>(true) : base::Optional<bool>() /* destination_is_loaded */, - std::get<6>(GetParam()) - ? base::Optional<bool>(true) - : base::Optional<bool>() /* destination_is_frozen */, - std::get<7>(GetParam()) /* show_reason_tab_switching */, - std::get<8>(GetParam()) /* show_reason_unoccluded */, - std::get<9>(GetParam()) /* show_reason_bfcache_restore */); + std::get<5>(GetParam()) /* show_reason_tab_switching */, + std::get<6>(GetParam()) /* show_reason_unoccluded */, + std::get<7>(GetParam()) /* show_reason_bfcache_restore */); } bool isOptionalBoolTrue(const base::Optional<bool>& data) { @@ -633,11 +525,6 @@ TEST_P(RecordContentToVisibleTimeRequest_MergeRequestTest, DoMerge) { ? isOptionalBoolTrue(request1.destination_is_loaded) || isOptionalBoolTrue(request2.destination_is_loaded) : base::Optional<bool>(), - (request1.destination_is_frozen.has_value() || - request2.destination_is_frozen.has_value()) - ? isOptionalBoolTrue(request1.destination_is_frozen) || - isOptionalBoolTrue(request2.destination_is_frozen) - : base::Optional<bool>(), request1.show_reason_tab_switching || request2.show_reason_tab_switching, request1.show_reason_unoccluded || request2.show_reason_unoccluded, request1.show_reason_bfcache_restore || @@ -655,7 +542,5 @@ INSTANTIATE_TEST_SUITE_P(All, testing::Bool(), testing::Bool(), testing::Bool(), - testing::Bool(), - testing::Bool(), testing::Bool())); } // namespace content diff --git a/chromium/content/common/text_input_client_messages.h b/chromium/content/common/text_input_client_messages.h index 17fff0a6442..f10568fee28 100644 --- a/chromium/content/common/text_input_client_messages.h +++ b/chromium/content/common/text_input_client_messages.h @@ -13,13 +13,27 @@ #include "ui/gfx/range/range.h" #if defined(OS_MACOSX) -#include "content/common/mac/attributed_string_coder.h" +#include "content/common/mac/attributed_string_type_converters.h" +#include "ui/base/mojom/attributed_string.mojom.h" #endif #define IPC_MESSAGE_START TextInputClientMsgStart #undef IPC_MESSAGE_EXPORT #define IPC_MESSAGE_EXPORT CONTENT_EXPORT +#if defined(OS_MACOSX) +IPC_STRUCT_TRAITS_BEGIN(ui::mojom::FontAttribute) + IPC_STRUCT_TRAITS_MEMBER(font_name) + IPC_STRUCT_TRAITS_MEMBER(font_point_size) + IPC_STRUCT_TRAITS_MEMBER(effective_range) +IPC_STRUCT_TRAITS_END() + +IPC_STRUCT_TRAITS_BEGIN(ui::mojom::AttributedString) + IPC_STRUCT_TRAITS_MEMBER(string) + IPC_STRUCT_TRAITS_MEMBER(attributes) +IPC_STRUCT_TRAITS_END() +#endif + // Browser -> Renderer Messages //////////////////////////////////////////////// // These messages are sent from the browser to the renderer. Each one has a // corresponding reply message. @@ -42,12 +56,12 @@ IPC_MESSAGE_ROUTED1(TextInputClientMsg_StringAtPoint, gfx::Point) #if defined(OS_MACOSX) // Reply message for TextInputClientMsg_StringForRange. IPC_MESSAGE_ROUTED2(TextInputClientReplyMsg_GotStringForRange, - mac::AttributedStringCoder::EncodedString, + ui::mojom::AttributedString, gfx::Point) // Reply message for TextInputClientMsg_StringAtPoint IPC_MESSAGE_ROUTED2(TextInputClientReplyMsg_GotStringAtPoint, - mac::AttributedStringCoder::EncodedString, + ui::mojom::AttributedString, gfx::Point) #endif // defined(OS_MACOSX) diff --git a/chromium/content/common/text_input_state.cc b/chromium/content/common/text_input_state.cc deleted file mode 100644 index d7bd82f0de7..00000000000 --- a/chromium/content/common/text_input_state.cc +++ /dev/null @@ -1,15 +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 "content/common/text_input_state.h" - -namespace content { - -TextInputState::TextInputState() = default; - -TextInputState::TextInputState(const TextInputState& other) = default; - -TextInputState::~TextInputState() = default; - -} // namespace content diff --git a/chromium/content/common/text_input_state.h b/chromium/content/common/text_input_state.h deleted file mode 100644 index 11c2c3f1639..00000000000 --- a/chromium/content/common/text_input_state.h +++ /dev/null @@ -1,79 +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 CONTENT_COMMON_TEXT_INPUT_STATE_H_ -#define CONTENT_COMMON_TEXT_INPUT_STATE_H_ - -#include "base/optional.h" -#include "base/strings/string16.h" -#include "content/common/content_export.h" -#include "ui/base/ime/text_input_action.h" -#include "ui/base/ime/text_input_mode.h" -#include "ui/base/ime/text_input_type.h" -#include "ui/gfx/geometry/rect.h" - -namespace content { - -// The text input state information for handling IME on the browser side. The -// text input state information such as type, mode, etc. are used by the input -// method to handle IME (the usage is specific to each platform). -struct CONTENT_EXPORT TextInputState { - TextInputState(); - TextInputState(const TextInputState& other); - ~TextInputState(); - - // Type of the input field. - ui::TextInputType type = ui::TEXT_INPUT_TYPE_NONE; - - // The mode of input field. - ui::TextInputMode mode = ui::TEXT_INPUT_MODE_DEFAULT; - - // The action of the input field. - ui::TextInputAction action = ui::TextInputAction::kDefault; - - // The flags of input field (autocorrect, autocomplete, etc.) - int flags = 0; - - // The value of input field. - base::string16 value; - - // The cursor position of the current selection start, or the caret position - // if nothing is selected. - int selection_start = 0; - - // The cursor position of the current selection end, or the caret position if - // nothing is selected. - int selection_end = 0; - - // The start position of the current composition, or -1 if there is none. - int composition_start = -1; - - // The end position of the current composition, or -1 if there is none. - int composition_end = -1; - - // Whether or not inline composition can be performed for the current input. - bool can_compose_inline = true; - - // Whether or not the IME should be shown as a result of this update. Even if - // true, the IME will only be shown if the input is appropriate (e.g. not - // TEXT_INPUT_TYPE_NONE). - bool show_ime_if_needed = false; - - // Whether or not the IME should always be hidden as a result of this update. - bool always_hide_ime = false; - - // Whether or not this is a reply to a request from IME. - bool reply_to_request = false; - - // Store control and selection bounds of EditContext. - // These optionals will be nullopts if there isn't any active EditContext. - // For non EditContext scenarios, the bounds are returned via - // |GetCompositionCharacterBounds| - base::Optional<gfx::Rect> edit_context_control_bounds; - base::Optional<gfx::Rect> edit_context_selection_bounds; -}; - -} // namespace content - -#endif // CONTENT_COMMON_TEXT_INPUT_STATE_H_ diff --git a/chromium/content/common/unique_name_helper.cc b/chromium/content/common/unique_name_helper.cc index 1664eac9b8f..2e833638fdc 100644 --- a/chromium/content/common/unique_name_helper.cc +++ b/chromium/content/common/unique_name_helper.cc @@ -312,11 +312,11 @@ void UniqueNameHelper::PreserveStableUniqueNameForTesting() { } std::string UniqueNameHelper::ExtractStableNameForTesting( - const std::string& unique_name) { + base::StringPiece unique_name) { size_t i = unique_name.rfind(kDynamicFrameMarker); if (i == std::string::npos) - return unique_name; - return unique_name.substr(0, i); + return unique_name.as_string(); + return unique_name.substr(0, i).as_string(); } } // namespace content diff --git a/chromium/content/common/unique_name_helper.h b/chromium/content/common/unique_name_helper.h index 5df9f5229c7..725b67f89a2 100644 --- a/chromium/content/common/unique_name_helper.h +++ b/chromium/content/common/unique_name_helper.h @@ -191,8 +191,7 @@ class CONTENT_EXPORT UniqueNameHelper { // // Note: This method only works if |unique_name| was calculated after calling // PreserveStableUniqueNameForTesting (see above). - static std::string ExtractStableNameForTesting( - const std::string& unique_name); + static std::string ExtractStableNameForTesting(base::StringPiece unique_name); private: FrameAdapter* const frame_; diff --git a/chromium/content/common/url_schemes.cc b/chromium/content/common/url_schemes.cc index c00901a2a4e..dc37f121130 100644 --- a/chromium/content/common/url_schemes.cc +++ b/chromium/content/common/url_schemes.cc @@ -84,6 +84,7 @@ void RegisterContentSchemes() { url::AddNoAccessScheme(scheme.c_str()); schemes.cors_enabled_schemes.push_back(kChromeUIScheme); + schemes.cors_enabled_schemes.push_back(kChromeUIUntrustedScheme); for (auto& scheme : schemes.cors_enabled_schemes) url::AddCorsEnabledScheme(scheme.c_str()); diff --git a/chromium/content/common/view_messages.h b/chromium/content/common/view_messages.h index 85a8c7e9e28..19fa7ac2692 100644 --- a/chromium/content/common/view_messages.h +++ b/chromium/content/common/view_messages.h @@ -144,8 +144,6 @@ IPC_MESSAGE_ROUTED0(ViewHostMsg_RouteCloseEvent) IPC_MESSAGE_ROUTED1(ViewHostMsg_UpdateTargetURL, GURL) -IPC_MESSAGE_ROUTED0(ViewHostMsg_Focus) - #if BUILDFLAG(ENABLE_PLUGINS) // A renderer sends this to the browser process when it wants to access a PPAPI // broker. In contrast to FrameHostMsg_OpenChannelToPpapiBroker, this is called diff --git a/chromium/content/common/visual_properties.h b/chromium/content/common/visual_properties.h index 82ffc7e2a3d..058fbee62b5 100644 --- a/chromium/content/common/visual_properties.h +++ b/chromium/content/common/visual_properties.h @@ -122,6 +122,12 @@ struct CONTENT_EXPORT VisualProperties { // It needs to be shared with subframes. float page_scale_factor = 1.f; + // The logical segments of the root widget, in widget-relative DIPs. This + // property is set by the root RenderWidget in the renderer process, then + // propagated to child local frame roots via RenderFrameProxy/ + // CrossProcessFrameConnector. + std::vector<gfx::Rect> root_widget_window_segments; + // Indicates whether a pinch gesture is currently active. Originates in the // main frame's renderer, and needs to be shared with subframes. bool is_pinch_gesture_active = false; diff --git a/chromium/content/common/widget.mojom b/chromium/content/common/widget.mojom deleted file mode 100644 index 6a2ed269a28..00000000000 --- a/chromium/content/common/widget.mojom +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module content.mojom; - -import "content/common/input/input_handler.mojom"; - -// Interface exposed by the renderer for Widgets. -interface Widget { - // Setup the input channel for this widget. If the widget is a frame, - // then it will have a FrameInputHandler and the WidgetInputHandler should - // be obtained using that interface instead. The frame's FrameInputHandler - // uses associated receivers to ensure serial ordering with the frame - // input messages. - SetupWidgetInputHandler(pending_receiver<WidgetInputHandler> request, - pending_remote<WidgetInputHandlerHost> host); -}; diff --git a/chromium/content/common/widget_messages.h b/chromium/content/common/widget_messages.h index ae6969230d7..676ce8bd627 100644 --- a/chromium/content/common/widget_messages.h +++ b/chromium/content/common/widget_messages.h @@ -13,7 +13,6 @@ #include "content/common/common_param_traits_macros.h" #include "content/common/content_param_traits.h" #include "content/common/content_to_visible_time_reporter.h" -#include "content/common/text_input_state.h" #include "content/common/visual_properties.h" #include "content/public/common/common_param_traits.h" #include "ipc/ipc_message_macros.h" @@ -57,39 +56,6 @@ IPC_STRUCT_TRAITS_BEGIN(blink::WebDeviceEmulationParams) IPC_STRUCT_TRAITS_MEMBER(screen_orientation_type) IPC_STRUCT_TRAITS_END() -IPC_ENUM_TRAITS_MAX_VALUE(base::i18n::TextDirection, - base::i18n::TEXT_DIRECTION_MAX) - -IPC_STRUCT_BEGIN(WidgetHostMsg_SelectionBounds_Params) - IPC_STRUCT_MEMBER(gfx::Rect, anchor_rect) - IPC_STRUCT_MEMBER(base::i18n::TextDirection, anchor_dir) - IPC_STRUCT_MEMBER(gfx::Rect, focus_rect) - IPC_STRUCT_MEMBER(base::i18n::TextDirection, focus_dir) - IPC_STRUCT_MEMBER(bool, is_anchor_first) -IPC_STRUCT_END() - -// Traits for TextInputState. -IPC_ENUM_TRAITS_MAX_VALUE(ui::TextInputAction, ui::TextInputAction::kMaxValue) -IPC_ENUM_TRAITS_MAX_VALUE(ui::TextInputMode, ui::TEXT_INPUT_MODE_MAX) - -IPC_STRUCT_TRAITS_BEGIN(content::TextInputState) - IPC_STRUCT_TRAITS_MEMBER(type) - IPC_STRUCT_TRAITS_MEMBER(mode) - IPC_STRUCT_TRAITS_MEMBER(action) - IPC_STRUCT_TRAITS_MEMBER(flags) - IPC_STRUCT_TRAITS_MEMBER(value) - IPC_STRUCT_TRAITS_MEMBER(selection_start) - IPC_STRUCT_TRAITS_MEMBER(selection_end) - IPC_STRUCT_TRAITS_MEMBER(composition_start) - IPC_STRUCT_TRAITS_MEMBER(composition_end) - IPC_STRUCT_TRAITS_MEMBER(can_compose_inline) - IPC_STRUCT_TRAITS_MEMBER(show_ime_if_needed) - IPC_STRUCT_TRAITS_MEMBER(always_hide_ime) - IPC_STRUCT_TRAITS_MEMBER(reply_to_request) - IPC_STRUCT_TRAITS_MEMBER(edit_context_control_bounds) - IPC_STRUCT_TRAITS_MEMBER(edit_context_selection_bounds) -IPC_STRUCT_TRAITS_END() - // // Browser -> Renderer Messages. // @@ -126,10 +92,6 @@ IPC_MESSAGE_ROUTED3(WidgetMsg_WasShown, // accordingly, etc.). IPC_MESSAGE_ROUTED1(WidgetMsg_SetActive, bool /* active */) -// Changes the text direction of the currently selected input field (if any). -IPC_MESSAGE_ROUTED1(WidgetMsg_SetTextDirection, - base::i18n::TextDirection /* direction */) - // Reply to WidgetHostMsg_RequestSetBounds, WidgetHostMsg_ShowWidget, and // FrameHostMsg_ShowCreatedWindow, to inform the renderer that the browser has // processed the bounds-setting. The browser may have ignored the new bounds, @@ -150,11 +112,6 @@ IPC_MESSAGE_ROUTED2(WidgetMsg_UpdateScreenRects, gfx::Rect /* widget_screen_rect */, gfx::Rect /* window_screen_rect */) -// Sent by the browser to ask the renderer to redraw. Robust to events that can -// happen in renderer (abortion of the commit or draw, loss of output surface -// etc.). -IPC_MESSAGE_ROUTED1(WidgetMsg_ForceRedraw, int /* snapshot_id */) - // Sent by a parent frame to notify its child about the state of the child's // intersection with the parent's viewport, primarily for use by the // IntersectionObserver API. Also see FrameHostMsg_UpdateViewportIntersection. @@ -177,34 +134,15 @@ IPC_MESSAGE_ROUTED1(WidgetMsg_WaitForNextFrameForTests, // message to close the widget. IPC_MESSAGE_ROUTED0(WidgetHostMsg_Close) -// Notification that the selection bounds have changed. -IPC_MESSAGE_ROUTED1(WidgetHostMsg_SelectionBoundsChanged, - WidgetHostMsg_SelectionBounds_Params) - // Sent in response to a WidgetMsg_UpdateScreenRects so that the renderer can // throttle these messages. IPC_MESSAGE_ROUTED0(WidgetHostMsg_UpdateScreenRects_ACK) -// Send the tooltip text for the current mouse position to the browser. -IPC_MESSAGE_ROUTED2(WidgetHostMsg_SetTooltipText, - base::string16 /* tooltip text string */, - base::i18n::TextDirection /* text direction hint */) - -// Notifies the browser if the text input state has changed. Primarily useful -// for IME as they need to know of all changes to update their interpretation -// of the characters that have been input. -IPC_MESSAGE_ROUTED1(WidgetHostMsg_TextInputStateChanged, - content::TextInputState /* text_input_state */) - // Sent by the renderer process to request that the browser change the bounds of // the widget. This corresponds to the window.resizeTo() and window.moveTo() // APIs, and the browser may ignore this message. IPC_MESSAGE_ROUTED1(WidgetHostMsg_RequestSetBounds, gfx::Rect /* bounds */) -// Sent by the renderer process in response to an earlier WidgetMsg_ForceRedraw -// message. The reply includes the snapshot-id from the request. -IPC_MESSAGE_ROUTED1(WidgetHostMsg_ForceRedrawComplete, int /* snapshot_id */) - // Sends a set of queued messages that were being held until the next // CompositorFrame is being submitted from the renderer. These messages are // sent before the OnRenderFrameMetadataChanged message is sent (via mojo) and @@ -221,8 +159,4 @@ IPC_MESSAGE_CONTROL1(WidgetHostMsg_Close_ACK, int /* old_route_id */) // Sent in reply to WidgetMsg_WaitForNextFrameForTests. IPC_MESSAGE_ROUTED0(WidgetHostMsg_WaitForNextFrameForTests_ACK) -// Sent once a paint happens after the first non empty layout. In other words, -// after the frame widget has painted something. -IPC_MESSAGE_ROUTED0(WidgetHostMsg_DidFirstVisuallyNonEmptyPaint) - #endif // CONTENT_COMMON_WIDGET_MESSAGES_H_ diff --git a/chromium/content/common/zygote/OWNERS b/chromium/content/common/zygote/OWNERS new file mode 100644 index 00000000000..eb4b322bdf5 --- /dev/null +++ b/chromium/content/common/zygote/OWNERS @@ -0,0 +1,4 @@ +file://content/zygote/OWNERS + +# TEAM: security-dev@chromium.org +# COMPONENT: Internals>Sandbox diff --git a/chromium/content/common/zygote/sandbox_support_linux.cc b/chromium/content/common/zygote/sandbox_support_linux.cc new file mode 100644 index 00000000000..dabc1009f72 --- /dev/null +++ b/chromium/content/common/zygote/sandbox_support_linux.cc @@ -0,0 +1,39 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/public/common/zygote/sandbox_support_linux.h" + +#include "base/pickle.h" +#include "base/posix/global_descriptors.h" +#include "base/posix/unix_domain_socket.h" +#include "build/build_config.h" +#include "services/service_manager/embedder/descriptors.h" +#include "services/service_manager/sandbox/linux/sandbox_linux.h" + +namespace content { + +#if !defined(OS_NACL_NONSFI) +int SharedMemoryIPCSupport::MakeSharedMemorySegment(size_t length, + bool executable) { + base::Pickle request; + request.WriteInt( + service_manager::SandboxLinux::METHOD_MAKE_SHARED_MEMORY_SEGMENT); + request.WriteUInt32(length); + request.WriteBool(executable); + uint8_t reply_buf[10]; + int result_fd; + ssize_t result = base::UnixDomainSocket::SendRecvMsg( + GetSandboxFD(), reply_buf, sizeof(reply_buf), &result_fd, request); + if (result == -1) + return -1; + return result_fd; +} +#endif + +int GetSandboxFD() { + return service_manager::kSandboxIPCChannel + + base::GlobalDescriptors::kBaseDescriptor; +} + +} // namespace content diff --git a/chromium/content/common/zygote/send_zygote_child_ping_linux.cc b/chromium/content/common/zygote/send_zygote_child_ping_linux.cc new file mode 100644 index 00000000000..ff07250fb72 --- /dev/null +++ b/chromium/content/common/zygote/send_zygote_child_ping_linux.cc @@ -0,0 +1,20 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/public/common/zygote/send_zygote_child_ping_linux.h" + +#include <vector> + +#include "base/posix/unix_domain_socket.h" +#include "content/common/zygote/zygote_commands_linux.h" + +namespace content { + +bool SendZygoteChildPing(int fd) { + return base::UnixDomainSocket::SendMsg(fd, kZygoteChildPingMessage, + sizeof(kZygoteChildPingMessage), + std::vector<int>()); +} + +} // namespace content diff --git a/chromium/content/common/zygote/zygote_commands_linux.h b/chromium/content/common/zygote/zygote_commands_linux.h new file mode 100644 index 00000000000..272b5b57871 --- /dev/null +++ b/chromium/content/common/zygote/zygote_commands_linux.h @@ -0,0 +1,54 @@ +// Copyright (c) 2012 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 CONTENT_COMMON_ZYGOTE_ZYGOTE_COMMANDS_LINUX_H_ +#define CONTENT_COMMON_ZYGOTE_ZYGOTE_COMMANDS_LINUX_H_ + +#include <stddef.h> + +#include "base/posix/global_descriptors.h" + +namespace content { + +// Contents of the initial message sent from the zygote to the browser right +// after it starts. +static const char kZygoteBootMessage[] = "ZYGOTE_BOOT"; + +// Contents of the initial message sent from the zygote to the browser when it +// is ready to go. +static const char kZygoteHelloMessage[] = "ZYGOTE_OK"; + +// Message sent by zygote children to the browser so the browser can discover +// the sending child's process ID. +static const char kZygoteChildPingMessage[] = "CHILD_PING"; + +// Maximum allowable length for messages sent to the zygote. +const size_t kZygoteMaxMessageLength = 12288; + +// File descriptors initialized by the Zygote Host +const int kZygoteSocketPairFd = base::GlobalDescriptors::kBaseDescriptor; + +// These are the command codes used on the wire between the browser and the +// zygote. +enum { + // Fork off a new renderer. + kZygoteCommandFork = 0, + + // Reap a renderer child. + kZygoteCommandReap = 1, + + // Check what happened to a child process. + kZygoteCommandGetTerminationStatus = 2, + + // Read a bitmask of kSandboxLinux* + kZygoteCommandGetSandboxStatus = 3, + + // Not a real zygote command, but a subcommand used during the zygote fork + // protocol. Sends the child's PID as seen from the browser process. + kZygoteCommandForkRealPID = 4 +}; + +} // namespace content + +#endif // CONTENT_COMMON_ZYGOTE_ZYGOTE_COMMANDS_LINUX_H_ diff --git a/chromium/content/common/zygote/zygote_communication_linux.cc b/chromium/content/common/zygote/zygote_communication_linux.cc new file mode 100644 index 00000000000..4ae0b9eebb3 --- /dev/null +++ b/chromium/content/common/zygote/zygote_communication_linux.cc @@ -0,0 +1,323 @@ +// 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 "content/common/zygote/zygote_communication_linux.h" + +#include <string.h> +#include <sys/socket.h> + +#include "base/base_switches.h" +#include "base/command_line.h" +#include "base/i18n/unicodestring.h" +#include "base/logging.h" +#include "base/metrics/histogram_functions.h" +#include "base/path_service.h" +#include "base/pickle.h" +#include "base/posix/eintr_wrapper.h" +#include "base/posix/unix_domain_socket.h" +#include "base/stl_util.h" +#include "content/common/zygote/zygote_commands_linux.h" +#include "content/public/common/content_switches.h" +#include "services/service_manager/embedder/result_codes.h" +#include "services/service_manager/embedder/switches.h" +#include "services/service_manager/sandbox/switches.h" +#include "third_party/icu/source/i18n/unicode/timezone.h" + +namespace content { + +ZygoteCommunication::ZygoteCommunication(ZygoteType type) + : type_(type), + pid_(), + sandbox_status_(0), + have_read_sandbox_status_word_(false), + init_(false) {} + +ZygoteCommunication::~ZygoteCommunication() {} + +bool ZygoteCommunication::SendMessage(const base::Pickle& data, + const std::vector<int>* fds) { + DCHECK(control_fd_.is_valid()); + CHECK(data.size() <= kZygoteMaxMessageLength) + << "Trying to send too-large message to zygote (sending " << data.size() + << " bytes, max is " << kZygoteMaxMessageLength << ")"; + CHECK(!fds || fds->size() <= base::UnixDomainSocket::kMaxFileDescriptors) + << "Trying to send message with too many file descriptors to zygote " + << "(sending " << fds->size() << ", max is " + << base::UnixDomainSocket::kMaxFileDescriptors << ")"; + + return base::UnixDomainSocket::SendMsg(control_fd_.get(), data.data(), + data.size(), + fds ? *fds : std::vector<int>()); +} + +ssize_t ZygoteCommunication::ReadSandboxStatus() { + DCHECK(control_fd_.is_valid()); + // At startup we send a kZygoteCommandGetSandboxStatus request to the zygote, + // but don't wait for the reply. Thus, the first time that we read from the + // zygote, we get the reply to that request. + ssize_t bytes_read = HANDLE_EINTR( + read(control_fd_.get(), &sandbox_status_, sizeof(sandbox_status_))); + if (bytes_read != sizeof(sandbox_status_)) { + return -1; + } + return bytes_read; +} + +ssize_t ZygoteCommunication::ReadReply(void* buf, size_t buf_len) { + DCHECK(control_fd_.is_valid()); + if (!have_read_sandbox_status_word_) { + if (ReadSandboxStatus() == -1) { + return -1; + } + have_read_sandbox_status_word_ = true; + base::UmaHistogramSparse("Linux.SandboxStatus", sandbox_status_); + } + + return HANDLE_EINTR(read(control_fd_.get(), buf, buf_len)); +} + +pid_t ZygoteCommunication::ForkRequest( + const std::vector<std::string>& argv, + const base::FileHandleMappingVector& mapping, + const std::string& process_type) { + DCHECK(init_); + + base::Pickle pickle; + int raw_socks[2]; + PCHECK(0 == socketpair(AF_UNIX, SOCK_SEQPACKET, 0, raw_socks)); + base::ScopedFD my_sock(raw_socks[0]); + base::ScopedFD peer_sock(raw_socks[1]); + CHECK(base::UnixDomainSocket::EnableReceiveProcessId(my_sock.get())); + + pickle.WriteInt(kZygoteCommandFork); + pickle.WriteString(process_type); + pickle.WriteInt(argv.size()); + for (std::vector<std::string>::const_iterator i = argv.begin(); + i != argv.end(); ++i) + pickle.WriteString(*i); + std::unique_ptr<icu::TimeZone> timezone(icu::TimeZone::createDefault()); + icu::UnicodeString timezone_id; + pickle.WriteString16( + base::i18n::UnicodeStringToString16(timezone->getID(timezone_id))); + + // Fork requests contain one file descriptor for the PID oracle, and one + // more for each file descriptor mapping for the child process. + const size_t num_fds_to_send = 1 + mapping.size(); + pickle.WriteInt(num_fds_to_send); + + std::vector<int> fds; + + // First FD to send is peer_sock. + // TODO(morrita): Ideally, this should be part of the mapping so that + // PosixFileDescriptorInfo can manages its lifetime. + fds.push_back(peer_sock.get()); + + // The rest come from mapping. + for (const auto& item : mapping) { + fds.push_back(item.first); + pickle.WriteUInt32(item.second); + } + + // Sanity check that we've populated |fds| correctly. + DCHECK_EQ(num_fds_to_send, fds.size()); + + pid_t pid; + { + base::AutoLock lock(control_lock_); + if (!SendMessage(pickle, &fds)) + return base::kNullProcessHandle; + peer_sock.reset(); + + { + char buf[sizeof(kZygoteChildPingMessage) + 1]; + std::vector<base::ScopedFD> recv_fds; + base::ProcessId real_pid; + + ssize_t n = base::UnixDomainSocket::RecvMsgWithPid( + my_sock.get(), buf, sizeof(buf), &recv_fds, &real_pid); + if (n != sizeof(kZygoteChildPingMessage) || + 0 != memcmp(buf, kZygoteChildPingMessage, + sizeof(kZygoteChildPingMessage))) { + // Zygote children should still be trustworthy when they're supposed to + // ping us, so something's broken if we don't receive a valid ping. + LOG(ERROR) << "Did not receive ping from zygote child"; + NOTREACHED(); + real_pid = -1; + } + my_sock.reset(); + + // Always send PID back to zygote. + base::Pickle pid_pickle; + pid_pickle.WriteInt(kZygoteCommandForkRealPID); + pid_pickle.WriteInt(real_pid); + if (!SendMessage(pid_pickle, nullptr)) + return base::kNullProcessHandle; + } + + // Read the reply, which pickles the PID and an optional UMA enumeration. + static const unsigned kMaxReplyLength = 2048; + char buf[kMaxReplyLength]; + const ssize_t len = ReadReply(buf, sizeof(buf)); + + base::Pickle reply_pickle(buf, len); + base::PickleIterator iter(reply_pickle); + if (len <= 0 || !iter.ReadInt(&pid)) + return base::kNullProcessHandle; + + // If there is a nonempty UMA name string, then there is a UMA + // enumeration to record. + std::string uma_name; + int uma_sample; + int uma_boundary_value; + if (iter.ReadString(&uma_name) && !uma_name.empty() && + iter.ReadInt(&uma_sample) && iter.ReadInt(&uma_boundary_value)) { + // We cannot use the UMA_HISTOGRAM_ENUMERATION macro here, + // because that's only for when the name is the same every time. + // Here we're using whatever name we got from the other side. + // But since it's likely that the same one will be used repeatedly + // (even though it's not guaranteed), we cache it here. + static base::HistogramBase* uma_histogram; + if (!uma_histogram || uma_histogram->histogram_name() != uma_name) { + uma_histogram = base::LinearHistogram::FactoryGet( + uma_name, 1, uma_boundary_value, uma_boundary_value + 1, + base::HistogramBase::kUmaTargetedHistogramFlag); + } + uma_histogram->Add(uma_sample); + } + + if (pid <= 0) + return base::kNullProcessHandle; + } + + ZygoteChildBorn(pid); + return pid; +} + +void ZygoteCommunication::EnsureProcessTerminated(pid_t process) { + DCHECK(init_); + base::Pickle pickle; + + pickle.WriteInt(kZygoteCommandReap); + pickle.WriteInt(process); + if (!SendMessage(pickle, nullptr)) + LOG(ERROR) << "Failed to send Reap message to zygote"; + ZygoteChildDied(process); +} + +void ZygoteCommunication::ZygoteChildBorn(pid_t process) { + base::AutoLock lock(child_tracking_lock_); + bool new_element_inserted = + list_of_running_zygote_children_.insert(process).second; + DCHECK(new_element_inserted); +} + +void ZygoteCommunication::ZygoteChildDied(pid_t process) { + base::AutoLock lock(child_tracking_lock_); + size_t num_erased = list_of_running_zygote_children_.erase(process); + DCHECK_EQ(1U, num_erased); +} + +void ZygoteCommunication::Init( + base::OnceCallback<pid_t(base::CommandLine*, base::ScopedFD*)> launcher) { + CHECK(!init_); + + base::FilePath chrome_path; + CHECK(base::PathService::Get(base::FILE_EXE, &chrome_path)); + + base::CommandLine cmd_line(chrome_path); + cmd_line.AppendSwitchASCII(service_manager::switches::kProcessType, + service_manager::switches::kZygoteProcess); + + if (type_ == ZygoteType::kUnsandboxed) + cmd_line.AppendSwitch(service_manager::switches::kNoZygoteSandbox); + + const base::CommandLine& browser_command_line = + *base::CommandLine::ForCurrentProcess(); + if (browser_command_line.HasSwitch(switches::kZygoteCmdPrefix)) { + cmd_line.PrependWrapper( + browser_command_line.GetSwitchValueNative(switches::kZygoteCmdPrefix)); + } + // Append any switches from the service manager that need to be forwarded on + // to the zygote/renderers. + static const char* const kForwardSwitches[] = { + service_manager::switches::kAllowSandboxDebugging, + service_manager::switches::kDisableInProcessStackTraces, + service_manager::switches::kDisableSeccompFilterSandbox, + service_manager::switches::kNoSandbox, + }; + cmd_line.CopySwitchesFrom(browser_command_line, kForwardSwitches, + base::size(kForwardSwitches)); + + pid_ = std::move(launcher).Run(&cmd_line, &control_fd_); + + base::Pickle pickle; + pickle.WriteInt(kZygoteCommandGetSandboxStatus); + if (!SendMessage(pickle, nullptr)) + LOG(FATAL) << "Cannot communicate with zygote"; + + init_ = true; +} + +base::TerminationStatus ZygoteCommunication::GetTerminationStatus( + base::ProcessHandle handle, + bool known_dead, + int* exit_code) { + DCHECK(init_); + base::Pickle pickle; + pickle.WriteInt(kZygoteCommandGetTerminationStatus); + pickle.WriteBool(known_dead); + pickle.WriteInt(handle); + + static const unsigned kMaxMessageLength = 128; + char buf[kMaxMessageLength]; + ssize_t len; + { + base::AutoLock lock(control_lock_); + if (!SendMessage(pickle, nullptr)) + LOG(ERROR) << "Failed to send GetTerminationStatus message to zygote"; + len = ReadReply(buf, sizeof(buf)); + } + + // Set this now to handle the error cases. + if (exit_code) + *exit_code = service_manager::RESULT_CODE_NORMAL_EXIT; + int status = base::TERMINATION_STATUS_NORMAL_TERMINATION; + + if (len == -1) { + PLOG(WARNING) << "Error reading message from zygote"; + } else if (len == 0) { + LOG(WARNING) << "Socket closed prematurely."; + } else { + base::Pickle read_pickle(buf, len); + int tmp_status, tmp_exit_code; + base::PickleIterator iter(read_pickle); + if (!iter.ReadInt(&tmp_status) || !iter.ReadInt(&tmp_exit_code)) { + LOG(WARNING) + << "Error parsing GetTerminationStatus response from zygote."; + } else { + if (exit_code) + *exit_code = tmp_exit_code; + status = tmp_status; + } + } + + if (status != base::TERMINATION_STATUS_STILL_RUNNING) { + ZygoteChildDied(handle); + } + return static_cast<base::TerminationStatus>(status); +} + +int ZygoteCommunication::GetSandboxStatus() { + if (have_read_sandbox_status_word_) { + return sandbox_status_; + } + if (ReadSandboxStatus() == -1) { + return 0; + } + have_read_sandbox_status_word_ = true; + base::UmaHistogramSparse("Linux.SandboxStatus", sandbox_status_); + return sandbox_status_; +} + +} // namespace content diff --git a/chromium/content/common/zygote/zygote_communication_linux.h b/chromium/content/common/zygote/zygote_communication_linux.h new file mode 100644 index 00000000000..37d8ec3e212 --- /dev/null +++ b/chromium/content/common/zygote/zygote_communication_linux.h @@ -0,0 +1,107 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_COMMON_ZYGOTE_ZYGOTE_COMMUNICATION_LINUX_H_ +#define CONTENT_COMMON_ZYGOTE_ZYGOTE_COMMUNICATION_LINUX_H_ + +#include <memory> +#include <set> +#include <string> +#include <vector> + +#include <sys/types.h> + +#include "base/callback.h" +#include "base/files/scoped_file.h" +#include "base/process/kill.h" +#include "base/process/launch.h" +#include "base/process/process_handle.h" +#include "base/synchronization/lock.h" +#include "content/common/content_export.h" + +namespace base { +class Pickle; +} // namespace base + +namespace content { + +// Handles interprocess communication with the Linux zygote process. The zygote +// does not use standard Chrome IPC or mojo, see: +// https://chromium.googlesource.com/chromium/src/+/master/docs/linux/sandbox_ipc.md +class CONTENT_EXPORT ZygoteCommunication { + public: + enum class ZygoteType { kSandboxed, kUnsandboxed }; + explicit ZygoteCommunication(ZygoteType type); + ~ZygoteCommunication(); + + void Init( + base::OnceCallback<pid_t(base::CommandLine*, base::ScopedFD*)> launcher); + + // Tries to start a process of type indicated by process_type. + // Returns its pid on success, otherwise base::kNullProcessHandle; + pid_t ForkRequest(const std::vector<std::string>& command_line, + const base::FileHandleMappingVector& mapping, + const std::string& process_type); + + void EnsureProcessTerminated(pid_t process); + + // Should be called every time a Zygote child died. + void ZygoteChildDied(pid_t process); + + // Get the termination status (and, optionally, the exit code) of + // the process. |exit_code| is set to the exit code of the child + // process. (|exit_code| may be NULL.) + // Unfortunately the Zygote can not accurately figure out if a process + // is already dead without waiting synchronously for it. + // |known_dead| should be set to true when we already know that the process + // is dead. When |known_dead| is false, processes could be seen as + // still running, even when they're not. When |known_dead| is true, the + // process will be SIGKILL-ed first (which should have no effect if it was + // really dead). This is to prevent a waiting waitpid() from blocking in + // a single-threaded Zygote. See https://crbug.com/157458. + base::TerminationStatus GetTerminationStatus(base::ProcessHandle handle, + bool known_dead, + int* exit_code); + + // Returns the sandbox status of this zygote. + int GetSandboxStatus(); + + private: + // Should be called every time a Zygote child is born. + void ZygoteChildBorn(pid_t process); + + // Read the reply from the zygote. + ssize_t ReadReply(void* buf, size_t buf_len); + + // Sends |data| to the zygote via |control_fd_|. If |fds| is non-NULL, the + // included file descriptors will also be passed. The caller is responsible + // for acquiring |control_lock_|. + bool SendMessage(const base::Pickle& data, const std::vector<int>* fds); + + // Get the sandbox status from the zygote. + ssize_t ReadSandboxStatus(); + + // Indicates whether the Zygote starts unsandboxed or not. + const ZygoteType type_; + + base::ScopedFD control_fd_; // the socket to the zygote. + // A lock protecting all communication with the zygote. This lock must be + // acquired before sending a command and released after the result has been + // received. + base::Lock control_lock_; + // The pid of the zygote. + pid_t pid_; + // The list of running zygote children. + std::set<pid_t> list_of_running_zygote_children_; + // The lock to guard the list of running zygote children. + base::Lock child_tracking_lock_; + int sandbox_status_; + bool have_read_sandbox_status_word_; + // Set to true when the zygote is initialized successfully. + bool init_; +}; + +} // namespace content + +#endif // CONTENT_COMMON_ZYGOTE_ZYGOTE_COMMUNICATION_LINUX_H_ diff --git a/chromium/content/common/zygote/zygote_handle_impl_linux.h b/chromium/content/common/zygote/zygote_handle_impl_linux.h new file mode 100644 index 00000000000..6a530828514 --- /dev/null +++ b/chromium/content/common/zygote/zygote_handle_impl_linux.h @@ -0,0 +1,31 @@ +// Copyright 2020 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 CONTENT_COMMON_ZYGOTE_ZYGOTE_HANDLE_IMPL_LINUX_H_ +#define CONTENT_COMMON_ZYGOTE_ZYGOTE_HANDLE_IMPL_LINUX_H_ + +#include "content/public/common/zygote/zygote_handle.h" + +namespace content { + +using ZygoteLaunchCallback = + base::OnceCallback<pid_t(base::CommandLine*, base::ScopedFD*)>; + +// Allocates and initializes the global generic zygote process, and returns the +// ZygoteHandle used to communicate with it. |launch_cb| is a callback that +// should actually launch the process, after adding additional command line +// switches to the ones composed by this function. It returns the pid created, +// and provides a control fd for it. +CONTENT_EXPORT +ZygoteHandle CreateGenericZygote(ZygoteLaunchCallback launch_cb); + +// Similar to the above but for creating an unsandboxed zygote from which +// processes which need non-generic sandboxes can be derived. +CONTENT_EXPORT +ZygoteHandle CreateUnsandboxedZygote(ZygoteLaunchCallback launch_cb); +CONTENT_EXPORT ZygoteHandle GetUnsandboxedZygote(); + +} // namespace content + +#endif // CONTENT_COMMON_ZYGOTE_ZYGOTE_HANDLE_IMPL_LINUX_H_ diff --git a/chromium/content/common/zygote/zygote_handle_linux.cc b/chromium/content/common/zygote/zygote_handle_linux.cc new file mode 100644 index 00000000000..dd0a0acaa65 --- /dev/null +++ b/chromium/content/common/zygote/zygote_handle_linux.cc @@ -0,0 +1,45 @@ +// 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 "content/public/common/zygote/zygote_handle.h" + +#include "content/common/zygote/zygote_communication_linux.h" +#include "content/common/zygote/zygote_handle_impl_linux.h" + +namespace content { +namespace { + +// Intentionally leaked. +ZygoteHandle g_generic_zygote = nullptr; +ZygoteHandle g_unsandboxed_zygote = nullptr; + +} // namespace + +ZygoteHandle CreateGenericZygote(ZygoteLaunchCallback launch_cb) { + CHECK(!g_generic_zygote); + g_generic_zygote = + new ZygoteCommunication(ZygoteCommunication::ZygoteType::kSandboxed); + g_generic_zygote->Init(std::move(launch_cb)); + return g_generic_zygote; +} + +ZygoteHandle GetGenericZygote() { + CHECK(g_generic_zygote); + return g_generic_zygote; +} + +ZygoteHandle CreateUnsandboxedZygote(ZygoteLaunchCallback launch_cb) { + CHECK(!g_unsandboxed_zygote); + g_unsandboxed_zygote = + new ZygoteCommunication(ZygoteCommunication::ZygoteType::kUnsandboxed); + g_unsandboxed_zygote->Init(std::move(launch_cb)); + return g_unsandboxed_zygote; +} + +ZygoteHandle GetUnsandboxedZygote() { + CHECK(g_unsandboxed_zygote); + return g_unsandboxed_zygote; +} + +} // namespace content |