1// Copyright 2014 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/browser/apps/app_window_registry_util.h"
6
7#include <vector>
8
9#include "chrome/browser/browser_process.h"
10#include "chrome/browser/profiles/profile.h"
11#include "chrome/browser/profiles/profile_manager.h"
12#include "extensions/browser/app_window/app_window.h"
13#include "extensions/browser/app_window/app_window_registry.h"
14#include "extensions/browser/app_window/native_app_window.h"
15
16using extensions::AppWindow;
17using extensions::AppWindowRegistry;
18
19typedef AppWindowRegistry::AppWindowList AppWindowList;
20typedef AppWindowRegistry::Factory Factory;
21
22// static
23AppWindow* AppWindowRegistryUtil::GetAppWindowForNativeWindowAnyProfile(
24    gfx::NativeWindow window) {
25  std::vector<Profile*> profiles =
26      g_browser_process->profile_manager()->GetLoadedProfiles();
27  for (std::vector<Profile*>::const_iterator i = profiles.begin();
28       i != profiles.end();
29       ++i) {
30    AppWindowRegistry* registry =
31        Factory::GetForBrowserContext(*i, false /* create */);
32    if (!registry)
33      continue;
34
35    AppWindow* app_window = registry->GetAppWindowForNativeWindow(window);
36    if (app_window)
37      return app_window;
38  }
39
40  return NULL;
41}
42
43// static
44bool AppWindowRegistryUtil::IsAppWindowRegisteredInAnyProfile(
45    int window_type_mask) {
46  std::vector<Profile*> profiles =
47      g_browser_process->profile_manager()->GetLoadedProfiles();
48  for (std::vector<Profile*>::const_iterator i = profiles.begin();
49       i != profiles.end();
50       ++i) {
51    AppWindowRegistry* registry =
52        Factory::GetForBrowserContext(*i, false /* create */);
53    if (!registry)
54      continue;
55
56    const AppWindowList& app_windows = registry->app_windows();
57    if (app_windows.empty())
58      continue;
59
60    if (window_type_mask == 0)
61      return true;
62
63    for (AppWindowList::const_iterator j = app_windows.begin();
64         j != app_windows.end(); ++j) {
65      if ((*j)->window_type() & window_type_mask)
66        return true;
67    }
68  }
69
70  return false;
71}
72
73// static
74void AppWindowRegistryUtil::CloseAllAppWindows() {
75  std::vector<Profile*> profiles =
76      g_browser_process->profile_manager()->GetLoadedProfiles();
77  for (std::vector<Profile*>::const_iterator i = profiles.begin();
78       i != profiles.end();
79       ++i) {
80    AppWindowRegistry* registry =
81        Factory::GetForBrowserContext(*i, false /* create */);
82    if (!registry)
83      continue;
84
85    while (!registry->app_windows().empty())
86      registry->app_windows().front()->GetBaseWindow()->Close();
87  }
88}
89