geolocation_provider_impl.cc 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. // Copyright (c) 2012 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. #include "services/device/geolocation/geolocation_provider_impl.h"
  5. #include <utility>
  6. #include "base/bind.h"
  7. #include "base/callback.h"
  8. #include "base/callback_helpers.h"
  9. #include "base/check.h"
  10. #include "base/lazy_instance.h"
  11. #include "base/location.h"
  12. #include "base/memory/ptr_util.h"
  13. #include "base/memory/singleton.h"
  14. #include "base/notreached.h"
  15. #include "base/task/single_thread_task_runner.h"
  16. #include "base/threading/thread_task_runner_handle.h"
  17. #include "base/time/default_tick_clock.h"
  18. #include "build/build_config.h"
  19. #include "net/base/network_change_notifier.h"
  20. #include "services/device/geolocation/location_arbitrator.h"
  21. #include "services/device/geolocation/position_cache_impl.h"
  22. #include "services/device/public/cpp/geolocation/geoposition.h"
  23. #include "services/network/public/cpp/shared_url_loader_factory.h"
  24. #if BUILDFLAG(IS_ANDROID)
  25. #include "base/android/jni_android.h"
  26. #include "services/device/geolocation/geolocation_jni_headers/LocationProviderFactory_jni.h"
  27. #endif
  28. namespace device {
  29. namespace {
  30. base::LazyInstance<CustomLocationProviderCallback>::Leaky
  31. g_custom_location_provider_callback = LAZY_INSTANCE_INITIALIZER;
  32. base::LazyInstance<std::unique_ptr<network::PendingSharedURLLoaderFactory>>::
  33. Leaky g_pending_url_loader_factory = LAZY_INSTANCE_INITIALIZER;
  34. base::LazyInstance<std::string>::Leaky g_api_key = LAZY_INSTANCE_INITIALIZER;
  35. GeolocationManager* g_geolocation_manager;
  36. } // namespace
  37. // static
  38. GeolocationProvider* GeolocationProvider::GetInstance() {
  39. return GeolocationProviderImpl::GetInstance();
  40. }
  41. // static
  42. void GeolocationProviderImpl::SetGeolocationConfiguration(
  43. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
  44. const std::string& api_key,
  45. const CustomLocationProviderCallback& custom_location_provider_getter,
  46. GeolocationManager* geolocation_manager,
  47. bool use_gms_core_location_provider) {
  48. if (url_loader_factory)
  49. g_pending_url_loader_factory.Get() = url_loader_factory->Clone();
  50. g_api_key.Get() = api_key;
  51. g_custom_location_provider_callback.Get() = custom_location_provider_getter;
  52. g_geolocation_manager = geolocation_manager;
  53. if (use_gms_core_location_provider) {
  54. #if BUILDFLAG(IS_ANDROID)
  55. JNIEnv* env = base::android::AttachCurrentThread();
  56. Java_LocationProviderFactory_useGmsCoreLocationProvider(env);
  57. #else
  58. NOTREACHED() << "GMS core location provider is only available for Android";
  59. #endif
  60. }
  61. }
  62. base::CallbackListSubscription
  63. GeolocationProviderImpl::AddLocationUpdateCallback(
  64. const LocationUpdateCallback& callback,
  65. bool enable_high_accuracy) {
  66. DCHECK(main_task_runner_->BelongsToCurrentThread());
  67. base::CallbackListSubscription subscription;
  68. if (enable_high_accuracy) {
  69. subscription = high_accuracy_callbacks_.Add(callback);
  70. } else {
  71. subscription = low_accuracy_callbacks_.Add(callback);
  72. }
  73. OnClientsChanged();
  74. if (ValidateGeoposition(position_) ||
  75. position_.error_code != mojom::Geoposition::ErrorCode::NONE) {
  76. callback.Run(position_);
  77. }
  78. return subscription;
  79. }
  80. bool GeolocationProviderImpl::HighAccuracyLocationInUse() {
  81. return !high_accuracy_callbacks_.empty();
  82. }
  83. void GeolocationProviderImpl::OverrideLocationForTesting(
  84. const mojom::Geoposition& position) {
  85. DCHECK(main_task_runner_->BelongsToCurrentThread());
  86. ignore_location_updates_ = true;
  87. NotifyClients(position);
  88. }
  89. void GeolocationProviderImpl::OnLocationUpdate(
  90. const LocationProvider* provider,
  91. const mojom::Geoposition& position) {
  92. DCHECK(OnGeolocationThread());
  93. // Will be true only in testing.
  94. if (ignore_location_updates_)
  95. return;
  96. main_task_runner_->PostTask(
  97. FROM_HERE, base::BindOnce(&GeolocationProviderImpl::NotifyClients,
  98. base::Unretained(this), position));
  99. }
  100. // static
  101. GeolocationProviderImpl* GeolocationProviderImpl::GetInstance() {
  102. return base::Singleton<GeolocationProviderImpl>::get();
  103. }
  104. void GeolocationProviderImpl::BindGeolocationControlReceiver(
  105. mojo::PendingReceiver<mojom::GeolocationControl> receiver) {
  106. // The |receiver_| has been bound already here means that more than one
  107. // GeolocationPermissionContext in chrome tried to bind to Device Service.
  108. // We only bind the first receiver. See more info in
  109. // geolocation_control.mojom.
  110. if (!receiver_.is_bound())
  111. receiver_.Bind(std::move(receiver));
  112. }
  113. void GeolocationProviderImpl::UserDidOptIntoLocationServices() {
  114. DCHECK(main_task_runner_->BelongsToCurrentThread());
  115. bool was_permission_granted = user_did_opt_into_location_services_;
  116. user_did_opt_into_location_services_ = true;
  117. if (IsRunning() && !was_permission_granted)
  118. InformProvidersPermissionGranted();
  119. }
  120. GeolocationProviderImpl::GeolocationProviderImpl()
  121. : base::Thread("Geolocation"),
  122. user_did_opt_into_location_services_(false),
  123. ignore_location_updates_(false),
  124. main_task_runner_(base::ThreadTaskRunnerHandle::Get()) {
  125. DCHECK(main_task_runner_->BelongsToCurrentThread());
  126. high_accuracy_callbacks_.set_removal_callback(base::BindRepeating(
  127. &GeolocationProviderImpl::OnClientsChanged, base::Unretained(this)));
  128. low_accuracy_callbacks_.set_removal_callback(base::BindRepeating(
  129. &GeolocationProviderImpl::OnClientsChanged, base::Unretained(this)));
  130. }
  131. GeolocationProviderImpl::~GeolocationProviderImpl() {
  132. Stop();
  133. DCHECK(!arbitrator_);
  134. }
  135. void GeolocationProviderImpl::SetArbitratorForTesting(
  136. std::unique_ptr<LocationProvider> arbitrator) {
  137. arbitrator_ = std::move(arbitrator);
  138. }
  139. bool GeolocationProviderImpl::OnGeolocationThread() const {
  140. return task_runner()->BelongsToCurrentThread();
  141. }
  142. void GeolocationProviderImpl::OnClientsChanged() {
  143. DCHECK(main_task_runner_->BelongsToCurrentThread());
  144. base::OnceClosure task;
  145. if (high_accuracy_callbacks_.empty() && low_accuracy_callbacks_.empty()) {
  146. DCHECK(IsRunning());
  147. if (!ignore_location_updates_) {
  148. // We have no more observers, so we clear the cached geoposition so that
  149. // when the next observer is added we will not provide a stale position.
  150. position_ = mojom::Geoposition();
  151. }
  152. task = base::BindOnce(&GeolocationProviderImpl::StopProviders,
  153. base::Unretained(this));
  154. } else {
  155. if (!IsRunning()) {
  156. base::Thread::Options options;
  157. #if BUILDFLAG(IS_MAC)
  158. options.message_pump_type = base::MessagePumpType::NS_RUNLOOP;
  159. #endif
  160. StartWithOptions(std::move(options));
  161. if (user_did_opt_into_location_services_)
  162. InformProvidersPermissionGranted();
  163. }
  164. // Determine a set of options that satisfies all clients.
  165. bool enable_high_accuracy = !high_accuracy_callbacks_.empty();
  166. // Send the current options to the providers as they may have changed.
  167. task = base::BindOnce(&GeolocationProviderImpl::StartProviders,
  168. base::Unretained(this), enable_high_accuracy);
  169. }
  170. task_runner()->PostTask(FROM_HERE, std::move(task));
  171. }
  172. void GeolocationProviderImpl::StopProviders() {
  173. DCHECK(OnGeolocationThread());
  174. DCHECK(arbitrator_);
  175. arbitrator_->StopProvider();
  176. }
  177. void GeolocationProviderImpl::StartProviders(bool enable_high_accuracy) {
  178. DCHECK(OnGeolocationThread());
  179. DCHECK(arbitrator_);
  180. arbitrator_->StartProvider(enable_high_accuracy);
  181. }
  182. void GeolocationProviderImpl::InformProvidersPermissionGranted() {
  183. DCHECK(IsRunning());
  184. if (!OnGeolocationThread()) {
  185. task_runner()->PostTask(
  186. FROM_HERE,
  187. base::BindOnce(
  188. &GeolocationProviderImpl::InformProvidersPermissionGranted,
  189. base::Unretained(this)));
  190. return;
  191. }
  192. DCHECK(OnGeolocationThread());
  193. DCHECK(arbitrator_);
  194. arbitrator_->OnPermissionGranted();
  195. }
  196. void GeolocationProviderImpl::NotifyClients(
  197. const mojom::Geoposition& position) {
  198. DCHECK(main_task_runner_->BelongsToCurrentThread());
  199. DCHECK(ValidateGeoposition(position) ||
  200. position.error_code != mojom::Geoposition::ErrorCode::NONE);
  201. position_ = position;
  202. high_accuracy_callbacks_.Notify(position_);
  203. low_accuracy_callbacks_.Notify(position_);
  204. }
  205. void GeolocationProviderImpl::Init() {
  206. DCHECK(OnGeolocationThread());
  207. if (arbitrator_)
  208. return;
  209. LocationProvider::LocationProviderUpdateCallback callback =
  210. base::BindRepeating(&GeolocationProviderImpl::OnLocationUpdate,
  211. base::Unretained(this));
  212. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory;
  213. if (g_pending_url_loader_factory.Get()) {
  214. url_loader_factory = network::SharedURLLoaderFactory::Create(
  215. std::move(g_pending_url_loader_factory.Get()));
  216. }
  217. DCHECK(!net::NetworkChangeNotifier::CreateIfNeeded())
  218. << "PositionCacheImpl needs a global NetworkChangeNotifier";
  219. arbitrator_ = std::make_unique<LocationArbitrator>(
  220. g_custom_location_provider_callback.Get(), g_geolocation_manager,
  221. main_task_runner_, std::move(url_loader_factory), g_api_key.Get(),
  222. std::make_unique<PositionCacheImpl>(
  223. base::DefaultTickClock::GetInstance()));
  224. arbitrator_->SetUpdateCallback(callback);
  225. }
  226. void GeolocationProviderImpl::CleanUp() {
  227. DCHECK(OnGeolocationThread());
  228. arbitrator_.reset();
  229. }
  230. } // namespace device