Fix issues with state save/restore

 Bug: 5144214
 Tracked down the issue with messed up state to a bug where
 tab ids were not unique, and would actually get messed up in restore.
 Switched it to the tab's responsibility to assign an id to itself
 in the ctor to make sure all possible paths where a tab is created
 are fixed as well as the tab being the best informed about whether
 or not it has an ID to restore from. Added some checks to watch for
 a similar problem in the future as well.

Change-Id: Icd8333232a0baca7a3639323538886ea595de05a
diff --git a/src/com/android/browser/Tab.java b/src/com/android/browser/Tab.java
index c519c91..672a1a6 100644
--- a/src/com/android/browser/Tab.java
+++ b/src/com/android/browser/Tab.java
@@ -1412,6 +1412,9 @@
                 R.dimen.tab_thumbnail_height);
         updateShouldCaptureThumbnails();
         restoreState(state);
+        if (getId() == -1) {
+            mId = TabControl.getNextId();
+        }
         setWebView(w);
         mHandler = new Handler() {
             @Override
@@ -1450,10 +1453,6 @@
         updateShouldCaptureThumbnails();
     }
 
-    public void setId(long id) {
-        mId = id;
-    }
-
     public long getId() {
         return mId;
     }
@@ -1592,6 +1591,9 @@
      * Set the parent tab of this tab.
      */
     void setParent(Tab parent) {
+        if (parent == this) {
+            throw new IllegalStateException("Cannot set parent to self!");
+        }
         mParent = parent;
         // This tab may have been freed due to low memory. If that is the case,
         // the parent tab id is already saved. If we are changing that id
@@ -1610,6 +1612,10 @@
                 != mSettings.hasDesktopUseragent(getWebView())) {
             mSettings.toggleDesktopUseragent(getWebView());
         }
+
+        if (parent != null && parent.getId() == getId()) {
+            throw new IllegalStateException("Parent has same ID as child!");
+        }
     }
 
     /**
@@ -1689,6 +1695,7 @@
         if (!mInForeground) {
             return;
         }
+        capture();
         mInForeground = false;
         pause();
         mMainView.setOnCreateContextMenuListener(null);
@@ -2175,4 +2182,27 @@
         }
     };
 
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder(100);
+        builder.append(mId);
+        builder.append(") has parent: ");
+        if (getParent() != null) {
+            builder.append("true[");
+            builder.append(getParent().getId());
+            builder.append("]");
+        } else {
+            builder.append("false");
+        }
+        builder.append(", incog: ");
+        builder.append(isPrivateBrowsingEnabled());
+        if (!isPrivateBrowsingEnabled()) {
+            builder.append(", title: ");
+            builder.append(getTitle());
+            builder.append(", url: ");
+            builder.append(getUrl());
+        }
+        return builder.toString();
+    }
+
 }