Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / ui / views / widget / desktop_aura / desktop_window_tree_host_win.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 "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h"
6
7 #include "base/win/metro.h"
8 #include "third_party/skia/include/core/SkPath.h"
9 #include "third_party/skia/include/core/SkRegion.h"
10 #include "ui/aura/client/aura_constants.h"
11 #include "ui/aura/client/cursor_client.h"
12 #include "ui/aura/client/focus_client.h"
13 #include "ui/aura/window_event_dispatcher.h"
14 #include "ui/aura/window_property.h"
15 #include "ui/base/cursor/cursor_loader_win.h"
16 #include "ui/base/ime/input_method.h"
17 #include "ui/base/win/shell.h"
18 #include "ui/compositor/compositor_constants.h"
19 #include "ui/gfx/insets.h"
20 #include "ui/gfx/native_widget_types.h"
21 #include "ui/gfx/path.h"
22 #include "ui/gfx/path_win.h"
23 #include "ui/gfx/vector2d.h"
24 #include "ui/gfx/win/dpi.h"
25 #include "ui/native_theme/native_theme_aura.h"
26 #include "ui/native_theme/native_theme_win.h"
27 #include "ui/views/corewm/tooltip_win.h"
28 #include "ui/views/ime/input_method_bridge.h"
29 #include "ui/views/widget/desktop_aura/desktop_cursor_loader_updater.h"
30 #include "ui/views/widget/desktop_aura/desktop_drag_drop_client_win.h"
31 #include "ui/views/widget/desktop_aura/desktop_native_cursor_manager.h"
32 #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
33 #include "ui/views/widget/root_view.h"
34 #include "ui/views/widget/widget_delegate.h"
35 #include "ui/views/widget/widget_hwnd_utils.h"
36 #include "ui/views/win/fullscreen_handler.h"
37 #include "ui/views/win/hwnd_message_handler.h"
38 #include "ui/wm/core/compound_event_filter.h"
39 #include "ui/wm/core/input_method_event_filter.h"
40 #include "ui/wm/core/window_animations.h"
41 #include "ui/wm/public/scoped_tooltip_disabler.h"
42
43 namespace views {
44
45 namespace {
46
47 gfx::Size GetExpandedWindowSize(DWORD window_style, gfx::Size size) {
48   if (!(window_style & WS_EX_COMPOSITED) || !ui::win::IsAeroGlassEnabled())
49     return size;
50
51   // Some AMD drivers can't display windows that are less than 64x64 pixels,
52   // so expand them to be at least that size. http://crbug.com/286609
53   gfx::Size expanded(std::max(size.width(), 64), std::max(size.height(), 64));
54   return expanded;
55 }
56
57 void InsetBottomRight(gfx::Rect* rect, gfx::Vector2d vector) {
58   rect->Inset(0, 0, vector.x(), vector.y());
59 }
60
61 }  // namespace
62
63 DEFINE_WINDOW_PROPERTY_KEY(aura::Window*, kContentWindowForRootWindow, NULL);
64
65 // Identifies the DesktopWindowTreeHostWin associated with the
66 // WindowEventDispatcher.
67 DEFINE_WINDOW_PROPERTY_KEY(DesktopWindowTreeHostWin*, kDesktopWindowTreeHostKey,
68                            NULL);
69
70 ////////////////////////////////////////////////////////////////////////////////
71 // DesktopWindowTreeHostWin, public:
72
73 bool DesktopWindowTreeHostWin::is_cursor_visible_ = true;
74
75 DesktopWindowTreeHostWin::DesktopWindowTreeHostWin(
76     internal::NativeWidgetDelegate* native_widget_delegate,
77     DesktopNativeWidgetAura* desktop_native_widget_aura)
78     : message_handler_(new HWNDMessageHandler(this)),
79       native_widget_delegate_(native_widget_delegate),
80       desktop_native_widget_aura_(desktop_native_widget_aura),
81       content_window_(NULL),
82       drag_drop_client_(NULL),
83       should_animate_window_close_(false),
84       pending_close_(false),
85       has_non_client_view_(false),
86       tooltip_(NULL),
87       need_synchronous_paint_(false),
88       in_sizing_loop_(false) {
89 }
90
91 DesktopWindowTreeHostWin::~DesktopWindowTreeHostWin() {
92   // WARNING: |content_window_| has been destroyed by the time we get here.
93   desktop_native_widget_aura_->OnDesktopWindowTreeHostDestroyed(this);
94   DestroyDispatcher();
95 }
96
97 // static
98 aura::Window* DesktopWindowTreeHostWin::GetContentWindowForHWND(HWND hwnd) {
99   aura::WindowTreeHost* host =
100       aura::WindowTreeHost::GetForAcceleratedWidget(hwnd);
101   return host ? host->window()->GetProperty(kContentWindowForRootWindow) : NULL;
102 }
103
104 // static
105 ui::NativeTheme* DesktopWindowTreeHost::GetNativeTheme(aura::Window* window) {
106   // Use NativeThemeWin for windows shown on the desktop, those not on the
107   // desktop come from Ash and get NativeThemeAura.
108   aura::WindowTreeHost* host = window ? window->GetHost() : NULL;
109   if (host) {
110     HWND host_hwnd = host->GetAcceleratedWidget();
111     if (host_hwnd &&
112         DesktopWindowTreeHostWin::GetContentWindowForHWND(host_hwnd)) {
113       return ui::NativeThemeWin::instance();
114     }
115   }
116   return ui::NativeThemeAura::instance();
117 }
118
119 ////////////////////////////////////////////////////////////////////////////////
120 // DesktopWindowTreeHostWin, DesktopWindowTreeHost implementation:
121
122 void DesktopWindowTreeHostWin::Init(aura::Window* content_window,
123                                     const Widget::InitParams& params) {
124   // TODO(beng): SetInitParams().
125   content_window_ = content_window;
126
127   aura::client::SetAnimationHost(content_window_, this);
128
129   ConfigureWindowStyles(message_handler_.get(), params,
130                         GetWidget()->widget_delegate(),
131                         native_widget_delegate_);
132
133   HWND parent_hwnd = NULL;
134   if (params.parent && params.parent->GetHost())
135     parent_hwnd = params.parent->GetHost()->GetAcceleratedWidget();
136
137   message_handler_->set_remove_standard_frame(params.remove_standard_frame);
138
139   has_non_client_view_ = Widget::RequiresNonClientView(params.type);
140
141   gfx::Rect pixel_bounds = gfx::win::DIPToScreenRect(params.bounds);
142   message_handler_->Init(parent_hwnd, pixel_bounds);
143   if (params.type == Widget::InitParams::TYPE_MENU) {
144     ::SetProp(GetAcceleratedWidget(),
145               kForceSoftwareCompositor,
146               reinterpret_cast<HANDLE>(true));
147   }
148   CreateCompositor(GetAcceleratedWidget());
149 }
150
151 void DesktopWindowTreeHostWin::OnNativeWidgetCreated(
152     const Widget::InitParams& params) {
153   // The cursor is not necessarily visible when the root window is created.
154   aura::client::CursorClient* cursor_client =
155       aura::client::GetCursorClient(window());
156   if (cursor_client)
157     is_cursor_visible_ = cursor_client->IsCursorVisible();
158
159   window()->SetProperty(kContentWindowForRootWindow, content_window_);
160   window()->SetProperty(kDesktopWindowTreeHostKey, this);
161
162   should_animate_window_close_ =
163       content_window_->type() != ui::wm::WINDOW_TYPE_NORMAL &&
164       !wm::WindowAnimationsDisabled(content_window_);
165
166 // TODO this is not invoked *after* Init(), but should be ok.
167   SetWindowTransparency();
168 }
169
170 scoped_ptr<corewm::Tooltip> DesktopWindowTreeHostWin::CreateTooltip() {
171   DCHECK(!tooltip_);
172   tooltip_ = new corewm::TooltipWin(GetAcceleratedWidget());
173   return scoped_ptr<corewm::Tooltip>(tooltip_);
174 }
175
176 scoped_ptr<aura::client::DragDropClient>
177 DesktopWindowTreeHostWin::CreateDragDropClient(
178     DesktopNativeCursorManager* cursor_manager) {
179   drag_drop_client_ = new DesktopDragDropClientWin(window(), GetHWND());
180   return scoped_ptr<aura::client::DragDropClient>(drag_drop_client_).Pass();
181 }
182
183 void DesktopWindowTreeHostWin::Close() {
184   // TODO(beng): Move this entire branch to DNWA so it can be shared with X11.
185   if (should_animate_window_close_) {
186     pending_close_ = true;
187     const bool is_animating =
188         content_window_->layer()->GetAnimator()->IsAnimatingProperty(
189             ui::LayerAnimationElement::VISIBILITY);
190     // Animation may not start for a number of reasons.
191     if (!is_animating)
192       message_handler_->Close();
193     // else case, OnWindowHidingAnimationCompleted does the actual Close.
194   } else {
195     message_handler_->Close();
196   }
197 }
198
199 void DesktopWindowTreeHostWin::CloseNow() {
200   message_handler_->CloseNow();
201 }
202
203 aura::WindowTreeHost* DesktopWindowTreeHostWin::AsWindowTreeHost() {
204   return this;
205 }
206
207 void DesktopWindowTreeHostWin::ShowWindowWithState(
208     ui::WindowShowState show_state) {
209   message_handler_->ShowWindowWithState(show_state);
210 }
211
212 void DesktopWindowTreeHostWin::ShowMaximizedWithBounds(
213     const gfx::Rect& restored_bounds) {
214   gfx::Rect pixel_bounds = gfx::win::DIPToScreenRect(restored_bounds);
215   message_handler_->ShowMaximizedWithBounds(pixel_bounds);
216 }
217
218 bool DesktopWindowTreeHostWin::IsVisible() const {
219   return message_handler_->IsVisible();
220 }
221
222 void DesktopWindowTreeHostWin::SetSize(const gfx::Size& size) {
223   gfx::Size size_in_pixels = gfx::win::DIPToScreenSize(size);
224   gfx::Size expanded = GetExpandedWindowSize(
225       message_handler_->window_ex_style(), size_in_pixels);
226   window_enlargement_ =
227       gfx::Vector2d(expanded.width() - size_in_pixels.width(),
228                     expanded.height() - size_in_pixels.height());
229   message_handler_->SetSize(expanded);
230 }
231
232 void DesktopWindowTreeHostWin::StackAtTop() {
233   message_handler_->StackAtTop();
234 }
235
236 void DesktopWindowTreeHostWin::CenterWindow(const gfx::Size& size) {
237   gfx::Size size_in_pixels = gfx::win::DIPToScreenSize(size);
238   gfx::Size expanded_size;
239   expanded_size = GetExpandedWindowSize(message_handler_->window_ex_style(),
240                                         size_in_pixels);
241   window_enlargement_ =
242       gfx::Vector2d(expanded_size.width() - size_in_pixels.width(),
243                     expanded_size.height() - size_in_pixels.height());
244   message_handler_->CenterWindow(expanded_size);
245 }
246
247 void DesktopWindowTreeHostWin::GetWindowPlacement(
248     gfx::Rect* bounds,
249     ui::WindowShowState* show_state) const {
250   message_handler_->GetWindowPlacement(bounds, show_state);
251   InsetBottomRight(bounds, window_enlargement_);
252   *bounds = gfx::win::ScreenToDIPRect(*bounds);
253 }
254
255 gfx::Rect DesktopWindowTreeHostWin::GetWindowBoundsInScreen() const {
256   gfx::Rect pixel_bounds = message_handler_->GetWindowBoundsInScreen();
257   InsetBottomRight(&pixel_bounds, window_enlargement_);
258   return gfx::win::ScreenToDIPRect(pixel_bounds);
259 }
260
261 gfx::Rect DesktopWindowTreeHostWin::GetClientAreaBoundsInScreen() const {
262   gfx::Rect pixel_bounds = message_handler_->GetClientAreaBoundsInScreen();
263   InsetBottomRight(&pixel_bounds, window_enlargement_);
264   return gfx::win::ScreenToDIPRect(pixel_bounds);
265 }
266
267 gfx::Rect DesktopWindowTreeHostWin::GetRestoredBounds() const {
268   gfx::Rect pixel_bounds = message_handler_->GetRestoredBounds();
269   InsetBottomRight(&pixel_bounds, window_enlargement_);
270   return gfx::win::ScreenToDIPRect(pixel_bounds);
271 }
272
273 gfx::Rect DesktopWindowTreeHostWin::GetWorkAreaBoundsInScreen() const {
274   MONITORINFO monitor_info;
275   monitor_info.cbSize = sizeof(monitor_info);
276   GetMonitorInfo(MonitorFromWindow(message_handler_->hwnd(),
277                                    MONITOR_DEFAULTTONEAREST),
278                  &monitor_info);
279   gfx::Rect pixel_bounds = gfx::Rect(monitor_info.rcWork);
280   return gfx::win::ScreenToDIPRect(pixel_bounds);
281 }
282
283 void DesktopWindowTreeHostWin::SetShape(gfx::NativeRegion native_region) {
284   if (native_region) {
285     // TODO(wez): This would be a lot simpler if we were passed an SkPath.
286     // See crbug.com/410593.
287     gfx::NativeRegion shape = native_region;
288     SkRegion device_region;
289     if (gfx::GetDPIScale() > 1.0) {
290       shape = &device_region;
291       const float& scale = gfx::GetDPIScale();
292       std::vector<SkIRect> rects;
293       for (SkRegion::Iterator it(*native_region); !it.done(); it.next()) {
294         const SkIRect& rect = it.rect();
295         SkRect scaled_rect =
296             SkRect::MakeLTRB(rect.left() * scale, rect.top() * scale,
297                              rect.right() * scale, rect.bottom() * scale);
298         SkIRect rounded_scaled_rect;
299         scaled_rect.roundOut(&rounded_scaled_rect);
300         rects.push_back(rounded_scaled_rect);
301       }
302       if (!rects.empty())
303         device_region.setRects(&rects[0], rects.size());
304     }
305
306     message_handler_->SetRegion(gfx::CreateHRGNFromSkRegion(*shape));
307   } else {
308     message_handler_->SetRegion(NULL);
309   }
310
311   delete native_region;
312 }
313
314 void DesktopWindowTreeHostWin::Activate() {
315   message_handler_->Activate();
316 }
317
318 void DesktopWindowTreeHostWin::Deactivate() {
319   message_handler_->Deactivate();
320 }
321
322 bool DesktopWindowTreeHostWin::IsActive() const {
323   return message_handler_->IsActive();
324 }
325
326 void DesktopWindowTreeHostWin::Maximize() {
327   message_handler_->Maximize();
328 }
329
330 void DesktopWindowTreeHostWin::Minimize() {
331   message_handler_->Minimize();
332 }
333
334 void DesktopWindowTreeHostWin::Restore() {
335   message_handler_->Restore();
336 }
337
338 bool DesktopWindowTreeHostWin::IsMaximized() const {
339   return message_handler_->IsMaximized();
340 }
341
342 bool DesktopWindowTreeHostWin::IsMinimized() const {
343   return message_handler_->IsMinimized();
344 }
345
346 bool DesktopWindowTreeHostWin::HasCapture() const {
347   return message_handler_->HasCapture();
348 }
349
350 void DesktopWindowTreeHostWin::SetAlwaysOnTop(bool always_on_top) {
351   message_handler_->SetAlwaysOnTop(always_on_top);
352 }
353
354 bool DesktopWindowTreeHostWin::IsAlwaysOnTop() const {
355   return message_handler_->IsAlwaysOnTop();
356 }
357
358 void DesktopWindowTreeHostWin::SetVisibleOnAllWorkspaces(bool always_visible) {
359   // Windows does not have the concept of workspaces.
360 }
361
362 bool DesktopWindowTreeHostWin::SetWindowTitle(const base::string16& title) {
363   return message_handler_->SetTitle(title);
364 }
365
366 void DesktopWindowTreeHostWin::ClearNativeFocus() {
367   message_handler_->ClearNativeFocus();
368 }
369
370 Widget::MoveLoopResult DesktopWindowTreeHostWin::RunMoveLoop(
371     const gfx::Vector2d& drag_offset,
372     Widget::MoveLoopSource source,
373     Widget::MoveLoopEscapeBehavior escape_behavior) {
374   const bool hide_on_escape =
375       escape_behavior == Widget::MOVE_LOOP_ESCAPE_BEHAVIOR_HIDE;
376   return message_handler_->RunMoveLoop(drag_offset, hide_on_escape) ?
377       Widget::MOVE_LOOP_SUCCESSFUL : Widget::MOVE_LOOP_CANCELED;
378 }
379
380 void DesktopWindowTreeHostWin::EndMoveLoop() {
381   message_handler_->EndMoveLoop();
382 }
383
384 void DesktopWindowTreeHostWin::SetVisibilityChangedAnimationsEnabled(
385     bool value) {
386   message_handler_->SetVisibilityChangedAnimationsEnabled(value);
387   content_window_->SetProperty(aura::client::kAnimationsDisabledKey, !value);
388 }
389
390 bool DesktopWindowTreeHostWin::ShouldUseNativeFrame() const {
391   return IsTranslucentWindowOpacitySupported();
392 }
393
394 bool DesktopWindowTreeHostWin::ShouldWindowContentsBeTransparent() const {
395   // If the window has a native frame, we assume it is an Aero Glass window, and
396   // is therefore transparent. Note: This is not equivalent to calling
397   // IsAeroGlassEnabled, because ShouldUseNativeFrame is overridden in a
398   // subclass.
399   return ShouldUseNativeFrame();
400 }
401
402 void DesktopWindowTreeHostWin::FrameTypeChanged() {
403   message_handler_->FrameTypeChanged();
404   SetWindowTransparency();
405 }
406
407 void DesktopWindowTreeHostWin::SetFullscreen(bool fullscreen) {
408   message_handler_->SetFullscreen(fullscreen);
409   // TODO(sky): workaround for ScopedFullscreenVisibility showing window
410   // directly. Instead of this should listen for visibility changes and then
411   // update window.
412   if (message_handler_->IsVisible() && !content_window_->TargetVisibility())
413     content_window_->Show();
414   SetWindowTransparency();
415 }
416
417 bool DesktopWindowTreeHostWin::IsFullscreen() const {
418   return message_handler_->fullscreen_handler()->fullscreen();
419 }
420
421 void DesktopWindowTreeHostWin::SetOpacity(unsigned char opacity) {
422   message_handler_->SetOpacity(static_cast<BYTE>(opacity));
423   content_window_->layer()->SetOpacity(opacity / 255.0);
424 }
425
426 void DesktopWindowTreeHostWin::SetWindowIcons(
427     const gfx::ImageSkia& window_icon, const gfx::ImageSkia& app_icon) {
428   message_handler_->SetWindowIcons(window_icon, app_icon);
429 }
430
431 void DesktopWindowTreeHostWin::InitModalType(ui::ModalType modal_type) {
432   message_handler_->InitModalType(modal_type);
433 }
434
435 void DesktopWindowTreeHostWin::FlashFrame(bool flash_frame) {
436   message_handler_->FlashFrame(flash_frame);
437 }
438
439 void DesktopWindowTreeHostWin::OnRootViewLayout() {
440 }
441
442 void DesktopWindowTreeHostWin::OnNativeWidgetFocus() {
443   // HWNDMessageHandler will perform the proper updating on its own.
444 }
445
446 void DesktopWindowTreeHostWin::OnNativeWidgetBlur() {
447 }
448
449 bool DesktopWindowTreeHostWin::IsAnimatingClosed() const {
450   return pending_close_;
451 }
452
453 bool DesktopWindowTreeHostWin::IsTranslucentWindowOpacitySupported() const {
454   return ui::win::IsAeroGlassEnabled();
455 }
456
457 void DesktopWindowTreeHostWin::SizeConstraintsChanged() {
458   message_handler_->SizeConstraintsChanged();
459 }
460
461 ////////////////////////////////////////////////////////////////////////////////
462 // DesktopWindowTreeHostWin, WindowTreeHost implementation:
463
464 ui::EventSource* DesktopWindowTreeHostWin::GetEventSource() {
465   return this;
466 }
467
468 gfx::AcceleratedWidget DesktopWindowTreeHostWin::GetAcceleratedWidget() {
469   return message_handler_->hwnd();
470 }
471
472 void DesktopWindowTreeHostWin::Show() {
473   message_handler_->Show();
474 }
475
476 void DesktopWindowTreeHostWin::Hide() {
477   if (!pending_close_)
478     message_handler_->Hide();
479 }
480
481 // GetBounds and SetBounds work in pixel coordinates, whereas other get/set
482 // methods work in DIP.
483
484 gfx::Rect DesktopWindowTreeHostWin::GetBounds() const {
485   gfx::Rect bounds(message_handler_->GetClientAreaBounds());
486   // If the window bounds were expanded we need to return the original bounds
487   // To achieve this we do the reverse of the expansion, i.e. add the
488   // window_expansion_top_left_delta_ to the origin and subtract the
489   // window_expansion_bottom_right_delta_ from the width and height.
490   gfx::Rect without_expansion(
491       bounds.x() + window_expansion_top_left_delta_.x(),
492       bounds.y() + window_expansion_top_left_delta_.y(),
493       bounds.width() - window_expansion_bottom_right_delta_.x() -
494           window_enlargement_.x(),
495       bounds.height() - window_expansion_bottom_right_delta_.y() -
496           window_enlargement_.y());
497   return without_expansion;
498 }
499
500 void DesktopWindowTreeHostWin::SetBounds(const gfx::Rect& bounds) {
501   // If the window bounds have to be expanded we need to subtract the
502   // window_expansion_top_left_delta_ from the origin and add the
503   // window_expansion_bottom_right_delta_ to the width and height
504   gfx::Size old_hwnd_size(message_handler_->GetClientAreaBounds().size());
505   gfx::Size old_content_size = GetBounds().size();
506
507   gfx::Rect expanded(
508       bounds.x() - window_expansion_top_left_delta_.x(),
509       bounds.y() - window_expansion_top_left_delta_.y(),
510       bounds.width() + window_expansion_bottom_right_delta_.x(),
511       bounds.height() + window_expansion_bottom_right_delta_.y());
512
513   gfx::Rect new_expanded(
514       expanded.origin(),
515       GetExpandedWindowSize(message_handler_->window_ex_style(),
516                             expanded.size()));
517   window_enlargement_ =
518       gfx::Vector2d(new_expanded.width() - expanded.width(),
519                     new_expanded.height() - expanded.height());
520   message_handler_->SetBounds(new_expanded, old_content_size != bounds.size());
521 }
522
523 gfx::Point DesktopWindowTreeHostWin::GetLocationOnNativeScreen() const {
524   return GetBounds().origin();
525 }
526
527 void DesktopWindowTreeHostWin::SetCapture() {
528   message_handler_->SetCapture();
529 }
530
531 void DesktopWindowTreeHostWin::ReleaseCapture() {
532   message_handler_->ReleaseCapture();
533 }
534
535 void DesktopWindowTreeHostWin::SetCursorNative(gfx::NativeCursor cursor) {
536   ui::CursorLoaderWin cursor_loader;
537   cursor_loader.SetPlatformCursor(&cursor);
538
539   message_handler_->SetCursor(cursor.platform());
540 }
541
542 void DesktopWindowTreeHostWin::OnCursorVisibilityChangedNative(bool show) {
543   if (is_cursor_visible_ == show)
544     return;
545   is_cursor_visible_ = show;
546   ::ShowCursor(!!show);
547 }
548
549 void DesktopWindowTreeHostWin::MoveCursorToNative(const gfx::Point& location) {
550   POINT cursor_location = location.ToPOINT();
551   ::ClientToScreen(GetHWND(), &cursor_location);
552   ::SetCursorPos(cursor_location.x, cursor_location.y);
553 }
554
555 ////////////////////////////////////////////////////////////////////////////////
556 // DesktopWindowTreeHostWin, ui::EventSource implementation:
557
558 ui::EventProcessor* DesktopWindowTreeHostWin::GetEventProcessor() {
559   return dispatcher();
560 }
561
562 ////////////////////////////////////////////////////////////////////////////////
563 // DesktopWindowTreeHostWin, aura::AnimationHost implementation:
564
565 void DesktopWindowTreeHostWin::SetHostTransitionOffsets(
566     const gfx::Vector2d& top_left_delta,
567     const gfx::Vector2d& bottom_right_delta) {
568   gfx::Rect bounds_without_expansion = GetBounds();
569   window_expansion_top_left_delta_ = top_left_delta;
570   window_expansion_bottom_right_delta_ = bottom_right_delta;
571   SetBounds(bounds_without_expansion);
572 }
573
574 void DesktopWindowTreeHostWin::OnWindowHidingAnimationCompleted() {
575   if (pending_close_)
576     message_handler_->Close();
577 }
578
579 ////////////////////////////////////////////////////////////////////////////////
580 // DesktopWindowTreeHostWin, HWNDMessageHandlerDelegate implementation:
581
582 bool DesktopWindowTreeHostWin::IsWidgetWindow() const {
583   return has_non_client_view_;
584 }
585
586 bool DesktopWindowTreeHostWin::IsUsingCustomFrame() const {
587   return !GetWidget()->ShouldUseNativeFrame();
588 }
589
590 void DesktopWindowTreeHostWin::SchedulePaint() {
591   GetWidget()->GetRootView()->SchedulePaint();
592 }
593
594 void DesktopWindowTreeHostWin::EnableInactiveRendering() {
595   native_widget_delegate_->EnableInactiveRendering();
596 }
597
598 bool DesktopWindowTreeHostWin::IsInactiveRenderingDisabled() {
599   return native_widget_delegate_->IsInactiveRenderingDisabled();
600 }
601
602 bool DesktopWindowTreeHostWin::CanResize() const {
603   return GetWidget()->widget_delegate()->CanResize();
604 }
605
606 bool DesktopWindowTreeHostWin::CanMaximize() const {
607   return GetWidget()->widget_delegate()->CanMaximize();
608 }
609
610 bool DesktopWindowTreeHostWin::CanMinimize() const {
611   return GetWidget()->widget_delegate()->CanMinimize();
612 }
613
614 bool DesktopWindowTreeHostWin::CanActivate() const {
615   if (IsModalWindowActive())
616     return true;
617   return native_widget_delegate_->CanActivate();
618 }
619
620 bool DesktopWindowTreeHostWin::WidgetSizeIsClientSize() const {
621   const Widget* widget = GetWidget()->GetTopLevelWidget();
622   return IsMaximized() || (widget && widget->ShouldUseNativeFrame());
623 }
624
625 bool DesktopWindowTreeHostWin::IsModal() const {
626   return native_widget_delegate_->IsModal();
627 }
628
629 int DesktopWindowTreeHostWin::GetInitialShowState() const {
630   return CanActivate() ? SW_SHOWNORMAL : SW_SHOWNOACTIVATE;
631 }
632
633 bool DesktopWindowTreeHostWin::WillProcessWorkAreaChange() const {
634   return GetWidget()->widget_delegate()->WillProcessWorkAreaChange();
635 }
636
637 int DesktopWindowTreeHostWin::GetNonClientComponent(
638     const gfx::Point& point) const {
639   gfx::Point dip_position = gfx::win::ScreenToDIPPoint(point);
640   return native_widget_delegate_->GetNonClientComponent(dip_position);
641 }
642
643 void DesktopWindowTreeHostWin::GetWindowMask(const gfx::Size& size,
644                                              gfx::Path* path) {
645   if (GetWidget()->non_client_view()) {
646     GetWidget()->non_client_view()->GetWindowMask(size, path);
647   } else if (!window_enlargement_.IsZero()) {
648     gfx::Rect bounds(WidgetSizeIsClientSize()
649                          ? message_handler_->GetClientAreaBoundsInScreen()
650                          : message_handler_->GetWindowBoundsInScreen());
651     InsetBottomRight(&bounds, window_enlargement_);
652     path->addRect(SkRect::MakeXYWH(0, 0, bounds.width(), bounds.height()));
653   }
654 }
655
656 bool DesktopWindowTreeHostWin::GetClientAreaInsets(gfx::Insets* insets) const {
657   return false;
658 }
659
660 void DesktopWindowTreeHostWin::GetMinMaxSize(gfx::Size* min_size,
661                                              gfx::Size* max_size) const {
662   *min_size = native_widget_delegate_->GetMinimumSize();
663   *max_size = native_widget_delegate_->GetMaximumSize();
664 }
665
666 gfx::Size DesktopWindowTreeHostWin::GetRootViewSize() const {
667   return GetWidget()->GetRootView()->size();
668 }
669
670 void DesktopWindowTreeHostWin::ResetWindowControls() {
671   GetWidget()->non_client_view()->ResetWindowControls();
672 }
673
674 void DesktopWindowTreeHostWin::PaintLayeredWindow(gfx::Canvas* canvas) {
675   GetWidget()->GetRootView()->Paint(canvas, views::CullSet());
676 }
677
678 gfx::NativeViewAccessible DesktopWindowTreeHostWin::GetNativeViewAccessible() {
679   return GetWidget()->GetRootView()->GetNativeViewAccessible();
680 }
681
682 InputMethod* DesktopWindowTreeHostWin::GetInputMethod() {
683   return GetWidget()->GetInputMethodDirect();
684 }
685
686 bool DesktopWindowTreeHostWin::ShouldHandleSystemCommands() const {
687   return GetWidget()->widget_delegate()->ShouldHandleSystemCommands();
688 }
689
690 void DesktopWindowTreeHostWin::HandleAppDeactivated() {
691   native_widget_delegate_->EnableInactiveRendering();
692 }
693
694 void DesktopWindowTreeHostWin::HandleActivationChanged(bool active) {
695   // This can be invoked from HWNDMessageHandler::Init(), at which point we're
696   // not in a good state and need to ignore it.
697   // TODO(beng): Do we need this still now the host owns the dispatcher?
698   if (!dispatcher())
699     return;
700
701   if (active)
702     OnHostActivated();
703   desktop_native_widget_aura_->HandleActivationChanged(active);
704 }
705
706 bool DesktopWindowTreeHostWin::HandleAppCommand(short command) {
707   // We treat APPCOMMAND ids as an extension of our command namespace, and just
708   // let the delegate figure out what to do...
709   return GetWidget()->widget_delegate() &&
710       GetWidget()->widget_delegate()->ExecuteWindowsCommand(command);
711 }
712
713 void DesktopWindowTreeHostWin::HandleCancelMode() {
714   dispatcher()->DispatchCancelModeEvent();
715 }
716
717 void DesktopWindowTreeHostWin::HandleCaptureLost() {
718   OnHostLostWindowCapture();
719 }
720
721 void DesktopWindowTreeHostWin::HandleClose() {
722   GetWidget()->Close();
723 }
724
725 bool DesktopWindowTreeHostWin::HandleCommand(int command) {
726   // Windows uses the 4 lower order bits of |notification_code| for type-
727   // specific information so we must exclude this when comparing.
728   static const int sc_mask = 0xFFF0;
729   switch (command & sc_mask) {
730     case SC_RESTORE:
731     case SC_MAXIMIZE:
732       need_synchronous_paint_ = true;
733       break;
734
735     case SC_SIZE:
736       in_sizing_loop_ = true;
737       break;
738
739     default:
740       break;
741   }
742   return GetWidget()->widget_delegate()->ExecuteWindowsCommand(command);
743 }
744
745 void DesktopWindowTreeHostWin::HandleAccelerator(
746     const ui::Accelerator& accelerator) {
747   GetWidget()->GetFocusManager()->ProcessAccelerator(accelerator);
748 }
749
750 void DesktopWindowTreeHostWin::HandleCreate() {
751   native_widget_delegate_->OnNativeWidgetCreated(true);
752 }
753
754 void DesktopWindowTreeHostWin::HandleDestroying() {
755   drag_drop_client_->OnNativeWidgetDestroying(GetHWND());
756   native_widget_delegate_->OnNativeWidgetDestroying();
757
758   // Destroy the compositor before destroying the HWND since shutdown
759   // may try to swap to the window.
760   DestroyCompositor();
761 }
762
763 void DesktopWindowTreeHostWin::HandleDestroyed() {
764   desktop_native_widget_aura_->OnHostClosed();
765 }
766
767 bool DesktopWindowTreeHostWin::HandleInitialFocus(
768     ui::WindowShowState show_state) {
769   return GetWidget()->SetInitialFocus(show_state);
770 }
771
772 void DesktopWindowTreeHostWin::HandleDisplayChange() {
773   GetWidget()->widget_delegate()->OnDisplayChanged();
774 }
775
776 void DesktopWindowTreeHostWin::HandleBeginWMSizeMove() {
777   if (in_sizing_loop_)
778     need_synchronous_paint_ = true;
779   native_widget_delegate_->OnNativeWidgetBeginUserBoundsChange();
780 }
781
782 void DesktopWindowTreeHostWin::HandleEndWMSizeMove() {
783   if (in_sizing_loop_) {
784     need_synchronous_paint_ = false;
785     in_sizing_loop_ = false;
786   }
787   native_widget_delegate_->OnNativeWidgetEndUserBoundsChange();
788 }
789
790 void DesktopWindowTreeHostWin::HandleMove() {
791   native_widget_delegate_->OnNativeWidgetMove();
792   OnHostMoved(GetBounds().origin());
793 }
794
795 void DesktopWindowTreeHostWin::HandleWorkAreaChanged() {
796   GetWidget()->widget_delegate()->OnWorkAreaChanged();
797 }
798
799 void DesktopWindowTreeHostWin::HandleVisibilityChanging(bool visible) {
800   native_widget_delegate_->OnNativeWidgetVisibilityChanging(visible);
801 }
802
803 void DesktopWindowTreeHostWin::HandleVisibilityChanged(bool visible) {
804   native_widget_delegate_->OnNativeWidgetVisibilityChanged(visible);
805 }
806
807 void DesktopWindowTreeHostWin::HandleClientSizeChanged(
808     const gfx::Size& new_size) {
809   if (dispatcher())
810     OnHostResized(new_size);
811 }
812
813 void DesktopWindowTreeHostWin::HandleFrameChanged() {
814   SetWindowTransparency();
815   // Replace the frame and layout the contents.
816   GetWidget()->non_client_view()->UpdateFrame();
817 }
818
819 void DesktopWindowTreeHostWin::HandleNativeFocus(HWND last_focused_window) {
820   // TODO(beng): inform the native_widget_delegate_.
821   InputMethod* input_method = GetInputMethod();
822   if (input_method)
823     input_method->OnFocus();
824 }
825
826 void DesktopWindowTreeHostWin::HandleNativeBlur(HWND focused_window) {
827   // TODO(beng): inform the native_widget_delegate_.
828   InputMethod* input_method = GetInputMethod();
829   if (input_method)
830     input_method->OnBlur();
831 }
832
833 bool DesktopWindowTreeHostWin::HandleMouseEvent(const ui::MouseEvent& event) {
834   SendEventToProcessor(const_cast<ui::MouseEvent*>(&event));
835   return event.handled();
836 }
837
838 bool DesktopWindowTreeHostWin::HandleKeyEvent(const ui::KeyEvent& event) {
839   return false;
840 }
841
842 bool DesktopWindowTreeHostWin::HandleUntranslatedKeyEvent(
843     const ui::KeyEvent& event) {
844   ui::KeyEvent duplicate_event(event);
845   SendEventToProcessor(&duplicate_event);
846   return duplicate_event.handled();
847 }
848
849 void DesktopWindowTreeHostWin::HandleTouchEvent(
850     const ui::TouchEvent& event) {
851   // HWNDMessageHandler asynchronously processes touch events. Because of this
852   // it's possible for the aura::WindowEventDispatcher to have been destroyed
853   // by the time we attempt to process them.
854   if (!GetWidget()->GetNativeView())
855     return;
856
857   // Currently we assume the window that has capture gets touch events too.
858   aura::WindowTreeHost* host =
859       aura::WindowTreeHost::GetForAcceleratedWidget(GetCapture());
860   if (host) {
861     DesktopWindowTreeHostWin* target =
862         host->window()->GetProperty(kDesktopWindowTreeHostKey);
863     if (target && target->HasCapture() && target != this) {
864       POINT target_location(event.location().ToPOINT());
865       ClientToScreen(GetHWND(), &target_location);
866       ScreenToClient(target->GetHWND(), &target_location);
867       ui::TouchEvent target_event(event, static_cast<View*>(NULL),
868                                   static_cast<View*>(NULL));
869       target_event.set_location(gfx::Point(target_location));
870       target_event.set_root_location(target_event.location());
871       target->SendEventToProcessor(&target_event);
872       return;
873     }
874   }
875   SendEventToProcessor(const_cast<ui::TouchEvent*>(&event));
876 }
877
878 bool DesktopWindowTreeHostWin::HandleIMEMessage(UINT message,
879                                                 WPARAM w_param,
880                                                 LPARAM l_param,
881                                                 LRESULT* result) {
882   MSG msg = {};
883   msg.hwnd = GetHWND();
884   msg.message = message;
885   msg.wParam = w_param;
886   msg.lParam = l_param;
887   return desktop_native_widget_aura_->input_method_event_filter()->
888       input_method()->OnUntranslatedIMEMessage(msg, result);
889 }
890
891 void DesktopWindowTreeHostWin::HandleInputLanguageChange(
892     DWORD character_set,
893     HKL input_language_id) {
894   desktop_native_widget_aura_->input_method_event_filter()->
895       input_method()->OnInputLocaleChanged();
896 }
897
898 bool DesktopWindowTreeHostWin::HandlePaintAccelerated(
899     const gfx::Rect& invalid_rect) {
900   return native_widget_delegate_->OnNativeWidgetPaintAccelerated(invalid_rect);
901 }
902
903 void DesktopWindowTreeHostWin::HandlePaint(gfx::Canvas* canvas) {
904   // It appears possible to get WM_PAINT after WM_DESTROY.
905   if (compositor())
906     compositor()->ScheduleRedrawRect(gfx::Rect());
907 }
908
909 bool DesktopWindowTreeHostWin::HandleTooltipNotify(int w_param,
910                                                    NMHDR* l_param,
911                                                    LRESULT* l_result) {
912   return tooltip_ && tooltip_->HandleNotify(w_param, l_param, l_result);
913 }
914
915 void DesktopWindowTreeHostWin::HandleMenuLoop(bool in_menu_loop) {
916   if (in_menu_loop) {
917     tooltip_disabler_.reset(
918         new aura::client::ScopedTooltipDisabler(window()));
919   } else {
920     tooltip_disabler_.reset();
921   }
922 }
923
924 bool DesktopWindowTreeHostWin::PreHandleMSG(UINT message,
925                                             WPARAM w_param,
926                                             LPARAM l_param,
927                                             LRESULT* result) {
928   return false;
929 }
930
931 void DesktopWindowTreeHostWin::PostHandleMSG(UINT message,
932                                              WPARAM w_param,
933                                              LPARAM l_param) {
934 }
935
936 bool DesktopWindowTreeHostWin::HandleScrollEvent(
937     const ui::ScrollEvent& event) {
938   SendEventToProcessor(const_cast<ui::ScrollEvent*>(&event));
939   return event.handled();
940 }
941
942 void DesktopWindowTreeHostWin::HandleWindowSizeChanging() {
943   if (compositor() && need_synchronous_paint_) {
944     compositor()->FinishAllRendering();
945     // If we received the window size changing notification due to a restore or
946     // maximize operation, then we can reset the need_synchronous_paint_ flag
947     // here. For a sizing operation, the flag will be reset at the end of the
948     // operation.
949     if (!in_sizing_loop_)
950       need_synchronous_paint_ = false;
951   }
952 }
953
954 ////////////////////////////////////////////////////////////////////////////////
955 // DesktopWindowTreeHostWin, private:
956
957 Widget* DesktopWindowTreeHostWin::GetWidget() {
958   return native_widget_delegate_->AsWidget();
959 }
960
961 const Widget* DesktopWindowTreeHostWin::GetWidget() const {
962   return native_widget_delegate_->AsWidget();
963 }
964
965 HWND DesktopWindowTreeHostWin::GetHWND() const {
966   return message_handler_->hwnd();
967 }
968
969 void DesktopWindowTreeHostWin::SetWindowTransparency() {
970   bool transparent = ShouldUseNativeFrame() && !IsFullscreen();
971   compositor()->SetHostHasTransparentBackground(transparent);
972   window()->SetTransparent(transparent);
973   content_window_->SetTransparent(transparent);
974 }
975
976 bool DesktopWindowTreeHostWin::IsModalWindowActive() const {
977   // This function can get called during window creation which occurs before
978   // dispatcher() has been created.
979   if (!dispatcher())
980     return false;
981
982   aura::Window::Windows::const_iterator index;
983   for (index = window()->children().begin();
984        index != window()->children().end();
985        ++index) {
986     if ((*index)->GetProperty(aura::client::kModalKey) !=
987         ui:: MODAL_TYPE_NONE && (*index)->TargetVisibility())
988       return true;
989   }
990   return false;
991 }
992
993 ////////////////////////////////////////////////////////////////////////////////
994 // DesktopWindowTreeHost, public:
995
996 // static
997 DesktopWindowTreeHost* DesktopWindowTreeHost::Create(
998     internal::NativeWidgetDelegate* native_widget_delegate,
999     DesktopNativeWidgetAura* desktop_native_widget_aura) {
1000   return new DesktopWindowTreeHostWin(native_widget_delegate,
1001                                       desktop_native_widget_aura);
1002 }
1003
1004 }  // namespace views