Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / views / chrome_views_delegate.cc
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/browser/ui/views/chrome_views_delegate.h"
6
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/views/accessibility/accessibility_event_router_views.h"
16 #include "chrome/common/pref_names.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"
24
25 #if defined(OS_WIN)
26 #include <dwmapi.h>
27 #include <shellapi.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"
33 #endif
34
35 #if defined(USE_AURA)
36 #include "ui/aura/window.h"
37 #include "ui/aura/window_event_dispatcher.h"
38 #endif
39
40 #if defined(USE_AURA) && !defined(OS_CHROMEOS)
41 #include "chrome/browser/ui/host_desktop.h"
42 #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
43 #include "ui/views/widget/native_widget_aura.h"
44 #endif
45
46 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
47 #include "ui/views/linux_ui/linux_ui.h"
48 #endif
49
50 #if defined(USE_ASH)
51 #include "ash/shell.h"
52 #include "ash/wm/window_state.h"
53 #include "chrome/browser/ui/ash/accessibility/automation_manager_views.h"
54 #include "chrome/browser/ui/ash/ash_init.h"
55 #include "chrome/browser/ui/ash/ash_util.h"
56 #endif
57
58
59 // Helpers --------------------------------------------------------------------
60
61 namespace {
62
63 Profile* GetProfileForWindow(const views::Widget* window) {
64   if (!window)
65     return NULL;
66   return reinterpret_cast<Profile*>(
67       window->GetNativeWindowProperty(Profile::kProfileKey));
68 }
69
70 // If the given window has a profile associated with it, use that profile's
71 // preference service. Otherwise, store and retrieve the data from Local State.
72 // This function may return NULL if the necessary pref service has not yet
73 // been initialized.
74 // TODO(mirandac): This function will also separate windows by profile in a
75 // multi-profile environment.
76 PrefService* GetPrefsForWindow(const views::Widget* window) {
77   Profile* profile = GetProfileForWindow(window);
78   if (!profile) {
79     // Use local state for windows that have no explicit profile.
80     return g_browser_process->local_state();
81   }
82   return profile->GetPrefs();
83 }
84
85 #if defined(OS_WIN)
86 bool MonitorHasTopmostAutohideTaskbarForEdge(UINT edge, const RECT& rect) {
87   APPBARDATA taskbar_data = { sizeof(APPBARDATA), NULL, 0, edge, rect };
88   // NOTE: This call spins a nested message loop.
89   HWND taskbar = reinterpret_cast<HWND>(SHAppBarMessage(ABM_GETAUTOHIDEBAREX,
90                                                         &taskbar_data));
91   return ::IsWindow(taskbar) &&
92       (GetWindowLong(taskbar, GWL_EXSTYLE) & WS_EX_TOPMOST);
93 }
94
95 int GetAppbarAutohideEdgesOnWorkerThread(HMONITOR monitor) {
96   DCHECK(monitor);
97
98   MONITORINFO mi = { sizeof(MONITORINFO) };
99   GetMonitorInfo(monitor, &mi);
100
101   int edges = 0;
102   if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_LEFT, mi.rcMonitor))
103     edges |= views::ViewsDelegate::EDGE_LEFT;
104   if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_TOP, mi.rcMonitor))
105     edges |= views::ViewsDelegate::EDGE_TOP;
106   if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_RIGHT, mi.rcMonitor))
107     edges |= views::ViewsDelegate::EDGE_RIGHT;
108   if (MonitorHasTopmostAutohideTaskbarForEdge(ABE_BOTTOM, mi.rcMonitor))
109     edges |= views::ViewsDelegate::EDGE_BOTTOM;
110   return edges;
111 }
112 #endif
113
114 }  // namespace
115
116
117 // ChromeViewsDelegate --------------------------------------------------------
118
119 #if defined(OS_WIN)
120 ChromeViewsDelegate::ChromeViewsDelegate()
121     : weak_factory_(this),
122       in_autohide_edges_callback_(false) {
123 #else
124 ChromeViewsDelegate::ChromeViewsDelegate() {
125 #endif
126 }
127
128 ChromeViewsDelegate::~ChromeViewsDelegate() {
129 }
130
131 void ChromeViewsDelegate::SaveWindowPlacement(const views::Widget* window,
132                                               const std::string& window_name,
133                                               const gfx::Rect& bounds,
134                                               ui::WindowShowState show_state) {
135   PrefService* prefs = GetPrefsForWindow(window);
136   if (!prefs)
137     return;
138
139   DCHECK(prefs->FindPreference(window_name.c_str()));
140   DictionaryPrefUpdate update(prefs, window_name.c_str());
141   base::DictionaryValue* window_preferences = update.Get();
142   window_preferences->SetInteger("left", bounds.x());
143   window_preferences->SetInteger("top", bounds.y());
144   window_preferences->SetInteger("right", bounds.right());
145   window_preferences->SetInteger("bottom", bounds.bottom());
146   window_preferences->SetBoolean("maximized",
147                                  show_state == ui::SHOW_STATE_MAXIMIZED);
148   gfx::Rect work_area(gfx::Screen::GetScreenFor(window->GetNativeView())->
149       GetDisplayNearestWindow(window->GetNativeView()).work_area());
150   window_preferences->SetInteger("work_area_left", work_area.x());
151   window_preferences->SetInteger("work_area_top", work_area.y());
152   window_preferences->SetInteger("work_area_right", work_area.right());
153   window_preferences->SetInteger("work_area_bottom", work_area.bottom());
154 }
155
156 bool ChromeViewsDelegate::GetSavedWindowPlacement(
157     const views::Widget* widget,
158     const std::string& window_name,
159     gfx::Rect* bounds,
160     ui::WindowShowState* show_state) const {
161   PrefService* prefs = g_browser_process->local_state();
162   if (!prefs)
163     return false;
164
165   DCHECK(prefs->FindPreference(window_name.c_str()));
166   const base::DictionaryValue* dictionary =
167       prefs->GetDictionary(window_name.c_str());
168   int left, top, right, bottom;
169   if (!dictionary || !dictionary->GetInteger("left", &left) ||
170       !dictionary->GetInteger("top", &top) ||
171       !dictionary->GetInteger("right", &right) ||
172       !dictionary->GetInteger("bottom", &bottom))
173     return false;
174
175   bounds->SetRect(left, top, right - left, bottom - top);
176
177   bool maximized = false;
178   if (dictionary)
179     dictionary->GetBoolean("maximized", &maximized);
180   *show_state = maximized ? ui::SHOW_STATE_MAXIMIZED : ui::SHOW_STATE_NORMAL;
181
182 #if defined(USE_ASH)
183   // On Ash environment, a window won't span across displays.  Adjust
184   // the bounds to fit the work area.
185   gfx::NativeView window = widget->GetNativeView();
186   if (chrome::GetHostDesktopTypeForNativeView(window) ==
187       chrome::HOST_DESKTOP_TYPE_ASH) {
188     gfx::Display display = gfx::Screen::GetScreenFor(window)->
189         GetDisplayMatching(*bounds);
190     bounds->AdjustToFit(display.work_area());
191     ash::wm::GetWindowState(window)->set_minimum_visibility(true);
192   }
193 #endif
194   return true;
195 }
196
197 void ChromeViewsDelegate::NotifyAccessibilityEvent(
198     views::View* view, ui::AXEvent event_type) {
199   AccessibilityEventRouterViews::GetInstance()->HandleAccessibilityEvent(
200       view, event_type);
201
202 #if defined(USE_ASH)
203   AutomationManagerViews::GetInstance()->HandleEvent(
204       GetProfileForWindow(view->GetWidget()), view, event_type);
205 #endif
206 }
207
208 void ChromeViewsDelegate::NotifyMenuItemFocused(
209     const base::string16& menu_name,
210     const base::string16& menu_item_name,
211     int item_index,
212     int item_count,
213     bool has_submenu) {
214   AccessibilityEventRouterViews::GetInstance()->HandleMenuItemFocused(
215       menu_name, menu_item_name, item_index, item_count, has_submenu);
216 }
217
218 #if defined(OS_WIN)
219 HICON ChromeViewsDelegate::GetDefaultWindowIcon() const {
220   return GetAppIcon();
221 }
222
223 bool ChromeViewsDelegate::IsWindowInMetro(gfx::NativeWindow window) const {
224   return chrome::IsNativeViewInAsh(window);
225 }
226
227 #elif defined(OS_LINUX) && !defined(OS_CHROMEOS)
228 gfx::ImageSkia* ChromeViewsDelegate::GetDefaultWindowIcon() const {
229   ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
230   return rb.GetImageSkiaNamed(IDR_PRODUCT_LOGO_64);
231 }
232 #endif
233
234 #if defined(USE_ASH)
235 views::NonClientFrameView* ChromeViewsDelegate::CreateDefaultNonClientFrameView(
236     views::Widget* widget) {
237   return chrome::IsNativeViewInAsh(widget->GetNativeView()) ?
238       ash::Shell::GetInstance()->CreateDefaultNonClientFrameView(widget) : NULL;
239 }
240 #endif
241
242 void ChromeViewsDelegate::AddRef() {
243   g_browser_process->AddRefModule();
244 }
245
246 void ChromeViewsDelegate::ReleaseRef() {
247   g_browser_process->ReleaseModule();
248 }
249
250 void ChromeViewsDelegate::OnBeforeWidgetInit(
251     views::Widget::InitParams* params,
252     views::internal::NativeWidgetDelegate* delegate) {
253   // We need to determine opacity if it's not already specified.
254   if (params->opacity == views::Widget::InitParams::INFER_OPACITY)
255     params->opacity = GetOpacityForInitParams(*params);
256
257   // If we already have a native_widget, we don't have to try to come
258   // up with one.
259   if (params->native_widget)
260     return;
261
262 #if defined(USE_AURA) && !defined(OS_CHROMEOS)
263   bool use_non_toplevel_window =
264       params->parent && params->type != views::Widget::InitParams::TYPE_MENU;
265
266 #if defined(OS_WIN)
267   // On desktop Linux Chrome must run in an environment that supports a variety
268   // of window managers, some of which do not play nicely with parts of our UI
269   // that have specific expectations about window sizing and placement. For this
270   // reason windows opened as top level (params.top_level) are always
271   // constrained by the browser frame, so we can position them correctly. This
272   // has some negative side effects, like dialogs being clipped by the browser
273   // frame, but the side effects are not as bad as the poor window manager
274   // interactions. On Windows however these WM interactions are not an issue, so
275   // we open windows requested as top_level as actual top level windows on the
276   // desktop.
277   use_non_toplevel_window = use_non_toplevel_window &&
278       (!params->top_level ||
279        chrome::GetHostDesktopTypeForNativeView(params->parent) !=
280           chrome::HOST_DESKTOP_TYPE_NATIVE);
281
282   if (!ui::win::IsAeroGlassEnabled()) {
283     // If we don't have composition (either because Glass is not enabled or
284     // because it was disabled at the command line), anything that requires
285     // transparency will be broken with a toplevel window, so force the use of
286     // a non toplevel window.
287     if (params->opacity == views::Widget::InitParams::TRANSLUCENT_WINDOW &&
288         params->type != views::Widget::InitParams::TYPE_MENU)
289       use_non_toplevel_window = true;
290   } else {
291     // If we're on Vista+ with composition enabled, then we can use toplevel
292     // windows for most things (they get blended via WS_EX_COMPOSITED, which
293     // allows for animation effects, but also exceeding the bounds of the parent
294     // window).
295     if (chrome::GetActiveDesktop() != chrome::HOST_DESKTOP_TYPE_ASH &&
296         params->parent &&
297         params->type != views::Widget::InitParams::TYPE_CONTROL &&
298         params->type != views::Widget::InitParams::TYPE_WINDOW) {
299       // When we set this to false, we get a DesktopNativeWidgetAura from the
300       // default case (not handled in this function).
301       use_non_toplevel_window = false;
302     }
303   }
304 #endif  // OS_WIN
305 #endif  // USE_AURA
306
307 #if defined(OS_CHROMEOS)
308   // When we are doing straight chromeos builds, we still need to handle the
309   // toplevel window case.
310   // There may be a few remaining widgets in Chrome OS that are not top level,
311   // but have neither a context nor a parent. Provide a fallback context so
312   // users don't crash. Developers will hit the DCHECK and should provide a
313   // context.
314   if (params->context)
315     params->context = params->context->GetRootWindow();
316   DCHECK(params->parent || params->context || params->top_level)
317       << "Please provide a parent or context for this widget.";
318   if (!params->parent && !params->context)
319     params->context = ash::Shell::GetPrimaryRootWindow();
320 #elif defined(USE_AURA)
321   // While the majority of the time, context wasn't plumbed through due to the
322   // existence of a global WindowTreeClient, if this window is a toplevel, it's
323   // possible that there is no contextual state that we can use.
324   if (params->parent == NULL && params->context == NULL && params->top_level) {
325     // We need to make a decision about where to place this window based on the
326     // desktop type.
327     switch (chrome::GetActiveDesktop()) {
328       case chrome::HOST_DESKTOP_TYPE_NATIVE:
329         // If we're native, we should give this window its own toplevel desktop
330         // widget.
331         params->native_widget = new views::DesktopNativeWidgetAura(delegate);
332         break;
333 #if defined(USE_ASH)
334       case chrome::HOST_DESKTOP_TYPE_ASH:
335         // If we're in ash, give this window the context of the main monitor.
336         params->context = ash::Shell::GetPrimaryRootWindow();
337         break;
338 #endif
339       default:
340         NOTREACHED();
341     }
342   } else if (use_non_toplevel_window) {
343     views::NativeWidgetAura* native_widget =
344         new views::NativeWidgetAura(delegate);
345     if (params->parent) {
346       Profile* parent_profile = reinterpret_cast<Profile*>(
347           params->parent->GetNativeWindowProperty(Profile::kProfileKey));
348       native_widget->SetNativeWindowProperty(Profile::kProfileKey,
349                                              parent_profile);
350     }
351     params->native_widget = native_widget;
352   } else if (params->type != views::Widget::InitParams::TYPE_TOOLTIP) {
353     // TODO(erg): Once we've threaded context to everywhere that needs it, we
354     // should remove this check here.
355     gfx::NativeView to_check =
356         params->context ? params->context : params->parent;
357     if (chrome::GetHostDesktopTypeForNativeView(to_check) ==
358         chrome::HOST_DESKTOP_TYPE_NATIVE) {
359       params->native_widget = new views::DesktopNativeWidgetAura(delegate);
360     }
361   }
362 #endif
363 }
364
365 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
366 bool ChromeViewsDelegate::WindowManagerProvidesTitleBar(bool maximized) {
367   // On Ubuntu Unity, the system always provides a title bar for maximized
368   // windows.
369   views::LinuxUI* ui = views::LinuxUI::instance();
370   return maximized && ui && ui->UnityIsRunning();
371 }
372 #endif
373
374 #if defined(OS_WIN)
375 int ChromeViewsDelegate::GetAppbarAutohideEdges(HMONITOR monitor,
376                                                 const base::Closure& callback) {
377   // Initialize the map with EDGE_BOTTOM. This is important, as if we return an
378   // initial value of 0 (no auto-hide edges) then we'll go fullscreen and
379   // windows will automatically remove WS_EX_TOPMOST from the appbar resulting
380   // in us thinking there is no auto-hide edges. By returning at least one edge
381   // we don't initially go fullscreen until we figure out the real auto-hide
382   // edges.
383   if (!appbar_autohide_edge_map_.count(monitor))
384     appbar_autohide_edge_map_[monitor] = EDGE_BOTTOM;
385   if (monitor && !in_autohide_edges_callback_) {
386     base::PostTaskAndReplyWithResult(
387         content::BrowserThread::GetBlockingPool(),
388         FROM_HERE,
389         base::Bind(&GetAppbarAutohideEdgesOnWorkerThread,
390                    monitor),
391         base::Bind(&ChromeViewsDelegate::OnGotAppbarAutohideEdges,
392                    weak_factory_.GetWeakPtr(),
393                    callback,
394                    monitor,
395                    appbar_autohide_edge_map_[monitor]));
396   }
397   return appbar_autohide_edge_map_[monitor];
398 }
399
400 void ChromeViewsDelegate::OnGotAppbarAutohideEdges(
401     const base::Closure& callback,
402     HMONITOR monitor,
403     int returned_edges,
404     int edges) {
405   appbar_autohide_edge_map_[monitor] = edges;
406   if (returned_edges == edges)
407     return;
408
409   base::AutoReset<bool> in_callback_setter(&in_autohide_edges_callback_, true);
410   callback.Run();
411 }
412 #endif
413
414 #if !defined(USE_AURA) && !defined(USE_CHROMEOS)
415 views::Widget::InitParams::WindowOpacity
416 ChromeViewsDelegate::GetOpacityForInitParams(
417     const views::Widget::InitParams& params) {
418   return views::Widget::InitParams::OPAQUE_WINDOW;
419 }
420 #endif