BookmarkManager: Fix 'new folder text field size changes on clicking it' issue.
[chromium-blink-merge.git] / chrome / browser / ui / views / chrome_views_delegate.cc
blobf7efbac74c2e794339c6c16fdd2d4b342eb54fb0
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 "components/version_info/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/controls/menu/menu_controller.h"
25 #include "ui/views/widget/native_widget.h"
26 #include "ui/views/widget/widget.h"
28 #if defined(OS_WIN)
29 #include <dwmapi.h>
30 #include <shellapi.h>
31 #include "base/profiler/scoped_tracker.h"
32 #include "base/task_runner_util.h"
33 #include "base/win/windows_version.h"
34 #include "chrome/browser/app_icon_win.h"
35 #include "content/public/browser/browser_thread.h"
36 #include "ui/base/win/shell.h"
37 #endif
39 #if defined(USE_AURA)
40 #include "chrome/browser/ui/aura/accessibility/automation_manager_aura.h"
41 #include "ui/aura/window.h"
42 #include "ui/aura/window_event_dispatcher.h"
43 #endif
45 #if defined(USE_AURA) && !defined(OS_CHROMEOS)
46 #include "chrome/browser/ui/host_desktop.h"
47 #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
48 #include "ui/views/widget/native_widget_aura.h"
49 #endif
51 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
52 #include "ui/views/linux_ui/linux_ui.h"
53 #endif
55 #if defined(USE_ASH)
56 #include "ash/accelerators/accelerator_controller.h"
57 #include "ash/shell.h"
58 #include "ash/wm/window_state.h"
59 #include "chrome/browser/ui/ash/ash_init.h"
60 #include "chrome/browser/ui/ash/ash_util.h"
61 #endif
64 // Helpers --------------------------------------------------------------------
66 namespace {
68 Profile* GetProfileForWindow(const views::Widget* window) {
69 if (!window)
70 return NULL;
71 return reinterpret_cast<Profile*>(
72 window->GetNativeWindowProperty(Profile::kProfileKey));
75 // If the given window has a profile associated with it, use that profile's
76 // preference service. Otherwise, store and retrieve the data from Local State.
77 // This function may return NULL if the necessary pref service has not yet
78 // been initialized.
79 // TODO(mirandac): This function will also separate windows by profile in a
80 // multi-profile environment.
81 PrefService* GetPrefsForWindow(const views::Widget* window) {
82 Profile* profile = GetProfileForWindow(window);
83 if (!profile) {
84 // Use local state for windows that have no explicit profile.
85 return g_browser_process->local_state();
87 return profile->GetPrefs();
90 #if defined(OS_WIN)
91 bool MonitorHasTopmostAutohideTaskbarForEdge(UINT edge, HMONITOR monitor) {
92 APPBARDATA taskbar_data = { sizeof(APPBARDATA), NULL, 0, edge };
94 // TODO(robliao): Remove ScopedTracker below once crbug.com/462368 is fixed.
95 tracked_objects::ScopedTracker tracking_profile(
96 FROM_HERE_WITH_EXPLICIT_FUNCTION(
97 "462368 MonitorHasTopmostAutohideTaskbarForEdge"));
99 // MSDN documents an ABM_GETAUTOHIDEBAREX, which supposedly takes a monitor
100 // rect and returns autohide bars on that monitor. This sounds like a good
101 // idea for multi-monitor systems. Unfortunately, it appears to not work at
102 // least some of the time (erroneously returning NULL) and there's almost no
103 // online documentation or other sample code using it that suggests ways to
104 // address this problem. So we just use ABM_GETAUTOHIDEBAR and hope the user
105 // only cares about autohide bars on the monitor with the primary taskbar.
107 // NOTE: This call spins a nested message loop.
108 HWND taskbar = reinterpret_cast<HWND>(SHAppBarMessage(ABM_GETAUTOHIDEBAR,
109 &taskbar_data));
110 return ::IsWindow(taskbar) &&
111 (MonitorFromWindow(taskbar, MONITOR_DEFAULTTONULL) == monitor) &&
112 (GetWindowLong(taskbar, GWL_EXSTYLE) & WS_EX_TOPMOST);
115 int GetAppbarAutohideEdgesOnWorkerThread(HMONITOR monitor) {
116 DCHECK(monitor);
118 int edges = 0;
119 if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_LEFT, monitor))
120 edges |= views::ViewsDelegate::EDGE_LEFT;
121 if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_TOP, monitor))
122 edges |= views::ViewsDelegate::EDGE_TOP;
123 if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_RIGHT, monitor))
124 edges |= views::ViewsDelegate::EDGE_RIGHT;
125 if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_BOTTOM, monitor))
126 edges |= views::ViewsDelegate::EDGE_BOTTOM;
127 return edges;
129 #endif
131 #if defined(USE_ASH)
132 void ProcessAcceleratorNow(const ui::Accelerator& accelerator) {
133 // TODO(afakhry): See if we need here to send the accelerator to the
134 // FocusManager of the active window in a follow-up CL.
135 ash::Shell::GetInstance()->accelerator_controller()->Process(accelerator);
137 #endif // defined(USE_ASH)
139 } // namespace
142 // ChromeViewsDelegate --------------------------------------------------------
144 #if defined(OS_WIN)
145 ChromeViewsDelegate::ChromeViewsDelegate()
146 : in_autohide_edges_callback_(false),
147 weak_factory_(this) {
148 #else
149 ChromeViewsDelegate::ChromeViewsDelegate() {
150 #endif
153 ChromeViewsDelegate::~ChromeViewsDelegate() {
156 void ChromeViewsDelegate::SaveWindowPlacement(const views::Widget* window,
157 const std::string& window_name,
158 const gfx::Rect& bounds,
159 ui::WindowShowState show_state) {
160 PrefService* prefs = GetPrefsForWindow(window);
161 if (!prefs)
162 return;
164 scoped_ptr<DictionaryPrefUpdate> pref_update =
165 chrome::GetWindowPlacementDictionaryReadWrite(window_name, prefs);
166 base::DictionaryValue* window_preferences = pref_update->Get();
167 window_preferences->SetInteger("left", bounds.x());
168 window_preferences->SetInteger("top", bounds.y());
169 window_preferences->SetInteger("right", bounds.right());
170 window_preferences->SetInteger("bottom", bounds.bottom());
171 window_preferences->SetBoolean("maximized",
172 show_state == ui::SHOW_STATE_MAXIMIZED);
173 window_preferences->SetBoolean("docked", show_state == ui::SHOW_STATE_DOCKED);
174 gfx::Rect work_area(gfx::Screen::GetScreenFor(window->GetNativeView())->
175 GetDisplayNearestWindow(window->GetNativeView()).work_area());
176 window_preferences->SetInteger("work_area_left", work_area.x());
177 window_preferences->SetInteger("work_area_top", work_area.y());
178 window_preferences->SetInteger("work_area_right", work_area.right());
179 window_preferences->SetInteger("work_area_bottom", work_area.bottom());
182 bool ChromeViewsDelegate::GetSavedWindowPlacement(
183 const views::Widget* widget,
184 const std::string& window_name,
185 gfx::Rect* bounds,
186 ui::WindowShowState* show_state) const {
187 PrefService* prefs = g_browser_process->local_state();
188 if (!prefs)
189 return false;
191 DCHECK(prefs->FindPreference(window_name));
192 const base::DictionaryValue* dictionary = prefs->GetDictionary(window_name);
193 int left = 0;
194 int top = 0;
195 int right = 0;
196 int bottom = 0;
197 if (!dictionary || !dictionary->GetInteger("left", &left) ||
198 !dictionary->GetInteger("top", &top) ||
199 !dictionary->GetInteger("right", &right) ||
200 !dictionary->GetInteger("bottom", &bottom))
201 return false;
203 bounds->SetRect(left, top, right - left, bottom - top);
205 bool maximized = false;
206 if (dictionary)
207 dictionary->GetBoolean("maximized", &maximized);
208 *show_state = maximized ? ui::SHOW_STATE_MAXIMIZED : ui::SHOW_STATE_NORMAL;
210 #if defined(USE_ASH)
211 // On Ash environment, a window won't span across displays. Adjust
212 // the bounds to fit the work area.
213 gfx::NativeView window = widget->GetNativeView();
214 if (chrome::GetHostDesktopTypeForNativeView(window) ==
215 chrome::HOST_DESKTOP_TYPE_ASH) {
216 gfx::Display display = gfx::Screen::GetScreenFor(window)->
217 GetDisplayMatching(*bounds);
218 bounds->AdjustToFit(display.work_area());
219 ash::wm::GetWindowState(window)->set_minimum_visibility(true);
221 #endif
222 return true;
225 void ChromeViewsDelegate::NotifyAccessibilityEvent(
226 views::View* view, ui::AXEvent event_type) {
227 #if defined(USE_AURA)
228 AutomationManagerAura::GetInstance()->HandleEvent(
229 GetProfileForWindow(view->GetWidget()), view, event_type);
230 #endif
233 views::ViewsDelegate::ProcessMenuAcceleratorResult
234 ChromeViewsDelegate::ProcessAcceleratorWhileMenuShowing(
235 const ui::Accelerator& accelerator) {
236 #if defined(USE_ASH)
237 // Handle ash accelerators only when a menu is opened on an ash desktop.
238 if (chrome::GetActiveDesktop() != chrome::HOST_DESKTOP_TYPE_ASH)
239 return views::ViewsDelegate::ProcessMenuAcceleratorResult::LEAVE_MENU_OPEN;
241 ash::AcceleratorController* accelerator_controller =
242 ash::Shell::GetInstance()->accelerator_controller();
244 accelerator_controller->accelerator_history()->StoreCurrentAccelerator(
245 accelerator);
246 if (accelerator_controller->ShouldCloseMenuAndRepostAccelerator(
247 accelerator)) {
248 base::MessageLoopForUI::current()->PostTask(
249 FROM_HERE,
250 base::Bind(ProcessAcceleratorNow, accelerator));
251 return views::ViewsDelegate::ProcessMenuAcceleratorResult::CLOSE_MENU;
254 ProcessAcceleratorNow(accelerator);
255 return views::ViewsDelegate::ProcessMenuAcceleratorResult::LEAVE_MENU_OPEN;
256 #else
257 return views::ViewsDelegate::ProcessMenuAcceleratorResult::LEAVE_MENU_OPEN;
258 #endif // defined(USE_ASH)
261 #if defined(OS_WIN)
262 HICON ChromeViewsDelegate::GetDefaultWindowIcon() const {
263 return GetAppIcon();
266 HICON ChromeViewsDelegate::GetSmallWindowIcon() const {
267 return GetSmallAppIcon();
270 bool ChromeViewsDelegate::IsWindowInMetro(gfx::NativeWindow window) const {
271 return chrome::IsNativeViewInAsh(window);
274 #elif defined(OS_LINUX) && !defined(OS_CHROMEOS)
275 gfx::ImageSkia* ChromeViewsDelegate::GetDefaultWindowIcon() const {
276 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
277 return rb.GetImageSkiaNamed(IDR_PRODUCT_LOGO_64);
279 #endif
281 #if defined(USE_ASH)
282 views::NonClientFrameView* ChromeViewsDelegate::CreateDefaultNonClientFrameView(
283 views::Widget* widget) {
284 return chrome::IsNativeViewInAsh(widget->GetNativeView()) ?
285 ash::Shell::GetInstance()->CreateDefaultNonClientFrameView(widget) : NULL;
287 #endif
289 void ChromeViewsDelegate::AddRef() {
290 g_browser_process->AddRefModule();
293 void ChromeViewsDelegate::ReleaseRef() {
294 g_browser_process->ReleaseModule();
297 void ChromeViewsDelegate::OnBeforeWidgetInit(
298 views::Widget::InitParams* params,
299 views::internal::NativeWidgetDelegate* delegate) {
300 // We need to determine opacity if it's not already specified.
301 if (params->opacity == views::Widget::InitParams::INFER_OPACITY)
302 params->opacity = GetOpacityForInitParams(*params);
304 // If we already have a native_widget, we don't have to try to come
305 // up with one.
306 if (params->native_widget)
307 return;
309 #if defined(USE_AURA) && !defined(OS_CHROMEOS)
310 bool use_non_toplevel_window =
311 params->parent &&
312 params->type != views::Widget::InitParams::TYPE_MENU &&
313 params->type != views::Widget::InitParams::TYPE_TOOLTIP;
315 #if defined(OS_WIN)
316 // On desktop Linux Chrome must run in an environment that supports a variety
317 // of window managers, some of which do not play nicely with parts of our UI
318 // that have specific expectations about window sizing and placement. For this
319 // reason windows opened as top level (!params.child) are always constrained
320 // by the browser frame, so we can position them correctly. This has some
321 // negative side effects, like dialogs being clipped by the browser frame, but
322 // the side effects are not as bad as the poor window manager interactions. On
323 // Windows however these WM interactions are not an issue, so we open windows
324 // requested as top_level as actual top level windows on the desktop.
325 use_non_toplevel_window = use_non_toplevel_window &&
326 (params->child ||
327 chrome::GetHostDesktopTypeForNativeView(params->parent) !=
328 chrome::HOST_DESKTOP_TYPE_NATIVE);
330 if (!ui::win::IsAeroGlassEnabled()) {
331 // If we don't have composition (either because Glass is not enabled or
332 // because it was disabled at the command line), anything that requires
333 // transparency will be broken with a toplevel window, so force the use of
334 // a non toplevel window.
335 if (params->opacity == views::Widget::InitParams::TRANSLUCENT_WINDOW &&
336 params->type != views::Widget::InitParams::TYPE_MENU)
337 use_non_toplevel_window = true;
338 } else {
339 // If we're on Vista+ with composition enabled, then we can use toplevel
340 // windows for most things (they get blended via WS_EX_COMPOSITED, which
341 // allows for animation effects, but also exceeding the bounds of the parent
342 // window).
343 if (chrome::GetActiveDesktop() != chrome::HOST_DESKTOP_TYPE_ASH &&
344 params->parent &&
345 params->type != views::Widget::InitParams::TYPE_CONTROL &&
346 params->type != views::Widget::InitParams::TYPE_WINDOW) {
347 // When we set this to false, we get a DesktopNativeWidgetAura from the
348 // default case (not handled in this function).
349 use_non_toplevel_window = false;
352 #endif // OS_WIN
353 #endif // USE_AURA
355 #if defined(OS_CHROMEOS)
356 // When we are doing straight chromeos builds, we still need to handle the
357 // toplevel window case.
358 // There may be a few remaining widgets in Chrome OS that are not top level,
359 // but have neither a context nor a parent. Provide a fallback context so
360 // users don't crash. Developers will hit the DCHECK and should provide a
361 // context.
362 if (params->context)
363 params->context = params->context->GetRootWindow();
364 DCHECK(params->parent || params->context || !params->child)
365 << "Please provide a parent or context for this widget.";
366 if (!params->parent && !params->context)
367 params->context = ash::Shell::GetPrimaryRootWindow();
368 #elif defined(USE_AURA)
369 // While the majority of the time, context wasn't plumbed through due to the
370 // existence of a global WindowTreeClient, if this window is toplevel, it's
371 // possible that there is no contextual state that we can use.
372 if (params->parent == NULL && params->context == NULL && !params->child) {
373 // We need to make a decision about where to place this window based on the
374 // desktop type.
375 switch (chrome::GetActiveDesktop()) {
376 case chrome::HOST_DESKTOP_TYPE_NATIVE:
377 // If we're native, we should give this window its own toplevel desktop
378 // widget.
379 params->native_widget = new views::DesktopNativeWidgetAura(delegate);
380 break;
381 #if defined(USE_ASH)
382 case chrome::HOST_DESKTOP_TYPE_ASH:
383 // If we're in ash, give this window the context of the main monitor.
384 params->context = ash::Shell::GetPrimaryRootWindow();
385 break;
386 #endif
387 default:
388 NOTREACHED();
390 } else if (use_non_toplevel_window) {
391 views::NativeWidgetAura* native_widget =
392 new views::NativeWidgetAura(delegate);
393 if (params->parent) {
394 Profile* parent_profile = reinterpret_cast<Profile*>(
395 params->parent->GetNativeWindowProperty(Profile::kProfileKey));
396 native_widget->SetNativeWindowProperty(Profile::kProfileKey,
397 parent_profile);
399 params->native_widget = native_widget;
400 } else {
401 // TODO(erg): Once we've threaded context to everywhere that needs it, we
402 // should remove this check here.
403 gfx::NativeView to_check =
404 params->context ? params->context : params->parent;
405 if (chrome::GetHostDesktopTypeForNativeView(to_check) ==
406 chrome::HOST_DESKTOP_TYPE_NATIVE) {
407 params->native_widget = new views::DesktopNativeWidgetAura(delegate);
410 #endif
413 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
414 bool ChromeViewsDelegate::WindowManagerProvidesTitleBar(bool maximized) {
415 // On Ubuntu Unity, the system always provides a title bar for maximized
416 // windows.
417 views::LinuxUI* ui = views::LinuxUI::instance();
418 return maximized && ui && ui->UnityIsRunning();
420 #endif
422 ui::ContextFactory* ChromeViewsDelegate::GetContextFactory() {
423 return content::GetContextFactory();
426 std::string ChromeViewsDelegate::GetApplicationName() {
427 return version_info::GetProductName();
430 #if defined(OS_WIN)
431 int ChromeViewsDelegate::GetAppbarAutohideEdges(HMONITOR monitor,
432 const base::Closure& callback) {
433 // Initialize the map with EDGE_BOTTOM. This is important, as if we return an
434 // initial value of 0 (no auto-hide edges) then we'll go fullscreen and
435 // windows will automatically remove WS_EX_TOPMOST from the appbar resulting
436 // in us thinking there is no auto-hide edges. By returning at least one edge
437 // we don't initially go fullscreen until we figure out the real auto-hide
438 // edges.
439 if (!appbar_autohide_edge_map_.count(monitor))
440 appbar_autohide_edge_map_[monitor] = EDGE_BOTTOM;
441 if (monitor && !in_autohide_edges_callback_) {
442 base::PostTaskAndReplyWithResult(
443 content::BrowserThread::GetBlockingPool(),
444 FROM_HERE,
445 base::Bind(&GetAppbarAutohideEdgesOnWorkerThread,
446 monitor),
447 base::Bind(&ChromeViewsDelegate::OnGotAppbarAutohideEdges,
448 weak_factory_.GetWeakPtr(),
449 callback,
450 monitor,
451 appbar_autohide_edge_map_[monitor]));
453 return appbar_autohide_edge_map_[monitor];
456 void ChromeViewsDelegate::OnGotAppbarAutohideEdges(
457 const base::Closure& callback,
458 HMONITOR monitor,
459 int returned_edges,
460 int edges) {
461 appbar_autohide_edge_map_[monitor] = edges;
462 if (returned_edges == edges)
463 return;
465 base::AutoReset<bool> in_callback_setter(&in_autohide_edges_callback_, true);
466 callback.Run();
468 #endif
470 scoped_refptr<base::TaskRunner>
471 ChromeViewsDelegate::GetBlockingPoolTaskRunner() {
472 return content::BrowserThread::GetBlockingPool();
475 #if !defined(USE_AURA) && !defined(USE_CHROMEOS)
476 views::Widget::InitParams::WindowOpacity
477 ChromeViewsDelegate::GetOpacityForInitParams(
478 const views::Widget::InitParams& params) {
479 return views::Widget::InitParams::OPAQUE_WINDOW;
481 #endif