MacViews: Use Mac's "Constrained Window Button" style for Button::STYLE_BUTTON LabelB...
[chromium-blink-merge.git] / chrome / browser / ui / views / chrome_views_delegate.cc
blob0b46a252e1d413b76792ed9b51aeeae1028b9ab2
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/common/chrome_version_info.h"
17 #include "content/public/browser/browser_thread.h"
18 #include "content/public/browser/context_factory.h"
19 #include "grit/chrome_unscaled_resources.h"
20 #include "ui/base/resource/resource_bundle.h"
21 #include "ui/base/ui_base_switches.h"
22 #include "ui/gfx/geometry/rect.h"
23 #include "ui/gfx/screen.h"
24 #include "ui/views/widget/native_widget.h"
25 #include "ui/views/widget/widget.h"
27 #if defined(OS_WIN)
28 #include <dwmapi.h>
29 #include <shellapi.h>
30 #include "base/profiler/scoped_tracker.h"
31 #include "base/task_runner_util.h"
32 #include "base/win/windows_version.h"
33 #include "chrome/browser/app_icon_win.h"
34 #include "content/public/browser/browser_thread.h"
35 #include "ui/base/win/shell.h"
36 #endif
38 #if defined(USE_AURA)
39 #include "chrome/browser/ui/aura/accessibility/automation_manager_aura.h"
40 #include "ui/aura/window.h"
41 #include "ui/aura/window_event_dispatcher.h"
42 #endif
44 #if defined(USE_AURA) && !defined(OS_CHROMEOS)
45 #include "chrome/browser/ui/host_desktop.h"
46 #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
47 #include "ui/views/widget/native_widget_aura.h"
48 #endif
50 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
51 #include "ui/views/linux_ui/linux_ui.h"
52 #endif
54 #if defined(USE_ASH)
55 #include "ash/shell.h"
56 #include "ash/wm/window_state.h"
57 #include "chrome/browser/ui/ash/ash_init.h"
58 #include "chrome/browser/ui/ash/ash_util.h"
59 #endif
62 // Helpers --------------------------------------------------------------------
64 namespace {
66 Profile* GetProfileForWindow(const views::Widget* window) {
67 if (!window)
68 return NULL;
69 return reinterpret_cast<Profile*>(
70 window->GetNativeWindowProperty(Profile::kProfileKey));
73 // If the given window has a profile associated with it, use that profile's
74 // preference service. Otherwise, store and retrieve the data from Local State.
75 // This function may return NULL if the necessary pref service has not yet
76 // been initialized.
77 // TODO(mirandac): This function will also separate windows by profile in a
78 // multi-profile environment.
79 PrefService* GetPrefsForWindow(const views::Widget* window) {
80 Profile* profile = GetProfileForWindow(window);
81 if (!profile) {
82 // Use local state for windows that have no explicit profile.
83 return g_browser_process->local_state();
85 return profile->GetPrefs();
88 #if defined(OS_WIN)
89 bool MonitorHasTopmostAutohideTaskbarForEdge(UINT edge, HMONITOR monitor) {
90 APPBARDATA taskbar_data = { sizeof(APPBARDATA), NULL, 0, edge };
92 // TODO(robliao): Remove ScopedTracker below once crbug.com/462368 is fixed.
93 tracked_objects::ScopedTracker tracking_profile(
94 FROM_HERE_WITH_EXPLICIT_FUNCTION(
95 "462368 MonitorHasTopmostAutohideTaskbarForEdge"));
97 // MSDN documents an ABM_GETAUTOHIDEBAREX, which supposedly takes a monitor
98 // rect and returns autohide bars on that monitor. This sounds like a good
99 // idea for multi-monitor systems. Unfortunately, it appears to not work at
100 // least some of the time (erroneously returning NULL) and there's almost no
101 // online documentation or other sample code using it that suggests ways to
102 // address this problem. So we just use ABM_GETAUTOHIDEBAR and hope the user
103 // only cares about autohide bars on the monitor with the primary taskbar.
105 // NOTE: This call spins a nested message loop.
106 HWND taskbar = reinterpret_cast<HWND>(SHAppBarMessage(ABM_GETAUTOHIDEBAR,
107 &taskbar_data));
108 return ::IsWindow(taskbar) &&
109 (MonitorFromWindow(taskbar, MONITOR_DEFAULTTONULL) == monitor) &&
110 (GetWindowLong(taskbar, GWL_EXSTYLE) & WS_EX_TOPMOST);
113 int GetAppbarAutohideEdgesOnWorkerThread(HMONITOR monitor) {
114 DCHECK(monitor);
116 int edges = 0;
117 if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_LEFT, monitor))
118 edges |= views::ViewsDelegate::EDGE_LEFT;
119 if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_TOP, monitor))
120 edges |= views::ViewsDelegate::EDGE_TOP;
121 if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_RIGHT, monitor))
122 edges |= views::ViewsDelegate::EDGE_RIGHT;
123 if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_BOTTOM, monitor))
124 edges |= views::ViewsDelegate::EDGE_BOTTOM;
125 return edges;
127 #endif
129 } // namespace
132 // ChromeViewsDelegate --------------------------------------------------------
134 #if defined(OS_WIN)
135 ChromeViewsDelegate::ChromeViewsDelegate()
136 : in_autohide_edges_callback_(false),
137 weak_factory_(this) {
138 #else
139 ChromeViewsDelegate::ChromeViewsDelegate() {
140 #endif
143 ChromeViewsDelegate::~ChromeViewsDelegate() {
146 void ChromeViewsDelegate::SaveWindowPlacement(const views::Widget* window,
147 const std::string& window_name,
148 const gfx::Rect& bounds,
149 ui::WindowShowState show_state) {
150 PrefService* prefs = GetPrefsForWindow(window);
151 if (!prefs)
152 return;
154 scoped_ptr<DictionaryPrefUpdate> pref_update =
155 chrome::GetWindowPlacementDictionaryReadWrite(window_name, prefs);
156 base::DictionaryValue* window_preferences = pref_update->Get();
157 window_preferences->SetInteger("left", bounds.x());
158 window_preferences->SetInteger("top", bounds.y());
159 window_preferences->SetInteger("right", bounds.right());
160 window_preferences->SetInteger("bottom", bounds.bottom());
161 window_preferences->SetBoolean("maximized",
162 show_state == ui::SHOW_STATE_MAXIMIZED);
163 window_preferences->SetBoolean("docked", show_state == ui::SHOW_STATE_DOCKED);
164 gfx::Rect work_area(gfx::Screen::GetScreenFor(window->GetNativeView())->
165 GetDisplayNearestWindow(window->GetNativeView()).work_area());
166 window_preferences->SetInteger("work_area_left", work_area.x());
167 window_preferences->SetInteger("work_area_top", work_area.y());
168 window_preferences->SetInteger("work_area_right", work_area.right());
169 window_preferences->SetInteger("work_area_bottom", work_area.bottom());
172 bool ChromeViewsDelegate::GetSavedWindowPlacement(
173 const views::Widget* widget,
174 const std::string& window_name,
175 gfx::Rect* bounds,
176 ui::WindowShowState* show_state) const {
177 PrefService* prefs = g_browser_process->local_state();
178 if (!prefs)
179 return false;
181 DCHECK(prefs->FindPreference(window_name.c_str()));
182 const base::DictionaryValue* dictionary =
183 prefs->GetDictionary(window_name.c_str());
184 int left = 0;
185 int top = 0;
186 int right = 0;
187 int bottom = 0;
188 if (!dictionary || !dictionary->GetInteger("left", &left) ||
189 !dictionary->GetInteger("top", &top) ||
190 !dictionary->GetInteger("right", &right) ||
191 !dictionary->GetInteger("bottom", &bottom))
192 return false;
194 bounds->SetRect(left, top, right - left, bottom - top);
196 bool maximized = false;
197 if (dictionary)
198 dictionary->GetBoolean("maximized", &maximized);
199 *show_state = maximized ? ui::SHOW_STATE_MAXIMIZED : ui::SHOW_STATE_NORMAL;
201 #if defined(USE_ASH)
202 // On Ash environment, a window won't span across displays. Adjust
203 // the bounds to fit the work area.
204 gfx::NativeView window = widget->GetNativeView();
205 if (chrome::GetHostDesktopTypeForNativeView(window) ==
206 chrome::HOST_DESKTOP_TYPE_ASH) {
207 gfx::Display display = gfx::Screen::GetScreenFor(window)->
208 GetDisplayMatching(*bounds);
209 bounds->AdjustToFit(display.work_area());
210 ash::wm::GetWindowState(window)->set_minimum_visibility(true);
212 #endif
213 return true;
216 void ChromeViewsDelegate::NotifyAccessibilityEvent(
217 views::View* view, ui::AXEvent event_type) {
218 #if defined(USE_AURA)
219 AutomationManagerAura::GetInstance()->HandleEvent(
220 GetProfileForWindow(view->GetWidget()), view, event_type);
221 #endif
224 #if defined(OS_WIN)
225 HICON ChromeViewsDelegate::GetDefaultWindowIcon() const {
226 return GetAppIcon();
229 HICON ChromeViewsDelegate::GetSmallWindowIcon() const {
230 return GetSmallAppIcon();
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);
242 #endif
244 #if defined(USE_ASH)
245 views::NonClientFrameView* ChromeViewsDelegate::CreateDefaultNonClientFrameView(
246 views::Widget* widget) {
247 return chrome::IsNativeViewInAsh(widget->GetNativeView()) ?
248 ash::Shell::GetInstance()->CreateDefaultNonClientFrameView(widget) : NULL;
250 #endif
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
268 // up with one.
269 if (params->native_widget)
270 return;
272 #if defined(USE_AURA) && !defined(OS_CHROMEOS)
273 bool use_non_toplevel_window =
274 params->parent &&
275 params->type != views::Widget::InitParams::TYPE_MENU &&
276 params->type != views::Widget::InitParams::TYPE_TOOLTIP;
278 #if defined(OS_WIN)
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 &&
289 (params->child ||
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;
301 } else {
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
305 // window).
306 if (chrome::GetActiveDesktop() != chrome::HOST_DESKTOP_TYPE_ASH &&
307 params->parent &&
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;
315 #endif // OS_WIN
316 #endif // USE_AURA
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
324 // context.
325 if (params->context)
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
337 // desktop type.
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
341 // widget.
342 params->native_widget = new views::DesktopNativeWidgetAura(delegate);
343 break;
344 #if defined(USE_ASH)
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();
348 break;
349 #endif
350 default:
351 NOTREACHED();
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,
360 parent_profile);
362 params->native_widget = native_widget;
363 } else {
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);
373 #endif
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
379 // windows.
380 views::LinuxUI* ui = views::LinuxUI::instance();
381 return maximized && ui && ui->UnityIsRunning();
383 #endif
385 ui::ContextFactory* ChromeViewsDelegate::GetContextFactory() {
386 return content::GetContextFactory();
389 std::string ChromeViewsDelegate::GetApplicationName() {
390 return chrome::VersionInfo().Name();
393 #if defined(OS_WIN)
394 int ChromeViewsDelegate::GetAppbarAutohideEdges(HMONITOR monitor,
395 const base::Closure& callback) {
396 // Initialize the map with EDGE_BOTTOM. This is important, as if we return an
397 // initial value of 0 (no auto-hide edges) then we'll go fullscreen and
398 // windows will automatically remove WS_EX_TOPMOST from the appbar resulting
399 // in us thinking there is no auto-hide edges. By returning at least one edge
400 // we don't initially go fullscreen until we figure out the real auto-hide
401 // edges.
402 if (!appbar_autohide_edge_map_.count(monitor))
403 appbar_autohide_edge_map_[monitor] = EDGE_BOTTOM;
404 if (monitor && !in_autohide_edges_callback_) {
405 base::PostTaskAndReplyWithResult(
406 content::BrowserThread::GetBlockingPool(),
407 FROM_HERE,
408 base::Bind(&GetAppbarAutohideEdgesOnWorkerThread,
409 monitor),
410 base::Bind(&ChromeViewsDelegate::OnGotAppbarAutohideEdges,
411 weak_factory_.GetWeakPtr(),
412 callback,
413 monitor,
414 appbar_autohide_edge_map_[monitor]));
416 return appbar_autohide_edge_map_[monitor];
419 void ChromeViewsDelegate::OnGotAppbarAutohideEdges(
420 const base::Closure& callback,
421 HMONITOR monitor,
422 int returned_edges,
423 int edges) {
424 appbar_autohide_edge_map_[monitor] = edges;
425 if (returned_edges == edges)
426 return;
428 base::AutoReset<bool> in_callback_setter(&in_autohide_edges_callback_, true);
429 callback.Run();
431 #endif
433 scoped_refptr<base::TaskRunner>
434 ChromeViewsDelegate::GetBlockingPoolTaskRunner() {
435 return content::BrowserThread::GetBlockingPool();
438 #if !defined(USE_AURA) && !defined(USE_CHROMEOS)
439 views::Widget::InitParams::WindowOpacity
440 ChromeViewsDelegate::GetOpacityForInitParams(
441 const views::Widget::InitParams& params) {
442 return views::Widget::InitParams::OPAQUE_WINDOW;
444 #endif