1// Copyright (c) 2012 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 "chrome/test/base/interactive_test_utils.h"
6
7#include <Psapi.h>
8
9#include "base/files/file_path.h"
10#include "base/logging.h"
11#include "base/path_service.h"
12#include "base/strings/stringprintf.h"
13#include "base/time/time.h"
14#include "chrome/browser/ui/host_desktop.h"
15#include "chrome/test/base/interactive_test_utils_aura.h"
16#include "ui/aura/window_tree_host.h"
17#include "ui/base/test/ui_controls.h"
18#include "ui/base/win/foreground_helper.h"
19#include "ui/views/focus/focus_manager.h"
20
21namespace ui_test_utils {
22
23void HideNativeWindow(gfx::NativeWindow window) {
24  if (chrome::GetHostDesktopTypeForNativeWindow(window) ==
25      chrome::HOST_DESKTOP_TYPE_ASH) {
26    HideNativeWindowAura(window);
27    return;
28  }
29  HWND hwnd = window->GetHost()->GetAcceleratedWidget();
30  ::ShowWindow(hwnd, SW_HIDE);
31}
32
33bool ShowAndFocusNativeWindow(gfx::NativeWindow window) {
34  if (chrome::GetHostDesktopTypeForNativeWindow(window) ==
35      chrome::HOST_DESKTOP_TYPE_ASH)
36    ShowAndFocusNativeWindowAura(window);
37  window->Show();
38  // Always make sure the window hosting ash is visible and focused.
39  HWND hwnd = window->GetHost()->GetAcceleratedWidget();
40
41  ::ShowWindow(hwnd, SW_SHOW);
42
43  if (GetForegroundWindow() != hwnd) {
44    VLOG(1) << "Forcefully refocusing front window";
45    ui::ForegroundHelper::SetForeground(hwnd);
46  }
47
48  // ShowWindow does not necessarily activate the window. In particular if a
49  // window from another app is the foreground window then the request to
50  // activate the window fails. See SetForegroundWindow for details.
51  HWND foreground_window = GetForegroundWindow();
52  if (foreground_window == hwnd)
53    return true;
54
55  wchar_t window_title[256];
56  std::wstring path_str;
57  if (foreground_window) {
58    DWORD process_id = 0;
59    GetWindowThreadProcessId(foreground_window, &process_id);
60    HANDLE process_handle = OpenProcess(
61        PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_id);
62    if (process_handle) {
63      wchar_t path[MAX_PATH];
64      if (GetModuleFileNameEx(process_handle, NULL, path, MAX_PATH))
65        path_str = path;
66      CloseHandle(process_handle);
67    }
68  }
69  GetWindowText(foreground_window, window_title, arraysize(window_title));
70  LOG(ERROR) << "ShowAndFocusNativeWindow failed. foreground window: "
71             << foreground_window << ", title: " << window_title << ", path: "
72             << path_str;
73  return false;
74}
75
76}  // namespace ui_test_utils
77