1 // Copyright 2014 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "content/browser/device_sensors/device_inertial_sensor_service.h" 6 7 #include "base/bind.h" 8 #include "base/logging.h" 9 #include "base/memory/singleton.h" 10 #include "content/browser/device_sensors/data_fetcher_shared_memory.h" 11 12 namespace content { 13 14 DeviceInertialSensorService::DeviceInertialSensorService() 15 : num_motion_readers_(0), 16 num_orientation_readers_(0), 17 is_shutdown_(false) { 18 } 19 20 DeviceInertialSensorService::~DeviceInertialSensorService() { 21 } 22 23 DeviceInertialSensorService* DeviceInertialSensorService::GetInstance() { 24 return Singleton<DeviceInertialSensorService, 25 LeakySingletonTraits<DeviceInertialSensorService> >::get(); 26 } 27 28 void DeviceInertialSensorService::AddConsumer(ConsumerType consumer_type) { 29 if (!ChangeNumberConsumers(consumer_type, 1)) 30 return; 31 32 DCHECK(GetNumberConsumers(consumer_type)); 33 34 if (!data_fetcher_) 35 data_fetcher_.reset(new DataFetcherSharedMemory); 36 data_fetcher_->StartFetchingDeviceData(consumer_type); 37 } 38 39 void DeviceInertialSensorService::RemoveConsumer(ConsumerType consumer_type) { 40 if (!ChangeNumberConsumers(consumer_type, -1)) 41 return; 42 43 if (GetNumberConsumers(consumer_type) == 0) 44 data_fetcher_->StopFetchingDeviceData(consumer_type); 45 } 46 47 bool DeviceInertialSensorService::ChangeNumberConsumers( 48 ConsumerType consumer_type, int delta) { 49 DCHECK(thread_checker_.CalledOnValidThread()); 50 if (is_shutdown_) 51 return false; 52 53 switch (consumer_type) { 54 case CONSUMER_TYPE_MOTION: 55 num_motion_readers_ += delta; 56 DCHECK_GE(num_motion_readers_, 0); 57 return true; 58 case CONSUMER_TYPE_ORIENTATION: 59 num_orientation_readers_ += delta; 60 DCHECK_GE(num_orientation_readers_ , 0); 61 return true; 62 default: 63 NOTREACHED(); 64 } 65 return false; 66 } 67 68 int DeviceInertialSensorService::GetNumberConsumers( 69 ConsumerType consumer_type) const { 70 switch (consumer_type) { 71 case CONSUMER_TYPE_MOTION: 72 return num_motion_readers_; 73 case CONSUMER_TYPE_ORIENTATION: 74 return num_orientation_readers_; 75 default: 76 NOTREACHED(); 77 } 78 return 0; 79 } 80 81 base::SharedMemoryHandle 82 DeviceInertialSensorService::GetSharedMemoryHandleForProcess( 83 ConsumerType consumer_type, base::ProcessHandle handle) { 84 DCHECK(thread_checker_.CalledOnValidThread()); 85 return data_fetcher_->GetSharedMemoryHandleForProcess(consumer_type, handle); 86 } 87 88 void DeviceInertialSensorService::Shutdown() { 89 data_fetcher_.reset(); 90 is_shutdown_ = true; 91 } 92 93 void DeviceInertialSensorService::SetDataFetcherForTesting( 94 DataFetcherSharedMemory* test_data_fetcher) { 95 data_fetcher_.reset(test_data_fetcher); 96 } 97 98 } // namespace content 99