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.
5 #include "chrome/browser/ui/views/chrome_views_delegate.h"
7 #include "base/memory/scoped_ptr.h"
8 #include "base/prefs/pref_service.h"
9 #include "base/prefs/scoped_user_pref_update.h"
10 #include "base/strings/string_util.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/time/time.h"
13 #include "chrome/browser/browser_process.h"
14 #include "chrome/browser/profiles/profile_manager.h"
15 #include "chrome/browser/ui/browser_window_state.h"
16 #include "chrome/browser/ui/views/accessibility/accessibility_event_router_views.h"
17 #include "grit/chrome_unscaled_resources.h"
18 #include "ui/base/resource/resource_bundle.h"
19 #include "ui/base/ui_base_switches.h"
20 #include "ui/gfx/rect.h"
21 #include "ui/gfx/screen.h"
22 #include "ui/views/widget/native_widget.h"
23 #include "ui/views/widget/widget.h"
28 #include "base/task_runner_util.h"
29 #include "base/win/windows_version.h"
30 #include "chrome/browser/app_icon_win.h"
31 #include "content/public/browser/browser_thread.h"
32 #include "ui/base/win/shell.h"
36 #include "content/public/browser/context_factory.h"
37 #include "ui/aura/window.h"
38 #include "ui/aura/window_event_dispatcher.h"
41 #if defined(USE_AURA) && !defined(OS_CHROMEOS)
42 #include "chrome/browser/ui/host_desktop.h"
43 #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
44 #include "ui/views/widget/native_widget_aura.h"
47 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
48 #include "ui/views/linux_ui/linux_ui.h"
52 #include "ash/shell.h"
53 #include "ash/wm/window_state.h"
54 #include "chrome/browser/ui/ash/accessibility/automation_manager_ash.h"
55 #include "chrome/browser/ui/ash/ash_init.h"
56 #include "chrome/browser/ui/ash/ash_util.h"
60 // Helpers --------------------------------------------------------------------
64 Profile* GetProfileForWindow(const views::Widget* window) {
67 return reinterpret_cast<Profile*>(
68 window->GetNativeWindowProperty(Profile::kProfileKey));
71 // If the given window has a profile associated with it, use that profile's
72 // preference service. Otherwise, store and retrieve the data from Local State.
73 // This function may return NULL if the necessary pref service has not yet
75 // TODO(mirandac): This function will also separate windows by profile in a
76 // multi-profile environment.
77 PrefService* GetPrefsForWindow(const views::Widget* window) {
78 Profile* profile = GetProfileForWindow(window);
80 // Use local state for windows that have no explicit profile.
81 return g_browser_process->local_state();
83 return profile->GetPrefs();
87 bool MonitorHasTopmostAutohideTaskbarForEdge(UINT edge, HMONITOR monitor) {
88 APPBARDATA taskbar_data = { sizeof(APPBARDATA), NULL, 0, edge };
89 // MSDN documents an ABM_GETAUTOHIDEBAREX, which supposedly takes a monitor
90 // rect and returns autohide bars on that monitor. This sounds like a good
91 // idea for multi-monitor systems. Unfortunately, it appears to not work at
92 // least some of the time (erroneously returning NULL) and there's almost no
93 // online documentation or other sample code using it that suggests ways to
94 // address this problem. So we just use ABM_GETAUTOHIDEBAR and hope the user
95 // only cares about autohide bars on the monitor with the primary taskbar.
97 // NOTE: This call spins a nested message loop.
98 HWND taskbar = reinterpret_cast<HWND>(SHAppBarMessage(ABM_GETAUTOHIDEBAR,
100 return ::IsWindow(taskbar) &&
101 (MonitorFromWindow(taskbar, MONITOR_DEFAULTTONULL) == monitor) &&
102 (GetWindowLong(taskbar, GWL_EXSTYLE) & WS_EX_TOPMOST);
105 int GetAppbarAutohideEdgesOnWorkerThread(HMONITOR monitor) {
109 if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_LEFT, monitor))
110 edges |= views::ViewsDelegate::EDGE_LEFT;
111 if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_TOP, monitor))
112 edges |= views::ViewsDelegate::EDGE_TOP;
113 if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_RIGHT, monitor))
114 edges |= views::ViewsDelegate::EDGE_RIGHT;
115 if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_BOTTOM, monitor))
116 edges |= views::ViewsDelegate::EDGE_BOTTOM;
124 // ChromeViewsDelegate --------------------------------------------------------
127 ChromeViewsDelegate::ChromeViewsDelegate()
128 : in_autohide_edges_callback_(false),
129 weak_factory_(this) {
131 ChromeViewsDelegate::ChromeViewsDelegate() {
135 ChromeViewsDelegate::~ChromeViewsDelegate() {
138 void ChromeViewsDelegate::SaveWindowPlacement(const views::Widget* window,
139 const std::string& window_name,
140 const gfx::Rect& bounds,
141 ui::WindowShowState show_state) {
142 PrefService* prefs = GetPrefsForWindow(window);
146 scoped_ptr<DictionaryPrefUpdate> pref_update =
147 chrome::GetWindowPlacementDictionaryReadWrite(window_name, prefs);
148 base::DictionaryValue* window_preferences = pref_update->Get();
149 window_preferences->SetInteger("left", bounds.x());
150 window_preferences->SetInteger("top", bounds.y());
151 window_preferences->SetInteger("right", bounds.right());
152 window_preferences->SetInteger("bottom", bounds.bottom());
153 window_preferences->SetBoolean("maximized",
154 show_state == ui::SHOW_STATE_MAXIMIZED);
155 gfx::Rect work_area(gfx::Screen::GetScreenFor(window->GetNativeView())->
156 GetDisplayNearestWindow(window->GetNativeView()).work_area());
157 window_preferences->SetInteger("work_area_left", work_area.x());
158 window_preferences->SetInteger("work_area_top", work_area.y());
159 window_preferences->SetInteger("work_area_right", work_area.right());
160 window_preferences->SetInteger("work_area_bottom", work_area.bottom());
163 bool ChromeViewsDelegate::GetSavedWindowPlacement(
164 const views::Widget* widget,
165 const std::string& window_name,
167 ui::WindowShowState* show_state) const {
168 PrefService* prefs = g_browser_process->local_state();
172 DCHECK(prefs->FindPreference(window_name.c_str()));
173 const base::DictionaryValue* dictionary =
174 prefs->GetDictionary(window_name.c_str());
179 if (!dictionary || !dictionary->GetInteger("left", &left) ||
180 !dictionary->GetInteger("top", &top) ||
181 !dictionary->GetInteger("right", &right) ||
182 !dictionary->GetInteger("bottom", &bottom))
185 bounds->SetRect(left, top, right - left, bottom - top);
187 bool maximized = false;
189 dictionary->GetBoolean("maximized", &maximized);
190 *show_state = maximized ? ui::SHOW_STATE_MAXIMIZED : ui::SHOW_STATE_NORMAL;
193 // On Ash environment, a window won't span across displays. Adjust
194 // the bounds to fit the work area.
195 gfx::NativeView window = widget->GetNativeView();
196 if (chrome::GetHostDesktopTypeForNativeView(window) ==
197 chrome::HOST_DESKTOP_TYPE_ASH) {
198 gfx::Display display = gfx::Screen::GetScreenFor(window)->
199 GetDisplayMatching(*bounds);
200 bounds->AdjustToFit(display.work_area());
201 ash::wm::GetWindowState(window)->set_minimum_visibility(true);
207 void ChromeViewsDelegate::NotifyAccessibilityEvent(
208 views::View* view, ui::AXEvent event_type) {
209 AccessibilityEventRouterViews::GetInstance()->HandleAccessibilityEvent(
213 AutomationManagerAsh::GetInstance()->HandleEvent(
214 GetProfileForWindow(view->GetWidget()), view, event_type);
218 void ChromeViewsDelegate::NotifyMenuItemFocused(
219 const base::string16& menu_name,
220 const base::string16& menu_item_name,
224 AccessibilityEventRouterViews::GetInstance()->HandleMenuItemFocused(
225 menu_name, menu_item_name, item_index, item_count, has_submenu);
229 HICON ChromeViewsDelegate::GetDefaultWindowIcon() const {
233 bool ChromeViewsDelegate::IsWindowInMetro(gfx::NativeWindow window) const {
234 return chrome::IsNativeViewInAsh(window);
237 #elif defined(OS_LINUX) && !defined(OS_CHROMEOS)
238 gfx::ImageSkia* ChromeViewsDelegate::GetDefaultWindowIcon() const {
239 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
240 return rb.GetImageSkiaNamed(IDR_PRODUCT_LOGO_64);
245 views::NonClientFrameView* ChromeViewsDelegate::CreateDefaultNonClientFrameView(
246 views::Widget* widget) {
247 return chrome::IsNativeViewInAsh(widget->GetNativeView()) ?
248 ash::Shell::GetInstance()->CreateDefaultNonClientFrameView(widget) : NULL;
252 void ChromeViewsDelegate::AddRef() {
253 g_browser_process->AddRefModule();
256 void ChromeViewsDelegate::ReleaseRef() {
257 g_browser_process->ReleaseModule();
260 void ChromeViewsDelegate::OnBeforeWidgetInit(
261 views::Widget::InitParams* params,
262 views::internal::NativeWidgetDelegate* delegate) {
263 // We need to determine opacity if it's not already specified.
264 if (params->opacity == views::Widget::InitParams::INFER_OPACITY)
265 params->opacity = GetOpacityForInitParams(*params);
267 // If we already have a native_widget, we don't have to try to come
269 if (params->native_widget)
272 #if defined(USE_AURA) && !defined(OS_CHROMEOS)
273 bool use_non_toplevel_window =
275 params->type != views::Widget::InitParams::TYPE_MENU &&
276 params->type != views::Widget::InitParams::TYPE_TOOLTIP;
279 // On desktop Linux Chrome must run in an environment that supports a variety
280 // of window managers, some of which do not play nicely with parts of our UI
281 // that have specific expectations about window sizing and placement. For this
282 // reason windows opened as top level (!params.child) are always constrained
283 // by the browser frame, so we can position them correctly. This has some
284 // negative side effects, like dialogs being clipped by the browser frame, but
285 // the side effects are not as bad as the poor window manager interactions. On
286 // Windows however these WM interactions are not an issue, so we open windows
287 // requested as top_level as actual top level windows on the desktop.
288 use_non_toplevel_window = use_non_toplevel_window &&
290 chrome::GetHostDesktopTypeForNativeView(params->parent) !=
291 chrome::HOST_DESKTOP_TYPE_NATIVE);
293 if (!ui::win::IsAeroGlassEnabled()) {
294 // If we don't have composition (either because Glass is not enabled or
295 // because it was disabled at the command line), anything that requires
296 // transparency will be broken with a toplevel window, so force the use of
297 // a non toplevel window.
298 if (params->opacity == views::Widget::InitParams::TRANSLUCENT_WINDOW &&
299 params->type != views::Widget::InitParams::TYPE_MENU)
300 use_non_toplevel_window = true;
302 // If we're on Vista+ with composition enabled, then we can use toplevel
303 // windows for most things (they get blended via WS_EX_COMPOSITED, which
304 // allows for animation effects, but also exceeding the bounds of the parent
306 if (chrome::GetActiveDesktop() != chrome::HOST_DESKTOP_TYPE_ASH &&
308 params->type != views::Widget::InitParams::TYPE_CONTROL &&
309 params->type != views::Widget::InitParams::TYPE_WINDOW) {
310 // When we set this to false, we get a DesktopNativeWidgetAura from the
311 // default case (not handled in this function).
312 use_non_toplevel_window = false;
318 #if defined(OS_CHROMEOS)
319 // When we are doing straight chromeos builds, we still need to handle the
320 // toplevel window case.
321 // There may be a few remaining widgets in Chrome OS that are not top level,
322 // but have neither a context nor a parent. Provide a fallback context so
323 // users don't crash. Developers will hit the DCHECK and should provide a
326 params->context = params->context->GetRootWindow();
327 DCHECK(params->parent || params->context || !params->child)
328 << "Please provide a parent or context for this widget.";
329 if (!params->parent && !params->context)
330 params->context = ash::Shell::GetPrimaryRootWindow();
331 #elif defined(USE_AURA)
332 // While the majority of the time, context wasn't plumbed through due to the
333 // existence of a global WindowTreeClient, if this window is toplevel, it's
334 // possible that there is no contextual state that we can use.
335 if (params->parent == NULL && params->context == NULL && !params->child) {
336 // We need to make a decision about where to place this window based on the
338 switch (chrome::GetActiveDesktop()) {
339 case chrome::HOST_DESKTOP_TYPE_NATIVE:
340 // If we're native, we should give this window its own toplevel desktop
342 params->native_widget = new views::DesktopNativeWidgetAura(delegate);
345 case chrome::HOST_DESKTOP_TYPE_ASH:
346 // If we're in ash, give this window the context of the main monitor.
347 params->context = ash::Shell::GetPrimaryRootWindow();
353 } else if (use_non_toplevel_window) {
354 views::NativeWidgetAura* native_widget =
355 new views::NativeWidgetAura(delegate);
356 if (params->parent) {
357 Profile* parent_profile = reinterpret_cast<Profile*>(
358 params->parent->GetNativeWindowProperty(Profile::kProfileKey));
359 native_widget->SetNativeWindowProperty(Profile::kProfileKey,
362 params->native_widget = native_widget;
364 // TODO(erg): Once we've threaded context to everywhere that needs it, we
365 // should remove this check here.
366 gfx::NativeView to_check =
367 params->context ? params->context : params->parent;
368 if (chrome::GetHostDesktopTypeForNativeView(to_check) ==
369 chrome::HOST_DESKTOP_TYPE_NATIVE) {
370 params->native_widget = new views::DesktopNativeWidgetAura(delegate);
376 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
377 bool ChromeViewsDelegate::WindowManagerProvidesTitleBar(bool maximized) {
378 // On Ubuntu Unity, the system always provides a title bar for maximized
380 views::LinuxUI* ui = views::LinuxUI::instance();
381 return maximized && ui && ui->UnityIsRunning();
385 #if defined(USE_AURA)
386 ui::ContextFactory* ChromeViewsDelegate::GetContextFactory() {
387 return content::GetContextFactory();
392 int ChromeViewsDelegate::GetAppbarAutohideEdges(HMONITOR monitor,
393 const base::Closure& callback) {
394 // Initialize the map with EDGE_BOTTOM. This is important, as if we return an
395 // initial value of 0 (no auto-hide edges) then we'll go fullscreen and
396 // windows will automatically remove WS_EX_TOPMOST from the appbar resulting
397 // in us thinking there is no auto-hide edges. By returning at least one edge
398 // we don't initially go fullscreen until we figure out the real auto-hide
400 if (!appbar_autohide_edge_map_.count(monitor))
401 appbar_autohide_edge_map_[monitor] = EDGE_BOTTOM;
402 if (monitor && !in_autohide_edges_callback_) {
403 base::PostTaskAndReplyWithResult(
404 content::BrowserThread::GetBlockingPool(),
406 base::Bind(&GetAppbarAutohideEdgesOnWorkerThread,
408 base::Bind(&ChromeViewsDelegate::OnGotAppbarAutohideEdges,
409 weak_factory_.GetWeakPtr(),
412 appbar_autohide_edge_map_[monitor]));
414 return appbar_autohide_edge_map_[monitor];
417 void ChromeViewsDelegate::OnGotAppbarAutohideEdges(
418 const base::Closure& callback,
422 appbar_autohide_edge_map_[monitor] = edges;
423 if (returned_edges == edges)
426 base::AutoReset<bool> in_callback_setter(&in_autohide_edges_callback_, true);
431 #if !defined(USE_AURA) && !defined(USE_CHROMEOS)
432 views::Widget::InitParams::WindowOpacity
433 ChromeViewsDelegate::GetOpacityForInitParams(
434 const views::Widget::InitParams& params) {
435 return views::Widget::InitParams::OPAQUE_WINDOW;