diff --git a/DEPS b/DEPS index 3f4bda79..a6b6d9b3 100644 --- a/DEPS +++ b/DEPS
@@ -43,7 +43,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': 'c66911aa4bec771552e1a32f1ca558509b15d677', + 'v8_revision': 'ec21f831870e79aef0417eb1718eefcef9456bff', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other.
diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.cc b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.cc index d9f573b6..56eceb88 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.cc +++ b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.cc
@@ -378,7 +378,6 @@ client(), base::MakeUnique<DeviceStatusCollector>( local_state_, chromeos::system::StatisticsProvider::GetInstance(), - DeviceStatusCollector::LocationUpdateRequester(), DeviceStatusCollector::VolumeInfoFetcher(), DeviceStatusCollector::CPUStatisticsFetcher(), DeviceStatusCollector::CPUTempFetcher()),
diff --git a/chrome/browser/chromeos/policy/device_status_collector.cc b/chrome/browser/chromeos/policy/device_status_collector.cc index 03e207b..616aa25 100644 --- a/chrome/browser/chromeos/policy/device_status_collector.cc +++ b/chrome/browser/chromeos/policy/device_status_collector.cc
@@ -18,16 +18,17 @@ #include "base/files/file_enumerator.h" #include "base/files/file_util.h" #include "base/format_macros.h" -#include "base/location.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" +#include "base/memory/ref_counted.h" #include "base/posix/eintr_wrapper.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/sys_info.h" #include "base/task_runner_util.h" +#include "base/threading/sequenced_task_runner_handle.h" #include "base/values.h" #include "base/version.h" #include "chrome/browser/browser_process.h" @@ -56,6 +57,7 @@ #include "components/user_manager/user_manager.h" #include "components/user_manager/user_type.h" #include "components/version_info/version_info.h" +#include "content/public/browser/browser_thread.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/extension.h" #include "storage/browser/fileapi/external_mount_points.h" @@ -76,21 +78,8 @@ // How many days in the future to store active periods for. const unsigned int kMaxStoredFutureActivityDays = 2; -// How often, in seconds, to update the device location. -const unsigned int kGeolocationPollIntervalSeconds = 30 * 60; - -// How often, in seconds, to sample the hardware state. -const unsigned int kHardwareStatusSampleIntervalSeconds = 120; - -// Keys for the geolocation status dictionary in local state. -const char kLatitude[] = "latitude"; -const char kLongitude[] = "longitude"; -const char kAltitude[] = "altitude"; -const char kAccuracy[] = "accuracy"; -const char kAltitudeAccuracy[] = "altitude_accuracy"; -const char kHeading[] = "heading"; -const char kSpeed[] = "speed"; -const char kTimestamp[] = "timestamp"; +// How often, in seconds, to sample the hardware resource usage. +const unsigned int kResourceUsageSampleIntervalSeconds = 120; // The location we read our CPU statistics from. const char kProcStat[] = "/proc/stat"; @@ -283,10 +272,111 @@ namespace policy { +// Helper class for state tracking of async status queries. Creates device and +// session status blobs in the constructor and sends them to the the status +// response callback in the destructor. +// +// Some methods like |SampleVolumeInfo| queue async queries to collect data. The +// response callback of these queries, e.g. |OnVolumeInfoReceived|, holds a +// reference to the instance of this class, so that the destructor will not be +// invoked and the status response callback will not be fired until the original +// owner of the instance releases its reference and all async queries finish. +// +// Therefore, if you create an instance of this class, make sure to release your +// reference after quering all async queries (if any), e.g. by using a local +// |scoped_refptr<GetStatusState>| and letting it go out of scope. +class GetStatusState : public base::RefCountedThreadSafe<GetStatusState> { + public: + explicit GetStatusState( + const scoped_refptr<base::SequencedTaskRunner> task_runner, + const policy::DeviceStatusCollector::StatusCallback& response) + : task_runner_(task_runner), response_(response) {} + + inline em::DeviceStatusReportRequest* device_status() { + return device_status_.get(); + } + + inline em::SessionStatusReportRequest* session_status() { + return session_status_.get(); + } + + inline void ResetDeviceStatus() { device_status_.reset(); } + + inline void ResetSessionStatus() { session_status_.reset(); } + + // Queues an async callback to query disk volume information. + void SampleVolumeInfo(const policy::DeviceStatusCollector::VolumeInfoFetcher& + volume_info_fetcher) { + // Create list of mounted disk volumes to query status. + std::vector<storage::MountPoints::MountPointInfo> external_mount_points; + storage::ExternalMountPoints::GetSystemInstance()->AddMountPointInfosTo( + &external_mount_points); + + std::vector<std::string> mount_points; + for (const auto& info : external_mount_points) + mount_points.push_back(info.path.value()); + + for (const auto& mount_info : + chromeos::disks::DiskMountManager::GetInstance()->mount_points()) { + // Extract a list of mount points to populate. + mount_points.push_back(mount_info.first); + } + + // Call out to the blocking pool to sample disk volume info. + base::PostTaskAndReplyWithResult( + content::BrowserThread::GetBlockingPool(), FROM_HERE, + base::Bind(volume_info_fetcher, mount_points), + base::Bind(&GetStatusState::OnVolumeInfoReceived, this)); + } + + // Queues an async callback to query CPU temperature information. + void SampleCPUTempInfo( + const policy::DeviceStatusCollector::CPUTempFetcher& cpu_temp_fetcher) { + // Call out to the blocking pool to sample CPU temp. + base::PostTaskAndReplyWithResult( + content::BrowserThread::GetBlockingPool(), FROM_HERE, cpu_temp_fetcher, + base::Bind(&GetStatusState::OnCPUTempInfoReceived, this)); + } + + private: + friend class RefCountedThreadSafe<GetStatusState>; + + // Posts the response on the UI thread. As long as there is an outstanding + // async query, the query holds a reference to us, so the destructor is + // not called. + ~GetStatusState() { + task_runner_->PostTask(FROM_HERE, + base::Bind(response_, base::Passed(&device_status_), + base::Passed(&session_status_))); + } + + void OnVolumeInfoReceived(const std::vector<em::VolumeInfo>& volume_info) { + device_status_->clear_volume_info(); + for (const em::VolumeInfo& info : volume_info) + *device_status_->add_volume_info() = info; + } + + void OnCPUTempInfoReceived( + const std::vector<em::CPUTempInfo>& cpu_temp_info) { + if (cpu_temp_info.empty()) + DLOG(WARNING) << "Unable to read CPU temp information."; + + device_status_->clear_cpu_temp_info(); + for (const em::CPUTempInfo& info : cpu_temp_info) + *device_status_->add_cpu_temp_info() = info; + } + + const scoped_refptr<base::SequencedTaskRunner> task_runner_; + policy::DeviceStatusCollector::StatusCallback response_; + std::unique_ptr<em::DeviceStatusReportRequest> device_status_ = + base::MakeUnique<em::DeviceStatusReportRequest>(); + std::unique_ptr<em::SessionStatusReportRequest> session_status_ = + base::MakeUnique<em::SessionStatusReportRequest>(); +}; + DeviceStatusCollector::DeviceStatusCollector( PrefService* local_state, chromeos::system::StatisticsProvider* provider, - const LocationUpdateRequester& location_update_requester, const VolumeInfoFetcher& volume_info_fetcher, const CPUStatisticsFetcher& cpu_statistics_fetcher, const CPUTempFetcher& cpu_temp_fetcher) @@ -299,9 +389,12 @@ cpu_temp_fetcher_(cpu_temp_fetcher), statistics_provider_(provider), cros_settings_(chromeos::CrosSettings::Get()), - location_update_requester_(location_update_requester), + task_runner_(nullptr), weak_factory_(this) { - CHECK(content::BrowserThread::GetCurrentThreadIdentifier(&creation_thread_)); + // Get the task runner of the current thread, so we can queue status responses + // on this thread. + CHECK(base::SequencedTaskRunnerHandle::IsSet()); + task_runner_ = base::SequencedTaskRunnerHandle::Get(); if (volume_info_fetcher_.is_null()) volume_info_fetcher_ = base::Bind(&GetVolumeInfo); @@ -315,10 +408,9 @@ idle_poll_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(kIdlePollIntervalSeconds), this, &DeviceStatusCollector::CheckIdleState); - hardware_status_sampling_timer_.Start( - FROM_HERE, - TimeDelta::FromSeconds(kHardwareStatusSampleIntervalSeconds), - this, &DeviceStatusCollector::SampleHardwareStatus); + resource_usage_sampling_timer_.Start( + FROM_HERE, TimeDelta::FromSeconds(kResourceUsageSampleIntervalSeconds), + this, &DeviceStatusCollector::SampleResourceUsage); // Watch for changes to the individual policies that control what the status // reports contain. @@ -331,8 +423,6 @@ chromeos::kReportDeviceActivityTimes, callback); boot_mode_subscription_ = cros_settings_->AddSettingsObserver( chromeos::kReportDeviceBootMode, callback); - location_subscription_ = cros_settings_->AddSettingsObserver( - chromeos::kReportDeviceLocation, callback); network_interfaces_subscription_ = cros_settings_->AddSettingsObserver( chromeos::kReportDeviceNetworkInterfaces, callback); users_subscription_ = cros_settings_->AddSettingsObserver( @@ -346,27 +436,6 @@ running_kiosk_app_subscription_ = cros_settings_->AddSettingsObserver( chromeos::kReportRunningKioskApp, callback); - // The last known location is persisted in local state. This makes location - // information available immediately upon startup and avoids the need to - // reacquire the location on every user session change or browser crash. - device::Geoposition position; - std::string timestamp_str; - int64_t timestamp; - const base::DictionaryValue* location = - local_state_->GetDictionary(prefs::kDeviceLocation); - if (location->GetDouble(kLatitude, &position.latitude) && - location->GetDouble(kLongitude, &position.longitude) && - location->GetDouble(kAltitude, &position.altitude) && - location->GetDouble(kAccuracy, &position.accuracy) && - location->GetDouble(kAltitudeAccuracy, &position.altitude_accuracy) && - location->GetDouble(kHeading, &position.heading) && - location->GetDouble(kSpeed, &position.speed) && - location->GetString(kTimestamp, ×tamp_str) && - base::StringToInt64(timestamp_str, ×tamp)) { - position.timestamp = Time::FromInternalValue(timestamp); - position_ = position; - } - // Fetch the current values of the policies. UpdateReportingSettings(); @@ -393,8 +462,6 @@ void DeviceStatusCollector::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterDictionaryPref(prefs::kDeviceActivityTimes, new base::DictionaryValue); - registry->RegisterDictionaryPref(prefs::kDeviceLocation, - new base::DictionaryValue); } void DeviceStatusCollector::CheckIdleState() { @@ -448,27 +515,12 @@ report_session_status_ = true; } - // Device location reporting is disabled by default because it is - // not launched yet. - if (!cros_settings_->GetBoolean( - chromeos::kReportDeviceLocation, &report_location_)) { - report_location_ = false; - } - - if (report_location_) { - ScheduleGeolocationUpdateRequest(); - } else { - geolocation_update_timer_.Stop(); - position_ = device::Geoposition(); - local_state_->ClearPref(prefs::kDeviceLocation); - } - if (!report_hardware_status_) { - ClearCachedHardwareStatus(); + ClearCachedResourceUsage(); } else if (!already_reporting_hardware_status) { // Turning on hardware status reporting - fetch an initial sample // immediately instead of waiting for the sampling timer to fire. - SampleHardwareStatus(); + SampleResourceUsage(); } // Os update status and running kiosk app reporting are disabled by default. @@ -546,8 +598,7 @@ } } -void DeviceStatusCollector::ClearCachedHardwareStatus() { - volume_info_.clear(); +void DeviceStatusCollector::ClearCachedResourceUsage() { resource_usage_.clear(); last_cpu_active_ = 0; last_cpu_idle_ = 0; @@ -594,48 +645,21 @@ return std::unique_ptr<DeviceLocalAccount>(); } -void DeviceStatusCollector::SampleHardwareStatus() { +void DeviceStatusCollector::SampleResourceUsage() { // Results must be written in the creation thread since that's where they // are read from in the Get*StatusAsync methods. - CHECK(content::BrowserThread::CurrentlyOn(creation_thread_)); + DCHECK(thread_checker_.CalledOnValidThread()); // If hardware reporting has been disabled, do nothing here. if (!report_hardware_status_) return; - // Create list of mounted disk volumes to query status. - std::vector<storage::MountPoints::MountPointInfo> external_mount_points; - storage::ExternalMountPoints::GetSystemInstance()->AddMountPointInfosTo( - &external_mount_points); - - std::vector<std::string> mount_points; - for (const auto& info : external_mount_points) - mount_points.push_back(info.path.value()); - - for (const auto& mount_info : - chromeos::disks::DiskMountManager::GetInstance()->mount_points()) { - // Extract a list of mount points to populate. - mount_points.push_back(mount_info.first); - } - - // Call out to the blocking pool to measure disk, CPU usage and CPU temp. - base::PostTaskAndReplyWithResult( - content::BrowserThread::GetBlockingPool(), - FROM_HERE, - base::Bind(volume_info_fetcher_, mount_points), - base::Bind(&DeviceStatusCollector::ReceiveVolumeInfo, - weak_factory_.GetWeakPtr())); - + // Call out to the blocking pool to sample CPU stats. base::PostTaskAndReplyWithResult( content::BrowserThread::GetBlockingPool(), FROM_HERE, cpu_statistics_fetcher_, base::Bind(&DeviceStatusCollector::ReceiveCPUStatistics, weak_factory_.GetWeakPtr())); - - base::PostTaskAndReplyWithResult( - content::BrowserThread::GetBlockingPool(), FROM_HERE, cpu_temp_fetcher_, - base::Bind(&DeviceStatusCollector::StoreCPUTempInfo, - weak_factory_.GetWeakPtr())); } void DeviceStatusCollector::ReceiveCPUStatistics(const std::string& stats) { @@ -691,18 +715,8 @@ resource_usage_.pop_front(); } -void DeviceStatusCollector::StoreCPUTempInfo( - const std::vector<em::CPUTempInfo>& info) { - if (info.empty()) { - DLOG(WARNING) << "Unable to read CPU temp information."; - } - - if (report_hardware_status_) - cpu_temp_info_ = info; -} - bool DeviceStatusCollector::GetActivityTimes( - em::DeviceStatusReportRequest* request) { + em::DeviceStatusReportRequest* status) { DictionaryPrefUpdate update(local_state_, prefs::kDeviceActivityTimes); base::DictionaryValue* activity_times = update.Get(); @@ -717,7 +731,7 @@ // second occurs, two consecutive seconds have the same timestamp. int64_t end_timestamp = start_timestamp + Time::kMillisecondsPerDay; - em::ActiveTimePeriod* active_period = request->add_active_period(); + em::ActiveTimePeriod* active_period = status->add_active_period(); em::TimePeriod* period = active_period->mutable_time_period(); period->set_start_timestamp(start_timestamp); period->set_end_timestamp(end_timestamp); @@ -735,57 +749,29 @@ } bool DeviceStatusCollector::GetVersionInfo( - em::DeviceStatusReportRequest* request) { - request->set_browser_version(version_info::GetVersionNumber()); - request->set_os_version(os_version_); - request->set_firmware_version(firmware_version_); + em::DeviceStatusReportRequest* status) { + status->set_browser_version(version_info::GetVersionNumber()); + status->set_os_version(os_version_); + status->set_firmware_version(firmware_version_); return true; } -bool DeviceStatusCollector::GetBootMode( - em::DeviceStatusReportRequest* request) { +bool DeviceStatusCollector::GetBootMode(em::DeviceStatusReportRequest* status) { std::string dev_switch_mode; bool anything_reported = false; if (statistics_provider_->GetMachineStatistic( chromeos::system::kDevSwitchBootKey, &dev_switch_mode)) { if (dev_switch_mode == chromeos::system::kDevSwitchBootValueDev) - request->set_boot_mode("Dev"); + status->set_boot_mode("Dev"); else if (dev_switch_mode == chromeos::system::kDevSwitchBootValueVerified) - request->set_boot_mode("Verified"); + status->set_boot_mode("Verified"); anything_reported = true; } return anything_reported; } -bool DeviceStatusCollector::GetLocation( - em::DeviceStatusReportRequest* request) { - em::DeviceLocation* location = request->mutable_device_location(); - if (!position_.Validate()) { - location->set_error_code( - em::DeviceLocation::ERROR_CODE_POSITION_UNAVAILABLE); - location->set_error_message(position_.error_message); - } else { - location->set_latitude(position_.latitude); - location->set_longitude(position_.longitude); - location->set_accuracy(position_.accuracy); - location->set_timestamp( - (position_.timestamp - Time::UnixEpoch()).InMilliseconds()); - // Lowest point on land is at approximately -400 meters. - if (position_.altitude > -10000.) - location->set_altitude(position_.altitude); - if (position_.altitude_accuracy >= 0.) - location->set_altitude_accuracy(position_.altitude_accuracy); - if (position_.heading >= 0. && position_.heading <= 360) - location->set_heading(position_.heading); - if (position_.speed >= 0.) - location->set_speed(position_.speed); - location->set_error_code(em::DeviceLocation::ERROR_CODE_NONE); - } - return true; -} - bool DeviceStatusCollector::GetNetworkInterfaces( - em::DeviceStatusReportRequest* request) { + em::DeviceStatusReportRequest* status) { // Maps shill device type strings to proto enum constants. static const struct { const char* type_string; @@ -837,7 +823,7 @@ if (type_idx >= arraysize(kDeviceTypeMap)) continue; - em::NetworkInterface* interface = request->add_network_interface(); + em::NetworkInterface* interface = status->add_network_interface(); interface->set_type(kDeviceTypeMap[type_idx].type_constant); if (!(*device)->mac_address().empty()) interface->set_mac_address((*device)->mac_address()); @@ -877,7 +863,7 @@ } // Copy fields from NetworkState into the status report. - em::NetworkState* proto_state = request->add_network_state(); + em::NetworkState* proto_state = status->add_network_state(); proto_state->set_connection_state(connection_state_enum); anything_reported = true; @@ -905,7 +891,7 @@ return anything_reported; } -bool DeviceStatusCollector::GetUsers(em::DeviceStatusReportRequest* request) { +bool DeviceStatusCollector::GetUsers(em::DeviceStatusReportRequest* status) { const user_manager::UserList& users = chromeos::ChromeUserManager::Get()->GetUsers(); @@ -915,7 +901,7 @@ if (!user->HasGaiaAccount()) continue; - em::DeviceUser* device_user = request->add_user(); + em::DeviceUser* device_user = status->add_user(); if (chromeos::ChromeUserManager::Get()->ShouldReportUser(user->email())) { device_user->set_type(em::DeviceUser::USER_TYPE_MANAGED); device_user->set_email(user->email()); @@ -929,13 +915,17 @@ } bool DeviceStatusCollector::GetHardwareStatus( - em::DeviceStatusReportRequest* status) { - // Add volume info. - status->clear_volume_info(); - for (const em::VolumeInfo& info : volume_info_) { - *status->add_volume_info() = info; - } + em::DeviceStatusReportRequest* status, + scoped_refptr<GetStatusState> state) { + // Sample disk volume info in a background thread. + state->SampleVolumeInfo(volume_info_fetcher_); + // Sample CPU temperature in a background thread. + state->SampleCPUTempInfo(cpu_temp_fetcher_); + + // Add CPU utilization and free RAM. Note that these stats are sampled in + // regular intervals. Unlike CPU temp and volume info these are not one-time + // sampled values, hence the difference in logic. status->set_system_ram_total(base::SysInfo::AmountOfPhysicalMemory()); status->clear_system_ram_free(); status->clear_cpu_utilization_pct(); @@ -943,12 +933,6 @@ status->add_cpu_utilization_pct(usage.cpu_usage_percent); status->add_system_ram_free(usage.bytes_of_ram_free); } - - // Add CPU temp info. - status->clear_cpu_temp_info(); - for (const em::CPUTempInfo& info : cpu_temp_info_) { - *status->add_cpu_temp_info() = info; - } return true; } @@ -1010,7 +994,7 @@ em::DeviceStatusReportRequest* status) { // Must be on creation thread since some stats are written to in that thread // and accessing them from another thread would lead to race conditions. - CHECK(content::BrowserThread::CurrentlyOn(creation_thread_)); + DCHECK(thread_checker_.CalledOnValidThread()); std::unique_ptr<const DeviceLocalAccount> account = GetAutoLaunchedKioskSessionInfo(); @@ -1039,73 +1023,82 @@ return true; } -void DeviceStatusCollector::GetDeviceStatusAsync( - const DeviceStatusCallback& response) { +void DeviceStatusCollector::GetDeviceAndSessionStatusAsync( + const StatusCallback& response) { // Must be on creation thread since some stats are written to in that thread // and accessing them from another thread would lead to race conditions. - CHECK(content::BrowserThread::CurrentlyOn(creation_thread_)); + DCHECK(thread_checker_.CalledOnValidThread()); - std::unique_ptr<em::DeviceStatusReportRequest> status = - base::MakeUnique<em::DeviceStatusReportRequest>(); - bool got_status = false; + // Some of the data we're collecting is gathered in background threads. + // This object keeps track of the state of each async request. + scoped_refptr<GetStatusState> state( + new GetStatusState(task_runner_, response)); - if (report_activity_times_) - got_status |= GetActivityTimes(status.get()); + // Gather device status (might queue some async queries) + GetDeviceStatus(state); - if (report_version_info_) - got_status |= GetVersionInfo(status.get()); + // Gather device status (might queue some async queries) + GetSessionStatus(state); - if (report_boot_mode_) - got_status |= GetBootMode(status.get()); - - if (report_location_) - got_status |= GetLocation(status.get()); - - if (report_network_interfaces_) - got_status |= GetNetworkInterfaces(status.get()); - - if (report_users_) - got_status |= GetUsers(status.get()); - - if (report_hardware_status_) - got_status |= GetHardwareStatus(status.get()); - - if (report_os_update_status_) - got_status |= GetOsUpdateStatus(status.get()); - - if (report_running_kiosk_app_) - got_status |= GetRunningKioskApp(status.get()); - - // Wipe pointer if we didn't actually add any data. - if (!got_status) - status.reset(); - - content::BrowserThread::PostTask(creation_thread_, FROM_HERE, - base::Bind(response, base::Passed(&status))); + // If there are no outstanding async queries, e.g. from GetHardwareStatus(), + // the destructor of |state| calls |response|. If there are async queries, the + // queries hold references to |state|, so that |state| is only destroyed when + // the last async query has finished. } -void DeviceStatusCollector::GetDeviceSessionStatusAsync( - const DeviceSessionStatusCallback& response) { - // Only generate session status reports if session status reporting is - // enabled. - if (!report_session_status_) { - content::BrowserThread::PostTask(creation_thread_, FROM_HERE, - base::Bind(response, nullptr)); - return; - } +void DeviceStatusCollector::GetDeviceStatus( + scoped_refptr<GetStatusState> state) { + em::DeviceStatusReportRequest* status = state->device_status(); + bool anything_reported = false; + if (report_activity_times_) + anything_reported |= GetActivityTimes(status); + + if (report_version_info_) + anything_reported |= GetVersionInfo(status); + + if (report_boot_mode_) + anything_reported |= GetBootMode(status); + + if (report_network_interfaces_) + anything_reported |= GetNetworkInterfaces(status); + + if (report_users_) + anything_reported |= GetUsers(status); + + if (report_hardware_status_) + anything_reported |= GetHardwareStatus(status, state); + + if (report_os_update_status_) + anything_reported |= GetOsUpdateStatus(status); + + if (report_running_kiosk_app_) + anything_reported |= GetRunningKioskApp(status); + + // Wipe pointer if we didn't actually add any data. + if (!anything_reported) + state->ResetDeviceStatus(); +} + +void DeviceStatusCollector::GetSessionStatus( + scoped_refptr<GetStatusState> state) { + em::SessionStatusReportRequest* status = state->session_status(); + bool anything_reported = false; + + if (report_session_status_) + anything_reported |= GetAccountStatus(status); + + // Wipe pointer if we didn't actually add any data. + if (!anything_reported) + state->ResetSessionStatus(); +} + +bool DeviceStatusCollector::GetAccountStatus( + em::SessionStatusReportRequest* status) { std::unique_ptr<const DeviceLocalAccount> account = GetAutoLaunchedKioskSessionInfo(); - // Only generate session status reports if we are in an auto-launched kiosk - // session. - if (!account) { - content::BrowserThread::PostTask(creation_thread_, FROM_HERE, - base::Bind(response, nullptr)); - return; - } - - std::unique_ptr<em::SessionStatusReportRequest> status = - base::MakeUnique<em::SessionStatusReportRequest>(); + if (!account) + return false; // Get the account ID associated with this user. status->set_device_local_account_id(account->account_id); @@ -1121,8 +1114,7 @@ app_status->set_extension_version(app_version); } - content::BrowserThread::PostTask(creation_thread_, FROM_HERE, - base::Bind(response, base::Passed(&status))); + return true; } std::string DeviceStatusCollector::GetAppVersion( @@ -1152,68 +1144,4 @@ firmware_version_ = version; } -void DeviceStatusCollector::ScheduleGeolocationUpdateRequest() { - if (geolocation_update_timer_.IsRunning() || geolocation_update_in_progress_) - return; - - if (position_.Validate()) { - TimeDelta elapsed = GetCurrentTime() - position_.timestamp; - TimeDelta interval = - TimeDelta::FromSeconds(kGeolocationPollIntervalSeconds); - if (elapsed <= interval) { - geolocation_update_timer_.Start( - FROM_HERE, - interval - elapsed, - this, - &DeviceStatusCollector::ScheduleGeolocationUpdateRequest); - return; - } - } - - geolocation_update_in_progress_ = true; - if (location_update_requester_.is_null()) { - geolocation_subscription_ = - device::GeolocationProvider::GetInstance()->AddLocationUpdateCallback( - base::Bind(&DeviceStatusCollector::ReceiveGeolocationUpdate, - weak_factory_.GetWeakPtr()), - true); - } else { - location_update_requester_.Run(base::Bind( - &DeviceStatusCollector::ReceiveGeolocationUpdate, - weak_factory_.GetWeakPtr())); - } -} - -void DeviceStatusCollector::ReceiveGeolocationUpdate( - const device::Geoposition& position) { - geolocation_update_in_progress_ = false; - - // Ignore update if device location reporting has since been disabled. - if (!report_location_) - return; - - if (position.Validate()) { - position_ = position; - base::DictionaryValue location; - location.SetDouble(kLatitude, position.latitude); - location.SetDouble(kLongitude, position.longitude); - location.SetDouble(kAltitude, position.altitude); - location.SetDouble(kAccuracy, position.accuracy); - location.SetDouble(kAltitudeAccuracy, position.altitude_accuracy); - location.SetDouble(kHeading, position.heading); - location.SetDouble(kSpeed, position.speed); - location.SetString(kTimestamp, - base::Int64ToString(position.timestamp.ToInternalValue())); - local_state_->Set(prefs::kDeviceLocation, location); - } - - ScheduleGeolocationUpdateRequest(); -} - -void DeviceStatusCollector::ReceiveVolumeInfo( - const std::vector<em::VolumeInfo>& info) { - if (report_hardware_status_) - volume_info_ = info; -} - } // namespace policy
diff --git a/chrome/browser/chromeos/policy/device_status_collector.h b/chrome/browser/chromeos/policy/device_status_collector.h index e6f4d10..80ee95d 100644 --- a/chrome/browser/chromeos/policy/device_status_collector.h +++ b/chrome/browser/chromeos/policy/device_status_collector.h
@@ -16,17 +16,16 @@ #include "base/callback_list.h" #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" +#include "base/sequenced_task_runner.h" #include "base/task/cancelable_task_tracker.h" +#include "base/threading/thread_checker.h" #include "base/time/time.h" #include "base/timer/timer.h" + #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chromeos/system/version_loader.h" #include "components/policy/proto/device_management_backend.pb.h" -#include "content/public/browser/browser_thread.h" -#include "device/geolocation/geolocation_provider.h" -#include "device/geolocation/geoposition.h" #include "ui/base/idle/idle.h" namespace chromeos { @@ -47,16 +46,11 @@ namespace policy { struct DeviceLocalAccount; +class GetStatusState; // Collects and summarizes the status of an enterprised-managed ChromeOS device. class DeviceStatusCollector { public: - // TODO(bartfab): Remove this once crbug.com/125931 is addressed and a proper - // way to mock geolocation exists. - typedef base::Callback<void( - const device::GeolocationProvider::LocationUpdateCallback& callback)> - LocationUpdateRequester; - using VolumeInfoFetcher = base::Callback< std::vector<enterprise_management::VolumeInfo>( const std::vector<std::string>& mount_points)>; @@ -74,14 +68,11 @@ using CPUTempFetcher = base::Callback<std::vector<enterprise_management::CPUTempInfo>()>; - // Called in the UI thread after the device status has been collected - // asynchronously in GetDeviceStatusAsync. - using DeviceStatusCallback = base::Callback<void( - std::unique_ptr<enterprise_management::DeviceStatusReportRequest>)>; - - // Called in the UI thread after the device session status has been collected - // asynchronously in GetDeviceSessionStatusAsync. - using DeviceSessionStatusCallback = base::Callback<void( + // Called in the UI thread after the device and session status have been + // collected asynchronously in GetDeviceAndSessionStatusAsync. Null pointers + // indicate errors or that device or session status reporting is disabled. + using StatusCallback = base::Callback<void( + std::unique_ptr<enterprise_management::DeviceStatusReportRequest>, std::unique_ptr<enterprise_management::SessionStatusReportRequest>)>; // Constructor. Callers can inject their own VolumeInfoFetcher, @@ -91,24 +82,15 @@ DeviceStatusCollector( PrefService* local_state, chromeos::system::StatisticsProvider* provider, - const LocationUpdateRequester& location_update_requester, const VolumeInfoFetcher& volume_info_fetcher, const CPUStatisticsFetcher& cpu_statistics_fetcher, const CPUTempFetcher& cpu_temp_fetcher); virtual ~DeviceStatusCollector(); - // Gathers device status information and calls the passed response callback. - // A null pointer passed into the response indicates an error or that - // device status reporting is disabled. - virtual void GetDeviceStatusAsync( - const DeviceStatusCallback& response); - - // Gathers device session status information and calls the passed response - // callback. A null pointer passed into the response indicates an error or - // that device session status reporting is disabled or that the active - // session is not a kiosk session. - virtual void GetDeviceSessionStatusAsync( - const DeviceSessionStatusCallback& response); + // Gathers device and session status information and calls the passed response + // callback. Null pointers passed into the response indicate errors or that + // device or session status reporting is disabled. + virtual void GetDeviceAndSessionStatusAsync(const StatusCallback& response); // Called after the status information has successfully been submitted to // the server. @@ -141,9 +123,9 @@ // Gets the version of the passed app. Virtual to allow mocking. virtual std::string GetAppVersion(const std::string& app_id); - // Samples the current hardware status to be sent up with the next device - // status update. - void SampleHardwareStatus(); + // Samples the current hardware resource usage to be sent up with the + // next device status update. + void SampleResourceUsage(); // The number of days in the past to store device activity. // This is kept in case device status uploads fail for a number of days. @@ -168,53 +150,46 @@ void AddActivePeriod(base::Time start, base::Time end); - // Clears the cached hardware status. - void ClearCachedHardwareStatus(); + // Clears the cached hardware resource usage. + void ClearCachedResourceUsage(); // Callbacks from chromeos::VersionLoader. void OnOSVersion(const std::string& version); void OnOSFirmware(const std::string& version); - // Helpers for the various portions of the status. Return true if they - // actually report any status. + void GetDeviceStatus(scoped_refptr<GetStatusState> state); + void GetSessionStatus(scoped_refptr<GetStatusState> state); + + // Helpers for the various portions of DEVICE STATUS. Return true if they + // actually report any status. Functions that queue async queries take + // a |GetStatusState| instance. bool GetActivityTimes( - enterprise_management::DeviceStatusReportRequest* request); - bool GetVersionInfo( - enterprise_management::DeviceStatusReportRequest* request); - bool GetBootMode( - enterprise_management::DeviceStatusReportRequest* request); - bool GetLocation( - enterprise_management::DeviceStatusReportRequest* request); + enterprise_management::DeviceStatusReportRequest* status); + bool GetVersionInfo(enterprise_management::DeviceStatusReportRequest* status); + bool GetBootMode(enterprise_management::DeviceStatusReportRequest* status); bool GetNetworkInterfaces( - enterprise_management::DeviceStatusReportRequest* request); - bool GetUsers( - enterprise_management::DeviceStatusReportRequest* request); + enterprise_management::DeviceStatusReportRequest* status); + bool GetUsers(enterprise_management::DeviceStatusReportRequest* status); bool GetHardwareStatus( - enterprise_management::DeviceStatusReportRequest* request); + enterprise_management::DeviceStatusReportRequest* status, + scoped_refptr<GetStatusState> state); // Queues async queries! bool GetOsUpdateStatus( - enterprise_management::DeviceStatusReportRequest* request); + enterprise_management::DeviceStatusReportRequest* status); bool GetRunningKioskApp( - enterprise_management::DeviceStatusReportRequest* request); + enterprise_management::DeviceStatusReportRequest* status); + + // Helpers for the various portions of SESSION STATUS. Return true if they + // actually report any status. Functions that queue async queries take + // a |GetStatusState| instance. + bool GetAccountStatus( + enterprise_management::SessionStatusReportRequest* status); // Update the cached values of the reporting settings. void UpdateReportingSettings(); - void ScheduleGeolocationUpdateRequest(); - - // device::GeolocationUpdateCallback implementation. - void ReceiveGeolocationUpdate(const device::Geoposition&); - - // Callback invoked to update our cached disk information. - void ReceiveVolumeInfo( - const std::vector<enterprise_management::VolumeInfo>& info); - // Callback invoked to update our cpu usage information. void ReceiveCPUStatistics(const std::string& statistics); - // Callback invoked to update our CPU temp information. - void StoreCPUTempInfo( - const std::vector<enterprise_management::CPUTempInfo>& info); - PrefService* const local_state_; // The last time an idle state check was performed. @@ -227,24 +202,12 @@ int64_t last_reported_day_ = 0; int duration_for_last_reported_day_ = 0; - // Whether a geolocation update is currently in progress. - bool geolocation_update_in_progress_ = false; - base::RepeatingTimer idle_poll_timer_; - base::RepeatingTimer hardware_status_sampling_timer_; - base::OneShotTimer geolocation_update_timer_; + base::RepeatingTimer resource_usage_sampling_timer_; std::string os_version_; std::string firmware_version_; - device::Geoposition position_; - - // Cached disk volume information. - std::vector<enterprise_management::VolumeInfo> volume_info_; - - // Cached CPU temp information. - std::vector<enterprise_management::CPUTempInfo> cpu_temp_info_; - struct ResourceUsage { // Sample of percentage-of-CPU-used. int cpu_usage_percent; @@ -275,18 +238,10 @@ uint64_t last_cpu_active_ = 0; uint64_t last_cpu_idle_ = 0; - // TODO(bartfab): Remove this once crbug.com/125931 is addressed and a proper - // way to mock geolocation exists. - LocationUpdateRequester location_update_requester_; - - std::unique_ptr<device::GeolocationProvider::Subscription> - geolocation_subscription_; - // Cached values of the reporting settings from the device policy. bool report_version_info_ = false; bool report_activity_times_ = false; bool report_boot_mode_ = false; - bool report_location_ = false; bool report_network_interfaces_ = false; bool report_users_ = false; bool report_hardware_status_ = false; @@ -301,8 +256,6 @@ std::unique_ptr<chromeos::CrosSettings::ObserverSubscription> boot_mode_subscription_; std::unique_ptr<chromeos::CrosSettings::ObserverSubscription> - location_subscription_; - std::unique_ptr<chromeos::CrosSettings::ObserverSubscription> network_interfaces_subscription_; std::unique_ptr<chromeos::CrosSettings::ObserverSubscription> users_subscription_; @@ -315,7 +268,9 @@ std::unique_ptr<chromeos::CrosSettings::ObserverSubscription> running_kiosk_app_subscription_; - content::BrowserThread::ID creation_thread_; + // Task runner in the creation thread where responses are sent to. + scoped_refptr<base::SequencedTaskRunner> task_runner_; + base::ThreadChecker thread_checker_; base::WeakPtrFactory<DeviceStatusCollector> weak_factory_;
diff --git a/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc b/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc index 0d1da1f..4f683f7 100644 --- a/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc +++ b/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc
@@ -54,7 +54,6 @@ #include "content/public/browser/browser_thread.h" #include "content/public/test/test_browser_thread.h" #include "content/public/test/test_utils.h" -#include "device/geolocation/geolocation_provider.h" #include "storage/browser/fileapi/external_mount_points.h" #include "storage/browser/fileapi/mount_points.h" #include "storage/common/fileapi/file_system_mount_option.h" @@ -79,42 +78,17 @@ const char kExternalMountPoint[] = "/a/b/c"; const char kPublicAccountId[] = "public_user@localhost"; -std::unique_ptr<device::Geoposition> mock_position_to_return_next; - -void SetMockPositionToReturnNext(const device::Geoposition& position) { - mock_position_to_return_next.reset(new device::Geoposition(position)); -} - -void MockPositionUpdateRequester( - const device::GeolocationProvider::LocationUpdateCallback& callback) { - if (!mock_position_to_return_next.get()) - return; - - // If the fix is invalid, the DeviceStatusCollector will immediately request - // another update when it receives the callback. This is desirable and safe in - // real life where geolocation updates arrive asynchronously. In this testing - // harness, the callback is invoked synchronously upon request, leading to a - // request-callback loop. The loop is broken by returning the mock position - // only once. - std::unique_ptr<device::Geoposition> position( - mock_position_to_return_next.release()); - callback.Run(*position); -} - class TestingDeviceStatusCollector : public policy::DeviceStatusCollector { public: TestingDeviceStatusCollector( PrefService* local_state, chromeos::system::StatisticsProvider* provider, - const policy::DeviceStatusCollector::LocationUpdateRequester& - location_update_requester, const policy::DeviceStatusCollector::VolumeInfoFetcher& volume_info_fetcher, const policy::DeviceStatusCollector::CPUStatisticsFetcher& cpu_fetcher, const policy::DeviceStatusCollector::CPUTempFetcher& cpu_temp_fetcher) : policy::DeviceStatusCollector(local_state, provider, - location_update_requester, volume_info_fetcher, cpu_fetcher, cpu_temp_fetcher) { @@ -160,7 +134,7 @@ } void RefreshSampleResourceUsage() { - SampleHardwareStatus(); + SampleResourceUsage(); content::BrowserThread::GetBlockingPool()->FlushForTesting(); } @@ -353,91 +327,35 @@ const policy::DeviceStatusCollector::VolumeInfoFetcher& volume_info, const policy::DeviceStatusCollector::CPUStatisticsFetcher& cpu_stats, const policy::DeviceStatusCollector::CPUTempFetcher& cpu_temp_fetcher) { - policy::DeviceStatusCollector::LocationUpdateRequester callback = - base::Bind(&MockPositionUpdateRequester); std::vector<em::VolumeInfo> expected_volume_info; status_collector_.reset(new TestingDeviceStatusCollector( - &prefs_, &fake_statistics_provider_, callback, volume_info, cpu_stats, + &prefs_, &fake_statistics_provider_, volume_info, cpu_stats, cpu_temp_fetcher)); } - void GetDeviceStatus() { + void GetStatus() { device_status_.Clear(); - run_loop_.reset(new base::RunLoop()); - status_collector_->GetDeviceStatusAsync( - base::Bind(&DeviceStatusCollectorTest::OnDeviceStatusReceived, - base::Unretained(this))); - run_loop_->Run(); - run_loop_.reset(); - } - - void OnDeviceStatusReceived( - std::unique_ptr<em::DeviceStatusReportRequest> status) { - if (status) - device_status_ = *status; - EXPECT_TRUE(run_loop_); - run_loop_->Quit(); - } - - void GetSessionStatus() { session_status_.Clear(); got_session_status_ = false; run_loop_.reset(new base::RunLoop()); - status_collector_->GetDeviceSessionStatusAsync( - base::Bind(&DeviceStatusCollectorTest::OnSessionStatusReceived, - base::Unretained(this))); + status_collector_->GetDeviceAndSessionStatusAsync(base::Bind( + &DeviceStatusCollectorTest::OnStatusReceived, base::Unretained(this))); run_loop_->Run(); run_loop_.reset(); } - void OnSessionStatusReceived( - std::unique_ptr<em::SessionStatusReportRequest> status) { - got_session_status_ = status != nullptr; + void OnStatusReceived( + std::unique_ptr<em::DeviceStatusReportRequest> device_status, + std::unique_ptr<em::SessionStatusReportRequest> session_status) { + if (device_status) + device_status_ = *device_status; + got_session_status_ = session_status != nullptr; if (got_session_status_) - session_status_ = *status; + session_status_ = *session_status; EXPECT_TRUE(run_loop_); run_loop_->Quit(); } - void CheckThatNoLocationIsReported() { - GetDeviceStatus(); - EXPECT_FALSE(device_status_.has_device_location()); - } - - void CheckThatAValidLocationIsReported() { - // Checks that a location is being reported which matches the valid fix - // set using SetMockPositionToReturnNext(). - GetDeviceStatus(); - EXPECT_TRUE(device_status_.has_device_location()); - em::DeviceLocation location = device_status_.device_location(); - if (location.has_error_code()) - EXPECT_EQ(em::DeviceLocation::ERROR_CODE_NONE, location.error_code()); - EXPECT_TRUE(location.has_latitude()); - EXPECT_TRUE(location.has_longitude()); - EXPECT_TRUE(location.has_accuracy()); - EXPECT_TRUE(location.has_timestamp()); - EXPECT_FALSE(location.has_altitude()); - EXPECT_FALSE(location.has_altitude_accuracy()); - EXPECT_FALSE(location.has_heading()); - EXPECT_FALSE(location.has_speed()); - EXPECT_FALSE(location.has_error_message()); - EXPECT_DOUBLE_EQ(4.3, location.latitude()); - EXPECT_DOUBLE_EQ(-7.8, location.longitude()); - EXPECT_DOUBLE_EQ(3., location.accuracy()); - // Check that the timestamp is not older than ten minutes. - EXPECT_TRUE(Time::Now() - Time::FromDoubleT(location.timestamp() / 1000.) < - TimeDelta::FromMinutes(10)); - } - - void CheckThatALocationErrorIsReported() { - GetDeviceStatus(); - EXPECT_TRUE(device_status_.has_device_location()); - em::DeviceLocation location = device_status_.device_location(); - EXPECT_TRUE(location.has_error_code()); - EXPECT_EQ(em::DeviceLocation::ERROR_CODE_POSITION_UNAVAILABLE, - location.error_code()); - } - void MockRunningKioskApp(const DeviceLocalAccount& account) { std::vector<DeviceLocalAccount> accounts; accounts.push_back(account); @@ -524,20 +442,20 @@ settings_helper_.SetBoolean(chromeos::kReportDeviceActivityTimes, true); // Test reporting with no data. - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(0, device_status_.active_period_size()); EXPECT_EQ(0, GetActiveMilliseconds(device_status_)); // Test reporting with a single idle sample. status_collector_->Simulate(test_states, 1); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(0, device_status_.active_period_size()); EXPECT_EQ(0, GetActiveMilliseconds(device_status_)); // Test reporting with multiple consecutive idle samples. status_collector_->Simulate(test_states, sizeof(test_states) / sizeof(ui::IdleState)); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(0, device_status_.active_period_size()); EXPECT_EQ(0, GetActiveMilliseconds(device_status_)); } @@ -552,7 +470,7 @@ // Test a single active sample. status_collector_->Simulate(test_states, 1); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(1, device_status_.active_period_size()); EXPECT_EQ(1 * ActivePeriodMilliseconds(), GetActiveMilliseconds(device_status_)); @@ -561,7 +479,7 @@ // Test multiple consecutive active samples. status_collector_->Simulate(test_states, sizeof(test_states) / sizeof(ui::IdleState)); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(1, device_status_.active_period_size()); EXPECT_EQ(4 * ActivePeriodMilliseconds(), GetActiveMilliseconds(device_status_)); @@ -580,7 +498,7 @@ settings_helper_.SetBoolean(chromeos::kReportDeviceActivityTimes, true); status_collector_->Simulate(test_states, sizeof(test_states) / sizeof(ui::IdleState)); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(4 * ActivePeriodMilliseconds(), GetActiveMilliseconds(device_status_)); } @@ -607,7 +525,7 @@ status_collector_->Simulate(test_states, sizeof(test_states) / sizeof(ui::IdleState)); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(6 * ActivePeriodMilliseconds(), GetActiveMilliseconds(device_status_)); } @@ -624,7 +542,7 @@ settings_helper_.SetBoolean(chromeos::kReportDeviceActivityTimes, true); status_collector_->Simulate(test_states, sizeof(test_states) / sizeof(ui::IdleState)); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(3 * ActivePeriodMilliseconds(), GetActiveMilliseconds(device_status_)); } @@ -651,7 +569,7 @@ } // Check that we don't exceed the max number of periods. - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(kMaxDays - 1, device_status_.active_period_size()); // Simulate some future times. @@ -671,7 +589,7 @@ // Check that we don't exceed the max number of periods. device_status_.clear_active_period(); - GetDeviceStatus(); + GetStatus(); EXPECT_LT(device_status_.active_period_size(), kMaxDays); } @@ -684,7 +602,7 @@ }; status_collector_->Simulate(test_states, sizeof(test_states) / sizeof(ui::IdleState)); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(1, device_status_.active_period_size()); EXPECT_EQ(3 * ActivePeriodMilliseconds(), GetActiveMilliseconds(device_status_)); @@ -701,7 +619,7 @@ }; status_collector_->Simulate(test_states, sizeof(test_states) / sizeof(ui::IdleState)); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(0, device_status_.active_period_size()); EXPECT_EQ(0, GetActiveMilliseconds(device_status_)); } @@ -717,7 +635,7 @@ Time::Now().LocalMidnight() + TimeDelta::FromSeconds(10)); status_collector_->Simulate(test_states, 1); - GetDeviceStatus(); + GetStatus(); ASSERT_EQ(2, device_status_.active_period_size()); em::ActiveTimePeriod period0 = device_status_.active_period(0); @@ -742,17 +660,21 @@ ui::IDLE_STATE_ACTIVE, ui::IDLE_STATE_ACTIVE, }; + // Make sure CPU stats get reported in time. If we don't run this, the second + // call to |GetStatus()| will contain these stats, but the first call won't + // and the EXPECT_EQ test below fails. base::RunLoop().RunUntilIdle(); + settings_helper_.SetBoolean(chromeos::kReportDeviceActivityTimes, true); status_collector_->Simulate(test_states, 2); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(2 * ActivePeriodMilliseconds(), GetActiveMilliseconds(device_status_)); em::DeviceStatusReportRequest first_status(device_status_); // The collector returns the same status again. - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(first_status.SerializeAsString(), device_status_.SerializeAsString()); @@ -760,7 +682,7 @@ // but what got collected meanwhile sticks around. status_collector_->Simulate(test_states, 1); status_collector_->OnSubmittedSuccessfully(); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(ActivePeriodMilliseconds(), GetActiveMilliseconds(device_status_)); } @@ -769,13 +691,13 @@ fake_statistics_provider_.SetMachineStatistic( chromeos::system::kDevSwitchBootKey, chromeos::system::kDevSwitchBootValueVerified); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ("Verified", device_status_.boot_mode()); // Test that boot mode data is not reported if the pref turned off. settings_helper_.SetBoolean(chromeos::kReportDeviceBootMode, false); - GetDeviceStatus(); + GetStatus(); EXPECT_FALSE(device_status_.has_boot_mode()); // Turn the pref on, and check that the status is reported iff the @@ -784,30 +706,30 @@ fake_statistics_provider_.SetMachineStatistic( chromeos::system::kDevSwitchBootKey, "(error)"); - GetDeviceStatus(); + GetStatus(); EXPECT_FALSE(device_status_.has_boot_mode()); fake_statistics_provider_.SetMachineStatistic( chromeos::system::kDevSwitchBootKey, " "); - GetDeviceStatus(); + GetStatus(); EXPECT_FALSE(device_status_.has_boot_mode()); fake_statistics_provider_.SetMachineStatistic( chromeos::system::kDevSwitchBootKey, chromeos::system::kDevSwitchBootValueVerified); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ("Verified", device_status_.boot_mode()); fake_statistics_provider_.SetMachineStatistic( chromeos::system::kDevSwitchBootKey, chromeos::system::kDevSwitchBootValueDev); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ("Dev", device_status_.boot_mode()); } TEST_F(DeviceStatusCollectorTest, VersionInfo) { // Expect the version info to be reported by default. - GetDeviceStatus(); + GetStatus(); EXPECT_TRUE(device_status_.has_browser_version()); EXPECT_TRUE(device_status_.has_os_version()); EXPECT_TRUE(device_status_.has_firmware_version()); @@ -815,13 +737,13 @@ // When the pref to collect this data is not enabled, expect that none of // the fields are present in the protobuf. settings_helper_.SetBoolean(chromeos::kReportDeviceVersionInfo, false); - GetDeviceStatus(); + GetStatus(); EXPECT_FALSE(device_status_.has_browser_version()); EXPECT_FALSE(device_status_.has_os_version()); EXPECT_FALSE(device_status_.has_firmware_version()); settings_helper_.SetBoolean(chromeos::kReportDeviceVersionInfo, true); - GetDeviceStatus(); + GetStatus(); EXPECT_TRUE(device_status_.has_browser_version()); EXPECT_TRUE(device_status_.has_os_version()); EXPECT_TRUE(device_status_.has_firmware_version()); @@ -832,56 +754,6 @@ EXPECT_NE("", device_status_.browser_version()); } -TEST_F(DeviceStatusCollectorTest, Location) { - device::Geoposition valid_fix; - valid_fix.latitude = 4.3; - valid_fix.longitude = -7.8; - valid_fix.accuracy = 3.; - valid_fix.timestamp = Time::Now(); - - device::Geoposition invalid_fix; - invalid_fix.error_code = device::Geoposition::ERROR_CODE_POSITION_UNAVAILABLE; - invalid_fix.timestamp = Time::Now(); - - // Check that when device location reporting is disabled, no location is - // reported. - SetMockPositionToReturnNext(valid_fix); - CheckThatNoLocationIsReported(); - - // Check that when device location reporting is enabled and a valid fix is - // available, the location is reported and is stored in local state. - SetMockPositionToReturnNext(valid_fix); - settings_helper_.SetBoolean(chromeos::kReportDeviceLocation, true); - EXPECT_FALSE(prefs_.GetDictionary(prefs::kDeviceLocation)->empty()); - CheckThatAValidLocationIsReported(); - - // Restart the status collector. Check that the last known location has been - // retrieved from local state without requesting a geolocation update. - SetMockPositionToReturnNext(valid_fix); - RestartStatusCollector(base::Bind(&GetEmptyVolumeInfo), - base::Bind(&GetEmptyCPUStatistics), - base::Bind(&GetEmptyCPUTempInfo)); - CheckThatAValidLocationIsReported(); - EXPECT_TRUE(mock_position_to_return_next.get()); - - // Check that after disabling location reporting again, the last known - // location has been cleared from local state and is no longer reported. - SetMockPositionToReturnNext(valid_fix); - settings_helper_.SetBoolean(chromeos::kReportDeviceLocation, false); - // Allow the new pref to propagate to the status collector. - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(prefs_.GetDictionary(prefs::kDeviceLocation)->empty()); - CheckThatNoLocationIsReported(); - - // Check that after enabling location reporting again, an error is reported - // if no valid fix is available. - SetMockPositionToReturnNext(invalid_fix); - settings_helper_.SetBoolean(chromeos::kReportDeviceLocation, true); - // Allow the new pref to propagate to the status collector. - base::RunLoop().RunUntilIdle(); - CheckThatALocationErrorIsReported(); -} - TEST_F(DeviceStatusCollectorTest, ReportUsers) { const AccountId public_account_id( AccountId::FromUserEmail("public@localhost")); @@ -901,12 +773,12 @@ user_manager_->AddUserWithAffiliation(account_id5, true); // Verify that users are reported by default. - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(6, device_status_.user_size()); // Verify that users are reported after enabling the setting. settings_helper_.SetBoolean(chromeos::kReportDeviceUsers, true); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(6, device_status_.user_size()); EXPECT_EQ(em::DeviceUser::USER_TYPE_MANAGED, device_status_.user(0).type()); EXPECT_EQ(account_id0.GetUserEmail(), device_status_.user(0).email()); @@ -923,7 +795,7 @@ // Verify that users are no longer reported if setting is disabled. settings_helper_.SetBoolean(chromeos::kReportDeviceUsers, false); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(0, device_status_.user_size()); } @@ -954,7 +826,7 @@ content::BrowserThread::GetBlockingPool()->FlushForTesting(); base::RunLoop().RunUntilIdle(); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(expected_mount_points.size(), static_cast<size_t>(device_status_.volume_info_size())); @@ -975,7 +847,7 @@ // Now turn off hardware status reporting - should have no data. settings_helper_.SetBoolean(chromeos::kReportDeviceHardwareStatus, false); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(0, device_status_.volume_info_size()); } @@ -988,7 +860,7 @@ status_collector_->RefreshSampleResourceUsage(); base::RunLoop().RunUntilIdle(); } - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(static_cast<int>(DeviceStatusCollector::kMaxResourceUsageSamples), device_status_.system_ram_free().size()); EXPECT_TRUE(device_status_.has_system_ram_total()); @@ -1006,7 +878,7 @@ // Force finishing tasks posted by ctor of DeviceStatusCollector. content::BrowserThread::GetBlockingPool()->FlushForTesting(); base::RunLoop().RunUntilIdle(); - GetDeviceStatus(); + GetStatus(); ASSERT_EQ(1, device_status_.cpu_utilization_pct().size()); EXPECT_EQ(100, device_status_.cpu_utilization_pct(0)); @@ -1014,7 +886,7 @@ // so should show 0% cpu usage). status_collector_->RefreshSampleResourceUsage(); base::RunLoop().RunUntilIdle(); - GetDeviceStatus(); + GetStatus(); ASSERT_EQ(2, device_status_.cpu_utilization_pct().size()); EXPECT_EQ(0, device_status_.cpu_utilization_pct(1)); @@ -1026,7 +898,7 @@ status_collector_->RefreshSampleResourceUsage(); base::RunLoop().RunUntilIdle(); } - GetDeviceStatus(); + GetStatus(); // Should not be more than kMaxResourceUsageSamples, and they should all show // the CPU is idle. @@ -1037,7 +909,7 @@ // Turning off hardware reporting should not report CPU utilization. settings_helper_.SetBoolean(chromeos::kReportDeviceHardwareStatus, false); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(0, device_status_.cpu_utilization_pct().size()); } @@ -1058,7 +930,7 @@ content::BrowserThread::GetBlockingPool()->FlushForTesting(); base::RunLoop().RunUntilIdle(); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(expected_temp_info.size(), static_cast<size_t>(device_status_.cpu_temp_info_size())); @@ -1078,14 +950,14 @@ // Now turn off hardware status reporting - should have no data. settings_helper_.SetBoolean(chromeos::kReportDeviceHardwareStatus, false); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(0, device_status_.cpu_temp_info_size()); } TEST_F(DeviceStatusCollectorTest, NoSessionStatusIfNotKioskMode) { // Should not report session status if we don't have an active kiosk app. settings_helper_.SetBoolean(chromeos::kReportDeviceSessionStatus, true); - GetSessionStatus(); + GetStatus(); EXPECT_FALSE(got_session_status_); } @@ -1097,7 +969,7 @@ // Set up a device-local account for single-app kiosk mode. MockRunningKioskApp(fake_device_local_account_); - GetSessionStatus(); + GetStatus(); EXPECT_FALSE(got_session_status_); } @@ -1109,7 +981,7 @@ // Set up a device-local account for single-app kiosk mode. MockRunningKioskApp(fake_device_local_account_); - GetSessionStatus(); + GetStatus(); EXPECT_TRUE(got_session_status_); ASSERT_EQ(1, session_status_.installed_apps_size()); EXPECT_EQ(kKioskAccountId, session_status_.device_local_account_id()); @@ -1126,7 +998,7 @@ MockAutoLaunchKioskAppWithRequiredPlatformVersion(fake_device_local_account_, "1234.0.0"); - GetDeviceStatus(); + GetStatus(); EXPECT_FALSE(device_status_.has_os_update_status()); } @@ -1140,7 +1012,7 @@ MockAutoLaunchKioskAppWithRequiredPlatformVersion( fake_device_local_account_, kRequiredPlatformVersions[i]); - GetDeviceStatus(); + GetStatus(); ASSERT_TRUE(device_status_.has_os_update_status()) << "Required platform version=" << kRequiredPlatformVersions[i]; EXPECT_EQ(em::OsUpdateStatus::OS_UP_TO_DATE, @@ -1161,7 +1033,7 @@ chromeos::UpdateEngineClient::Status update_status; update_status.status = chromeos::UpdateEngineClient::UPDATE_STATUS_IDLE; - GetDeviceStatus(); + GetStatus(); ASSERT_TRUE(device_status_.has_os_update_status()); EXPECT_EQ(em::OsUpdateStatus::OS_IMAGE_DOWNLOAD_NOT_STARTED, device_status_.os_update_status().update_status()); @@ -1178,7 +1050,7 @@ update_status.new_version = "1235.1.2"; update_engine_client_->PushLastStatus(update_status); - GetDeviceStatus(); + GetStatus(); ASSERT_TRUE(device_status_.has_os_update_status()); EXPECT_EQ(em::OsUpdateStatus::OS_IMAGE_DOWNLOAD_IN_PROGRESS, device_status_.os_update_status().update_status()); @@ -1192,7 +1064,7 @@ update_status.status = chromeos::UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT; update_engine_client_->PushLastStatus(update_status); - GetDeviceStatus(); + GetStatus(); ASSERT_TRUE(device_status_.has_os_update_status()); EXPECT_EQ(em::OsUpdateStatus::OS_UPDATE_NEED_REBOOT, device_status_.os_update_status().update_status()); @@ -1206,7 +1078,7 @@ base::MakeUnique<policy::DeviceLocalAccount>(fake_device_local_account_)); MockRunningKioskApp(fake_device_local_account_); - GetDeviceStatus(); + GetStatus(); EXPECT_FALSE(device_status_.has_running_kiosk_app()); } @@ -1216,7 +1088,7 @@ MockAutoLaunchKioskAppWithRequiredPlatformVersion(fake_device_local_account_, "1234.0.0"); - GetDeviceStatus(); + GetStatus(); EXPECT_FALSE(device_status_.has_running_kiosk_app()); } @@ -1229,7 +1101,7 @@ status_collector_->set_kiosk_account( base::MakeUnique<policy::DeviceLocalAccount>(fake_device_local_account_)); - GetDeviceStatus(); + GetStatus(); ASSERT_TRUE(device_status_.has_running_kiosk_app()); const em::AppStatus app = device_status_.running_kiosk_app(); EXPECT_EQ(kKioskAppId, app.app_id()); @@ -1501,7 +1373,7 @@ TEST_F(DeviceStatusCollectorNetworkInterfacesTest, NoNetworkStateIfNotKiosk) { // If not in an active kiosk session, there should be network interfaces // reported, but no network state. - GetDeviceStatus(); + GetStatus(); EXPECT_LT(0, device_status_.network_interface_size()); EXPECT_EQ(0, device_status_.network_state_size()); } @@ -1512,19 +1384,19 @@ base::MakeUnique<policy::DeviceLocalAccount>(fake_device_local_account_)); // Interfaces should be reported by default. - GetDeviceStatus(); + GetStatus(); EXPECT_LT(0, device_status_.network_interface_size()); EXPECT_LT(0, device_status_.network_state_size()); // No interfaces should be reported if the policy is off. settings_helper_.SetBoolean(chromeos::kReportDeviceNetworkInterfaces, false); - GetDeviceStatus(); + GetStatus(); EXPECT_EQ(0, device_status_.network_interface_size()); EXPECT_EQ(0, device_status_.network_state_size()); // Switch the policy on and verify the interface list is present. settings_helper_.SetBoolean(chromeos::kReportDeviceNetworkInterfaces, true); - GetDeviceStatus(); + GetStatus(); VerifyNetworkReporting(); } @@ -1537,7 +1409,7 @@ .WillRepeatedly(Return(true)); settings_helper_.SetBoolean(chromeos::kReportDeviceNetworkInterfaces, true); - GetDeviceStatus(); + GetStatus(); VerifyNetworkReporting(); }
diff --git a/chrome/browser/chromeos/policy/status_uploader.cc b/chrome/browser/chromeos/policy/status_uploader.cc index 9cdfa7c..10b1c719 100644 --- a/chrome/browser/chromeos/policy/status_uploader.cc +++ b/chrome/browser/chromeos/policy/status_uploader.cc
@@ -176,58 +176,9 @@ } void StatusUploader::UploadStatus() { - // Submit the responses of the asynchronous calls to collector_ - // in a small ref-counted state tracker class, so that we can - // a) track that both responses fired and - // b) quick subsequent calls to UploadStatus() won't mess up state. - scoped_refptr<StatusGetter> getter( - new StatusGetter(weak_factory_.GetWeakPtr())); - - // Note that the two base::Binds keep references to getter, - // so getter stays alive until both callbacks are called. - collector_->GetDeviceStatusAsync( - base::Bind(&StatusGetter::OnDeviceStatusReceived, getter)); - - collector_->GetDeviceSessionStatusAsync( - base::Bind(&StatusGetter::OnSessionStatusReceived, getter)); -} - -StatusUploader::StatusGetter::StatusGetter( - const base::WeakPtr<StatusUploader>& uploader) - : uploader_(uploader), - device_status_response_received_(false), - session_status_response_received_(false) {} - -StatusUploader::StatusGetter::~StatusGetter() {} - -void StatusUploader::StatusGetter::OnDeviceStatusReceived( - std::unique_ptr<em::DeviceStatusReportRequest> device_status) { - DCHECK(!device_status_response_received_); - device_status_ = std::move(device_status); - device_status_response_received_ = true; - CheckDone(); -} - -void StatusUploader::StatusGetter::OnSessionStatusReceived( - std::unique_ptr<em::SessionStatusReportRequest> session_status) { - DCHECK(!session_status_response_received_); - session_status_ = std::move(session_status); - session_status_response_received_ = true; - CheckDone(); -} - -void StatusUploader::StatusGetter::CheckDone() { - // Did we receive BOTH responses? - if (device_status_response_received_ && session_status_response_received_) { - // Notify the uploader if it's still alive - StatusUploader* uploader = uploader_.get(); - if (uploader) { - uploader->OnStatusReceived(std::move(device_status_), - std::move(session_status_)); - // Reset just to make sure this doesn't get called multiple times - uploader_.reset(); - } - } + // Gather status in the background. + collector_->GetDeviceAndSessionStatusAsync(base::Bind( + &StatusUploader::OnStatusReceived, weak_factory_.GetWeakPtr())); } void StatusUploader::OnStatusReceived(
diff --git a/chrome/browser/chromeos/policy/status_uploader.h b/chrome/browser/chromeos/policy/status_uploader.h index 877c821..9cbefce 100644 --- a/chrome/browser/chromeos/policy/status_uploader.h +++ b/chrome/browser/chromeos/policy/status_uploader.h
@@ -111,37 +111,6 @@ // invalidate the weak pointers before any other members are destroyed. base::WeakPtrFactory<StatusUploader> weak_factory_; - // Small helper class for state tracking. Necessary because - // DeviceStatusCollector has two independent async calls for getting device - // and session status, but we need BOTH results before we can upload data. - class StatusGetter : public base::RefCountedThreadSafe<StatusGetter> { - public: - explicit StatusGetter(const base::WeakPtr<StatusUploader>& uploader); - - void OnDeviceStatusReceived( - std::unique_ptr<enterprise_management::DeviceStatusReportRequest> - device_status); - void OnSessionStatusReceived( - std::unique_ptr<enterprise_management::SessionStatusReportRequest> - session_status); - - private: - friend class RefCountedThreadSafe<StatusGetter>; - ~StatusGetter(); - - void CheckDone(); - - std::unique_ptr<enterprise_management::DeviceStatusReportRequest> - device_status_; - std::unique_ptr<enterprise_management::SessionStatusReportRequest> - session_status_; - - base::WeakPtr<StatusUploader> uploader_; - - bool device_status_response_received_; - bool session_status_response_received_; - }; - DISALLOW_COPY_AND_ASSIGN(StatusUploader); };
diff --git a/chrome/browser/chromeos/policy/status_uploader_unittest.cc b/chrome/browser/chromeos/policy/status_uploader_unittest.cc index 39d55c65..fe34815 100644 --- a/chrome/browser/chromeos/policy/status_uploader_unittest.cc +++ b/chrome/browser/chromeos/policy/status_uploader_unittest.cc
@@ -53,17 +53,12 @@ : DeviceStatusCollector( local_state, nullptr, - policy::DeviceStatusCollector::LocationUpdateRequester(), policy::DeviceStatusCollector::VolumeInfoFetcher(), policy::DeviceStatusCollector::CPUStatisticsFetcher(), policy::DeviceStatusCollector::CPUTempFetcher()) {} - MOCK_METHOD1( - GetDeviceStatusAsync, - void(const policy::DeviceStatusCollector::DeviceStatusCallback&)); - MOCK_METHOD1( - GetDeviceSessionStatusAsync, - void(const policy::DeviceStatusCollector::DeviceSessionStatusCallback&)); + MOCK_METHOD1(GetDeviceAndSessionStatusAsync, + void(const policy::DeviceStatusCollector::StatusCallback&)); // Explicit mock implementation declared here, since gmock::Invoke can't // handle returning non-moveable types like scoped_ptr. @@ -107,12 +102,9 @@ // Running the task should pass two callbacks into GetDeviceStatusAsync // and GetDeviceSessionStatusAsync. We'll grab these two callbacks. EXPECT_TRUE(task_runner_->HasPendingTask()); - DeviceStatusCollector::DeviceStatusCallback ds_callback; - DeviceStatusCollector::DeviceSessionStatusCallback ss_callback; - EXPECT_CALL(*collector_ptr_, GetDeviceStatusAsync(_)) - .WillOnce(SaveArg<0>(&ds_callback)); - EXPECT_CALL(*collector_ptr_, GetDeviceSessionStatusAsync(_)) - .WillOnce(SaveArg<0>(&ss_callback)); + DeviceStatusCollector::StatusCallback status_callback; + EXPECT_CALL(*collector_ptr_, GetDeviceAndSessionStatusAsync(_)) + .WillOnce(SaveArg<0>(&status_callback)); task_runner_->RunPendingTasks(); testing::Mock::VerifyAndClearExpectations(&device_management_service_); @@ -128,8 +120,7 @@ CloudPolicyClient::StatusCallback callback; EXPECT_CALL(client_, UploadDeviceStatus(_, _, _)) .WillOnce(SaveArg<2>(&callback)); - ds_callback.Run(std::move(device_status)); - ss_callback.Run(std::move(session_status)); + status_callback.Run(std::move(device_status), std::move(session_status)); testing::Mock::VerifyAndClearExpectations(&device_management_service_); // Make sure no status upload is queued up yet (since an upload is in @@ -214,12 +205,9 @@ // and GetDeviceSessionStatusAsync. We'll grab these two callbacks and send // nullptrs to them in order to simulate failure to get status. EXPECT_EQ(1U, task_runner_->NumPendingTasks()); - DeviceStatusCollector::DeviceStatusCallback ds_callback; - DeviceStatusCollector::DeviceSessionStatusCallback ss_callback; - EXPECT_CALL(*collector_ptr_, GetDeviceStatusAsync(_)) - .WillOnce(SaveArg<0>(&ds_callback)); - EXPECT_CALL(*collector_ptr_, GetDeviceSessionStatusAsync(_)) - .WillOnce(SaveArg<0>(&ss_callback)); + DeviceStatusCollector::StatusCallback status_callback; + EXPECT_CALL(*collector_ptr_, GetDeviceAndSessionStatusAsync(_)) + .WillOnce(SaveArg<0>(&status_callback)); task_runner_->RunPendingTasks(); testing::Mock::VerifyAndClearExpectations(&device_management_service_); @@ -227,12 +215,10 @@ // StatusUploader::OnStatusReceived, which in turn should recognize the // failure to get status and queue another status upload. std::unique_ptr<em::DeviceStatusReportRequest> invalid_device_status; - ds_callback.Run(std::move(invalid_device_status)); - EXPECT_EQ(0U, task_runner_->NumPendingTasks()); // Not yet... - std::unique_ptr<em::SessionStatusReportRequest> invalid_session_status; - ss_callback.Run(std::move(invalid_session_status)); - EXPECT_EQ(1U, task_runner_->NumPendingTasks()); // but now! + status_callback.Run(std::move(invalid_device_status), + std::move(invalid_session_status)); + EXPECT_EQ(1U, task_runner_->NumPendingTasks()); // Check the delay of the queued upload const base::TimeDelta expected_delay = base::TimeDelta::FromMilliseconds(
diff --git a/chrome/browser/ui/login/login_handler_browsertest.cc b/chrome/browser/ui/login/login_handler_browsertest.cc index fc05de5..532374d 100644 --- a/chrome/browser/ui/login/login_handler_browsertest.cc +++ b/chrome/browser/ui/login/login_handler_browsertest.cc
@@ -348,15 +348,8 @@ EXPECT_TRUE(observer.handlers().empty()); } -// Flaky on linux chromeos bots: crbug.com/648826. -#if defined(OS_LINUX) && defined(OS_CHROMEOS) -#define MAYBE_TestCancelAuth_OnNavigation DISABLED_TestCancelAuth_OnNavigation -#else -#define MAYBE_TestCancelAuth_OnNavigation TestCancelAuth_OnNavigation -#endif // Test login prompt cancellation on navigation to a new page. -IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, - MAYBE_TestCancelAuth_OnNavigation) { +IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, TestCancelAuth_OnNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); const GURL kAuthURL = embedded_test_server()->GetURL(kAuthBasicPage); const GURL kNoAuthURL = embedded_test_server()->GetURL(kNoAuthPage1); @@ -367,8 +360,9 @@ LoginPromptBrowserTestObserver observer; observer.Register(content::Source<NavigationController>(controller)); - // One LOAD_STOP event for kAuthURL and one for kNoAuthURL. - const int kLoadStopEvents = 2; + // One LOAD_STOP event for LoginInterstitial, second for kAuthURL and third + // for kNoAuthURL. + const int kLoadStopEvents = 3; WindowedLoadStopObserver load_stop_waiter(controller, kLoadStopEvents); WindowedAuthNeededObserver auth_needed_waiter(controller); browser()->OpenURL(OpenURLParams(kAuthURL, Referrer(),
diff --git a/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc b/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc index 2bc366cf..25faf41 100644 --- a/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc +++ b/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc
@@ -116,15 +116,10 @@ source->AddResourcePath("downloads.js", IDR_MD_DOWNLOADS_DOWNLOADS_JS); source->AddResourcePath("i18n_setup.html", IDR_MD_DOWNLOADS_I18N_SETUP_HTML); source->AddResourcePath("icons.html", IDR_MD_DOWNLOADS_ICONS_HTML); - source->AddResourcePath("item.css", IDR_MD_DOWNLOADS_ITEM_CSS); source->AddResourcePath("item.html", IDR_MD_DOWNLOADS_ITEM_HTML); source->AddResourcePath("item.js", IDR_MD_DOWNLOADS_ITEM_JS); - source->AddResourcePath("manager.css", IDR_MD_DOWNLOADS_MANAGER_CSS); source->AddResourcePath("manager.html", IDR_MD_DOWNLOADS_MANAGER_HTML); source->AddResourcePath("manager.js", IDR_MD_DOWNLOADS_MANAGER_JS); - source->AddResourcePath("shared_style.css", - IDR_MD_DOWNLOADS_SHARED_STYLE_CSS); - source->AddResourcePath("toolbar.css", IDR_MD_DOWNLOADS_TOOLBAR_CSS); source->AddResourcePath("toolbar.html", IDR_MD_DOWNLOADS_TOOLBAR_HTML); source->AddResourcePath("toolbar.js", IDR_MD_DOWNLOADS_TOOLBAR_JS); source->SetDefaultResource(IDR_MD_DOWNLOADS_DOWNLOADS_HTML);
diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index b75daa165..bde96d1f 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc
@@ -1736,10 +1736,6 @@ // them to the policy server. const char kDeviceActivityTimes[] = "device_status.activity_times"; -// A pref holding the last known location when device location reporting is -// enabled. -const char kDeviceLocation[] = "device_status.location"; - // A pref holding the value of the policy used to disable mounting of external // storage for the user. const char kExternalStorageDisabled[] = "hardware.external_storage_disabled";
diff --git a/chrome/common/pref_names.h b/chrome/common/pref_names.h index 483fda90..bb6d8106 100644 --- a/chrome/common/pref_names.h +++ b/chrome/common/pref_names.h
@@ -619,7 +619,6 @@ extern const char kShouldAutoEnroll[]; extern const char kAutoEnrollmentPowerLimit[]; extern const char kDeviceActivityTimes[]; -extern const char kDeviceLocation[]; extern const char kExternalStorageDisabled[]; extern const char kExternalStorageReadOnly[]; extern const char kOwnerPrimaryMouseButtonRight[];
diff --git a/components/policy/proto/device_management_backend.proto b/components/policy/proto/device_management_backend.proto index 04551fa..2e17eed 100644 --- a/components/policy/proto/device_management_backend.proto +++ b/components/policy/proto/device_management_backend.proto
@@ -668,7 +668,7 @@ repeated ActiveTimePeriod active_period = 6; // The device location. - optional DeviceLocation device_location = 7; + optional DeviceLocation deprecated_device_location = 7 [deprecated = true]; // List of network interfaces. repeated NetworkInterface network_interface = 8;
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 34373e3..f0070ed0c 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -4943,7 +4943,7 @@ 'features': { 'dynamic_refresh': True, }, - 'example_value': 180000, + 'example_value': 10800000, 'id': 292, 'caption': '''Frequency of device status report uploads''', 'tags': ['admin-sharing'],
diff --git a/gin/public/v8_platform.h b/gin/public/v8_platform.h index 2dd32a0..6506ce4 100644 --- a/gin/public/v8_platform.h +++ b/gin/public/v8_platform.h
@@ -34,17 +34,19 @@ const uint8_t* GetCategoryGroupEnabled(const char* name) override; const char* GetCategoryGroupName( const uint8_t* category_enabled_flag) override; - uint64_t AddTraceEvent(char phase, - const uint8_t* category_enabled_flag, - const char* name, - const char* scope, - uint64_t id, - uint64_t bind_id, - int32_t num_args, - const char** arg_names, - const uint8_t* arg_types, - const uint64_t* arg_values, - unsigned int flags) override; + uint64_t AddTraceEvent( + char phase, + const uint8_t* category_enabled_flag, + const char* name, + const char* scope, + uint64_t id, + uint64_t bind_id, + int32_t num_args, + const char** arg_names, + const uint8_t* arg_types, + const uint64_t* arg_values, + std::unique_ptr<v8::ConvertableToTraceFormat>* arg_convertibles, + unsigned int flags) override; void UpdateTraceEventDuration(const uint8_t* category_enabled_flag, const char* name, uint64_t handle) override;
diff --git a/gin/v8_platform.cc b/gin/v8_platform.cc index f9d2d6a..945eee0c 100644 --- a/gin/v8_platform.cc +++ b/gin/v8_platform.cc
@@ -86,28 +86,50 @@ category_enabled_flag); } -uint64_t V8Platform::AddTraceEvent(char phase, - const uint8_t* category_enabled_flag, - const char* name, - const char* scope, - uint64_t id, - uint64_t bind_id, - int32_t num_args, - const char** arg_names, - const uint8_t* arg_types, - const uint64_t* arg_values, - unsigned int flags) { +namespace { + +class ConvertableToTraceFormatWrapper + : public base::trace_event::ConvertableToTraceFormat { + public: + explicit ConvertableToTraceFormatWrapper( + std::unique_ptr<v8::ConvertableToTraceFormat>& inner) + : inner_(std::move(inner)) {} + ~ConvertableToTraceFormatWrapper() override = default; + void AppendAsTraceFormat(std::string* out) const final { + inner_->AppendAsTraceFormat(out); + } + + private: + std::unique_ptr<v8::ConvertableToTraceFormat> inner_; + + DISALLOW_COPY_AND_ASSIGN(ConvertableToTraceFormatWrapper); +}; + +} // namespace + +uint64_t V8Platform::AddTraceEvent( + char phase, + const uint8_t* category_enabled_flag, + const char* name, + const char* scope, + uint64_t id, + uint64_t bind_id, + int32_t num_args, + const char** arg_names, + const uint8_t* arg_types, + const uint64_t* arg_values, + std::unique_ptr<v8::ConvertableToTraceFormat>* arg_convertables, + unsigned int flags) { std::unique_ptr<base::trace_event::ConvertableToTraceFormat> convertables[2]; if (num_args > 0 && arg_types[0] == TRACE_VALUE_TYPE_CONVERTABLE) { convertables[0].reset( - reinterpret_cast<base::trace_event::ConvertableToTraceFormat*>( - arg_values[0])); + new ConvertableToTraceFormatWrapper(arg_convertables[0])); } if (num_args > 1 && arg_types[1] == TRACE_VALUE_TYPE_CONVERTABLE) { convertables[1].reset( - reinterpret_cast<base::trace_event::ConvertableToTraceFormat*>( - arg_values[1])); + new ConvertableToTraceFormatWrapper(arg_convertables[1])); } + DCHECK_LE(num_args, 2); base::trace_event::TraceEventHandle handle = TRACE_EVENT_API_ADD_TRACE_EVENT_WITH_BIND_ID( phase, category_enabled_flag, name, scope, id, bind_id, num_args,
diff --git a/infra/config/recipes.cfg b/infra/config/recipes.cfg index dd76de7..8aaba70 100644 --- a/infra/config/recipes.cfg +++ b/infra/config/recipes.cfg
@@ -5,7 +5,7 @@ project_id: "build" url: "https://chromium.googlesource.com/chromium/tools/build.git" branch: "master" - revision: "597c27e7cd712b9a07dd091a44f22af5b957c54a" + revision: "567475a8f817b58253b6e305bf5eb5c980f04bc6" } deps { project_id: "depot_tools"
diff --git a/ios/chrome/app/deferred_initialization_runner.h b/ios/chrome/app/deferred_initialization_runner.h index 336fa03..9c37caa2 100644 --- a/ios/chrome/app/deferred_initialization_runner.h +++ b/ios/chrome/app/deferred_initialization_runner.h
@@ -18,17 +18,6 @@ // Returns singleton instance. + (DeferredInitializationRunner*)sharedInstance; -// Deprecated, use |enqueueBlockNamed:block:| instead. -// Schedules |block| to be run after |delaySeconds| on the current queue. -// This |block| is stored as |name| so code can force this initialization to -// be run synchronously if necessary. This method may be called more than -// once with the same |name| parameter. Any block with the same |name| -// cancels a previously scheduled block of the same |name| if the block has -// not been run yet. -- (void)runBlockNamed:(NSString*)name - after:(NSTimeInterval)delaySeconds - block:(ProceduralBlock)block; - // Stores |block| under |name| to a queue of blocks to run. All blocks are run // sequentially with a small delay before the first block and between each // successive block. If a block is already registered under |name|, it is
diff --git a/ios/chrome/app/deferred_initialization_runner.mm b/ios/chrome/app/deferred_initialization_runner.mm index 3fa0812..7e175b4 100644 --- a/ios/chrome/app/deferred_initialization_runner.mm +++ b/ios/chrome/app/deferred_initialization_runner.mm
@@ -26,10 +26,6 @@ - (instancetype)initWithName:(NSString*)name block:(ProceduralBlock)block NS_DESIGNATED_INITIALIZER; -// Dispatches the deferred execution the block after |delaySeconds|. -// Deprecated. -- (void)dispatch:(NSTimeInterval)delaySeconds; - // Executes the deferred block now. - (void)run; @@ -46,15 +42,6 @@ return nil; } -- (void)dispatch:(NSTimeInterval)delaySeconds { - int64_t nanoseconds = delaySeconds * NSEC_PER_SEC; - DCHECK([NSThread isMainThread]); - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, nanoseconds), - dispatch_get_main_queue(), ^() { - [self run]; - }); -} - - (instancetype)initWithName:(NSString*)name block:(ProceduralBlock)block { DCHECK(block); self = [super init]; @@ -112,7 +99,7 @@ return instance; } -- (id)init { +- (instancetype)init { self = [super init]; if (self) { _blocksNameQueue.reset([[NSMutableArray array] retain]); @@ -163,22 +150,6 @@ [_blocksNameQueue removeObjectAtIndex:0]; } -- (void)runBlockNamed:(NSString*)name - after:(NSTimeInterval)delaySeconds - block:(ProceduralBlock)block { - DCHECK(name); - // Safety check in case this function is called with a nanosecond or - // microsecond parameter by mistake. - DCHECK(delaySeconds < 3600.0); - // Cancels the previously scheduled block, if there is one, so this - // |name| block will not be run more than once. - [[_runBlocks objectForKey:name] cancel]; - base::scoped_nsobject<DeferredInitializationBlock> deferredBlock( - [[DeferredInitializationBlock alloc] initWithName:name block:block]); - [_runBlocks setObject:deferredBlock forKey:name]; - [deferredBlock dispatch:delaySeconds]; -} - - (void)runBlockIfNecessary:(NSString*)name { DCHECK([NSThread isMainThread]); [[_runBlocks objectForKey:name] run];
diff --git a/ios/third_party/earl_grey/BUILD.gn b/ios/third_party/earl_grey/BUILD.gn index 277f5f5..be7a6f68 100644 --- a/ios/third_party/earl_grey/BUILD.gn +++ b/ios/third_party/earl_grey/BUILD.gn
@@ -254,8 +254,12 @@ public_configs = [ ":config" ] - configs -= [ "//build/config/gcc:symbol_visibility_hidden" ] + configs -= [ + "//build/config/gcc:symbol_visibility_hidden", + "//build/config/compiler:chromium_code", + ] configs += [ + "//build/config/compiler:no_chromium_code", "//build/config/compiler:enable_arc", "//build/config/gcc:symbol_visibility_default", ]
diff --git a/ios/third_party/ochamcrest/BUILD.gn b/ios/third_party/ochamcrest/BUILD.gn index 9c1038b..815a85d 100644 --- a/ios/third_party/ochamcrest/BUILD.gn +++ b/ios/third_party/ochamcrest/BUILD.gn
@@ -229,7 +229,13 @@ "UIKit.framework", ] - configs += [ "//build/config/compiler:enable_arc" ] - configs -= [ "//build/config/gcc:symbol_visibility_hidden" ] - configs += [ "//build/config/gcc:symbol_visibility_default" ] + configs -= [ + "//build/config/compiler:chromium_code", + "//build/config/gcc:symbol_visibility_hidden", + ] + configs += [ + "//build/config/compiler:enable_arc", + "//build/config/compiler:no_chromium_code", + "//build/config/gcc:symbol_visibility_default", + ] }
diff --git a/remoting/host/host_config_unittest.cc b/remoting/host/host_config_unittest.cc index c082491..e8f8a120 100644 --- a/remoting/host/host_config_unittest.cc +++ b/remoting/host/host_config_unittest.cc
@@ -44,13 +44,13 @@ TEST_F(HostConfigTest, InvalidFile) { ASSERT_TRUE(test_dir_.CreateUniqueTempDir()); base::FilePath non_existent_file = - test_dir_.path().AppendASCII("non_existent.json"); + test_dir_.GetPath().AppendASCII("non_existent.json"); EXPECT_FALSE(HostConfigFromJsonFile(non_existent_file)); } TEST_F(HostConfigTest, Read) { ASSERT_TRUE(test_dir_.CreateUniqueTempDir()); - base::FilePath test_file = test_dir_.path().AppendASCII("read.json"); + base::FilePath test_file = test_dir_.GetPath().AppendASCII("read.json"); WriteTestFile(test_file); std::unique_ptr<base::DictionaryValue> target( HostConfigFromJsonFile(test_file)); @@ -74,7 +74,7 @@ TEST_F(HostConfigTest, Write) { ASSERT_TRUE(test_dir_.CreateUniqueTempDir()); - base::FilePath test_file = test_dir_.path().AppendASCII("write.json"); + base::FilePath test_file = test_dir_.GetPath().AppendASCII("write.json"); WriteTestFile(test_file); std::unique_ptr<base::DictionaryValue> target( HostConfigFromJsonFile(test_file));
diff --git a/remoting/host/linux/audio_pipe_reader_unittest.cc b/remoting/host/linux/audio_pipe_reader_unittest.cc index dc396768..65e87dc 100644 --- a/remoting/host/linux/audio_pipe_reader_unittest.cc +++ b/remoting/host/linux/audio_pipe_reader_unittest.cc
@@ -30,7 +30,7 @@ void SetUp() override { ASSERT_TRUE(test_dir_.CreateUniqueTempDir()); - pipe_path_ = test_dir_.path().AppendASCII("test_pipe"); + pipe_path_ = test_dir_.GetPath().AppendASCII("test_pipe"); audio_thread_.reset(new base::Thread("TestAudioThread")); audio_thread_->StartWithOptions( base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
diff --git a/remoting/host/linux/certificate_watcher_unittest.cc b/remoting/host/linux/certificate_watcher_unittest.cc index 62c9821..10cb564 100644 --- a/remoting/host/linux/certificate_watcher_unittest.cc +++ b/remoting/host/linux/certificate_watcher_unittest.cc
@@ -32,7 +32,7 @@ base::Unretained(this)), task_runner_)); watcher_->SetDelayForTests(base::TimeDelta::FromSeconds(0)); - watcher_->SetWatchPathForTests(temp_dir_.path()); + watcher_->SetWatchPathForTests(temp_dir_.GetPath()); } ~CertificateWatcherTest() override { @@ -84,7 +84,7 @@ void TouchFileTask(const char* filename) { std::string testWriteString = std::to_string(rand()); - base::FilePath path = temp_dir_.path().AppendASCII(filename); + base::FilePath path = temp_dir_.GetPath().AppendASCII(filename); if (base::PathExists(path)) { EXPECT_TRUE(base::AppendToFile(path, testWriteString.c_str(),
diff --git a/remoting/host/security_key/security_key_auth_handler_posix_unittest.cc b/remoting/host/security_key/security_key_auth_handler_posix_unittest.cc index de2aa7df..52d5625 100644 --- a/remoting/host/security_key/security_key_auth_handler_posix_unittest.cc +++ b/remoting/host/security_key/security_key_auth_handler_posix_unittest.cc
@@ -58,7 +58,7 @@ : run_loop_(new base::RunLoop()), file_thread_("SecurityKeyAuthHandlerPosixTest_FileThread") { EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); - socket_path_ = temp_dir_.path().Append(kSocketFilename); + socket_path_ = temp_dir_.GetPath().Append(kSocketFilename); remoting::SecurityKeyAuthHandler::SetSecurityKeySocketName(socket_path_); EXPECT_TRUE(file_thread_.StartWithOptions(
diff --git a/rlz/lib/rlz_lib_test.cc b/rlz/lib/rlz_lib_test.cc index 1a908ed..911a8f4 100644 --- a/rlz/lib/rlz_lib_test.cc +++ b/rlz/lib/rlz_lib_test.cc
@@ -847,8 +847,8 @@ void ReadonlyRlzDirectoryTest::SetUp() { RlzLibTestNoMachineState::SetUp(); // Make the rlz directory non-writeable. - int chmod_result = chmod(m_rlz_test_helper_.temp_dir_.path().value().c_str(), - 0500); + int chmod_result = + chmod(m_rlz_test_helper_.temp_dir_.GetPath().value().c_str(), 0500); ASSERT_EQ(0, chmod_result); }
diff --git a/rlz/test/rlz_test_helpers.cc b/rlz/test/rlz_test_helpers.cc index f2b347a..4e870fd 100644 --- a/rlz/test/rlz_test_helpers.cc +++ b/rlz/test/rlz_test_helpers.cc
@@ -137,7 +137,7 @@ #endif // defined(OS_WIN) #if defined(OS_POSIX) ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - rlz_lib::testing::SetRlzStoreDirectory(temp_dir_.path()); + rlz_lib::testing::SetRlzStoreDirectory(temp_dir_.GetPath()); #endif // defined(OS_POSIX) }
diff --git a/rlz/test/rlz_unittest_main.cc b/rlz/test/rlz_unittest_main.cc index d6da7e7..b7a41ca9 100644 --- a/rlz/test/rlz_unittest_main.cc +++ b/rlz/test/rlz_unittest_main.cc
@@ -33,7 +33,7 @@ // creates and owns RlzValueStore object for its lifetime. base::ScopedTempDir temp_dir; if (temp_dir.CreateUniqueTempDir()) - rlz_lib::testing::SetRlzStoreDirectory(temp_dir.path()); + rlz_lib::testing::SetRlzStoreDirectory(temp_dir.GetPath()); #endif rlz_lib::SupplementaryBranding branding("TEST"); ret = RUN_ALL_TESTS();
diff --git a/sandbox/win/src/address_sanitizer_test.cc b/sandbox/win/src/address_sanitizer_test.cc index 75fb0eb..0800cde 100644 --- a/sandbox/win/src/address_sanitizer_test.cc +++ b/sandbox/win/src/address_sanitizer_test.cc
@@ -62,7 +62,8 @@ base::ScopedTempDir temp_directory; base::FilePath temp_file_name; ASSERT_TRUE(temp_directory.CreateUniqueTempDir()); - ASSERT_TRUE(CreateTemporaryFileInDir(temp_directory.path(), &temp_file_name)); + ASSERT_TRUE( + CreateTemporaryFileInDir(temp_directory.GetPath(), &temp_file_name)); SECURITY_ATTRIBUTES attrs = {}; attrs.nLength = sizeof(attrs);
diff --git a/sandbox/win/src/handle_inheritance_test.cc b/sandbox/win/src/handle_inheritance_test.cc index 939ace6..e7c6903 100644 --- a/sandbox/win/src/handle_inheritance_test.cc +++ b/sandbox/win/src/handle_inheritance_test.cc
@@ -23,7 +23,8 @@ base::ScopedTempDir temp_directory; base::FilePath temp_file_name; ASSERT_TRUE(temp_directory.CreateUniqueTempDir()); - ASSERT_TRUE(CreateTemporaryFileInDir(temp_directory.path(), &temp_file_name)); + ASSERT_TRUE( + CreateTemporaryFileInDir(temp_directory.GetPath(), &temp_file_name)); SECURITY_ATTRIBUTES attrs = {}; attrs.nLength = sizeof(attrs);
diff --git a/sandbox/win/src/process_mitigations_test.cc b/sandbox/win/src/process_mitigations_test.cc index 7870906..7aae596 100644 --- a/sandbox/win/src/process_mitigations_test.cc +++ b/sandbox/win/src/process_mitigations_test.cc
@@ -477,7 +477,7 @@ base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); - base::FilePath new_path = temp_dir.path(); + base::FilePath new_path = temp_dir.GetPath(); new_path = new_path.Append(L"lowIL_calc.exe"); // Test file will be cleaned up by the ScopedTempDir.
diff --git a/sql/test/sql_test_base.cc b/sql/test/sql_test_base.cc index bdd427f..52930bb 100644 --- a/sql/test/sql_test_base.cc +++ b/sql/test/sql_test_base.cc
@@ -16,7 +16,7 @@ } base::FilePath SQLTestBase::db_path() { - return temp_dir_.path().AppendASCII("SQLTest.db"); + return temp_dir_.GetPath().AppendASCII("SQLTest.db"); } sql::Connection& SQLTestBase::db() {
diff --git a/third_party/WebKit/LayoutTests/sensor/ambient-light-sensor.html b/third_party/WebKit/LayoutTests/sensor/ambient-light-sensor.html new file mode 100644 index 0000000..340cd57 --- /dev/null +++ b/third_party/WebKit/LayoutTests/sensor/ambient-light-sensor.html
@@ -0,0 +1,189 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script src="../resources/mojo-helpers.js"></script> +<script src="resources/sensor-helpers.js"></script> +<script> + +'use strict'; + +if (!window.testRunner) + debug('This test cannot be run without the TestRunner'); + +const kDefaultReadingValue = 3.1415; + +function update_sensor_reading(buffer) { + buffer[0] = window.performance.now(); + buffer[1] = kDefaultReadingValue; +} + +sensor_test(sensor => { + let ambientLightSensor = new AmbientLightSensor({frequency: 60}); + ambientLightSensor.start(); + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then((mockSensor) => { + return new Promise((resolve, reject) => { + ambientLightSensor.onstatechange = event => { + if (ambientLightSensor.state === 'idle') { + resolve(mockSensor); + } + + if (ambientLightSensor.state === 'active') { + ambientLightSensor.stop(); + } + }; + ambientLightSensor.onerror = reject; + }); + }) + .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); + + return testPromise; +}, 'Test that sensor can be successfully created if sensor is supported.'); + +sensor_test(sensor => { + let ambientLightSensor = new AmbientLightSensor(); + ambientLightSensor.start(); + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then((mockSensor) => { + return new Promise((resolve, reject) => { + ambientLightSensor.onstatechange = event => { + if (ambientLightSensor.state === 'idle') { + resolve(mockSensor); + } + + if (ambientLightSensor.state === 'active') { + ambientLightSensor.stop(); + } + }; + + ambientLightSensor.onerror = reject; + }); + }) + .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); + + return testPromise; +}, 'Test that sensor can be constructed with default configuration.'); + +sensor_test(sensor => { + let ambientLightSensor = new AmbientLightSensor({frequency: 60}); + ambientLightSensor.start(); + + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then(mockSensor => { return mockSensor.addConfigurationCalled(); }) + .then(mockSensor => { + return new Promise((resolve, reject) => { + ambientLightSensor.onstatechange = event => { + if (ambientLightSensor.state === 'idle') { + resolve(mockSensor); + } + + if (ambientLightSensor.state === 'active') { + ambientLightSensor.stop(); + } + }; + }); + }) + .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); + + return testPromise; +}, 'Test that addConfiguration and removeConfiguration is called.'); + +sensor_test(sensor => { + let ambientLightSensor = new AmbientLightSensor({frequency: 60}); + ambientLightSensor.start(); + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then(mockSensor => { + return mockSensor.setUpdateSensorReadingFunction(update_sensor_reading); + }) + .then((mockSensor) => { + return new Promise((resolve, reject) => { + ambientLightSensor.onstatechange = event => { + if (ambientLightSensor.state === 'idle') { + resolve(mockSensor); + } + }; + + ambientLightSensor.onchange = e => { + assert_equals(e.reading.illuminance, kDefaultReadingValue); + ambientLightSensor.stop(); + }; + + ambientLightSensor.onerror = reject; + }); + }) + .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); + + return testPromise; +}, 'Test that onChange is called and sensor reading is valid.'); + +sensor_test(sensor => { + let ambientLightSensor = new AmbientLightSensor({frequency: 60}); + ambientLightSensor.start(); + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then(mockSensor => { + return mockSensor.setUpdateSensorReadingFunction(update_sensor_reading); + }) + .then((mockSensor) => { + return new Promise((resolve, reject) => { + ambientLightSensor.onstatechange = () => { + if (ambientLightSensor.state === 'idle') { + assert_equals(ambientLightSensor.reading, null); + resolve(mockSensor); + } + } + + ambientLightSensor.onchange = e => { + assert_equals(e.reading.illuminance, kDefaultReadingValue); + ambientLightSensor.stop(); + } + ambientLightSensor.onerror = reject; + }); + }) + .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); + + return testPromise; +}, 'Test that sensor reading is not updated when sensor is stopped.'); + +sensor_test(sensor => { + let ambientLightSensor = new AmbientLightSensor(); + ambientLightSensor.start(); + let testPromise = sensor.mockSensorProvider.getCreatedSensor() + .then(mockSensor => { + return mockSensor.setUpdateSensorReadingFunction(update_sensor_reading); + }) + .then((mockSensor) => { + return new Promise((resolve, reject) => { + ambientLightSensor.onchange = e => { + if (e.reading.illuminance == kDefaultReadingValue) { + resolve(mockSensor); + } + } + ambientLightSensor.onerror = reject; + }); + }) + .then((mockSensor) => { + testRunner.setPageVisibility("hidden"); + return mockSensor.suspendCalled(); + }) + .then((mockSensor) => { + testRunner.setPageVisibility("visible"); + return mockSensor.resumeCalled(); + }) + .then((mockSensor) => { + return new Promise((resolve, reject) => { + ambientLightSensor.onstatechange = () => { + if (ambientLightSensor.state === 'idle') { + resolve(mockSensor); + } + } + ambientLightSensor.stop(); + ambientLightSensor.onerror = reject; + }); + }) + .then(mockSensor => { return mockSensor.removeConfigurationCalled(); }); + + return testPromise; +}, 'Test that sensor receives suspend / resume notifications when page' + +' visibility changes.'); + +</script>
diff --git a/third_party/WebKit/LayoutTests/sensor/idl-AmbientLightSensor.html b/third_party/WebKit/LayoutTests/sensor/idl-AmbientLightSensor.html new file mode 100644 index 0000000..660772f --- /dev/null +++ b/third_party/WebKit/LayoutTests/sensor/idl-AmbientLightSensor.html
@@ -0,0 +1,14 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script> + +test(function() { + // Test that AmbientLightSensor interface exists + assert_true('AmbientLightSensor' in window); + // Test that AmbientLightSensorReading interface exists + assert_true('AmbientLightSensorReading' in window); +}, 'Test that the AmbientLightSensor and AmbientLightSensorReading interfaces' + + ' are present.'); + +</script>
diff --git a/third_party/WebKit/LayoutTests/sensor/mock-sensor.html b/third_party/WebKit/LayoutTests/sensor/mock-sensor.html new file mode 100644 index 0000000..79683101 --- /dev/null +++ b/third_party/WebKit/LayoutTests/sensor/mock-sensor.html
@@ -0,0 +1,14 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script src="../resources/mojo-helpers.js"></script> +<script src="resources/sensor-helpers.js"></script> +<script> + +'use strict'; + +sensor_test(sensor => { + assert_true(sensor instanceof Object); + assert_true(sensor.mockSensorProvider instanceof Object); +}, 'Sensor Mojo bindings and mock interfaces are available to tests.') +</script> \ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/sensor/resources/sensor-helpers.js b/third_party/WebKit/LayoutTests/sensor/resources/sensor-helpers.js new file mode 100644 index 0000000..6eb0f8d --- /dev/null +++ b/third_party/WebKit/LayoutTests/sensor/resources/sensor-helpers.js
@@ -0,0 +1,302 @@ +'use strict'; + +function sensor_mocks(mojo) { + return define('Generic Sensor API mocks', [ + 'mojo/public/js/core', + 'mojo/public/js/bindings', + 'mojo/public/js/connection', + 'device/generic_sensor/public/interfaces/sensor_provider.mojom', + 'device/generic_sensor/public/interfaces/sensor.mojom', + ], (core, bindings, connection, sensor_provider, sensor) => { + + // Helper function that returns resolved promise with result. + function sensorResponse(success) { + return Promise.resolve({success}); + } + + // Class that mocks Sensor interface defined in sensor.mojom + class MockSensor { + constructor(stub, handle, offset, size, reportingMode) { + this.client_ = null; + this.stub_ = stub; + this.start_should_fail_ = false; + this.reporting_mode_ = reportingMode; + this.sensor_reading_timer_id_ = null; + this.update_reading_function_ = null; + this.suspend_called_ = null; + this.resume_called_ = null; + this.add_configuration_called_ = null; + this.remove_configuration_called_ = null; + this.active_sensor_configurations_ = []; + let rv = core.mapBuffer(handle, offset, size, + core.MAP_BUFFER_FLAG_NONE); + assert_equals(rv.result, core.RESULT_OK, "Failed to map shared buffer"); + this.buffer_array_ = rv.buffer; + this.buffer_ = new Float64Array(this.buffer_array_); + bindings.StubBindings(this.stub_).delegate = this; + bindings.StubBindings(this.stub_).connectionErrorHandler = () => { + reset(); + }; + } + + // Returns default configuration. + getDefaultConfiguration() { + return Promise.resolve({frequency: 5}); + } + + // Adds configuration for the sensor and starts reporting fake data + // through update_reading_function_ callback. + addConfiguration(configuration) { + assert_not_equals(configuration, null, "Invalid sensor configuration."); + + if (this.add_configuration_called_ != null) { + this.add_configuration_called_(this); + } + + if (!this.start_should_fail_ && this.update_reading_function_ != null) { + let timeout = (1 / configuration.frequency) * 1000; + this.sensor_reading_timer_id_ = window.setTimeout(() => { + this.update_reading_function_(this.buffer_); + if (this.reporting_mode_ === sensor.ReportingMode.ON_CHANGE) { + this.client_.sensorReadingChanged(); + } + }, timeout); + + this.active_sensor_configurations_.push(configuration); + } + + return sensorResponse(!this.start_should_fail_); + } + + // Removes sensor configuration from the list of active configurations and + // stops notification about sensor reading changes if + // active_sensor_configurations_ is empty. + removeConfiguration(configuration) { + if (this.remove_configuration_called_ != null) { + this.remove_configuration_called_(this); + } + + let index = this.active_sensor_configurations_.indexOf(configuration); + if (index !== -1) { + this.active_sensor_configurations_.splice(index, 1); + } else { + return sensorResponse(false); + } + + if (this.sensor_reading_timer_id_ != null + && this.active_sensor_configurations_.length === 0) { + window.clearTimeout(this.sensor_reading_timer_id_); + this.sensor_reading_timer_id_ = null; + } + + return sensorResponse(true); + } + + // Suspends sensor. + suspend() { + if (this.suspend_called_ != null) { + this.suspend_called_(this); + } + } + + // Resumes sensor. + resume() { + if (this.resume_called_ != null) { + this.resume_called_(this); + } + } + + // Mock functions + + // Resets mock Sensor state. + reset() { + if (this.sensor_reading_timer_id_) { + window.clearTimeout(this.sensor_reading_timer_id_); + } + + this.start_should_fail_ = false; + this.sensor_reading_timer_id_ = null; + this.active_sensor_configurations_ = []; + this.suspend_called_ = null; + this.resume_called_ = null; + this.add_configuration_called_ = null; + this.remove_configuration_called_ = null; + for (let i = 0; i < this.buffer_.length; ++i) { + this.buffer_[i] = 0; + } + } + + // Sets callback that is used to deliver sensor reading updates. + setUpdateSensorReadingFunction(update_reading_function) { + this.update_reading_function_ = update_reading_function; + return Promise.resolve(this); + } + + // Sets flag that forces sensor to fail when addConfiguration is invoked. + setStartShouldFail(should_fail) { + this.start_should_fail_ = should_fail; + } + + // Returns resolved promise if suspend() was called, rejected otherwise. + suspendCalled() { + return new Promise((resolve, reject) => { + this.suspend_called_ = resolve; + }); + } + + // Returns resolved promise if resume() was called, rejected otherwise. + resumeCalled() { + return new Promise((resolve, reject) => { + this.resume_called_ = resolve; + }); + } + + // Resolves promise when addConfiguration() is called. + addConfigurationCalled() { + return new Promise((resolve, reject) => { + this.add_configuration_called_ = resolve; + }); + } + + // Resolves promise when removeConfiguration() is called. + removeConfigurationCalled() { + return new Promise((resolve, reject) => { + this.remove_configuration_called_ = resolve; + }); + } + + } + + // Helper function that returns resolved promise for getSensor() function. + function getSensorResponse(init_params, client_request) { + return Promise.resolve({init_params, client_request}); + } + + // Class that mocks SensorProvider interface defined in + // sensor_provider.mojom + class MockSensorProvider { + constructor() { + this.reading_size_in_bytes_ = + sensor_provider.SensorInitParams.kReadBufferSize; + this.shared_buffer_size_in_bytes_ = this.reading_size_in_bytes_ * + sensor.SensorType.LAST; + let rv = + core.createSharedBuffer( + this.shared_buffer_size_in_bytes_, + core.CREATE_SHARED_BUFFER_OPTIONS_FLAG_NONE); + assert_equals(rv.result, core.RESULT_OK, "Failed to create buffer"); + this.shared_buffer_handle_ = rv.handle; + this.active_sensor_ = null; + this.get_sensor_should_fail_ = false; + this.resolve_func_ = null; + this.is_continuous_ = false; + } + + // Returns initialized Sensor proxy to the client. + getSensor(type, stub) { + if (this.get_sensor_should_fail_) { + return getSensorResponse(null, null); + } + + let offset = + (sensor.SensorType.LAST - type) * this.reading_size_in_bytes_; + let reporting_mode = sensor.ReportingMode.ON_CHANGE; + if (this.is_continuous_) { + reporting_mode = sensor.ReportingMode.CONTINUOUS; + } + + if (this.active_sensor_ == null) { + let mockSensor = new MockSensor(stub, this.shared_buffer_handle_, + offset, this.reading_size_in_bytes_, reporting_mode); + this.active_sensor_ = mockSensor; + } + + let rv = + core.duplicateBufferHandle( + this.shared_buffer_handle_, + core.DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_NONE); + + assert_equals(rv.result, core.RESULT_OK); + + let default_config = {frequency: 5}; + + let init_params = + new sensor_provider.SensorInitParams( + { memory: rv.handle, + buffer_offset: offset, + mode: reporting_mode, + default_configuration: default_config }); + + if (this.resolve_func_ !== null) { + this.resolve_func_(this.active_sensor_); + } + + var client_handle = connection.bindProxy(proxy => { + this.active_sensor_.client_ = proxy; + }, sensor.SensorClient); + + return getSensorResponse(init_params, client_handle); + } + + // Binds object to mojo message pipe + bindToPipe(pipe) { + this.stub_ = connection.bindHandleToStub( + pipe, sensor_provider.SensorProvider); + bindings.StubBindings(this.stub_).delegate = this; + } + + // Mock functions + + // Resets state of mock SensorProvider between test runs. + reset() { + if (this.active_sensor_ != null) { + this.active_sensor_.reset(); + } + + this.get_sensor_should_fail_ = false; + this.resolve_func_ = null; + } + + // Sets flag that forces mock SensorProvider to fail when getSensor() is + // invoked. + setGetSensorShouldFail(should_fail) { + this.get_sensor_should_fail_ = should_fail; + } + + // Returns mock sensor that was created in getSensor to the layout test. + getCreatedSensor() { + if (this.active_sensor_ != null) { + return Promise.resolve(this.active_sensor_); + } + + return new Promise((resolve, reject) => { + this.resolve_func_ = resolve; + }); + } + + // Forces sensor to use |reporting_mode| as an update mode. + setContinuousReportingMode(reporting_mode) { + this.is_continuous_ = reporting_mode; + } + } + + let mockSensorProvider = new MockSensorProvider; + mojo.frameInterfaces.addInterfaceOverrideForTesting( + sensor_provider.SensorProvider.name, + pipe => { + mockSensorProvider.bindToPipe(pipe); + }); + + return Promise.resolve({ + mockSensorProvider: mockSensorProvider, + }); + }); +} + +function sensor_test(func, name, properties) { + mojo_test(mojo => sensor_mocks(mojo).then(sensor => { + let result = Promise.resolve(func(sensor)); + let cleanUp = () => { sensor.mockSensorProvider.reset(); }; + return result.then(cleanUp, cleanUp); + }), name, properties); +}
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt index 9fd1cc3..f9f31ac9 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt
@@ -17,6 +17,14 @@ [INTERFACES] +interface AmbientLightSensor : Sensor + attribute @@toStringTag + getter reading + method constructor +interface AmbientLightSensorReading : SensorReading + attribute @@toStringTag + getter illuminance + method constructor interface AnalyserNode : AudioNode attribute @@toStringTag getter fftSize
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8PerformanceObserverCallback.cpp b/third_party/WebKit/Source/bindings/core/v8/V8PerformanceObserverCallback.cpp index 45fdb98..10347a3 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8PerformanceObserverCallback.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8PerformanceObserverCallback.cpp
@@ -17,8 +17,7 @@ namespace blink { V8PerformanceObserverCallback::V8PerformanceObserverCallback(v8::Local<v8::Function> callback, v8::Local<v8::Object> owner, ScriptState* scriptState) - : ActiveDOMCallback(scriptState->getExecutionContext()) - , m_callback(V8PerformanceObserverInnerCallback::create(scriptState->isolate(), callback)) + : m_callback(V8PerformanceObserverInnerCallback::create(scriptState->isolate(), callback)) , m_scriptState(scriptState) { V8PrivateProperty::getPerformanceObserverCallback(scriptState->isolate()).set(scriptState->context(), owner, m_callback->v8Value(scriptState->isolate())); @@ -30,9 +29,6 @@ void V8PerformanceObserverCallback::handleEvent(PerformanceObserverEntryList* entries, PerformanceObserver* observer) { - if (!canInvokeCallback()) - return; - TrackExceptionState exceptionState; m_callback->call(m_scriptState.get(), observer, exceptionState, entries, observer); } @@ -41,7 +37,6 @@ { visitor->trace(m_callback); PerformanceObserverCallback::trace(visitor); - ActiveDOMCallback::trace(visitor); } } // namespace blink
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8PerformanceObserverCallback.h b/third_party/WebKit/Source/bindings/core/v8/V8PerformanceObserverCallback.h index 0bef031..d44516a 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8PerformanceObserverCallback.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8PerformanceObserverCallback.h
@@ -14,8 +14,7 @@ namespace blink { -class V8PerformanceObserverCallback final : public PerformanceObserverCallback, public ActiveDOMCallback { - USING_GARBAGE_COLLECTED_MIXIN(V8PerformanceObserverCallback); +class V8PerformanceObserverCallback final : public PerformanceObserverCallback { public: static V8PerformanceObserverCallback* create(v8::Local<v8::Function> callback, v8::Local<v8::Object> owner, ScriptState* scriptState) { @@ -27,7 +26,13 @@ DECLARE_VIRTUAL_TRACE(); void handleEvent(PerformanceObserverEntryList*, PerformanceObserver*) override; - ExecutionContext* getExecutionContext() const override { return ContextLifecycleObserver::getExecutionContext(); } + + // TODO(lkawai,bashi): This function should be removed. + ExecutionContext* getExecutionContext() const override + { + NOTREACHED(); + return nullptr; + } private: CORE_EXPORT V8PerformanceObserverCallback(v8::Local<v8::Function>, v8::Local<v8::Object>, ScriptState*);
diff --git a/third_party/WebKit/Source/bindings/core/v8/custom/V8PerformanceObserverCustom.cpp b/third_party/WebKit/Source/bindings/core/v8/custom/V8PerformanceObserverCustom.cpp index 18ee50d..03c0b8a 100644 --- a/third_party/WebKit/Source/bindings/core/v8/custom/V8PerformanceObserverCustom.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/custom/V8PerformanceObserverCustom.cpp
@@ -41,7 +41,7 @@ } callback = V8PerformanceObserverCallback::create(v8::Local<v8::Function>::Cast(info[0]), wrapper, ScriptState::current(info.GetIsolate())); } - PerformanceObserver* observer = PerformanceObserver::create(performance, callback); + PerformanceObserver* observer = PerformanceObserver::create(ScriptState::forReceiverObject(info), performance, callback); v8SetReturnValue(info, V8DOMWrapper::associateObjectWithWrapper(info.GetIsolate(), observer, &wrapperTypeInfo, wrapper)); }
diff --git a/third_party/WebKit/Source/bindings/modules/BUILD.gn b/third_party/WebKit/Source/bindings/modules/BUILD.gn index 7a01b57..208b90f7 100644 --- a/third_party/WebKit/Source/bindings/modules/BUILD.gn +++ b/third_party/WebKit/Source/bindings/modules/BUILD.gn
@@ -95,7 +95,7 @@ compute_interfaces_info_individual("interfaces_info_individual_modules") { sources = modules_definition_idl_files + modules_static_dependency_idl_files + - modules_generated_dependency_idl_files + modules_generated_dependency_idl_files interfaces_info_file = "$bindings_modules_output_dir/InterfacesInfoOverallIndividual.pickle" component_info_file = @@ -118,7 +118,6 @@ ] args = [ - "--write-file-only-if-changed=1", "--", rebase_path("$bindings_core_output_dir/InterfacesInfoCoreIndividual.pickle", root_build_dir),
diff --git a/third_party/WebKit/Source/bindings/modules/v8/BUILD.gn b/third_party/WebKit/Source/bindings/modules/v8/BUILD.gn index 5c9d6e2..514da4d 100644 --- a/third_party/WebKit/Source/bindings/modules/v8/BUILD.gn +++ b/third_party/WebKit/Source/bindings/modules/v8/BUILD.gn
@@ -61,7 +61,6 @@ "--output", rebase_path(bindings_modules_generated_init_partial_interfaces_file, root_build_dir), - "--write-file-only-if-changed=1", ] deps = [
diff --git a/third_party/WebKit/Source/bindings/scripts/compute_global_objects.py b/third_party/WebKit/Source/bindings/scripts/compute_global_objects.py index 2e83e466..9538f85a 100755 --- a/third_party/WebKit/Source/bindings/scripts/compute_global_objects.py +++ b/third_party/WebKit/Source/bindings/scripts/compute_global_objects.py
@@ -29,15 +29,11 @@ usage = 'Usage: %prog [options] [GlobalObjectsComponent.pickle]... [GlobalObjects.pickle]' parser = optparse.OptionParser(usage=usage) parser.add_option('--idl-files-list', help='file listing IDL files') - parser.add_option('--write-file-only-if-changed', type='int', help='if true, do not write an output file if it would be identical to the existing one, which avoids unnecessary rebuilds in ninja') options, args = parser.parse_args() if options.idl_files_list is None: parser.error('Must specify a file listing IDL files using --idl-files-list.') - if options.write_file_only_if_changed is None: - parser.error('Must specify whether output files are only written if changed using --write-file-only-if-changed.') - options.write_file_only_if_changed = bool(options.write_file_only_if_changed) if not args: parser.error('Must specify an output pickle filename as argument, ' 'optionally preceeded by input pickle filenames.') @@ -103,8 +99,7 @@ idl_files_to_interface_name_global_names(idl_files)) write_pickle_file(output_global_objects_filename, - interface_name_global_names, - options.write_file_only_if_changed) + interface_name_global_names) if __name__ == '__main__':
diff --git a/third_party/WebKit/Source/bindings/scripts/compute_interfaces_info_individual.py b/third_party/WebKit/Source/bindings/scripts/compute_interfaces_info_individual.py index 6c7d954..4fd741a 100755 --- a/third_party/WebKit/Source/bindings/scripts/compute_interfaces_info_individual.py +++ b/third_party/WebKit/Source/bindings/scripts/compute_interfaces_info_individual.py
@@ -75,16 +75,12 @@ parser.add_option('--idl-files-list', help='file listing IDL files') parser.add_option('--interfaces-info-file', help='interface info pickle file') parser.add_option('--component-info-file', help='component wide info pickle file') - parser.add_option('--write-file-only-if-changed', type='int', help='if true, do not write an output file if it would be identical to the existing one, which avoids unnecessary rebuilds in ninja') options, args = parser.parse_args() if options.interfaces_info_file is None: parser.error('Must specify an output file using --interfaces-info-file.') if options.idl_files_list is None: parser.error('Must specify a file listing IDL files using --idl-files-list.') - if options.write_file_only_if_changed is None: - parser.error('Must specify whether file is only written if changed using --write-file-only-if-changed.') - options.write_file_only_if_changed = bool(options.write_file_only_if_changed) return options, args @@ -360,11 +356,9 @@ info_collector.collect_info(idl_filename) write_pickle_file(options.interfaces_info_file, - info_collector.get_info_as_dict(), - options.write_file_only_if_changed) + info_collector.get_info_as_dict()) write_pickle_file(options.component_info_file, - info_collector.get_component_info_as_dict(), - options.write_file_only_if_changed) + info_collector.get_component_info_as_dict()) if __name__ == '__main__': sys.exit(main())
diff --git a/third_party/WebKit/Source/bindings/scripts/compute_interfaces_info_overall.py b/third_party/WebKit/Source/bindings/scripts/compute_interfaces_info_overall.py index ed5c9df2..6dd0e85 100755 --- a/third_party/WebKit/Source/bindings/scripts/compute_interfaces_info_overall.py +++ b/third_party/WebKit/Source/bindings/scripts/compute_interfaces_info_overall.py
@@ -113,13 +113,8 @@ def parse_options(): usage = 'Usage: %prog [InfoIndividual.pickle]... [Info.pickle]' parser = optparse.OptionParser(usage=usage) - parser.add_option('--write-file-only-if-changed', type='int', help='if true, do not write an output file if it would be identical to the existing one, which avoids unnecessary rebuilds in ninja') - options, args = parser.parse_args() - if options.write_file_only_if_changed is None: - parser.error('Must specify whether file is only written if changed using --write-file-only-if-changed.') - options.write_file_only_if_changed = bool(options.write_file_only_if_changed) - return options, args + return parser.parse_args() def dict_of_dicts_of_lists_update_or_append(existing, other): @@ -315,15 +310,13 @@ ################################################################################ def main(): - options, args = parse_options() + _, args = parse_options() # args = Input1, Input2, ..., Output interfaces_info_filename = args.pop() info_individuals = read_pickle_files(args) compute_interfaces_info_overall(info_individuals) - write_pickle_file(interfaces_info_filename, - interfaces_info, - options.write_file_only_if_changed) + write_pickle_file(interfaces_info_filename, interfaces_info) if __name__ == '__main__':
diff --git a/third_party/WebKit/Source/bindings/scripts/generate_event_interfaces.py b/third_party/WebKit/Source/bindings/scripts/generate_event_interfaces.py index 6a2cc6a..565dd17f 100755 --- a/third_party/WebKit/Source/bindings/scripts/generate_event_interfaces.py +++ b/third_party/WebKit/Source/bindings/scripts/generate_event_interfaces.py
@@ -59,7 +59,6 @@ parser = OptionParser() parser.add_option('--event-idl-files-list', help='file listing event IDL files') parser.add_option('--event-interfaces-file', help='output file') - parser.add_option('--write-file-only-if-changed', type='int', help='if true, do not write an output file if it would be identical to the existing one, which avoids unnecessary rebuilds in ninja') parser.add_option('--suffix', help='specify a suffix to the namespace, i.e., "Modules". Default is None.') options, args = parser.parse_args() @@ -67,15 +66,12 @@ parser.error('Must specify a file listing event IDL files using --event-idl-files-list.') if options.event_interfaces_file is None: parser.error('Must specify an output file using --event-interfaces-file.') - if options.write_file_only_if_changed is None: - parser.error('Must specify whether file is only written if changed using --write-file-only-if-changed.') - options.write_file_only_if_changed = bool(options.write_file_only_if_changed) if args: parser.error('No arguments allowed, but %d given.' % len(args)) return options -def write_event_interfaces_file(event_idl_files, destination_filename, only_if_changed, suffix): +def write_event_interfaces_file(event_idl_files, destination_filename, suffix): def extended_attribute_string(name, value): if name == 'RuntimeEnabled': value += 'Enabled' @@ -106,7 +102,7 @@ for event_idl_file in event_idl_files] interface_lines.sort() lines.extend(interface_lines) - write_file(''.join(lines), destination_filename, only_if_changed) + write_file(''.join(lines), destination_filename) ################################################################################ @@ -116,7 +112,6 @@ event_idl_files = read_file_to_list(options.event_idl_files_list) write_event_interfaces_file(event_idl_files, options.event_interfaces_file, - options.write_file_only_if_changed, options.suffix)
diff --git a/third_party/WebKit/Source/bindings/scripts/generate_global_constructors.py b/third_party/WebKit/Source/bindings/scripts/generate_global_constructors.py index 6965f9af..417f9a8 100755 --- a/third_party/WebKit/Source/bindings/scripts/generate_global_constructors.py +++ b/third_party/WebKit/Source/bindings/scripts/generate_global_constructors.py
@@ -42,17 +42,12 @@ parser = optparse.OptionParser() parser.add_option('--idl-files-list', help='file listing IDL files') parser.add_option('--global-objects-file', help='pickle file of global objects') - parser.add_option('--write-file-only-if-changed', type='int', help='if true, do not write an output file if it would be identical to the existing one, which avoids unnecessary rebuilds in ninja') - options, args = parser.parse_args() if options.idl_files_list is None: parser.error('Must specify a file listing IDL files using --idl-files-list.') if options.global_objects_file is None: parser.error('Must specify a pickle file of global objects using --global-objects-file.') - if options.write_file_only_if_changed is None: - parser.error('Must specify whether output files are only written if changed using --write-file-only-if-changed.') - options.write_file_only_if_changed = bool(options.write_file_only_if_changed) return options, args @@ -131,18 +126,17 @@ return attributes_list -def write_global_constructors_partial_interface(interface_name, idl_filename, constructor_attributes_list, only_if_changed): +def write_global_constructors_partial_interface(interface_name, idl_filename, constructor_attributes_list): # FIXME: replace this with a simple Jinja template lines = (['partial interface %s {\n' % interface_name] + [' %s;\n' % constructor_attribute # FIXME: sort by interface name (not first by extended attributes) for constructor_attribute in sorted(constructor_attributes_list)] + ['};\n']) - write_file(''.join(lines), idl_filename, only_if_changed) + write_file(''.join(lines), idl_filename) header_filename = os.path.splitext(idl_filename)[0] + '.h' idl_basename = os.path.basename(idl_filename) - write_file(HEADER_FORMAT.format(idl_basename=idl_basename), - header_filename, only_if_changed) + write_file(HEADER_FORMAT.format(idl_basename=idl_basename), header_filename) ################################################################################ @@ -182,10 +176,7 @@ for interface_name, idl_filename in interface_name_idl_filename: constructors = interface_name_to_constructors(interface_name) write_global_constructors_partial_interface( - interface_name, - idl_filename, - constructors, - options.write_file_only_if_changed) + interface_name, idl_filename, constructors) if __name__ == '__main__':
diff --git a/third_party/WebKit/Source/bindings/scripts/generate_init_partial_interfaces.py b/third_party/WebKit/Source/bindings/scripts/generate_init_partial_interfaces.py index d3a49df..0cc923ca 100755 --- a/third_party/WebKit/Source/bindings/scripts/generate_init_partial_interfaces.py +++ b/third_party/WebKit/Source/bindings/scripts/generate_init_partial_interfaces.py
@@ -42,7 +42,6 @@ parser = OptionParser(usage=usage) parser.add_option('--idl-files-list', help="a text file containing the IDL file paths, so the command line doesn't exceed OS length limits.") parser.add_option('--gyp-format-list', default=False, action='store_true', help="if specified, idl-files-list is newline separated. When unspecified, it's formatted as a Posix command line.") - parser.add_option('--write-file-only-if-changed', type='int', help='if true, do not write an output file if it would be identical to the existing one, which avoids unnecessary rebuilds in ninja') parser.add_option('--output') options, args = parser.parse_args() @@ -50,9 +49,6 @@ parser.error('Must specify output file using --output.') if options.idl_files_list is None: parser.error('Must specify a list of IDL files using --idl-files-list.') - if options.write_file_only_if_changed is None: - parser.error('Must specify whether file is only written if changed using --write-file-only-if-changed.') - options.write_file_only_if_changed = bool(options.write_file_only_if_changed) return options @@ -103,8 +99,7 @@ '\n'.join(includes), '\n'.join(initialize_calls)) - write_file(content, options.output, - only_if_changed=options.write_file_only_if_changed) + write_file(content, options.output) if __name__ == '__main__':
diff --git a/third_party/WebKit/Source/bindings/scripts/idl_compiler.py b/third_party/WebKit/Source/bindings/scripts/idl_compiler.py index 902859ea..ffb2591 100755 --- a/third_party/WebKit/Source/bindings/scripts/idl_compiler.py +++ b/third_party/WebKit/Source/bindings/scripts/idl_compiler.py
@@ -59,7 +59,6 @@ parser.add_option('--output-directory') parser.add_option('--impl-output-directory') parser.add_option('--info-dir') - parser.add_option('--write-file-only-if-changed', type='int') # FIXME: We should always explicitly specify --target-component and # remove the default behavior. parser.add_option('--target-component', @@ -73,7 +72,6 @@ options, args = parser.parse_args() if options.output_directory is None: parser.error('Must specify output directory using --output-directory.') - options.write_file_only_if_changed = bool(options.write_file_only_if_changed) if len(args) != 1: parser.error('Must specify exactly 1 input file as argument, but %d given.' % len(args)) idl_filename = os.path.realpath(args[0]) @@ -98,21 +96,18 @@ def __init__(self, output_directory, cache_directory=None, code_generator=None, info_provider=None, - only_if_changed=False, target_component=None): + target_component=None): """ Args: output_directory: directory to put output files. cache_directory: directory which contains PLY caches. code_generator: code generator to be used. info_provider: component-specific information provider. - only_if_changed: True when the compiler should only write output files - when the contents are changed. target_component: component to be processed. """ self.cache_directory = cache_directory self.code_generator = code_generator self.info_provider = info_provider - self.only_if_changed = only_if_changed self.output_directory = output_directory self.target_component = target_component self.reader = IdlReader(info_provider.interfaces_info, cache_directory) @@ -124,7 +119,7 @@ output_code_list = self.code_generator.generate_code( target_definitions, interface_name) for output_path, output_code in output_code_list: - write_file(output_code, output_path, self.only_if_changed) + write_file(output_code, output_path) @abc.abstractmethod def compile_file(self, idl_filename): @@ -159,7 +154,6 @@ options.output_directory, cache_directory=options.cache_directory, info_provider=info_provider, - only_if_changed=options.write_file_only_if_changed, target_component=options.target_component) idl_compiler.compile_file(input_filename) @@ -171,7 +165,6 @@ options.impl_output_directory, cache_directory=options.cache_directory, info_provider=info_provider, - only_if_changed=options.write_file_only_if_changed, target_component=options.target_component) idl_filenames = read_idl_files_list_from_file(input_filename, @@ -193,7 +186,7 @@ options.target_component) output_code_list = generator.generate_code() for output_path, output_code in output_code_list: - write_file(output_code, output_path, options.write_file_only_if_changed) + write_file(output_code, output_path) def generate_callback_function_impl(options): @@ -206,7 +199,7 @@ options.target_component) output_code_list = generator.generate_code() for output_path, output_code in output_code_list: - write_file(output_code, output_path, options.write_file_only_if_changed) + write_file(output_code, output_path) def main():
diff --git a/third_party/WebKit/Source/bindings/scripts/scripts.gni b/third_party/WebKit/Source/bindings/scripts/scripts.gni index 9166a877..bf6a701 100644 --- a/third_party/WebKit/Source/bindings/scripts/scripts.gni +++ b/third_party/WebKit/Source/bindings/scripts/scripts.gni
@@ -84,7 +84,6 @@ rebase_path(invoker.interfaces_info_file, root_build_dir), "--component-info-file", rebase_path(invoker.component_info_file, root_build_dir), - "--write-file-only-if-changed=1", ] deps = [ "//third_party/WebKit/Source/bindings/scripts:cached_lex_yacc_tables" ] + invoker.deps @@ -120,7 +119,6 @@ rebase_path(idl_files_list, root_build_dir), "--event-interfaces-file", rebase_path(output_file, root_build_dir), - "--write-file-only-if-changed=1", # Always true for Ninja. ] if (defined(invoker.suffix)) { @@ -185,7 +183,6 @@ rebase_path(output_dir, root_build_dir), "--info-dir", rebase_path("$bindings_output_dir", root_build_dir), - "--write-file-only-if-changed=1", # Always true for Ninja. "--target-component", invoker.target_component, "{{source}}", @@ -242,7 +239,6 @@ rebase_path("$bindings_output_dir", root_build_dir), "--target-component", invoker.target_component, - "--write-file-only-if-changed=1", "--generate-impl", rebase_path(idl_files_list, root_build_dir), ] @@ -313,7 +309,6 @@ args = [ "--idl-files-list", rebase_path(idl_files_list, root_build_dir), - "--write-file-only-if-changed=1", # Always true for Ninja. "--", ] args += rebase_path(invoker.sources_generated, root_build_dir) @@ -353,7 +348,6 @@ rebase_path(idl_files_list, root_build_dir), "--global-objects-file", rebase_path(invoker.global_objects_file, root_build_dir), - "--write-file-only-if-changed=1", # Always true for Ninja. "--", ]
diff --git a/third_party/WebKit/Source/bindings/scripts/utilities.py b/third_party/WebKit/Source/bindings/scripts/utilities.py index a9871f6d..ab37173 100644 --- a/third_party/WebKit/Source/bindings/scripts/utilities.py +++ b/third_party/WebKit/Source/bindings/scripts/utilities.py
@@ -303,11 +303,13 @@ yield pickle.load(pickle_file) -def write_file(new_text, destination_filename, only_if_changed): - if only_if_changed and os.path.isfile(destination_filename): +def write_file(new_text, destination_filename): + # If |new_text| is same with the file content, we skip updating. + if os.path.isfile(destination_filename): with open(destination_filename) as destination_file: if destination_file.read() == new_text: return + destination_dirname = os.path.dirname(destination_filename) if not os.path.exists(destination_dirname): os.makedirs(destination_dirname) @@ -315,8 +317,9 @@ destination_file.write(new_text) -def write_pickle_file(pickle_filename, data, only_if_changed): - if only_if_changed and os.path.isfile(pickle_filename): +def write_pickle_file(pickle_filename, data): + # If |data| is same with the file content, we skip updating. + if os.path.isfile(pickle_filename): with open(pickle_filename) as pickle_file: try: if pickle.load(pickle_file) == data:
diff --git a/third_party/WebKit/Source/bindings/scripts/v8_callback_function.py b/third_party/WebKit/Source/bindings/scripts/v8_callback_function.py index a8da75645..9f03f57 100644 --- a/third_party/WebKit/Source/bindings/scripts/v8_callback_function.py +++ b/third_party/WebKit/Source/bindings/scripts/v8_callback_function.py
@@ -20,6 +20,7 @@ 'bindings/core/v8/ScriptState.h', 'bindings/core/v8/ToV8.h', 'bindings/core/v8/V8Binding.h', + 'core/dom/ExecutionContext.h', 'wtf/Assertions.h', ])
diff --git a/third_party/WebKit/Source/bindings/templates/callback_function.cpp.tmpl b/third_party/WebKit/Source/bindings/templates/callback_function.cpp.tmpl index 9ab682e..f54060e8 100644 --- a/third_party/WebKit/Source/bindings/templates/callback_function.cpp.tmpl +++ b/third_party/WebKit/Source/bindings/templates/callback_function.cpp.tmpl
@@ -27,6 +27,11 @@ if (!scriptState->contextIsValid()) return false; + ExecutionContext* context = scriptState->getExecutionContext(); + DCHECK(context); + if (context->activeDOMObjectsAreSuspended() || context->activeDOMObjectsAreStopped()) + return false; + if (m_callback.isEmpty()) return false;
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8LongExperimentalCallbackFunction.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8LongExperimentalCallbackFunction.cpp index 4275c8e..27d7a0aa 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8LongExperimentalCallbackFunction.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8LongExperimentalCallbackFunction.cpp
@@ -11,6 +11,7 @@ #include "bindings/core/v8/ScriptState.h" #include "bindings/core/v8/ToV8.h" #include "bindings/core/v8/V8Binding.h" +#include "core/dom/ExecutionContext.h" #include "wtf/Assertions.h" namespace blink { @@ -31,6 +32,11 @@ if (!scriptState->contextIsValid()) return false; + ExecutionContext* context = scriptState->getExecutionContext(); + DCHECK(context); + if (context->activeDOMObjectsAreSuspended() || context->activeDOMObjectsAreStopped()) + return false; + if (m_callback.isEmpty()) return false;
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8StringSequenceCallbackFunctionLongSequenceArg.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8StringSequenceCallbackFunctionLongSequenceArg.cpp index 3294509..3c89664 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8StringSequenceCallbackFunctionLongSequenceArg.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8StringSequenceCallbackFunctionLongSequenceArg.cpp
@@ -11,6 +11,7 @@ #include "bindings/core/v8/ScriptState.h" #include "bindings/core/v8/ToV8.h" #include "bindings/core/v8/V8Binding.h" +#include "core/dom/ExecutionContext.h" #include "wtf/Assertions.h" namespace blink { @@ -31,6 +32,11 @@ if (!scriptState->contextIsValid()) return false; + ExecutionContext* context = scriptState->getExecutionContext(); + DCHECK(context); + if (context->activeDOMObjectsAreSuspended() || context->activeDOMObjectsAreStopped()) + return false; + if (m_callback.isEmpty()) return false;
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8VoidCallbackFunctionInterfaceArg.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8VoidCallbackFunctionInterfaceArg.cpp index 1024d64..3e707244 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8VoidCallbackFunctionInterfaceArg.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8VoidCallbackFunctionInterfaceArg.cpp
@@ -12,6 +12,7 @@ #include "bindings/core/v8/ToV8.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8HTMLDivElement.h" +#include "core/dom/ExecutionContext.h" #include "wtf/Assertions.h" namespace blink { @@ -32,6 +33,11 @@ if (!scriptState->contextIsValid()) return false; + ExecutionContext* context = scriptState->getExecutionContext(); + DCHECK(context); + if (context->activeDOMObjectsAreSuspended() || context->activeDOMObjectsAreStopped()) + return false; + if (m_callback.isEmpty()) return false;
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8VoidExperimentalCallbackFunction.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8VoidExperimentalCallbackFunction.cpp index 9c1f326..dfd61a52 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8VoidExperimentalCallbackFunction.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8VoidExperimentalCallbackFunction.cpp
@@ -11,6 +11,7 @@ #include "bindings/core/v8/ScriptState.h" #include "bindings/core/v8/ToV8.h" #include "bindings/core/v8/V8Binding.h" +#include "core/dom/ExecutionContext.h" #include "wtf/Assertions.h" namespace blink { @@ -31,6 +32,11 @@ if (!scriptState->contextIsValid()) return false; + ExecutionContext* context = scriptState->getExecutionContext(); + DCHECK(context); + if (context->activeDOMObjectsAreSuspended() || context->activeDOMObjectsAreStopped()) + return false; + if (m_callback.isEmpty()) return false;
diff --git a/third_party/WebKit/Source/core/BUILD.gn b/third_party/WebKit/Source/core/BUILD.gn index ed865ba..f76ebcd 100644 --- a/third_party/WebKit/Source/core/BUILD.gn +++ b/third_party/WebKit/Source/core/BUILD.gn
@@ -1004,7 +1004,6 @@ "dom/DOMMatrixTest.cpp", "dom/DocumentStatisticsCollectorTest.cpp", "dom/DocumentTest.cpp", - "dom/ElementRareDataTest.cpp", "dom/ElementTest.cpp", "dom/ExecutionContextTaskTest.cpp", "dom/MainThreadTaskRunnerTest.cpp",
diff --git a/third_party/WebKit/Source/core/dom/Element.cpp b/third_party/WebKit/Source/core/dom/Element.cpp index 3a29fbac..eef8d64 100644 --- a/third_party/WebKit/Source/core/dom/Element.cpp +++ b/third_party/WebKit/Source/core/dom/Element.cpp
@@ -1562,7 +1562,7 @@ // need to clear any state that's been added since then. if (hasRareData() && getStyleChangeType() == NeedsReattachStyleChange) { ElementRareData* data = elementRareData(); - data->clearComputedStyleIfNoLayoutObject(); + data->clearComputedStyle(); } if (!isSlotOrActiveInsertionPoint()) @@ -1608,7 +1608,7 @@ // attachLayoutTree() will clear the computed style for us when inside recalcStyle. if (!document().inStyleRecalc()) - data->clearComputedStyleIfNoLayoutObject(); + data->clearComputedStyle(); if (ElementAnimations* elementAnimations = data->elementAnimations()) { if (context.performingReattach) { @@ -1738,7 +1738,7 @@ if (hasRareData()) { ElementRareData* data = elementRareData(); if (change != IndependentInherit) - data->clearComputedStyleIfNoLayoutObject(); + data->clearComputedStyle(); if (change >= IndependentInherit) { if (ElementAnimations* elementAnimations = data->elementAnimations())
diff --git a/third_party/WebKit/Source/core/dom/ElementRareData.h b/third_party/WebKit/Source/core/dom/ElementRareData.h index 665b59a5..ffd2c45 100644 --- a/third_party/WebKit/Source/core/dom/ElementRareData.h +++ b/third_party/WebKit/Source/core/dom/ElementRareData.h
@@ -92,25 +92,9 @@ NamedNodeMap* attributeMap() const { return m_attributeMap.get(); } void setAttributeMap(NamedNodeMap* attributeMap) { m_attributeMap = attributeMap; } - ComputedStyle* computedStyle() const - { - DCHECK(!(layoutObject() && m_computedStyle)); - if (layoutObject()) - return layoutObject()->mutableStyle(); - return m_computedStyle.get(); - } - void setComputedStyle(PassRefPtr<ComputedStyle> computedStyle) - { - if (layoutObject()) - layoutObject()->setStyleInternal(std::move(computedStyle)); - else - m_computedStyle = computedStyle; - } - void clearComputedStyleIfNoLayoutObject() - { - DCHECK(!(layoutObject() && m_computedStyle)); - m_computedStyle = nullptr; - } + ComputedStyle* computedStyle() const { return m_computedStyle.get(); } + void setComputedStyle(PassRefPtr<ComputedStyle> computedStyle) { m_computedStyle = computedStyle; } + void clearComputedStyle() { m_computedStyle = nullptr; } ClassList* classList() const { return m_classList.get(); } void setClassList(ClassList* classList) { m_classList = classList; }
diff --git a/third_party/WebKit/Source/core/dom/ElementRareDataTest.cpp b/third_party/WebKit/Source/core/dom/ElementRareDataTest.cpp deleted file mode 100644 index 8bc5bfa6..0000000 --- a/third_party/WebKit/Source/core/dom/ElementRareDataTest.cpp +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "core/dom/ElementRareData.h" - -#include "core/layout/LayoutInline.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace blink { - -TEST(ElementRareDataTest, ComputedStyleStorage) -{ - // Without LayoutObject - ElementRareData* rareData = ElementRareData::create(nullptr); - RefPtr<ComputedStyle> style = ComputedStyle::create(); - rareData->setComputedStyle(style); - EXPECT_EQ(style.get(), rareData->computedStyle()); - - // With LayoutObject - LayoutObject* layoutObject = new LayoutInline(nullptr); - rareData = ElementRareData::create(layoutObject); - rareData->setComputedStyle(style); - EXPECT_EQ(style.get(), rareData->computedStyle()); - - rareData->setLayoutObject(nullptr); - delete layoutObject; -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/Fullscreen.cpp b/third_party/WebKit/Source/core/dom/Fullscreen.cpp index cd9e032e..7c60811f 100644 --- a/third_party/WebKit/Source/core/dom/Fullscreen.cpp +++ b/third_party/WebKit/Source/core/dom/Fullscreen.cpp
@@ -27,10 +27,8 @@ #include "core/dom/Fullscreen.h" -#include "core/HTMLNames.h" #include "core/dom/Document.h" #include "core/dom/ElementTraversal.h" -#include "core/dom/StyleChangeReason.h" #include "core/dom/StyleEngine.h" #include "core/events/Event.h" #include "core/frame/FrameHost.h" @@ -39,7 +37,6 @@ #include "core/frame/Settings.h" #include "core/frame/UseCounter.h" #include "core/html/HTMLIFrameElement.h" -#include "core/html/HTMLMediaElement.h" #include "core/input/EventHandler.h" #include "core/inspector/ConsoleMessage.h" #include "core/layout/LayoutBlockFlow.h" @@ -51,8 +48,6 @@ namespace blink { -using namespace HTMLNames; - namespace { // https://html.spec.whatwg.org/multipage/embedded-content.html#allowed-to-use @@ -65,7 +60,7 @@ if (!frame) return false; - // 2. If |document|'s browsing context has no browsing context container, then + // 2. If |document|'s browsing context is a top-level browsing context, then // return true. if (frame->isMainFrame()) return true; @@ -121,7 +116,7 @@ return false; // |element|'s node document is allowed to use the feature indicated by - // |attribute name allowfullscreen. + // attribute name allowfullscreen. if (!allowedToUseFullscreen(element.document().frame())) return false;
diff --git a/third_party/WebKit/Source/core/dom/Node.h b/third_party/WebKit/Source/core/dom/Node.h index 28e011ea..a86e928 100644 --- a/third_party/WebKit/Source/core/dom/Node.h +++ b/third_party/WebKit/Source/core/dom/Node.h
@@ -110,7 +110,7 @@ NotDefinedFlag = 2 << nodeCustomElementShift, }; -class CORE_EXPORT NodeRareDataBase { +class NodeRareDataBase { public: LayoutObject* layoutObject() const { return m_layoutObject; } void setLayoutObject(LayoutObject* layoutObject) { m_layoutObject = layoutObject; }
diff --git a/third_party/WebKit/Source/core/dom/NodeRareData.h b/third_party/WebKit/Source/core/dom/NodeRareData.h index a15ff99..5103db61 100644 --- a/third_party/WebKit/Source/core/dom/NodeRareData.h +++ b/third_party/WebKit/Source/core/dom/NodeRareData.h
@@ -60,7 +60,7 @@ NodeMutationObserverData() { } }; -class CORE_EXPORT NodeRareData : public GarbageCollectedFinalized<NodeRareData>, public NodeRareDataBase { +class NodeRareData : public GarbageCollectedFinalized<NodeRareData>, public NodeRareDataBase { WTF_MAKE_NONCOPYABLE(NodeRareData); public: static NodeRareData* create(LayoutObject* layoutObject)
diff --git a/third_party/WebKit/Source/core/editing/SurroundingTextTest.cpp b/third_party/WebKit/Source/core/editing/SurroundingTextTest.cpp index 46ceeac..96066c4 100644 --- a/third_party/WebKit/Source/core/editing/SurroundingTextTest.cpp +++ b/third_party/WebKit/Source/core/editing/SurroundingTextTest.cpp
@@ -37,6 +37,7 @@ void SurroundingTextTest::setHTML(const String& content) { document().body()->setInnerHTML(content, ASSERT_NO_EXCEPTION); + document().updateStyleAndLayout(); } VisibleSelection SurroundingTextTest::select(int start, int end)
diff --git a/third_party/WebKit/Source/core/editing/VisibleSelection.cpp b/third_party/WebKit/Source/core/editing/VisibleSelection.cpp index ff6def1..5a20dac7 100644 --- a/third_party/WebKit/Source/core/editing/VisibleSelection.cpp +++ b/third_party/WebKit/Source/core/editing/VisibleSelection.cpp
@@ -67,6 +67,12 @@ , m_granularity(CharacterGranularity) , m_hasTrailingWhitespace(false) { + Document* document = m_base.document() ? m_base.document() : m_extent.document(); + if (document) { + // TODO(xiaochengh): The use of updateStyleAndLayoutIgnorePendingStylesheets + // needs to be audited. see http://crbug.com/590369 for more details. + document->updateStyleAndLayoutIgnorePendingStylesheets(); + } validate(); } @@ -154,6 +160,7 @@ template <typename Strategy> void VisibleSelectionTemplate<Strategy>::setBase(const PositionTemplate<Strategy>& position) { + DCHECK(!needsLayoutTreeUpdate(position)); m_base = position; validate(); } @@ -161,6 +168,7 @@ template <typename Strategy> void VisibleSelectionTemplate<Strategy>::setBase(const VisiblePositionTemplate<Strategy>& visiblePosition) { + DCHECK(visiblePosition.isValid()); m_base = visiblePosition.deepEquivalent(); validate(); } @@ -168,6 +176,7 @@ template <typename Strategy> void VisibleSelectionTemplate<Strategy>::setExtent(const PositionTemplate<Strategy>& position) { + DCHECK(!needsLayoutTreeUpdate(position)); m_extent = position; validate(); } @@ -175,6 +184,7 @@ template <typename Strategy> void VisibleSelectionTemplate<Strategy>::setExtent(const VisiblePositionTemplate<Strategy>& visiblePosition) { + DCHECK(visiblePosition.isValid()); m_extent = visiblePosition.deepEquivalent(); validate(); } @@ -492,13 +502,8 @@ template <typename Strategy> void VisibleSelectionTemplate<Strategy>::validate(TextGranularity granularity) { - Document* document = m_base.isNotNull() ? m_base.document() : m_extent.document(); - if (document) { - // TODO(xiaochengh): The use of updateStyleAndLayoutIgnorePendingStylesheets - // needs to be audited. see http://crbug.com/590369 for more details. - document->updateStyleAndLayoutIgnorePendingStylesheets(); - } - + DCHECK(!needsLayoutTreeUpdate(m_base)); + DCHECK(!needsLayoutTreeUpdate(m_extent)); // TODO(xiaochengh): Add a DocumentLifecycle::DisallowTransitionScope here. m_granularity = granularity;
diff --git a/third_party/WebKit/Source/core/timing/PerformanceBaseTest.cpp b/third_party/WebKit/Source/core/timing/PerformanceBaseTest.cpp index 4bbe857..7ceb3ed 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceBaseTest.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceBaseTest.cpp
@@ -4,6 +4,7 @@ #include "core/timing/Performance.h" +#include "bindings/core/v8/V8BindingForTesting.h" #include "core/timing/PerformanceBase.h" #include "core/timing/PerformanceLongTaskTiming.h" #include "core/timing/PerformanceObserver.h" @@ -51,11 +52,11 @@ class PerformanceBaseTest : public ::testing::Test { protected: - void SetUp() override + void initialize(ScriptState* scriptState) { m_base = new TestPerformanceBase(); m_cb = new MockPerformanceObserverCallback(); - m_observer = PerformanceObserver::create(m_base, m_cb); + m_observer = PerformanceObserver::create(scriptState, m_base, m_cb); } Persistent<TestPerformanceBase> m_base; @@ -65,6 +66,9 @@ TEST_F(PerformanceBaseTest, Register) { + V8TestingScope scope; + initialize(scope.getScriptState()); + EXPECT_EQ(0, m_base->numObservers()); EXPECT_EQ(0, m_base->numActiveObservers()); @@ -79,6 +83,9 @@ TEST_F(PerformanceBaseTest, Activate) { + V8TestingScope scope; + initialize(scope.getScriptState()); + EXPECT_EQ(0, m_base->numObservers()); EXPECT_EQ(0, m_base->numActiveObservers()); @@ -97,6 +104,9 @@ TEST_F(PerformanceBaseTest, AddLongTaskTiming) { + V8TestingScope scope; + initialize(scope.getScriptState()); + // Add a long task entry, but no observer registered. m_base->addLongTaskTiming(1234, 5678, "www.foo.com/bar"); EXPECT_EQ(0, m_base->numLongTaskTimingEntries()); // has no effect
diff --git a/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp b/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp index 47aaa0f..8f2e1e66 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp
@@ -16,14 +16,15 @@ namespace blink { -PerformanceObserver* PerformanceObserver::create(PerformanceBase* performance, PerformanceObserverCallback* callback) +PerformanceObserver* PerformanceObserver::create(ScriptState* scriptState, PerformanceBase* performance, PerformanceObserverCallback* callback) { ASSERT(isMainThread()); - return new PerformanceObserver(performance, callback); + return new PerformanceObserver(scriptState, performance, callback); } -PerformanceObserver::PerformanceObserver(PerformanceBase* performance, PerformanceObserverCallback* callback) - : m_callback(callback) +PerformanceObserver::PerformanceObserver(ScriptState* scriptState, PerformanceBase* performance, PerformanceObserverCallback* callback) + : m_scriptState(scriptState) + , m_callback(callback) , m_performance(performance) , m_filterOptions(PerformanceEntry::Invalid) , m_isRegistered(false) @@ -74,7 +75,7 @@ bool PerformanceObserver::shouldBeSuspended() const { - return m_callback->getExecutionContext() && m_callback->getExecutionContext()->activeDOMObjectsAreSuspended(); + return m_scriptState->getExecutionContext() && m_scriptState->getExecutionContext()->activeDOMObjectsAreSuspended(); } void PerformanceObserver::deliver()
diff --git a/third_party/WebKit/Source/core/timing/PerformanceObserver.h b/third_party/WebKit/Source/core/timing/PerformanceObserver.h index f344c1c..48ec11f 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceObserver.h +++ b/third_party/WebKit/Source/core/timing/PerformanceObserver.h
@@ -18,15 +18,16 @@ class PerformanceObserverCallback; class PerformanceObserver; class PerformanceObserverInit; +class ScriptState; using PerformanceEntryVector = HeapVector<Member<PerformanceEntry>>; -class CORE_EXPORT PerformanceObserver final : public GarbageCollected<PerformanceObserver>, public ScriptWrappable { +class CORE_EXPORT PerformanceObserver final : public GarbageCollectedFinalized<PerformanceObserver>, public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); friend class PerformanceBase; friend class PerformanceObserverTest; public: - static PerformanceObserver* create(PerformanceBase*, PerformanceObserverCallback*); + static PerformanceObserver* create(ScriptState*, PerformanceBase*, PerformanceObserverCallback*); static void resumeSuspendedObservers(); void observe(const PerformanceObserverInit&, ExceptionState&); @@ -37,10 +38,11 @@ DECLARE_TRACE(); private: - explicit PerformanceObserver(PerformanceBase*, PerformanceObserverCallback*); + PerformanceObserver(ScriptState*, PerformanceBase*, PerformanceObserverCallback*); void deliver(); bool shouldBeSuspended() const; + RefPtr<ScriptState> m_scriptState; Member<PerformanceObserverCallback> m_callback; WeakMember<PerformanceBase> m_performance; PerformanceEntryVector m_performanceEntries;
diff --git a/third_party/WebKit/Source/core/timing/PerformanceObserverTest.cpp b/third_party/WebKit/Source/core/timing/PerformanceObserverTest.cpp index 9efcd4a..96293d89 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceObserverTest.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceObserverTest.cpp
@@ -4,6 +4,7 @@ #include "core/timing/PerformanceObserver.h" +#include "bindings/core/v8/V8BindingForTesting.h" #include "core/timing/Performance.h" #include "core/timing/PerformanceBase.h" #include "core/timing/PerformanceMark.h" @@ -35,11 +36,11 @@ class PerformanceObserverTest : public ::testing::Test { protected: - void SetUp() override + void initialize(ScriptState* scriptState) { m_base = new MockPerformanceBase(); m_cb = new MockPerformanceObserverCallback(); - m_observer = PerformanceObserver::create(m_base, m_cb); + m_observer = PerformanceObserver::create(scriptState, m_base, m_cb); } bool isRegistered() @@ -62,6 +63,9 @@ TEST_F(PerformanceObserverTest, Observe) { + V8TestingScope scope; + initialize(scope.getScriptState()); + NonThrowableExceptionState exceptionState; PerformanceObserverInit options; Vector<String> entryTypeVec; @@ -74,6 +78,9 @@ TEST_F(PerformanceObserverTest, Enqueue) { + V8TestingScope scope; + initialize(scope.getScriptState()); + Persistent<PerformanceEntry> entry = PerformanceMark::create("m", 1234); EXPECT_EQ(0, numPerformanceEntries()); @@ -83,6 +90,9 @@ TEST_F(PerformanceObserverTest, Deliver) { + V8TestingScope scope; + initialize(scope.getScriptState()); + Persistent<PerformanceEntry> entry = PerformanceMark::create("m", 1234); EXPECT_EQ(0, numPerformanceEntries()); @@ -95,6 +105,9 @@ TEST_F(PerformanceObserverTest, Disconnect) { + V8TestingScope scope; + initialize(scope.getScriptState()); + Persistent<PerformanceEntry> entry = PerformanceMark::create("m", 1234); EXPECT_EQ(0, numPerformanceEntries());
diff --git a/third_party/WebKit/Source/modules/modules_idl_files.gni b/third_party/WebKit/Source/modules/modules_idl_files.gni index dc1558b..0daf053 100644 --- a/third_party/WebKit/Source/modules/modules_idl_files.gni +++ b/third_party/WebKit/Source/modules/modules_idl_files.gni
@@ -217,6 +217,8 @@ "remoteplayback/RemotePlayback.idl", "remoteplayback/RemotePlaybackAvailability.idl", "screen_orientation/ScreenOrientation.idl", + "sensor/AmbientLightSensor.idl", + "sensor/AmbientLightSensorReading.idl", "sensor/Sensor.idl", "sensor/SensorErrorEvent.idl", "sensor/SensorReading.idl", @@ -452,6 +454,7 @@ "push_messaging/PushEventInit.idl", "push_messaging/PushSubscriptionOptionsInit.idl", "quota/StorageEstimate.idl", + "sensor/AmbientLightSensorReadingInit.idl", "sensor/SensorErrorEventInit.idl", "sensor/SensorReadingEventInit.idl", "sensor/SensorOptions.idl", @@ -777,6 +780,8 @@ "$blink_modules_output_dir/push_messaging/PushSubscriptionOptionsInit.h", "$blink_modules_output_dir/quota/StorageEstimate.cpp", "$blink_modules_output_dir/quota/StorageEstimate.h", + "$blink_modules_output_dir/sensor/AmbientLightSensorReadingInit.cpp", + "$blink_modules_output_dir/sensor/AmbientLightSensorReadingInit.h", "$blink_modules_output_dir/sensor/SensorErrorEventInit.cpp", "$blink_modules_output_dir/sensor/SensorErrorEventInit.h", "$blink_modules_output_dir/sensor/SensorReadingEventInit.cpp",
diff --git a/third_party/WebKit/Source/modules/sensor/AmbientLightSensor.cpp b/third_party/WebKit/Source/modules/sensor/AmbientLightSensor.cpp new file mode 100644 index 0000000..aaede9f --- /dev/null +++ b/third_party/WebKit/Source/modules/sensor/AmbientLightSensor.cpp
@@ -0,0 +1,54 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "modules/sensor/AmbientLightSensor.h" + +#include "bindings/core/v8/ScriptPromise.h" +#include "bindings/core/v8/ScriptPromiseResolver.h" +#include "modules/sensor/AmbientLightSensorReading.h" + +using device::mojom::blink::SensorType; + +namespace blink { + +// static +AmbientLightSensor* AmbientLightSensor::create(ExecutionContext* context, const SensorOptions& sensorOptions) +{ + return new AmbientLightSensor(context, sensorOptions); +} + +// static +AmbientLightSensor* AmbientLightSensor::create(ExecutionContext* context) +{ + return create(context, SensorOptions()); +} + +AmbientLightSensor::AmbientLightSensor(ExecutionContext* executionContext, const SensorOptions& sensorOptions) + : Sensor(executionContext, sensorOptions, SensorType::AMBIENT_LIGHT) +{ +} + +AmbientLightSensorReading* AmbientLightSensor::reading() const +{ + return static_cast<AmbientLightSensorReading*>(Sensor::reading()); +} + +SensorReading* AmbientLightSensor::createSensorReading(SensorProxy* proxy) +{ + return AmbientLightSensorReading::create(proxy); +} + +auto AmbientLightSensor::createSensorConfig(const SensorOptions& options, const SensorConfiguration& defaultConfig) -> SensorConfigurationPtr +{ + auto result = device::mojom::blink::SensorConfiguration::New(); + result->frequency = options.hasFrequency() ? options.frequency() : defaultConfig.frequency; + return result; +} + +DEFINE_TRACE(AmbientLightSensor) +{ + Sensor::trace(visitor); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/modules/sensor/AmbientLightSensor.h b/third_party/WebKit/Source/modules/sensor/AmbientLightSensor.h new file mode 100644 index 0000000..ba0660d --- /dev/null +++ b/third_party/WebKit/Source/modules/sensor/AmbientLightSensor.h
@@ -0,0 +1,33 @@ +// 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 AmbientLightSensor_h +#define AmbientLightSensor_h + +#include "modules/sensor/Sensor.h" + +namespace blink { + +class AmbientLightSensorReading; + +class AmbientLightSensor final : public Sensor { + DEFINE_WRAPPERTYPEINFO(); +public: + static AmbientLightSensor* create(ExecutionContext*, const SensorOptions&); + static AmbientLightSensor* create(ExecutionContext*); + + AmbientLightSensorReading* reading() const; + + DECLARE_VIRTUAL_TRACE(); + +private: + AmbientLightSensor(ExecutionContext*, const SensorOptions&); + // Sensor overrides. + SensorReading* createSensorReading(SensorProxy*) override; + SensorConfigurationPtr createSensorConfig(const SensorOptions&, const SensorConfiguration& defaultConfig) override; +}; + +} // namespace blink + +#endif // AmbientLightSensor_h
diff --git a/third_party/WebKit/Source/modules/sensor/AmbientLightSensor.idl b/third_party/WebKit/Source/modules/sensor/AmbientLightSensor.idl new file mode 100644 index 0000000..eb3daf8 --- /dev/null +++ b/third_party/WebKit/Source/modules/sensor/AmbientLightSensor.idl
@@ -0,0 +1,14 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Specification at: +// https://w3c.github.io/ambient-light/#ambient-light-sensor-interface + +[ + RuntimeEnabled=Sensor, + Constructor(optional SensorOptions sensorOptions), + ConstructorCallWith=ExecutionContext, +] interface AmbientLightSensor : Sensor { + readonly attribute AmbientLightSensorReading? reading; +};
diff --git a/third_party/WebKit/Source/modules/sensor/AmbientLightSensorReading.cpp b/third_party/WebKit/Source/modules/sensor/AmbientLightSensorReading.cpp new file mode 100644 index 0000000..5c923af --- /dev/null +++ b/third_party/WebKit/Source/modules/sensor/AmbientLightSensorReading.cpp
@@ -0,0 +1,47 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "modules/sensor/AmbientLightSensorReading.h" + +#include "modules/sensor/SensorProxy.h" + +namespace blink { + +AmbientLightSensorReading::AmbientLightSensorReading(const AmbientLightSensorReadingInit& init) + : SensorReading(nullptr) + , mAmbientLightSensorReadingInit(init) +{ +} + +AmbientLightSensorReading::AmbientLightSensorReading(SensorProxy* proxy) + : SensorReading(proxy) + , mAmbientLightSensorReadingInit(AmbientLightSensorReadingInit()) +{ +} + +AmbientLightSensorReading::~AmbientLightSensorReading() = default; + +double AmbientLightSensorReading::illuminance() const +{ + if (mAmbientLightSensorReadingInit.hasIlluminance()) + return mAmbientLightSensorReadingInit.illuminance(); + + if (!m_sensorProxy) + return 0.0; + return m_sensorProxy->reading().reading[0]; +} + +bool AmbientLightSensorReading::isReadingUpdated(const SensorProxy::Reading& previous) const +{ + if (!m_sensorProxy) + return false; + return previous.reading[0] != illuminance(); +} + +DEFINE_TRACE(AmbientLightSensorReading) +{ + SensorReading::trace(visitor); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/modules/sensor/AmbientLightSensorReading.h b/third_party/WebKit/Source/modules/sensor/AmbientLightSensorReading.h new file mode 100644 index 0000000..78b89a7 --- /dev/null +++ b/third_party/WebKit/Source/modules/sensor/AmbientLightSensorReading.h
@@ -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. + +#ifndef AmbientLightSensorReading_h +#define AmbientLightSensorReading_h + +#include "modules/sensor/AmbientLightSensorReadingInit.h" +#include "modules/sensor/SensorReading.h" + +namespace blink { + +class AmbientLightSensorReading final : public SensorReading { + DEFINE_WRAPPERTYPEINFO(); +public: + + static AmbientLightSensorReading* create(const AmbientLightSensorReadingInit& init) + { + return new AmbientLightSensorReading(init); + } + + static AmbientLightSensorReading* create(SensorProxy* proxy) + { + return new AmbientLightSensorReading(proxy); + } + + ~AmbientLightSensorReading() override; + + double illuminance() const; + + bool isReadingUpdated(const SensorProxy::Reading&) const override; + + DECLARE_VIRTUAL_TRACE(); + +private: + explicit AmbientLightSensorReading(const AmbientLightSensorReadingInit&); + explicit AmbientLightSensorReading(SensorProxy*); + +private: + AmbientLightSensorReadingInit mAmbientLightSensorReadingInit; +}; + +} // namepsace blink + +#endif // AmbientLightSensorReading_h
diff --git a/third_party/WebKit/Source/modules/sensor/AmbientLightSensorReading.idl b/third_party/WebKit/Source/modules/sensor/AmbientLightSensorReading.idl new file mode 100644 index 0000000..041e5cb --- /dev/null +++ b/third_party/WebKit/Source/modules/sensor/AmbientLightSensorReading.idl
@@ -0,0 +1,13 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Specification at: +// https://w3c.github.io/ambient-light/#ambient-light-sensor-reading-interface + +[ + RuntimeEnabled=Sensor, + Constructor(AmbientLightSensorReadingInit ambientLightSensorReadingInit) +] interface AmbientLightSensorReading : SensorReading { + readonly attribute unrestricted double illuminance; +};
diff --git a/third_party/WebKit/Source/modules/sensor/AmbientLightSensorReadingInit.idl b/third_party/WebKit/Source/modules/sensor/AmbientLightSensorReadingInit.idl new file mode 100644 index 0000000..30dc03e --- /dev/null +++ b/third_party/WebKit/Source/modules/sensor/AmbientLightSensorReadingInit.idl
@@ -0,0 +1,10 @@ +// 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. + +// Specification at: +// https://w3c.github.io/ambient-light/#dictdef-ambientlightsensorreadinginit + +dictionary AmbientLightSensorReadingInit { + unrestricted double illuminance; +};
diff --git a/third_party/WebKit/Source/modules/sensor/BUILD.gn b/third_party/WebKit/Source/modules/sensor/BUILD.gn index 5de226f6..65e7088 100644 --- a/third_party/WebKit/Source/modules/sensor/BUILD.gn +++ b/third_party/WebKit/Source/modules/sensor/BUILD.gn
@@ -6,6 +6,10 @@ blink_modules_sources("sensor") { sources = [ + "AmbientLightSensor.cpp", + "AmbientLightSensor.h", + "AmbientLightSensorReading.cpp", + "AmbientLightSensorReading.h", "Sensor.cpp", "Sensor.h", "SensorErrorEvent.cpp",
diff --git a/third_party/WebKit/Source/modules/sensor/SensorReading.cpp b/third_party/WebKit/Source/modules/sensor/SensorReading.cpp index 12c1488..675d6c2 100644 --- a/third_party/WebKit/Source/modules/sensor/SensorReading.cpp +++ b/third_party/WebKit/Source/modules/sensor/SensorReading.cpp
@@ -14,9 +14,10 @@ SensorReading::SensorReading(SensorProxy* sensorProxy) : m_sensorProxy(sensorProxy) { - DCHECK(m_sensorProxy); } +SensorReading::~SensorReading() = default; + DEFINE_TRACE(SensorReading) { visitor->trace(m_sensorProxy); @@ -31,6 +32,15 @@ Performance* performance = DOMWindowPerformance::performance(*window); DCHECK(performance); + if (!m_sensorProxy) { + // In cases when SensorReading derived classes are constructed from JS + // side, e.g. to create syntetic SensorReadingEvent for testing + // purposes, |m_sensorProxy| will be null and SensorReading.timeStamp + // would return current DOMHighResTimeStamp, while reading value should + // be provided by derived classes. + return performance->now(); + } + return performance->monotonicTimeToDOMHighResTimeStamp(m_sensorProxy->reading().timestamp); }
diff --git a/third_party/WebKit/Source/modules/sensor/SensorReading.h b/third_party/WebKit/Source/modules/sensor/SensorReading.h index 2eaf7e6..9bc2a72 100644 --- a/third_party/WebKit/Source/modules/sensor/SensorReading.h +++ b/third_party/WebKit/Source/modules/sensor/SensorReading.h
@@ -16,7 +16,7 @@ class ScriptState; class SensorReading - : public GarbageCollected<SensorReading> + : public GarbageCollectedFinalized<SensorReading> , public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: @@ -28,6 +28,8 @@ // previous one; otherwise returns 'false'. virtual bool isReadingUpdated(const SensorProxy::Reading& previous) const = 0; + virtual ~SensorReading(); + protected: explicit SensorReading(SensorProxy*);
diff --git a/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp b/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp index 35f082f..2fe90bb 100644 --- a/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp +++ b/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp
@@ -1197,6 +1197,11 @@ void WebLocalFrameImpl::moveRangeSelection(const WebPoint& baseInViewport, const WebPoint& extentInViewport, WebFrame::TextGranularity granularity) { TRACE_EVENT0("blink", "WebLocalFrameImpl::moveRangeSelection"); + + // TODO(xiaochengh): The use of updateStyleAndLayoutIgnorePendingStylesheets + // needs to be audited. See http://crbug.com/590369 for more details. + frame()->document()->updateStyleAndLayoutIgnorePendingStylesheets(); + blink::TextGranularity blinkGranularity = blink::CharacterGranularity; if (granularity == WebFrame::WordGranularity) blinkGranularity = blink::WordGranularity;
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/bindings/bindings_tests.py b/third_party/WebKit/Tools/Scripts/webkitpy/bindings/bindings_tests.py index dd300bc9..354f5568 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/bindings/bindings_tests.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/bindings/bindings_tests.py
@@ -274,7 +274,7 @@ output_dir=output_directory, target_component=component) outputs = generator.generate_code() for output_path, output_code in outputs: - write_file(output_code, output_path, only_if_changed=True) + write_file(output_code, output_path) def generate_callback_function_impl(output_directory, component): generator = CodeGeneratorCallbackFunction( @@ -282,7 +282,7 @@ output_dir=output_directory, target_component=component) outputs = generator.generate_code() for output_path, output_code in outputs: - write_file(output_code, output_path, only_if_changed=True) + write_file(output_code, output_path) try: generate_interface_dependencies() @@ -297,7 +297,6 @@ idl_compiler = IdlCompilerV8( output_dir, info_provider=component_info_providers[component], - only_if_changed=True, target_component=component) if component == 'core': partial_interface_output_dir = os.path.join(output_directory, @@ -307,14 +306,13 @@ idl_partial_interface_compiler = IdlCompilerV8( partial_interface_output_dir, info_provider=component_info_providers['modules'], - only_if_changed=True, target_component='modules') else: idl_partial_interface_compiler = None dictionary_impl_compiler = IdlCompilerDictionaryImpl( output_dir, info_provider=component_info_providers[component], - only_if_changed=True, target_component=component) + target_component=component) idl_filenames = [] input_directory = os.path.join(test_input_directory, component)
diff --git a/third_party/leveldatabase/env_chromium_unittest.cc b/third_party/leveldatabase/env_chromium_unittest.cc index 368b24a..57bca24 100644 --- a/third_party/leveldatabase/env_chromium_unittest.cc +++ b/third_party/leveldatabase/env_chromium_unittest.cc
@@ -99,7 +99,7 @@ base::ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); - base::FilePath dir = scoped_temp_dir.path(); + base::FilePath dir = scoped_temp_dir.GetPath(); DB* db; Status status = DB::Open(options, dir.AsUTF8Unsafe(), &db); @@ -136,7 +136,7 @@ TEST(ChromiumEnv, GetChildrenEmptyDir) { base::ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); - base::FilePath dir = scoped_temp_dir.path(); + base::FilePath dir = scoped_temp_dir.GetPath(); Env* env = Env::Default(); std::vector<std::string> result; @@ -148,7 +148,7 @@ TEST(ChromiumEnv, GetChildrenPriorResults) { base::ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); - base::FilePath dir = scoped_temp_dir.path(); + base::FilePath dir = scoped_temp_dir.GetPath(); base::FilePath new_file_dir = dir.Append(FPL("tmp_file")); FILE* f = fopen(new_file_dir.AsUTF8Unsafe().c_str(), "w");
diff --git a/third_party/zlib/google/zip_reader_unittest.cc b/third_party/zlib/google/zip_reader_unittest.cc index 0073bbb6..4e023dc 100644 --- a/third_party/zlib/google/zip_reader_unittest.cc +++ b/third_party/zlib/google/zip_reader_unittest.cc
@@ -121,7 +121,7 @@ PlatformTest::SetUp(); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - test_dir_ = temp_dir_.path(); + test_dir_ = temp_dir_.GetPath(); ASSERT_TRUE(GetTestDataDirectory(&test_data_dir_));
diff --git a/third_party/zlib/google/zip_unittest.cc b/third_party/zlib/google/zip_unittest.cc index 3a6eedf..2d969d7 100644 --- a/third_party/zlib/google/zip_unittest.cc +++ b/third_party/zlib/google/zip_unittest.cc
@@ -37,7 +37,7 @@ PlatformTest::SetUp(); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - test_dir_ = temp_dir_.path(); + test_dir_ = temp_dir_.GetPath(); base::FilePath zip_path(test_dir_); zip_contents_.insert(zip_path.AppendASCII("foo.txt")); @@ -122,9 +122,9 @@ base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); - base::FilePath zip_file = temp_dir.path().AppendASCII("out.zip"); - base::FilePath src_dir = temp_dir.path().AppendASCII("input"); - base::FilePath out_dir = temp_dir.path().AppendASCII("output"); + base::FilePath zip_file = temp_dir.GetPath().AppendASCII("out.zip"); + base::FilePath src_dir = temp_dir.GetPath().AppendASCII("input"); + base::FilePath out_dir = temp_dir.GetPath().AppendASCII("output"); base::FilePath src_file = src_dir.AppendASCII("test.txt"); base::FilePath out_file = out_dir.AppendASCII("test.txt"); @@ -220,7 +220,7 @@ base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); - base::FilePath zip_file = temp_dir.path().AppendASCII("out.zip"); + base::FilePath zip_file = temp_dir.GetPath().AppendASCII("out.zip"); EXPECT_TRUE(zip::Zip(src_dir, zip_file, true)); TestUnzipFile(zip_file, true); @@ -233,7 +233,7 @@ base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); - base::FilePath zip_file = temp_dir.path().AppendASCII("out.zip"); + base::FilePath zip_file = temp_dir.GetPath().AppendASCII("out.zip"); EXPECT_TRUE(zip::Zip(src_dir, zip_file, false)); TestUnzipFile(zip_file, false); @@ -247,11 +247,10 @@ base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); // Append 'Тест' (in cyrillic). - base::FilePath src_dir_russian = - temp_dir.path().Append(base::FilePath::FromUTF8Unsafe( - "\xD0\xA2\xD0\xB5\xD1\x81\xD1\x82")); + base::FilePath src_dir_russian = temp_dir.GetPath().Append( + base::FilePath::FromUTF8Unsafe("\xD0\xA2\xD0\xB5\xD1\x81\xD1\x82")); base::CopyDirectory(src_dir, src_dir_russian, true); - base::FilePath zip_file = temp_dir.path().AppendASCII("out_russian.zip"); + base::FilePath zip_file = temp_dir.GetPath().AppendASCII("out_russian.zip"); EXPECT_TRUE(zip::Zip(src_dir_russian, zip_file, true)); TestUnzipFile(zip_file, true); @@ -287,7 +286,7 @@ base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); - base::FilePath zip_name = temp_dir.path().AppendASCII("out.zip"); + base::FilePath zip_name = temp_dir.GetPath().AppendASCII("out.zip"); base::File zip_file(zip_name, base::File::FLAG_CREATE | base::File::FLAG_WRITE); @@ -321,7 +320,7 @@ base::ScopedTempDir scoped_temp_dir; ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); - const base::FilePath& temp_dir = scoped_temp_dir.path(); + const base::FilePath& temp_dir = scoped_temp_dir.GetPath(); ASSERT_TRUE(zip::Unzip(test_zip_file, temp_dir)); EXPECT_TRUE(base::DirectoryExists(temp_dir.AppendASCII("d")));
diff --git a/tools/android/customtabs_benchmark/java/src/org/chromium/customtabs/test/MainActivity.java b/tools/android/customtabs_benchmark/java/src/org/chromium/customtabs/test/MainActivity.java index 3638b92..0b7b2a2e 100644 --- a/tools/android/customtabs_benchmark/java/src/org/chromium/customtabs/test/MainActivity.java +++ b/tools/android/customtabs_benchmark/java/src/org/chromium/customtabs/test/MainActivity.java
@@ -40,26 +40,36 @@ String packageName = intent.getStringExtra("package_name"); if (packageName == null) packageName = DEFAULT_PACKAGE; boolean warmup = intent.getBooleanExtra("warmup", false); - boolean noPrerendering = intent.getBooleanExtra("no_prerendering", false); int delayToMayLaunchUrl = intent.getIntExtra("delay_to_may_launch_url", -1); int delayToLaunchUrl = intent.getIntExtra("delay_to_launch_url", -1); + + int prerenderMode = 0; + switch(intent.getStringExtra("prerender_mode")) { + case "disabled": prerenderMode = 0; break; + case "enabled": prerenderMode = 1; break; + case "prefetch": prerenderMode = 2; break; + default: + throw new IllegalArgumentException( + "Invalid prerender mode: " + intent.getStringExtra("prerender_mode")); + } + launchCustomTabs( - packageName, url, warmup, noPrerendering, delayToMayLaunchUrl, delayToLaunchUrl); + packageName, url, warmup, prerenderMode, delayToMayLaunchUrl, delayToLaunchUrl); } private static final class CustomCallback extends CustomTabsCallback { private final boolean mWarmup; - private final boolean mNoPrerendering; + private final int mPrerenderMode; private final int mDelayToMayLaunchUrl; private final int mDelayToLaunchUrl; private long mIntentSentMs = 0; private long mPageLoadStartedMs = 0; private long mPageLoadFinishedMs = 0; - public CustomCallback(boolean warmup, boolean noPrerendering, int delayToMayLaunchUrl, + public CustomCallback(boolean warmup, int prerenderMode, int delayToMayLaunchUrl, int delayToLaunchUrl) { mWarmup = warmup; - mNoPrerendering = noPrerendering; + mPrerenderMode = prerenderMode; mDelayToMayLaunchUrl = delayToMayLaunchUrl; mDelayToLaunchUrl = delayToLaunchUrl; } @@ -77,7 +87,7 @@ case CustomTabsCallback.NAVIGATION_FINISHED: mPageLoadFinishedMs = SystemClock.elapsedRealtime(); if (mIntentSentMs != 0 && mPageLoadStartedMs != 0) { - String logLine = (mWarmup ? "1" : "0") + "," + (mNoPrerendering ? "1" : "0") + String logLine = (mWarmup ? "1" : "0") + "," + mPrerenderMode + "," + mDelayToMayLaunchUrl + "," + mDelayToLaunchUrl + "," + mIntentSentMs + "," + mPageLoadStartedMs + "," + mPageLoadFinishedMs; @@ -91,7 +101,7 @@ } private void onCustomTabsServiceConnected(CustomTabsClient client, final Uri uri, - final CustomCallback cb, boolean warmup, final boolean noPrerendering, + final CustomCallback cb, boolean warmup, final int prerenderMode, int delayToMayLaunchUrl, final int delayToLaunchUrl) { final Handler handler = new Handler(Looper.getMainLooper()); final CustomTabsSession session = client.newSession(cb); @@ -108,7 +118,8 @@ public void run() { Bundle extras = new Bundle(); extras.putBoolean( - "android.support.customtabs.maylaunchurl.NO_PRERENDERING", noPrerendering); + "android.support.customtabs.maylaunchurl.NO_PRERENDERING", + prerenderMode == 0); session.mayLaunchUrl(uri, extras, null); handler.postDelayed(launchRunnable, delayToLaunchUrl); } @@ -123,10 +134,10 @@ } private void launchCustomTabs(String packageName, String url, final boolean warmup, - final boolean noPrerendering, final int delayToMayLaunchUrl, + final int prerenderMode, final int delayToMayLaunchUrl, final int delayToLaunchUrl) { final CustomCallback cb = - new CustomCallback(warmup, noPrerendering, delayToMayLaunchUrl, delayToLaunchUrl); + new CustomCallback(warmup, prerenderMode, delayToMayLaunchUrl, delayToLaunchUrl); final Uri uri = Uri.parse(url); CustomTabsClient.bindCustomTabsService( this, packageName, new CustomTabsServiceConnection() { @@ -134,7 +145,7 @@ public void onCustomTabsServiceConnected( ComponentName name, final CustomTabsClient client) { MainActivity.this.onCustomTabsServiceConnected(client, uri, cb, warmup, - noPrerendering, delayToMayLaunchUrl, delayToLaunchUrl); + prerenderMode, delayToMayLaunchUrl, delayToLaunchUrl); } @Override
diff --git a/tools/android/customtabs_benchmark/scripts/customtabs_benchmark.py b/tools/android/customtabs_benchmark/scripts/customtabs_benchmark.py index 9c45880..e8974ea 100755 --- a/tools/android/customtabs_benchmark/scripts/customtabs_benchmark.py +++ b/tools/android/customtabs_benchmark/scripts/customtabs_benchmark.py
@@ -10,6 +10,7 @@ import optparse import os import re +import subprocess import sys import time @@ -25,22 +26,58 @@ sys.path.append(os.path.join(_SRC_PATH, 'build', 'android')) import devil_chromium +sys.path.append(os.path.join(_SRC_PATH, 'tools', 'android', 'loading')) +import device_setup -def RunOnce(device, url, warmup, no_prerendering, delay_to_may_launch_url, + +# Local build of Chrome (not Chromium). +_CHROME_PACKAGE = 'com.google.android.apps.chrome' + + +# Command line arguments for Chrome. +_CHROME_ARGS = [ + # Disable backgound network requests that may pollute WPR archive, pollute + # HTTP cache generation, and introduce noise in loading performance. + '--disable-background-networking', + '--disable-default-apps', + '--no-proxy-server', + # TODO(droger): Remove once crbug.com/354743 is fixed. + '--safebrowsing-disable-auto-update', + + # Disables actions that chrome performs only on first run or each launches, + # which can interfere with page load performance, or even block its + # execution by waiting for user input. + '--disable-fre', + '--no-default-browser-check', + '--no-first-run', +] + + +def ResetChromeLocalState(device): + """Remove the Chrome Profile and the various disk caches.""" + profile_dirs = ['app_chrome/Default', 'cache', 'app_chrome/ShaderCache', + 'app_tabs'] + cmd = ['rm', '-rf'] + cmd.extend( + '/data/data/{}/{}'.format(_CHROME_PACKAGE, d) for d in profile_dirs) + device.adb.Shell(subprocess.list2cmdline(cmd)) + + +def RunOnce(device, url, warmup, prerender_mode, delay_to_may_launch_url, delay_to_launch_url, cold): """Runs a test on a device once. Args: device: (DeviceUtils) device to run the tests on. warmup: (bool) Whether to call warmup. - no_prerendering: (bool) Whether to disable prerendering. + prerender_mode: (str) Prerender mode (disabled, enabled or prefetch). delay_to_may_launch_url: (int) Delay to mayLaunchUrl() in ms. delay_to_launch_url: (int) Delay to launchUrl() in ms. cold: (bool) Whether the page cache should be dropped. Returns: The output line (str), like this (one line only): - <warmup>,<no_prerendering>,<delay_to_may_launch_url>,<delay_to_launch>, + <warmup>,<prerender_mode>,<delay_to_may_launch_url>,<delay_to_launch>, <intent_sent_ms>,<page_load_started_ms>,<page_load_finished_ms> or None on error. """ @@ -48,14 +85,16 @@ action='android.intent.action.MAIN', package='org.chromium.customtabsclient.test', activity='org.chromium.customtabs.test.MainActivity', - extras={'url': url, 'warmup': warmup, 'no_prerendering': no_prerendering, + extras={'url': url, 'warmup': warmup, 'prerender_mode': prerender_mode, 'delay_to_may_launch_url': delay_to_may_launch_url, 'delay_to_launch_url': delay_to_launch_url}) result_line_re = re.compile(r'CUSTOMTABSBENCH.*: (.*)') logcat_monitor = device.GetLogcatMonitor(clear=True) logcat_monitor.Start() - device.ForceStop('com.google.android.apps.chrome') + device.ForceStop(_CHROME_PACKAGE) device.ForceStop('org.chromium.customtabsclient.test') + ResetChromeLocalState(device) + if cold: if not device.HasRoot(): device.EnableRoot() @@ -69,7 +108,7 @@ return match.group(1) if match is not None else None -def LoopOnDevice(device, url, warmup, no_prerendering, delay_to_may_launch_url, +def LoopOnDevice(device, url, warmup, prerender_mode, delay_to_may_launch_url, delay_to_launch_url, cold, output_filename, once=False): """Loops the tests on a device. @@ -77,7 +116,7 @@ device: (DeviceUtils) device to run the tests on. url: (str) URL to navigate to. warmup: (bool) Whether to call warmup. - no_prerendering: (bool) Whether to disable prerendering. + prerender_mode: (str) Prerender mode (disabled, enabled or prefetch). delay_to_may_launch_url: (int) Delay to mayLaunchUrl() in ms. delay_to_launch_url: (int) Delay to launchUrl() in ms. cold: (bool) Whether the page cache should be dropped. @@ -87,7 +126,7 @@ while True: out = sys.stdout if output_filename == '-' else open(output_filename, 'a') try: - result = RunOnce(device, url, warmup, no_prerendering, + result = RunOnce(device, url, warmup, prerender_mode, delay_to_may_launch_url, delay_to_launch_url, cold) if result is not None: out.write(result + '\n') @@ -112,12 +151,12 @@ import numpy as np data = np.genfromtxt(filename, delimiter=',') result = np.array(np.zeros(len(data)), - dtype=[('warmup', bool), ('no_prerendering', bool), + dtype=[('warmup', bool), ('prerender_mode', np.int32), ('delay_to_may_launch_url', np.int32), ('delay_to_launch_url', np.int32), ('commit', np.int32), ('plt', np.int32)]) result['warmup'] = data[:, 0] - result['no_prerendering'] = data[:, 1] + result['prerender_mode'] = data[:, 1] result['delay_to_may_launch_url'] = data[:, 2] result['delay_to_launch_url'] = data[:, 3] result['commit'] = data[:, 5] - data[:, 4] @@ -134,8 +173,9 @@ default='https://www.android.com') parser.add_option('--warmup', help='Call warmup.', default=False, action='store_true') - parser.add_option('--no_prerendering', help='Disable prerendering.', - default=False, action='store_true') + parser.add_option('--prerender_mode', default='enabled', + help='The prerender mode (disabled, enabled or prefetch).', + choices=['disabled', 'enabled', 'prefetch']) parser.add_option('--delay_to_may_launch_url', help='Delay before calling mayLaunchUrl() in ms.', type='int') @@ -166,9 +206,14 @@ logging.error('Device not found.') sys.exit(0) device = matching_devices[0] - LoopOnDevice(device, options.url, options.warmup, options.no_prerendering, - options.delay_to_may_launch_url, options.delay_to_launch_url, - options.cold, options.output_file, options.once) + + with device_setup.FlagReplacer( + device, '/data/local/tmp/chrome-command-line', + _CHROME_ARGS + ['--prerender=' + options.prerender_mode]): + LoopOnDevice(device, options.url, options.warmup, + options.prerender_mode, + options.delay_to_may_launch_url, options.delay_to_launch_url, + options.cold, options.output_file, options.once) if __name__ == '__main__':
diff --git a/tools/gn/exec_process_unittest.cc b/tools/gn/exec_process_unittest.cc index 70a208c9..51ce7b7 100644 --- a/tools/gn/exec_process_unittest.cc +++ b/tools/gn/exec_process_unittest.cc
@@ -26,6 +26,7 @@ std::string* std_err, int* exit_code) { base::ScopedTempDir temp_dir; + CHECK(temp_dir.CreateUniqueTempDir()); base::CommandLine::StringVector args; #if defined(OS_WIN) args.push_back(L"python"); @@ -36,8 +37,8 @@ args.push_back("-c"); args.push_back(command); #endif - return ExecProcess( - base::CommandLine(args), temp_dir.path(), std_out, std_err, exit_code); + return ExecProcess(base::CommandLine(args), temp_dir.GetPath(), std_out, + std_err, exit_code); } } // namespace
diff --git a/tools/gn/filesystem_utils_unittest.cc b/tools/gn/filesystem_utils_unittest.cc index 240ed61..f5724c43 100644 --- a/tools/gn/filesystem_utils_unittest.cc +++ b/tools/gn/filesystem_utils_unittest.cc
@@ -581,7 +581,7 @@ std::string data = "foo"; - base::FilePath file_path = temp_dir.path().AppendASCII("foo.txt"); + base::FilePath file_path = temp_dir.GetPath().AppendASCII("foo.txt"); base::WriteFile(file_path, data.c_str(), static_cast<int>(data.size())); EXPECT_TRUE(ContentsEqual(file_path, data)); @@ -602,7 +602,7 @@ // Write if file doesn't exist. Create also directory. base::FilePath file_path = - temp_dir.path().AppendASCII("bar").AppendASCII("foo.txt"); + temp_dir.GetPath().AppendASCII("bar").AppendASCII("foo.txt"); EXPECT_TRUE(WriteFileIfChanged(file_path, data, nullptr)); base::File::Info file_info;
diff --git a/tools/gn/function_write_file_unittest.cc b/tools/gn/function_write_file_unittest.cc index 50a0f43..8f2b42a 100644 --- a/tools/gn/function_write_file_unittest.cc +++ b/tools/gn/function_write_file_unittest.cc
@@ -40,7 +40,7 @@ // Make a real directory for writing the files. base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); - setup.build_settings()->SetRootPath(temp_dir.path()); + setup.build_settings()->SetRootPath(temp_dir.GetPath()); setup.build_settings()->SetBuildDir(SourceDir("//out/")); Value some_string(nullptr, "some string contents"); @@ -52,8 +52,9 @@ // Should be able to write to a new dir inside the out dir. EXPECT_TRUE(CallWriteFile(setup.scope(), "//out/foo.txt", some_string)); - base::FilePath foo_name = temp_dir.path().Append(FILE_PATH_LITERAL("out")) - .Append(FILE_PATH_LITERAL("foo.txt")); + base::FilePath foo_name = temp_dir.GetPath() + .Append(FILE_PATH_LITERAL("out")) + .Append(FILE_PATH_LITERAL("foo.txt")); std::string result_contents; EXPECT_TRUE(base::ReadFileToString(foo_name, &result_contents)); EXPECT_EQ(some_string.string_value(), result_contents);
diff --git a/tools/perf/page_sets/data/mobile_infinite_scroll.json b/tools/perf/page_sets/data/mobile_infinite_scroll.json index 68f3f4c..6bdab300 100644 --- a/tools/perf/page_sets/data/mobile_infinite_scroll.json +++ b/tools/perf/page_sets/data/mobile_infinite_scroll.json
@@ -1,12 +1,15 @@ { - "description": "Describes the Web Page Replay archives for a story set. Don't edit by hand! Use record_wpr for updating.", "archives": { "mobile_infinite_scroll_000.wpr": [ - "facebook", - "flickr", - "tumblr", - "discourse", + "facebook", + "flickr", + "tumblr", + "discourse", "twitter" + ], + "mobile_infinite_scroll_001.wpr": [ + "pinterest" ] - } + }, + "description": "Describes the Web Page Replay archives for a story set. Don't edit by hand! Use record_wpr for updating." } \ No newline at end of file
diff --git a/tools/perf/page_sets/data/mobile_infinite_scroll_001.wpr.sha1 b/tools/perf/page_sets/data/mobile_infinite_scroll_001.wpr.sha1 new file mode 100644 index 0000000..16f9bab --- /dev/null +++ b/tools/perf/page_sets/data/mobile_infinite_scroll_001.wpr.sha1
@@ -0,0 +1 @@ +29b293f9d8bbe10577858fd9104c0811028d66be \ No newline at end of file
diff --git a/tools/perf/page_sets/mobile_infinite_scroll_cases.py b/tools/perf/page_sets/mobile_infinite_scroll_cases.py index 0f626fe1..adf4271 100644 --- a/tools/perf/page_sets/mobile_infinite_scroll_cases.py +++ b/tools/perf/page_sets/mobile_infinite_scroll_cases.py
@@ -84,7 +84,7 @@ SCROLL_PAGE = 1 pages = [ ('https://m.facebook.com/shakira', 'facebook', SCROLL_FAR, 0, 0), - ('https://mobile.twitter.com/taylorswift13', 'twitter', SCROLL_PAGE, 10, 30), + ('https://www.pinterest.com/all', 'pinterest', SCROLL_FAR, 0, 0), ('http://techcrunch.tumblr.com/', 'tumblr', SCROLL_FAR, 0, 0), ('https://www.flickr.com/explore', 'flickr', SCROLL_FAR, 0, 0), ('https://meta.discourse.org/t/the-official-discourse-tags-plugin-discourse-tagging/26482',
diff --git a/ui/app_list/search/history_data_store_unittest.cc b/ui/app_list/search/history_data_store_unittest.cc index 69fb2a0..9b582d68 100644 --- a/ui/app_list/search/history_data_store_unittest.cc +++ b/ui/app_list/search/history_data_store_unittest.cc
@@ -53,7 +53,7 @@ } void OpenStore(const std::string& file_name) { - data_file_ = temp_dir_.path().AppendASCII(file_name); + data_file_ = temp_dir_.GetPath().AppendASCII(file_name); store_ = new HistoryDataStore(scoped_refptr<DictionaryDataStore>( new DictionaryDataStore(data_file_, worker_pool_owner_.pool().get()))); Load(); @@ -70,8 +70,8 @@ } void WriteDataFile(const std::string& file_name, const std::string& data) { - base::WriteFile( - temp_dir_.path().AppendASCII(file_name), data.c_str(), data.size()); + base::WriteFile(temp_dir_.GetPath().AppendASCII(file_name), data.c_str(), + data.size()); } HistoryDataStore* store() { return store_.get(); }
diff --git a/ui/base/resource/data_pack_unittest.cc b/ui/base/resource/data_pack_unittest.cc index 33d5e416..11b7f7a 100644 --- a/ui/base/resource/data_pack_unittest.cc +++ b/ui/base/resource/data_pack_unittest.cc
@@ -35,7 +35,8 @@ TEST(DataPackTest, LoadFromPath) { base::ScopedTempDir dir; ASSERT_TRUE(dir.CreateUniqueTempDir()); - base::FilePath data_path = dir.path().Append(FILE_PATH_LITERAL("sample.pak")); + base::FilePath data_path = + dir.GetPath().Append(FILE_PATH_LITERAL("sample.pak")); // Dump contents into the pak file. ASSERT_EQ(base::WriteFile(data_path, kSamplePakContents, kSamplePakSize), @@ -67,7 +68,8 @@ TEST(DataPackTest, LoadFromFile) { base::ScopedTempDir dir; ASSERT_TRUE(dir.CreateUniqueTempDir()); - base::FilePath data_path = dir.path().Append(FILE_PATH_LITERAL("sample.pak")); + base::FilePath data_path = + dir.GetPath().Append(FILE_PATH_LITERAL("sample.pak")); // Dump contents into the pak file. ASSERT_EQ(base::WriteFile(data_path, kSamplePakContents, kSamplePakSize), @@ -102,7 +104,8 @@ TEST(DataPackTest, LoadFromFileRegion) { base::ScopedTempDir dir; ASSERT_TRUE(dir.CreateUniqueTempDir()); - base::FilePath data_path = dir.path().Append(FILE_PATH_LITERAL("sample.pak")); + base::FilePath data_path = + dir.GetPath().Append(FILE_PATH_LITERAL("sample.pak")); // Construct a file which has a non page-aligned zero-filled header followed // by the actual pak file content. @@ -158,7 +161,7 @@ TEST_P(DataPackTest, Write) { base::ScopedTempDir dir; ASSERT_TRUE(dir.CreateUniqueTempDir()); - base::FilePath file = dir.path().Append(FILE_PATH_LITERAL("data.pak")); + base::FilePath file = dir.GetPath().Append(FILE_PATH_LITERAL("data.pak")); std::string one("one"); std::string two("two"); @@ -196,7 +199,8 @@ TEST(DataPackTest, ModifiedWhileUsed) { base::ScopedTempDir dir; ASSERT_TRUE(dir.CreateUniqueTempDir()); - base::FilePath data_path = dir.path().Append(FILE_PATH_LITERAL("sample.pak")); + base::FilePath data_path = + dir.GetPath().Append(FILE_PATH_LITERAL("sample.pak")); // Dump contents into the pak file. ASSERT_EQ(base::WriteFile(data_path, kSamplePakContents, kSamplePakSize),
diff --git a/ui/base/resource/resource_bundle_unittest.cc b/ui/base/resource/resource_bundle_unittest.cc index bd93ac03..f9156ac 100644 --- a/ui/base/resource/resource_bundle_unittest.cc +++ b/ui/base/resource/resource_bundle_unittest.cc
@@ -372,7 +372,7 @@ } // Returns the path of temporary directory to write test data packs into. - const base::FilePath& dir_path() { return dir_.path(); } + const base::FilePath& dir_path() { return dir_.GetPath(); } // Returns the number of DataPacks managed by |resource_bundle|. size_t NumDataPacksInResourceBundle(ResourceBundle* resource_bundle) {
diff --git a/ui/gfx/font_render_params_linux_unittest.cc b/ui/gfx/font_render_params_linux_unittest.cc index c5ba2d3..ca782e5f 100644 --- a/ui/gfx/font_render_params_linux_unittest.cc +++ b/ui/gfx/font_render_params_linux_unittest.cc
@@ -72,40 +72,44 @@ TEST_F(FontRenderParamsTest, Default) { ASSERT_TRUE(LoadSystemFontIntoFontconfig("arial.ttf")); - ASSERT_TRUE(LoadConfigDataIntoFontconfig(temp_dir_.path(), + ASSERT_TRUE(LoadConfigDataIntoFontconfig( + temp_dir_.GetPath(), std::string(kFontconfigFileHeader) + - // Specify the desired defaults via a font match rather than a pattern - // match (since this is the style generally used in /etc/fonts/conf.d). - kFontconfigMatchFontHeader + - CreateFontconfigEditStanza("antialias", "bool", "true") + - CreateFontconfigEditStanza("autohint", "bool", "true") + - CreateFontconfigEditStanza("hinting", "bool", "true") + - CreateFontconfigEditStanza("hintstyle", "const", "hintslight") + - CreateFontconfigEditStanza("rgba", "const", "rgb") + - kFontconfigMatchFooter + - // Add a font match for Arial. Since it specifies a family, it shouldn't - // take effect when querying default settings. - kFontconfigMatchFontHeader + - CreateFontconfigTestStanza("family", "eq", "string", "Arial") + - CreateFontconfigEditStanza("antialias", "bool", "true") + - CreateFontconfigEditStanza("autohint", "bool", "false") + - CreateFontconfigEditStanza("hinting", "bool", "true") + - CreateFontconfigEditStanza("hintstyle", "const", "hintfull") + - CreateFontconfigEditStanza("rgba", "const", "none") + - kFontconfigMatchFooter + - // Add font matches for fonts between 10 and 20 points or pixels. Since - // they specify sizes, they also should not affect the defaults. - kFontconfigMatchFontHeader + - CreateFontconfigTestStanza("size", "more_eq", "double", "10.0") + - CreateFontconfigTestStanza("size", "less_eq", "double", "20.0") + - CreateFontconfigEditStanza("antialias", "bool", "false") + - kFontconfigMatchFooter + - kFontconfigMatchFontHeader + - CreateFontconfigTestStanza("pixel_size", "more_eq", "double", "10.0") + - CreateFontconfigTestStanza("pixel_size", "less_eq", "double", "20.0") + - CreateFontconfigEditStanza("antialias", "bool", "false") + - kFontconfigMatchFooter + - kFontconfigFileFooter)); + // Specify the desired defaults via a font match rather than a pattern + // match (since this is the style generally used in + // /etc/fonts/conf.d). + kFontconfigMatchFontHeader + + CreateFontconfigEditStanza("antialias", "bool", "true") + + CreateFontconfigEditStanza("autohint", "bool", "true") + + CreateFontconfigEditStanza("hinting", "bool", "true") + + CreateFontconfigEditStanza("hintstyle", "const", "hintslight") + + CreateFontconfigEditStanza("rgba", "const", "rgb") + + kFontconfigMatchFooter + + // Add a font match for Arial. Since it specifies a family, it + // shouldn't + // take effect when querying default settings. + kFontconfigMatchFontHeader + + CreateFontconfigTestStanza("family", "eq", "string", "Arial") + + CreateFontconfigEditStanza("antialias", "bool", "true") + + CreateFontconfigEditStanza("autohint", "bool", "false") + + CreateFontconfigEditStanza("hinting", "bool", "true") + + CreateFontconfigEditStanza("hintstyle", "const", "hintfull") + + CreateFontconfigEditStanza("rgba", "const", "none") + + kFontconfigMatchFooter + + // Add font matches for fonts between 10 and 20 points or pixels. + // Since + // they specify sizes, they also should not affect the defaults. + kFontconfigMatchFontHeader + + CreateFontconfigTestStanza("size", "more_eq", "double", "10.0") + + CreateFontconfigTestStanza("size", "less_eq", "double", "20.0") + + CreateFontconfigEditStanza("antialias", "bool", "false") + + kFontconfigMatchFooter + kFontconfigMatchFontHeader + + CreateFontconfigTestStanza("pixel_size", "more_eq", "double", + "10.0") + + CreateFontconfigTestStanza("pixel_size", "less_eq", "double", + "20.0") + + CreateFontconfigEditStanza("antialias", "bool", "false") + + kFontconfigMatchFooter + kFontconfigFileFooter)); FontRenderParams params = GetFontRenderParams( FontRenderParamsQuery(), NULL); @@ -120,24 +124,21 @@ TEST_F(FontRenderParamsTest, Size) { ASSERT_TRUE(LoadSystemFontIntoFontconfig("arial.ttf")); - ASSERT_TRUE(LoadConfigDataIntoFontconfig(temp_dir_.path(), - std::string(kFontconfigFileHeader) + - kFontconfigMatchPatternHeader + - CreateFontconfigEditStanza("antialias", "bool", "true") + - CreateFontconfigEditStanza("hinting", "bool", "true") + - CreateFontconfigEditStanza("hintstyle", "const", "hintfull") + - CreateFontconfigEditStanza("rgba", "const", "none") + - kFontconfigMatchFooter + - kFontconfigMatchPatternHeader + - CreateFontconfigTestStanza("pixelsize", "less_eq", "double", "10") + - CreateFontconfigEditStanza("antialias", "bool", "false") + - kFontconfigMatchFooter + - kFontconfigMatchPatternHeader + - CreateFontconfigTestStanza("size", "more_eq", "double", "20") + - CreateFontconfigEditStanza("hintstyle", "const", "hintslight") + - CreateFontconfigEditStanza("rgba", "const", "rgb") + - kFontconfigMatchFooter + - kFontconfigFileFooter)); + ASSERT_TRUE(LoadConfigDataIntoFontconfig( + temp_dir_.GetPath(), + std::string(kFontconfigFileHeader) + kFontconfigMatchPatternHeader + + CreateFontconfigEditStanza("antialias", "bool", "true") + + CreateFontconfigEditStanza("hinting", "bool", "true") + + CreateFontconfigEditStanza("hintstyle", "const", "hintfull") + + CreateFontconfigEditStanza("rgba", "const", "none") + + kFontconfigMatchFooter + kFontconfigMatchPatternHeader + + CreateFontconfigTestStanza("pixelsize", "less_eq", "double", "10") + + CreateFontconfigEditStanza("antialias", "bool", "false") + + kFontconfigMatchFooter + kFontconfigMatchPatternHeader + + CreateFontconfigTestStanza("size", "more_eq", "double", "20") + + CreateFontconfigEditStanza("hintstyle", "const", "hintslight") + + CreateFontconfigEditStanza("rgba", "const", "rgb") + + kFontconfigMatchFooter + kFontconfigFileFooter)); // The defaults should be used when the supplied size isn't matched by the // second or third blocks. @@ -169,23 +170,20 @@ ASSERT_TRUE(LoadSystemFontIntoFontconfig("arial.ttf")); // Load a config that disables subpixel rendering for bold text and disables // hinting for italic text. - ASSERT_TRUE(LoadConfigDataIntoFontconfig(temp_dir_.path(), - std::string(kFontconfigFileHeader) + - kFontconfigMatchPatternHeader + - CreateFontconfigEditStanza("antialias", "bool", "true") + - CreateFontconfigEditStanza("hinting", "bool", "true") + - CreateFontconfigEditStanza("hintstyle", "const", "hintslight") + - CreateFontconfigEditStanza("rgba", "const", "rgb") + - kFontconfigMatchFooter + - kFontconfigMatchPatternHeader + - CreateFontconfigTestStanza("weight", "eq", "const", "bold") + - CreateFontconfigEditStanza("rgba", "const", "none") + - kFontconfigMatchFooter + - kFontconfigMatchPatternHeader + - CreateFontconfigTestStanza("slant", "eq", "const", "italic") + - CreateFontconfigEditStanza("hinting", "bool", "false") + - kFontconfigMatchFooter + - kFontconfigFileFooter)); + ASSERT_TRUE(LoadConfigDataIntoFontconfig( + temp_dir_.GetPath(), + std::string(kFontconfigFileHeader) + kFontconfigMatchPatternHeader + + CreateFontconfigEditStanza("antialias", "bool", "true") + + CreateFontconfigEditStanza("hinting", "bool", "true") + + CreateFontconfigEditStanza("hintstyle", "const", "hintslight") + + CreateFontconfigEditStanza("rgba", "const", "rgb") + + kFontconfigMatchFooter + kFontconfigMatchPatternHeader + + CreateFontconfigTestStanza("weight", "eq", "const", "bold") + + CreateFontconfigEditStanza("rgba", "const", "none") + + kFontconfigMatchFooter + kFontconfigMatchPatternHeader + + CreateFontconfigTestStanza("slant", "eq", "const", "italic") + + CreateFontconfigEditStanza("hinting", "bool", "false") + + kFontconfigMatchFooter + kFontconfigFileFooter)); FontRenderParamsQuery query; query.style = Font::NORMAL; @@ -217,16 +215,14 @@ TEST_F(FontRenderParamsTest, Scalable) { // Load a config that only enables antialiasing for scalable fonts. - ASSERT_TRUE(LoadConfigDataIntoFontconfig(temp_dir_.path(), - std::string(kFontconfigFileHeader) + - kFontconfigMatchPatternHeader + - CreateFontconfigEditStanza("antialias", "bool", "false") + - kFontconfigMatchFooter + - kFontconfigMatchPatternHeader + - CreateFontconfigTestStanza("scalable", "eq", "bool", "true") + - CreateFontconfigEditStanza("antialias", "bool", "true") + - kFontconfigMatchFooter + - kFontconfigFileFooter)); + ASSERT_TRUE(LoadConfigDataIntoFontconfig( + temp_dir_.GetPath(), + std::string(kFontconfigFileHeader) + kFontconfigMatchPatternHeader + + CreateFontconfigEditStanza("antialias", "bool", "false") + + kFontconfigMatchFooter + kFontconfigMatchPatternHeader + + CreateFontconfigTestStanza("scalable", "eq", "bool", "true") + + CreateFontconfigEditStanza("antialias", "bool", "true") + + kFontconfigMatchFooter + kFontconfigFileFooter)); // Check that we specifically ask how scalable fonts should be rendered. FontRenderParams params = GetFontRenderParams( @@ -237,16 +233,14 @@ TEST_F(FontRenderParamsTest, UseBitmaps) { ASSERT_TRUE(LoadSystemFontIntoFontconfig("arial.ttf")); // Load a config that enables embedded bitmaps for fonts <= 10 pixels. - ASSERT_TRUE(LoadConfigDataIntoFontconfig(temp_dir_.path(), - std::string(kFontconfigFileHeader) + - kFontconfigMatchPatternHeader + - CreateFontconfigEditStanza("embeddedbitmap", "bool", "false") + - kFontconfigMatchFooter + - kFontconfigMatchPatternHeader + - CreateFontconfigTestStanza("pixelsize", "less_eq", "double", "10") + - CreateFontconfigEditStanza("embeddedbitmap", "bool", "true") + - kFontconfigMatchFooter + - kFontconfigFileFooter)); + ASSERT_TRUE(LoadConfigDataIntoFontconfig( + temp_dir_.GetPath(), + std::string(kFontconfigFileHeader) + kFontconfigMatchPatternHeader + + CreateFontconfigEditStanza("embeddedbitmap", "bool", "false") + + kFontconfigMatchFooter + kFontconfigMatchPatternHeader + + CreateFontconfigTestStanza("pixelsize", "less_eq", "double", "10") + + CreateFontconfigEditStanza("embeddedbitmap", "bool", "true") + + kFontconfigMatchFooter + kFontconfigFileFooter)); FontRenderParamsQuery query; FontRenderParams params = GetFontRenderParams(query, NULL); @@ -260,15 +254,14 @@ TEST_F(FontRenderParamsTest, ForceFullHintingWhenAntialiasingIsDisabled) { // Load a config that disables antialiasing and hinting while requesting // subpixel rendering. - ASSERT_TRUE(LoadConfigDataIntoFontconfig(temp_dir_.path(), - std::string(kFontconfigFileHeader) + - kFontconfigMatchPatternHeader + - CreateFontconfigEditStanza("antialias", "bool", "false") + - CreateFontconfigEditStanza("hinting", "bool", "false") + - CreateFontconfigEditStanza("hintstyle", "const", "hintnone") + - CreateFontconfigEditStanza("rgba", "const", "rgb") + - kFontconfigMatchFooter + - kFontconfigFileFooter)); + ASSERT_TRUE(LoadConfigDataIntoFontconfig( + temp_dir_.GetPath(), + std::string(kFontconfigFileHeader) + kFontconfigMatchPatternHeader + + CreateFontconfigEditStanza("antialias", "bool", "false") + + CreateFontconfigEditStanza("hinting", "bool", "false") + + CreateFontconfigEditStanza("hintstyle", "const", "hintnone") + + CreateFontconfigEditStanza("rgba", "const", "rgb") + + kFontconfigMatchFooter + kFontconfigFileFooter)); // Full hinting should be forced. See the comment in GetFontRenderParams() for // more information. @@ -310,12 +303,11 @@ // Load a Fontconfig config that enables antialiasing but doesn't say anything // about subpixel rendering. - ASSERT_TRUE(LoadConfigDataIntoFontconfig(temp_dir_.path(), - std::string(kFontconfigFileHeader) + - kFontconfigMatchPatternHeader + - CreateFontconfigEditStanza("antialias", "bool", "true") + - kFontconfigMatchFooter + - kFontconfigFileFooter)); + ASSERT_TRUE(LoadConfigDataIntoFontconfig( + temp_dir_.GetPath(), + std::string(kFontconfigFileHeader) + kFontconfigMatchPatternHeader + + CreateFontconfigEditStanza("antialias", "bool", "true") + + kFontconfigMatchFooter + kFontconfigFileFooter)); // The subpixel rendering setting from the delegate should make it through. FontRenderParams params = GetFontRenderParams( @@ -363,14 +355,14 @@ // Configure Fontconfig to use Verdana for both Helvetica and Arial. ASSERT_TRUE(LoadSystemFontIntoFontconfig("arial.ttf")); ASSERT_TRUE(LoadSystemFontIntoFontconfig("verdana.ttf")); - ASSERT_TRUE(LoadConfigDataIntoFontconfig(temp_dir_.path(), + ASSERT_TRUE(LoadConfigDataIntoFontconfig( + temp_dir_.GetPath(), std::string(kFontconfigFileHeader) + - CreateFontconfigAliasStanza("Helvetica", "Verdana") + - kFontconfigMatchPatternHeader + - CreateFontconfigTestStanza("family", "eq", "string", "Arial") + - CreateFontconfigEditStanza("family", "string", "Verdana") + - kFontconfigMatchFooter + - kFontconfigFileFooter)); + CreateFontconfigAliasStanza("Helvetica", "Verdana") + + kFontconfigMatchPatternHeader + + CreateFontconfigTestStanza("family", "eq", "string", "Arial") + + CreateFontconfigEditStanza("family", "string", "Verdana") + + kFontconfigMatchFooter + kFontconfigFileFooter)); FontRenderParamsQuery query; query.families.push_back("Helvetica");
diff --git a/ui/gfx/icon_util_unittest.cc b/ui/gfx/icon_util_unittest.cc index 7995427..0e24c55e 100644 --- a/ui/gfx/icon_util_unittest.cc +++ b/ui/gfx/icon_util_unittest.cc
@@ -200,10 +200,10 @@ TEST_F(IconUtilTest, TestCreateIconFileInvalidParameters) { std::unique_ptr<SkBitmap> bitmap; gfx::ImageFamily image_family; - base::FilePath valid_icon_filename = temp_directory_.path().AppendASCII( - kTempIconFilename); - base::FilePath invalid_icon_filename = temp_directory_.path().AppendASCII( - "<>?.ico"); + base::FilePath valid_icon_filename = + temp_directory_.GetPath().AppendASCII(kTempIconFilename); + base::FilePath invalid_icon_filename = + temp_directory_.GetPath().AppendASCII("<>?.ico"); // Wrong bitmap format. bitmap.reset(new SkBitmap); @@ -252,8 +252,8 @@ // This test case makes sure IconUtil::CreateIconFileFromImageFamily fails if // the image family is empty or invalid. TEST_F(IconUtilTest, TestCreateIconFileEmptyImageFamily) { - base::FilePath icon_filename = temp_directory_.path().AppendASCII( - kTempIconFilename); + base::FilePath icon_filename = + temp_directory_.GetPath().AppendASCII(kTempIconFilename); // Empty image family. EXPECT_FALSE(IconUtil::CreateIconFileFromImageFamily(gfx::ImageFamily(), @@ -342,7 +342,7 @@ TEST_F(IconUtilTest, TestCreateIconFileFromImageFamily) { gfx::ImageFamily image_family; base::FilePath icon_filename = - temp_directory_.path().AppendASCII(kTempIconFilename); + temp_directory_.GetPath().AppendASCII(kTempIconFilename); // Test with only a 16x16 icon. Should only scale up to 48x48. image_family.Add(gfx::Image::CreateFrom1xBitmap(