1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "content/test/accessibility_browser_test_utils.h"
6
7#include "base/bind.h"
8#include "base/logging.h"
9#include "base/strings/string_util.h"
10#include "base/strings/utf_string_conversions.h"
11#include "content/browser/renderer_host/render_view_host_impl.h"
12#include "content/port/browser/render_widget_host_view_port.h"
13#include "content/public/browser/web_contents.h"
14#include "content/public/common/url_constants.h"
15#include "content/public/test/test_utils.h"
16#include "content/shell/shell.h"
17
18namespace content {
19
20AccessibilityNotificationWaiter::AccessibilityNotificationWaiter(
21    Shell* shell,
22    AccessibilityMode accessibility_mode,
23    AccessibilityNotification notification)
24    : shell_(shell),
25      notification_to_wait_for_(notification),
26      loop_runner_(new MessageLoopRunner()),
27      weak_factory_(this) {
28  WebContents* web_contents = shell_->web_contents();
29  view_host_ = static_cast<RenderViewHostImpl*>(
30      web_contents->GetRenderViewHost());
31  view_host_->SetAccessibilityCallbackForTesting(
32      base::Bind(&AccessibilityNotificationWaiter::OnAccessibilityNotification,
33                 weak_factory_.GetWeakPtr()));
34  view_host_->SetAccessibilityMode(accessibility_mode);
35}
36
37AccessibilityNotificationWaiter::~AccessibilityNotificationWaiter() {
38}
39
40void AccessibilityNotificationWaiter::WaitForNotification() {
41  loop_runner_->Run();
42}
43
44const AccessibilityNodeDataTreeNode&
45AccessibilityNotificationWaiter::GetAccessibilityNodeDataTree() const {
46  return view_host_->accessibility_tree_for_testing();
47}
48
49void AccessibilityNotificationWaiter::OnAccessibilityNotification(
50    AccessibilityNotification notification) {
51  if (!IsAboutBlank() && notification_to_wait_for_ == notification)
52    loop_runner_->Quit();
53}
54
55bool AccessibilityNotificationWaiter::IsAboutBlank() {
56  // Skip any accessibility notifications related to "about:blank",
57  // to avoid a possible race condition between the test beginning
58  // listening for accessibility events and "about:blank" loading.
59  const AccessibilityNodeDataTreeNode& root = GetAccessibilityNodeDataTree();
60  typedef AccessibilityNodeData::StringAttribute StringAttribute;
61  std::map<StringAttribute, string16>::const_iterator iter;
62  iter = root.string_attributes.find(AccessibilityNodeData::ATTR_DOC_URL);
63  if (iter != root.string_attributes.end()) {
64    string16 doc_url = iter->second;
65    if (doc_url == ASCIIToUTF16(kAboutBlankURL))
66      return true;
67  }
68  return false;
69}
70
71}  // namespace content
72