WindowActivityWatcher: Verify browser window exists

It's apparently possible for
BrowserList::SetLastActive(Browser* browser) to be called before
|browser| is added to the BrowserList. This might happen, e.g., if a
BrowserView's widget receives an activation event before
CreateBrowserWindow() returns.

This will cause WindowActivityWatcher's CreateMetrics() helper function
to dereference the null pointer at browser->window().

(cherry picked from commit 3c2815cfbf41f0c76d74c64800d6d60c328d3d7b)

Bug: 811243,811191
Change-Id: Ia377a810b73494f88d1cd2b4532367950f35b1f7
Reviewed-on: https://chromium-review.googlesource.com/924353
Commit-Queue: Michael Giuffrida <michaelpg@chromium.org>
Reviewed-by: Scott Violet <sky@chromium.org>
Cr-Original-Commit-Position: refs/heads/master@{#537825}
Reviewed-on: https://chromium-review.googlesource.com/932008
Cr-Commit-Position: refs/branch-heads/3325@{#562}
Cr-Branched-From: bc084a8b5afa3744a74927344e304c02ae54189f-refs/heads/master@{#530369}
diff --git a/chrome/browser/ui/tabs/window_activity_watcher.cc b/chrome/browser/ui/tabs/window_activity_watcher.cc
index bb093ee..c015d93 100644
--- a/chrome/browser/ui/tabs/window_activity_watcher.cc
+++ b/chrome/browser/ui/tabs/window_activity_watcher.cc
@@ -34,6 +34,8 @@
 
 // Returns a populated WindowMetrics for the browser.
 WindowMetrics CreateMetrics(const Browser* browser) {
+  DCHECK(browser->window());
+
   WindowMetrics window_metrics;
   window_metrics.window_id = browser->session_id().id();
 
@@ -112,11 +114,19 @@
 }
 
 void WindowActivityWatcher::OnBrowserSetLastActive(Browser* browser) {
-  if (!browser->profile()->IsOffTheRecord())
+  // The browser may not have a window yet if activation calls happen during
+  // initialization.
+  // TODO(michaelpg): The browser window check should be unnecessary
+  // (https://crbug.com/811191, https://crbug.com/811243).
+  if (!browser->profile()->IsOffTheRecord() && browser->window())
     CreateOrUpdateWindowMetrics(browser);
 }
 
 void WindowActivityWatcher::OnBrowserNoLongerActive(Browser* browser) {
-  if (!browser->profile()->IsOffTheRecord())
+  // The browser may not have a window yet if activation calls happen during
+  // initialization.
+  // TODO(michaelpg): The browser window check should be unnecessary
+  // (https://crbug.com/811191, https://crbug.com/811243).
+  if (!browser->profile()->IsOffTheRecord() && browser->window())
     CreateOrUpdateWindowMetrics(browser);
 }