Fix to keep FocusWidget's setElement() implementation from clobbering
tabindex when it's already set. This comes up in practice when calling, e.g.,
TextBox.wrap() on a static element that already had a perfectly good
tabindex.

Second attempt at this patch -- the first one broke tests because of the
weird DOM structure created by CheckBox/RadioButton. This one uses onAttach()
rather than setElement(), which is cleaner anyway, and I've tested it pretty
thoroughly.

Review at http://gwt-code-reviews.appspot.com/153817


git-svn-id: https://google-web-toolkit.googlecode.com/svn/trunk@7642 8db76d5a-ed1c-0410-87a9-c151d255dfc7
diff --git a/user/src/com/google/gwt/user/client/ui/FocusWidget.java b/user/src/com/google/gwt/user/client/ui/FocusWidget.java
index f7390f8..3ed68e9 100644
--- a/user/src/com/google/gwt/user/client/ui/FocusWidget.java
+++ b/user/src/com/google/gwt/user/client/ui/FocusWidget.java
@@ -264,15 +264,17 @@
   }
 
   @Override
-  protected void setElement(com.google.gwt.user.client.Element elem) {
-    super.setElement(elem);
+  protected void onAttach() {
+    super.onAttach();
 
     // Accessibility: setting tab index to be 0 by default, ensuring element
-    // appears in tab sequence. Note that this call will not interfere with
-    // any calls made to FocusWidget.setTabIndex(int) by user code, because
-    // FocusWidget.setTabIndex(int) cannot be called until setElement(elem)
-    // has been called.
-    setTabIndex(0);
+    // appears in tab sequence. We must ensure that the element doesn't already
+    // have a tabIndex set. This is not a problem for normal widgets, but when
+    // a widget is used to wrap an existing static element, it can already have
+    // a tabIndex.
+    int tabIndex = getTabIndex();
+    if (-1 == tabIndex) {
+      setTabIndex(0);
+    }
   }
-
 }
diff --git a/user/test/com/google/gwt/user/client/ui/TextBoxTest.java b/user/test/com/google/gwt/user/client/ui/TextBoxTest.java
index 42a6963..80b5f17 100644
--- a/user/test/com/google/gwt/user/client/ui/TextBoxTest.java
+++ b/user/test/com/google/gwt/user/client/ui/TextBoxTest.java
@@ -15,6 +15,9 @@
  */
 package com.google.gwt.user.client.ui;
 
+import com.google.gwt.dom.client.DivElement;
+import com.google.gwt.dom.client.Document;
+
 /**
  * Testing TextBox.
  */
@@ -32,7 +35,7 @@
     // As our setText does not honor max length, no way to text it in the wild
     // here.
   }
- 
+
   public void testMinLength() {
     TextBox b = createTextBoxBase();
     b.setVisibleLength(5);
@@ -44,4 +47,14 @@
     // Now check visible length.
     assertEquals(5, b.getVisibleLength());
   }
+
+  public void testNoNukeTabIndex() {
+    Document doc = Document.get();
+    DivElement div = doc.createDivElement();
+    div.setInnerHTML("<input type='text' id='tb' tabindex='1'></input>");
+    doc.getBody().appendChild(div);
+
+    TextBox tb = TextBox.wrap(doc.getElementById("tb"));
+    assertEquals(1, tb.getTabIndex());
+  }
 }