Bluetooth: Use WeakPtr for prompt controllers

The desktop chooser and scanning prompt hold controller raw pointers.
The controllers might be destroyed immediately, leaving bad pointers.
Use WeakPtrs instead of raw pointers and refactor init patterns.

Bug: 1149692
Change-Id: Ic1efee18ec2e98921206bea14c3c1500ea085877
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2551936
Reviewed-by: Reilly Grant <[email protected]>
Commit-Queue: Michael Wasserman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#829523}
diff --git a/chrome/browser/ui/bluetooth/bluetooth_scanning_prompt_desktop.cc b/chrome/browser/ui/bluetooth/bluetooth_scanning_prompt_desktop.cc
index 1997e57..6950520e 100644
--- a/chrome/browser/ui/bluetooth/bluetooth_scanning_prompt_desktop.cc
+++ b/chrome/browser/ui/bluetooth/bluetooth_scanning_prompt_desktop.cc
@@ -6,21 +6,24 @@
 
 #include "base/check.h"
 #include "chrome/browser/ui/bluetooth/bluetooth_scanning_prompt_controller.h"
+#include "chrome/browser/ui/browser_dialogs.h"
 
 BluetoothScanningPromptDesktop::BluetoothScanningPromptDesktop(
-    BluetoothScanningPromptController* bluetooth_scanning_prompt_controller,
-    base::OnceClosure&& close_closure)
-    : bluetooth_scanning_prompt_controller_(
-          bluetooth_scanning_prompt_controller),
-      close_closure_(std::move(close_closure)) {
-  DCHECK(bluetooth_scanning_prompt_controller_);
+    content::RenderFrameHost* frame,
+    const content::BluetoothScanningPrompt::EventHandler& event_handler) {
+  auto controller =
+      std::make_unique<BluetoothScanningPromptController>(frame, event_handler);
+  bluetooth_scanning_prompt_controller_ = controller->GetWeakPtr();
+  close_closure_ =
+      chrome::ShowDeviceChooserDialog(frame, std::move(controller));
 }
 
 BluetoothScanningPromptDesktop::~BluetoothScanningPromptDesktop() {
   // This satisfies the WebContentsDelegate::ShowBluetoothScanningPrompt()
   // requirement that the EventHandler can be destroyed any time after the
   // BluetoothScanningPrompt instance.
-  bluetooth_scanning_prompt_controller_->ResetEventHandler();
+  if (bluetooth_scanning_prompt_controller_)
+    bluetooth_scanning_prompt_controller_->ResetEventHandler();
   if (close_closure_)
     std::move(close_closure_).Run();
 }
@@ -29,6 +32,8 @@
     const std::string& device_id,
     bool should_update_name,
     const base::string16& device_name) {
-  bluetooth_scanning_prompt_controller_->AddOrUpdateDevice(
-      device_id, should_update_name, device_name);
+  if (bluetooth_scanning_prompt_controller_) {
+    bluetooth_scanning_prompt_controller_->AddOrUpdateDevice(
+        device_id, should_update_name, device_name);
+  }
 }