Fix RemoveSelfIfParented() for RetainedTreeNode<>.

The addition of the RemoveSelfIfParented() method to the base
TreeNode<> class means that RetainedTreeNode<> has a bit of work
to do to get the types to line up properly.

Change-Id: I24e0979bebcefd5a3823577998f7c63adf33beb9
Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/54430
Reviewed-by: Lei Zhang <thestig@chromium.org>
Commit-Queue: Tom Sepez <tsepez@chromium.org>
diff --git a/core/fxcrt/retained_tree_node.h b/core/fxcrt/retained_tree_node.h
index e091fb5..a859ae5 100644
--- a/core/fxcrt/retained_tree_node.h
+++ b/core/fxcrt/retained_tree_node.h
@@ -40,6 +40,13 @@
     TreeNode<T>::RemoveChild(child.Get());
   }
 
+  void RemoveSelfIfParented() {
+    if (T* parent = TreeNode<T>::GetParent()) {
+      parent->TreeNode<T>::RemoveChild(
+          pdfium::WrapRetain(static_cast<T*>(this)).Get());
+    }
+  }
+
  protected:
   RetainedTreeNode() = default;
   ~RetainedTreeNode() override {
diff --git a/core/fxcrt/retained_tree_node_unittest.cpp b/core/fxcrt/retained_tree_node_unittest.cpp
index 3fabb80..02c23e5 100644
--- a/core/fxcrt/retained_tree_node_unittest.cpp
+++ b/core/fxcrt/retained_tree_node_unittest.cpp
@@ -132,6 +132,19 @@
   EXPECT_FALSE(watcher.Get());
 }
 
+TEST(RetainedTreeNode, RemoveSelf) {
+  ObservableRetainedTreeNodeForTest::ObservedPtr watcher;
+  auto parent = pdfium::MakeRetain<ObservableRetainedTreeNodeForTest>();
+  {
+    auto child = pdfium::MakeRetain<ObservableRetainedTreeNodeForTest>();
+    watcher = ObservableRetainedTreeNodeForTest::ObservedPtr(child.Get());
+    parent->AppendFirstChild(child);
+  }
+  EXPECT_TRUE(watcher.Get());
+  watcher->RemoveSelfIfParented();
+  EXPECT_FALSE(watcher.Get());
+}
+
 TEST(RetainedTreeNode, InsertBeforeAfter) {
   ObservableRetainedTreeNodeForTest::ObservedPtr watcher;
   RetainPtr<ObservableRetainedTreeNodeForTest> parent =