Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / ash / wm / workspace / workspace_window_resizer.cc
blob75fedaa35a9b9623fd849e3d2f1fa867d9fdd484
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 "ash/wm/workspace/workspace_window_resizer.h"
7 #include <algorithm>
8 #include <cmath>
9 #include <utility>
10 #include <vector>
12 #include "ash/ash_switches.h"
13 #include "ash/display/display_controller.h"
14 #include "ash/metrics/user_metrics_recorder.h"
15 #include "ash/root_window_controller.h"
16 #include "ash/screen_util.h"
17 #include "ash/shell.h"
18 #include "ash/shell_window_ids.h"
19 #include "ash/wm/coordinate_conversion.h"
20 #include "ash/wm/default_window_resizer.h"
21 #include "ash/wm/dock/docked_window_layout_manager.h"
22 #include "ash/wm/dock/docked_window_resizer.h"
23 #include "ash/wm/drag_window_resizer.h"
24 #include "ash/wm/panels/panel_window_resizer.h"
25 #include "ash/wm/window_state.h"
26 #include "ash/wm/window_util.h"
27 #include "ash/wm/wm_event.h"
28 #include "ash/wm/workspace/phantom_window_controller.h"
29 #include "ash/wm/workspace/two_step_edge_cycler.h"
30 #include "base/command_line.h"
31 #include "base/memory/weak_ptr.h"
32 #include "ui/aura/client/aura_constants.h"
33 #include "ui/aura/client/screen_position_client.h"
34 #include "ui/aura/window.h"
35 #include "ui/aura/window_delegate.h"
36 #include "ui/aura/window_event_dispatcher.h"
37 #include "ui/base/hit_test.h"
38 #include "ui/compositor/layer.h"
39 #include "ui/gfx/screen.h"
40 #include "ui/gfx/transform.h"
41 #include "ui/wm/core/window_util.h"
42 #include "ui/wm/public/window_types.h"
44 namespace ash {
46 scoped_ptr<WindowResizer> CreateWindowResizer(
47 aura::Window* window,
48 const gfx::Point& point_in_parent,
49 int window_component,
50 aura::client::WindowMoveSource source) {
51 DCHECK(window);
52 wm::WindowState* window_state = wm::GetWindowState(window);
53 // No need to return a resizer when the window cannot get resized or when a
54 // resizer already exists for this window.
55 if ((!window_state->CanResize() && window_component != HTCAPTION) ||
56 window_state->drag_details()) {
57 return scoped_ptr<WindowResizer>();
60 if (window_component == HTCAPTION && !window_state->can_be_dragged())
61 return scoped_ptr<WindowResizer>();
63 // TODO(varkha): The chaining of window resizers causes some of the logic
64 // to be repeated and the logic flow difficult to control. With some windows
65 // classes using reparenting during drag operations it becomes challenging to
66 // implement proper transition from one resizer to another during or at the
67 // end of the drag. This also causes http://crbug.com/247085.
68 // It seems the only thing the panel or dock resizer needs to do is notify the
69 // layout manager when a docked window is being dragged. We should have a
70 // better way of doing this, perhaps by having a way of observing drags or
71 // having a generic drag window wrapper which informs a layout manager that a
72 // drag has started or stopped.
73 // It may be possible to refactor and eliminate chaining.
74 WindowResizer* window_resizer = NULL;
76 if (!window_state->IsNormalOrSnapped())
77 return scoped_ptr<WindowResizer>();
79 int bounds_change = WindowResizer::GetBoundsChangeForWindowComponent(
80 window_component);
81 if (bounds_change == WindowResizer::kBoundsChangeDirection_None)
82 return scoped_ptr<WindowResizer>();
84 window_state->CreateDragDetails(window, point_in_parent, window_component,
85 source);
86 if (window->parent() &&
87 (window->parent()->id() == kShellWindowId_DefaultContainer ||
88 window->parent()->id() == kShellWindowId_DockedContainer ||
89 window->parent()->id() == kShellWindowId_PanelContainer)) {
90 window_resizer = WorkspaceWindowResizer::Create(
91 window_state, std::vector<aura::Window*>());
92 } else {
93 window_resizer = DefaultWindowResizer::Create(window_state);
95 window_resizer = DragWindowResizer::Create(window_resizer, window_state);
96 if (window->type() == ui::wm::WINDOW_TYPE_PANEL)
97 window_resizer = PanelWindowResizer::Create(window_resizer, window_state);
98 if (switches::UseDockedWindows() && window_resizer && window->parent() &&
99 !::wm::GetTransientParent(window) &&
100 (window->parent()->id() == kShellWindowId_DefaultContainer ||
101 window->parent()->id() == kShellWindowId_DockedContainer ||
102 window->parent()->id() == kShellWindowId_PanelContainer)) {
103 window_resizer = DockedWindowResizer::Create(window_resizer, window_state);
105 return make_scoped_ptr<WindowResizer>(window_resizer);
108 namespace {
110 // Snapping distance used instead of WorkspaceWindowResizer::kScreenEdgeInset
111 // when resizing a window using touchscreen.
112 const int kScreenEdgeInsetForTouchDrag = 32;
114 // Returns true if the window should stick to the edge.
115 bool ShouldStickToEdge(int distance_from_edge, int sticky_size) {
116 return distance_from_edge < sticky_size &&
117 distance_from_edge > -sticky_size * 2;
120 // Returns the coordinate along the secondary axis to snap to.
121 int CoordinateAlongSecondaryAxis(SecondaryMagnetismEdge edge,
122 int leading,
123 int trailing,
124 int none) {
125 switch (edge) {
126 case SECONDARY_MAGNETISM_EDGE_LEADING:
127 return leading;
128 case SECONDARY_MAGNETISM_EDGE_TRAILING:
129 return trailing;
130 case SECONDARY_MAGNETISM_EDGE_NONE:
131 return none;
133 NOTREACHED();
134 return none;
137 // Returns the origin for |src| when magnetically attaching to |attach_to| along
138 // the edges |edges|. |edges| is a bitmask of the MagnetismEdges.
139 gfx::Point OriginForMagneticAttach(const gfx::Rect& src,
140 const gfx::Rect& attach_to,
141 const MatchedEdge& edge) {
142 int x = 0, y = 0;
143 switch (edge.primary_edge) {
144 case MAGNETISM_EDGE_TOP:
145 y = attach_to.bottom();
146 break;
147 case MAGNETISM_EDGE_LEFT:
148 x = attach_to.right();
149 break;
150 case MAGNETISM_EDGE_BOTTOM:
151 y = attach_to.y() - src.height();
152 break;
153 case MAGNETISM_EDGE_RIGHT:
154 x = attach_to.x() - src.width();
155 break;
157 switch (edge.primary_edge) {
158 case MAGNETISM_EDGE_TOP:
159 case MAGNETISM_EDGE_BOTTOM:
160 x = CoordinateAlongSecondaryAxis(
161 edge.secondary_edge, attach_to.x(), attach_to.right() - src.width(),
162 src.x());
163 break;
164 case MAGNETISM_EDGE_LEFT:
165 case MAGNETISM_EDGE_RIGHT:
166 y = CoordinateAlongSecondaryAxis(
167 edge.secondary_edge, attach_to.y(), attach_to.bottom() - src.height(),
168 src.y());
169 break;
171 return gfx::Point(x, y);
174 // Returns the bounds for a magnetic attach when resizing. |src| is the bounds
175 // of window being resized, |attach_to| the bounds of the window to attach to
176 // and |edge| identifies the edge to attach to.
177 gfx::Rect BoundsForMagneticResizeAttach(const gfx::Rect& src,
178 const gfx::Rect& attach_to,
179 const MatchedEdge& edge) {
180 int x = src.x();
181 int y = src.y();
182 int w = src.width();
183 int h = src.height();
184 gfx::Point attach_origin(OriginForMagneticAttach(src, attach_to, edge));
185 switch (edge.primary_edge) {
186 case MAGNETISM_EDGE_LEFT:
187 x = attach_origin.x();
188 w = src.right() - x;
189 break;
190 case MAGNETISM_EDGE_RIGHT:
191 w += attach_origin.x() - src.x();
192 break;
193 case MAGNETISM_EDGE_TOP:
194 y = attach_origin.y();
195 h = src.bottom() - y;
196 break;
197 case MAGNETISM_EDGE_BOTTOM:
198 h += attach_origin.y() - src.y();
199 break;
201 switch (edge.primary_edge) {
202 case MAGNETISM_EDGE_LEFT:
203 case MAGNETISM_EDGE_RIGHT:
204 if (edge.secondary_edge == SECONDARY_MAGNETISM_EDGE_LEADING) {
205 y = attach_origin.y();
206 h = src.bottom() - y;
207 } else if (edge.secondary_edge == SECONDARY_MAGNETISM_EDGE_TRAILING) {
208 h += attach_origin.y() - src.y();
210 break;
211 case MAGNETISM_EDGE_TOP:
212 case MAGNETISM_EDGE_BOTTOM:
213 if (edge.secondary_edge == SECONDARY_MAGNETISM_EDGE_LEADING) {
214 x = attach_origin.x();
215 w = src.right() - x;
216 } else if (edge.secondary_edge == SECONDARY_MAGNETISM_EDGE_TRAILING) {
217 w += attach_origin.x() - src.x();
219 break;
221 return gfx::Rect(x, y, w, h);
224 // Converts a window component edge to the magnetic edge to snap to.
225 uint32 WindowComponentToMagneticEdge(int window_component) {
226 switch (window_component) {
227 case HTTOPLEFT:
228 return MAGNETISM_EDGE_LEFT | MAGNETISM_EDGE_TOP;
229 case HTTOPRIGHT:
230 return MAGNETISM_EDGE_TOP | MAGNETISM_EDGE_RIGHT;
231 case HTBOTTOMLEFT:
232 return MAGNETISM_EDGE_LEFT | MAGNETISM_EDGE_BOTTOM;
233 case HTBOTTOMRIGHT:
234 return MAGNETISM_EDGE_RIGHT | MAGNETISM_EDGE_BOTTOM;
235 case HTTOP:
236 return MAGNETISM_EDGE_TOP;
237 case HTBOTTOM:
238 return MAGNETISM_EDGE_BOTTOM;
239 case HTRIGHT:
240 return MAGNETISM_EDGE_RIGHT;
241 case HTLEFT:
242 return MAGNETISM_EDGE_LEFT;
243 default:
244 break;
246 return 0;
249 } // namespace
251 // static
252 const int WorkspaceWindowResizer::kMinOnscreenSize = 20;
254 // static
255 const int WorkspaceWindowResizer::kMinOnscreenHeight = 32;
257 // static
258 const int WorkspaceWindowResizer::kScreenEdgeInset = 8;
260 // static
261 WorkspaceWindowResizer* WorkspaceWindowResizer::instance_ = NULL;
263 // Represents the width or height of a window with constraints on its minimum
264 // and maximum size. 0 represents a lack of a constraint.
265 class WindowSize {
266 public:
267 WindowSize(int size, int min, int max)
268 : size_(size),
269 min_(min),
270 max_(max) {
271 // Grow the min/max bounds to include the starting size.
272 if (is_underflowing())
273 min_ = size_;
274 if (is_overflowing())
275 max_ = size_;
278 bool is_at_capacity(bool shrinking) {
279 return size_ == (shrinking ? min_ : max_);
282 int size() const {
283 return size_;
286 bool has_min() const {
287 return min_ != 0;
290 bool has_max() const {
291 return max_ != 0;
294 bool is_valid() const {
295 return !is_overflowing() && !is_underflowing();
298 bool is_overflowing() const {
299 return has_max() && size_ > max_;
302 bool is_underflowing() const {
303 return has_min() && size_ < min_;
306 // Add |amount| to this WindowSize not exceeding min or max size constraints.
307 // Returns by how much |size_| + |amount| exceeds the min/max constraints.
308 int Add(int amount) {
309 DCHECK(is_valid());
310 int new_value = size_ + amount;
312 if (has_min() && new_value < min_) {
313 size_ = min_;
314 return new_value - min_;
317 if (has_max() && new_value > max_) {
318 size_ = max_;
319 return new_value - max_;
322 size_ = new_value;
323 return 0;
326 private:
327 int size_;
328 int min_;
329 int max_;
332 WorkspaceWindowResizer::~WorkspaceWindowResizer() {
333 if (did_lock_cursor_) {
334 Shell* shell = Shell::GetInstance();
335 shell->cursor_manager()->UnlockCursor();
337 if (instance_ == this)
338 instance_ = NULL;
341 // static
342 WorkspaceWindowResizer* WorkspaceWindowResizer::Create(
343 wm::WindowState* window_state,
344 const std::vector<aura::Window*>& attached_windows) {
345 return new WorkspaceWindowResizer(window_state, attached_windows);
348 void WorkspaceWindowResizer::Drag(const gfx::Point& location_in_parent,
349 int event_flags) {
350 last_mouse_location_ = location_in_parent;
352 int sticky_size;
353 if (event_flags & ui::EF_CONTROL_DOWN) {
354 sticky_size = 0;
355 } else if ((details().bounds_change & kBoundsChange_Resizes) &&
356 details().source == aura::client::WINDOW_MOVE_SOURCE_TOUCH) {
357 sticky_size = kScreenEdgeInsetForTouchDrag;
358 } else {
359 sticky_size = kScreenEdgeInset;
361 // |bounds| is in |GetTarget()->parent()|'s coordinates.
362 gfx::Rect bounds = CalculateBoundsForDrag(location_in_parent);
363 AdjustBoundsForMainWindow(sticky_size, &bounds);
365 if (bounds != GetTarget()->bounds()) {
366 if (!did_move_or_resize_) {
367 if (!details().restore_bounds.IsEmpty())
368 window_state()->ClearRestoreBounds();
369 RestackWindows();
371 did_move_or_resize_ = true;
374 gfx::Point location_in_screen = location_in_parent;
375 wm::ConvertPointToScreen(GetTarget()->parent(), &location_in_screen);
377 aura::Window* root = NULL;
378 gfx::Display display =
379 ScreenUtil::FindDisplayContainingPoint(location_in_screen);
380 // Track the last screen that the pointer was on to keep the snap phantom
381 // window there.
382 if (display.is_valid()) {
383 root = Shell::GetInstance()->display_controller()->
384 GetRootWindowForDisplayId(display.id());
386 if (!attached_windows_.empty())
387 LayoutAttachedWindows(&bounds);
388 if (bounds != GetTarget()->bounds()) {
389 // SetBounds needs to be called to update the layout which affects where the
390 // phantom window is drawn. Keep track if the window was destroyed during
391 // the drag and quit early if so.
392 base::WeakPtr<WorkspaceWindowResizer> resizer(
393 weak_ptr_factory_.GetWeakPtr());
394 GetTarget()->SetBounds(bounds);
395 if (!resizer)
396 return;
398 const bool in_original_root = !root || root == GetTarget()->GetRootWindow();
399 // Hide a phantom window for snapping if the cursor is in another root window.
400 if (in_original_root) {
401 UpdateSnapPhantomWindow(location_in_parent, bounds);
402 } else {
403 snap_type_ = SNAP_NONE;
404 snap_phantom_window_controller_.reset();
405 edge_cycler_.reset();
406 SetDraggedWindowDocked(false);
410 void WorkspaceWindowResizer::CompleteDrag() {
411 if (!did_move_or_resize_)
412 return;
414 window_state()->set_bounds_changed_by_user(true);
415 snap_phantom_window_controller_.reset();
417 // If the window's state type changed over the course of the drag do not snap
418 // the window. This happens when the user minimizes or maximizes the window
419 // using a keyboard shortcut while dragging it.
420 if (window_state()->GetStateType() != details().initial_state_type)
421 return;
423 bool snapped = false;
424 if (snap_type_ == SNAP_LEFT || snap_type_ == SNAP_RIGHT) {
425 if (!window_state()->HasRestoreBounds()) {
426 gfx::Rect initial_bounds = ScreenUtil::ConvertRectToScreen(
427 GetTarget()->parent(), details().initial_bounds_in_parent);
428 window_state()->SetRestoreBoundsInScreen(
429 details().restore_bounds.IsEmpty() ?
430 initial_bounds :
431 details().restore_bounds);
433 if (!dock_layout_->is_dragged_window_docked()) {
434 UserMetricsRecorder* metrics = Shell::GetInstance()->metrics();
435 // TODO(oshima): Add event source type to WMEvent and move
436 // metrics recording inside WindowState::OnWMEvent.
437 const wm::WMEvent event(snap_type_ == SNAP_LEFT ?
438 wm::WM_EVENT_SNAP_LEFT : wm::WM_EVENT_SNAP_RIGHT);
439 window_state()->OnWMEvent(&event);
440 metrics->RecordUserMetricsAction(
441 snap_type_ == SNAP_LEFT ?
442 UMA_DRAG_MAXIMIZE_LEFT : UMA_DRAG_MAXIMIZE_RIGHT);
443 snapped = true;
447 if (!snapped && window_state()->IsSnapped()) {
448 // Keep the window snapped if the user resizes the window such that the
449 // window has valid bounds for a snapped window. Always unsnap the window
450 // if the user dragged the window via the caption area because doing this is
451 // slightly less confusing.
452 if (details().window_component == HTCAPTION ||
453 !AreBoundsValidSnappedBounds(window_state()->GetStateType(),
454 GetTarget()->bounds())) {
455 // Set the window to WINDOW_STATE_TYPE_NORMAL but keep the
456 // window at the bounds that the user has moved/resized the
457 // window to. ClearRestoreBounds() is used instead of
458 // SaveCurrentBoundsForRestore() because most of the restore
459 // logic is skipped because we are still in the middle of a
460 // drag. TODO(pkotwicz): Fix this and use
461 // SaveCurrentBoundsForRestore().
462 window_state()->ClearRestoreBounds();
463 window_state()->Restore();
468 void WorkspaceWindowResizer::RevertDrag() {
469 window_state()->set_bounds_changed_by_user(initial_bounds_changed_by_user_);
470 snap_phantom_window_controller_.reset();
472 if (!did_move_or_resize_)
473 return;
475 GetTarget()->SetBounds(details().initial_bounds_in_parent);
476 if (!details().restore_bounds.IsEmpty()) {
477 window_state()->SetRestoreBoundsInScreen(details().restore_bounds);
480 if (details().window_component == HTRIGHT) {
481 int last_x = details().initial_bounds_in_parent.right();
482 for (size_t i = 0; i < attached_windows_.size(); ++i) {
483 gfx::Rect bounds(attached_windows_[i]->bounds());
484 bounds.set_x(last_x);
485 bounds.set_width(initial_size_[i]);
486 attached_windows_[i]->SetBounds(bounds);
487 last_x = attached_windows_[i]->bounds().right();
489 } else {
490 int last_y = details().initial_bounds_in_parent.bottom();
491 for (size_t i = 0; i < attached_windows_.size(); ++i) {
492 gfx::Rect bounds(attached_windows_[i]->bounds());
493 bounds.set_y(last_y);
494 bounds.set_height(initial_size_[i]);
495 attached_windows_[i]->SetBounds(bounds);
496 last_y = attached_windows_[i]->bounds().bottom();
501 WorkspaceWindowResizer::WorkspaceWindowResizer(
502 wm::WindowState* window_state,
503 const std::vector<aura::Window*>& attached_windows)
504 : WindowResizer(window_state),
505 attached_windows_(attached_windows),
506 did_lock_cursor_(false),
507 did_move_or_resize_(false),
508 initial_bounds_changed_by_user_(window_state_->bounds_changed_by_user()),
509 total_min_(0),
510 total_initial_size_(0),
511 snap_type_(SNAP_NONE),
512 num_mouse_moves_since_bounds_change_(0),
513 magnetism_window_(NULL),
514 weak_ptr_factory_(this) {
515 DCHECK(details().is_resizable);
517 // A mousemove should still show the cursor even if the window is
518 // being moved or resized with touch, so do not lock the cursor.
519 if (details().source != aura::client::WINDOW_MOVE_SOURCE_TOUCH) {
520 Shell* shell = Shell::GetInstance();
521 shell->cursor_manager()->LockCursor();
522 did_lock_cursor_ = true;
525 aura::Window* dock_container = Shell::GetContainer(
526 GetTarget()->GetRootWindow(), kShellWindowId_DockedContainer);
527 dock_layout_ = static_cast<DockedWindowLayoutManager*>(
528 dock_container->layout_manager());
530 // Only support attaching to the right/bottom.
531 DCHECK(attached_windows_.empty() ||
532 (details().window_component == HTRIGHT ||
533 details().window_component == HTBOTTOM));
535 // TODO: figure out how to deal with window going off the edge.
537 // Calculate sizes so that we can maintain the ratios if we need to resize.
538 int total_available = 0;
539 for (size_t i = 0; i < attached_windows_.size(); ++i) {
540 gfx::Size min(attached_windows_[i]->delegate()->GetMinimumSize());
541 int initial_size = PrimaryAxisSize(attached_windows_[i]->bounds().size());
542 initial_size_.push_back(initial_size);
543 // If current size is smaller than the min, use the current size as the min.
544 // This way we don't snap on resize.
545 int min_size = std::min(initial_size,
546 std::max(PrimaryAxisSize(min), kMinOnscreenSize));
547 total_min_ += min_size;
548 total_initial_size_ += initial_size;
549 total_available += std::max(min_size, initial_size) - min_size;
551 instance_ = this;
554 void WorkspaceWindowResizer::LayoutAttachedWindows(
555 gfx::Rect* bounds) {
556 gfx::Rect work_area(ScreenUtil::GetDisplayWorkAreaBoundsInParent(
557 GetTarget()));
558 int initial_size = PrimaryAxisSize(details().initial_bounds_in_parent.size());
559 int current_size = PrimaryAxisSize(bounds->size());
560 int start = PrimaryAxisCoordinate(bounds->right(), bounds->bottom());
561 int end = PrimaryAxisCoordinate(work_area.right(), work_area.bottom());
563 int delta = current_size - initial_size;
564 int available_size = end - start;
565 std::vector<int> sizes;
566 int leftovers = CalculateAttachedSizes(delta, available_size, &sizes);
568 // leftovers > 0 means that the attached windows can't grow to compensate for
569 // the shrinkage of the main window. This line causes the attached windows to
570 // be moved so they are still flush against the main window, rather than the
571 // main window being prevented from shrinking.
572 leftovers = std::min(0, leftovers);
573 // Reallocate any leftover pixels back into the main window. This is
574 // necessary when, for example, the main window shrinks, but none of the
575 // attached windows can grow without exceeding their max size constraints.
576 // Adding the pixels back to the main window effectively prevents the main
577 // window from resizing too far.
578 if (details().window_component == HTRIGHT)
579 bounds->set_width(bounds->width() + leftovers);
580 else
581 bounds->set_height(bounds->height() + leftovers);
583 DCHECK_EQ(attached_windows_.size(), sizes.size());
584 int last = PrimaryAxisCoordinate(bounds->right(), bounds->bottom());
585 for (size_t i = 0; i < attached_windows_.size(); ++i) {
586 gfx::Rect attached_bounds(attached_windows_[i]->bounds());
587 if (details().window_component == HTRIGHT) {
588 attached_bounds.set_x(last);
589 attached_bounds.set_width(sizes[i]);
590 } else {
591 attached_bounds.set_y(last);
592 attached_bounds.set_height(sizes[i]);
594 attached_windows_[i]->SetBounds(attached_bounds);
595 last += sizes[i];
599 int WorkspaceWindowResizer::CalculateAttachedSizes(
600 int delta,
601 int available_size,
602 std::vector<int>* sizes) const {
603 std::vector<WindowSize> window_sizes;
604 CreateBucketsForAttached(&window_sizes);
606 // How much we need to grow the attached by (collectively).
607 int grow_attached_by = 0;
608 if (delta > 0) {
609 // If the attached windows don't fit when at their initial size, we will
610 // have to shrink them by how much they overflow.
611 if (total_initial_size_ >= available_size)
612 grow_attached_by = available_size - total_initial_size_;
613 } else {
614 // If we're shrinking, we grow the attached so the total size remains
615 // constant.
616 grow_attached_by = -delta;
619 int leftover_pixels = 0;
620 while (grow_attached_by != 0) {
621 int leftovers = GrowFairly(grow_attached_by, window_sizes);
622 if (leftovers == grow_attached_by) {
623 leftover_pixels = leftovers;
624 break;
626 grow_attached_by = leftovers;
629 for (size_t i = 0; i < window_sizes.size(); ++i)
630 sizes->push_back(window_sizes[i].size());
632 return leftover_pixels;
635 int WorkspaceWindowResizer::GrowFairly(
636 int pixels,
637 std::vector<WindowSize>& sizes) const {
638 bool shrinking = pixels < 0;
639 std::vector<WindowSize*> nonfull_windows;
640 for (size_t i = 0; i < sizes.size(); ++i) {
641 if (!sizes[i].is_at_capacity(shrinking))
642 nonfull_windows.push_back(&sizes[i]);
644 std::vector<float> ratios;
645 CalculateGrowthRatios(nonfull_windows, &ratios);
647 int remaining_pixels = pixels;
648 bool add_leftover_pixels_to_last = true;
649 for (size_t i = 0; i < nonfull_windows.size(); ++i) {
650 int grow_by = pixels * ratios[i];
651 // Put any leftover pixels into the last window.
652 if (i == nonfull_windows.size() - 1 && add_leftover_pixels_to_last)
653 grow_by = remaining_pixels;
654 int remainder = nonfull_windows[i]->Add(grow_by);
655 int consumed = grow_by - remainder;
656 remaining_pixels -= consumed;
657 if (nonfull_windows[i]->is_at_capacity(shrinking) && remainder > 0) {
658 // Because this window overflowed, some of the pixels in
659 // |remaining_pixels| aren't there due to rounding errors. Rather than
660 // unfairly giving all those pixels to the last window, we refrain from
661 // allocating them so that this function can be called again to distribute
662 // the pixels fairly.
663 add_leftover_pixels_to_last = false;
666 return remaining_pixels;
669 void WorkspaceWindowResizer::CalculateGrowthRatios(
670 const std::vector<WindowSize*>& sizes,
671 std::vector<float>* out_ratios) const {
672 DCHECK(out_ratios->empty());
673 int total_value = 0;
674 for (size_t i = 0; i < sizes.size(); ++i)
675 total_value += sizes[i]->size();
677 for (size_t i = 0; i < sizes.size(); ++i)
678 out_ratios->push_back(
679 (static_cast<float>(sizes[i]->size())) / total_value);
682 void WorkspaceWindowResizer::CreateBucketsForAttached(
683 std::vector<WindowSize>* sizes) const {
684 for (size_t i = 0; i < attached_windows_.size(); i++) {
685 int initial_size = initial_size_[i];
686 aura::WindowDelegate* delegate = attached_windows_[i]->delegate();
687 int min = PrimaryAxisSize(delegate->GetMinimumSize());
688 int max = PrimaryAxisSize(delegate->GetMaximumSize());
690 sizes->push_back(WindowSize(initial_size, min, max));
694 void WorkspaceWindowResizer::MagneticallySnapToOtherWindows(gfx::Rect* bounds) {
695 if (UpdateMagnetismWindow(*bounds, kAllMagnetismEdges)) {
696 gfx::Point point = OriginForMagneticAttach(
697 ScreenUtil::ConvertRectToScreen(GetTarget()->parent(), *bounds),
698 magnetism_window_->GetBoundsInScreen(),
699 magnetism_edge_);
700 aura::client::GetScreenPositionClient(GetTarget()->GetRootWindow())->
701 ConvertPointFromScreen(GetTarget()->parent(), &point);
702 bounds->set_origin(point);
706 void WorkspaceWindowResizer::MagneticallySnapResizeToOtherWindows(
707 gfx::Rect* bounds) {
708 const uint32 edges = WindowComponentToMagneticEdge(
709 details().window_component);
710 if (UpdateMagnetismWindow(*bounds, edges)) {
711 *bounds = ScreenUtil::ConvertRectFromScreen(
712 GetTarget()->parent(),
713 BoundsForMagneticResizeAttach(
714 ScreenUtil::ConvertRectToScreen(GetTarget()->parent(), *bounds),
715 magnetism_window_->GetBoundsInScreen(),
716 magnetism_edge_));
720 bool WorkspaceWindowResizer::UpdateMagnetismWindow(const gfx::Rect& bounds,
721 uint32 edges) {
722 // |bounds| are in coordinates of original window's parent.
723 gfx::Rect bounds_in_screen =
724 ScreenUtil::ConvertRectToScreen(GetTarget()->parent(), bounds);
725 MagnetismMatcher matcher(bounds_in_screen, edges);
727 // If we snapped to a window then check it first. That way we don't bounce
728 // around when close to multiple edges.
729 if (magnetism_window_) {
730 if (window_tracker_.Contains(magnetism_window_) &&
731 matcher.ShouldAttach(magnetism_window_->GetBoundsInScreen(),
732 &magnetism_edge_)) {
733 return true;
735 window_tracker_.Remove(magnetism_window_);
736 magnetism_window_ = NULL;
739 // Avoid magnetically snapping windows that are not resizable.
740 // TODO(oshima): change this to window.type() == TYPE_NORMAL.
741 if (!window_state()->CanResize())
742 return false;
744 aura::Window::Windows root_windows = Shell::GetAllRootWindows();
745 for (aura::Window::Windows::iterator iter = root_windows.begin();
746 iter != root_windows.end(); ++iter) {
747 const aura::Window* root_window = *iter;
748 // Test all children from the desktop in each root window.
749 const aura::Window::Windows& children = Shell::GetContainer(
750 root_window, kShellWindowId_DefaultContainer)->children();
751 for (aura::Window::Windows::const_reverse_iterator i = children.rbegin();
752 i != children.rend() && !matcher.AreEdgesObscured(); ++i) {
753 wm::WindowState* other_state = wm::GetWindowState(*i);
754 if (other_state->window() == GetTarget() ||
755 !other_state->window()->IsVisible() ||
756 !other_state->IsNormalOrSnapped() ||
757 !other_state->CanResize()) {
758 continue;
760 if (matcher.ShouldAttach(
761 other_state->window()->GetBoundsInScreen(), &magnetism_edge_)) {
762 magnetism_window_ = other_state->window();
763 window_tracker_.Add(magnetism_window_);
764 return true;
768 return false;
771 void WorkspaceWindowResizer::AdjustBoundsForMainWindow(
772 int sticky_size,
773 gfx::Rect* bounds) {
774 gfx::Point last_mouse_location_in_screen = last_mouse_location_;
775 wm::ConvertPointToScreen(GetTarget()->parent(),
776 &last_mouse_location_in_screen);
777 gfx::Display display = Shell::GetScreen()->GetDisplayNearestPoint(
778 last_mouse_location_in_screen);
779 gfx::Rect work_area =
780 ScreenUtil::ConvertRectFromScreen(GetTarget()->parent(),
781 display.work_area());
782 if (details().window_component == HTCAPTION) {
783 // Adjust the bounds to the work area where the mouse cursor is located.
784 // Always keep kMinOnscreenHeight or the window height (whichever is less)
785 // on the bottom.
786 int max_y = work_area.bottom() - std::min(kMinOnscreenHeight,
787 bounds->height());
788 if (bounds->y() > max_y) {
789 bounds->set_y(max_y);
790 } else if (bounds->y() <= work_area.y()) {
791 // Don't allow dragging above the top of the display until the mouse
792 // cursor reaches the work area above if any.
793 bounds->set_y(work_area.y());
796 if (sticky_size > 0) {
797 // Possibly stick to edge except when a mouse pointer is outside the
798 // work area.
799 if (display.work_area().Contains(last_mouse_location_in_screen))
800 StickToWorkAreaOnMove(work_area, sticky_size, bounds);
801 MagneticallySnapToOtherWindows(bounds);
803 } else if (sticky_size > 0) {
804 MagneticallySnapResizeToOtherWindows(bounds);
805 if (!magnetism_window_ && sticky_size > 0)
806 StickToWorkAreaOnResize(work_area, sticky_size, bounds);
809 if (attached_windows_.empty())
810 return;
812 if (details().window_component == HTRIGHT) {
813 bounds->set_width(std::min(bounds->width(),
814 work_area.right() - total_min_ - bounds->x()));
815 } else {
816 DCHECK_EQ(HTBOTTOM, details().window_component);
817 bounds->set_height(std::min(bounds->height(),
818 work_area.bottom() - total_min_ - bounds->y()));
822 bool WorkspaceWindowResizer::StickToWorkAreaOnMove(
823 const gfx::Rect& work_area,
824 int sticky_size,
825 gfx::Rect* bounds) const {
826 const int left_edge = work_area.x();
827 const int right_edge = work_area.right();
828 const int top_edge = work_area.y();
829 const int bottom_edge = work_area.bottom();
830 bool updated = false;
831 if (ShouldStickToEdge(bounds->x() - left_edge, sticky_size)) {
832 bounds->set_x(left_edge);
833 updated = true;
834 } else if (ShouldStickToEdge(right_edge - bounds->right(), sticky_size)) {
835 bounds->set_x(right_edge - bounds->width());
836 updated = true;
838 if (ShouldStickToEdge(bounds->y() - top_edge, sticky_size)) {
839 bounds->set_y(top_edge);
840 updated = true;
841 } else if (ShouldStickToEdge(bottom_edge - bounds->bottom(), sticky_size) &&
842 bounds->height() < (bottom_edge - top_edge)) {
843 // Only snap to the bottom if the window is smaller than the work area.
844 // Doing otherwise can lead to window snapping in weird ways as it bounces
845 // between snapping to top then bottom.
846 bounds->set_y(bottom_edge - bounds->height());
847 updated = true;
849 return updated;
852 void WorkspaceWindowResizer::StickToWorkAreaOnResize(
853 const gfx::Rect& work_area,
854 int sticky_size,
855 gfx::Rect* bounds) const {
856 const uint32 edges = WindowComponentToMagneticEdge(
857 details().window_component);
858 const int left_edge = work_area.x();
859 const int right_edge = work_area.right();
860 const int top_edge = work_area.y();
861 const int bottom_edge = work_area.bottom();
862 if (edges & MAGNETISM_EDGE_TOP &&
863 ShouldStickToEdge(bounds->y() - top_edge, sticky_size)) {
864 bounds->set_height(bounds->bottom() - top_edge);
865 bounds->set_y(top_edge);
867 if (edges & MAGNETISM_EDGE_LEFT &&
868 ShouldStickToEdge(bounds->x() - left_edge, sticky_size)) {
869 bounds->set_width(bounds->right() - left_edge);
870 bounds->set_x(left_edge);
872 if (edges & MAGNETISM_EDGE_BOTTOM &&
873 ShouldStickToEdge(bottom_edge - bounds->bottom(), sticky_size)) {
874 bounds->set_height(bottom_edge - bounds->y());
876 if (edges & MAGNETISM_EDGE_RIGHT &&
877 ShouldStickToEdge(right_edge - bounds->right(), sticky_size)) {
878 bounds->set_width(right_edge - bounds->x());
882 int WorkspaceWindowResizer::PrimaryAxisSize(const gfx::Size& size) const {
883 return PrimaryAxisCoordinate(size.width(), size.height());
886 int WorkspaceWindowResizer::PrimaryAxisCoordinate(int x, int y) const {
887 switch (details().window_component) {
888 case HTRIGHT:
889 return x;
890 case HTBOTTOM:
891 return y;
892 default:
893 NOTREACHED();
895 return 0;
898 void WorkspaceWindowResizer::UpdateSnapPhantomWindow(const gfx::Point& location,
899 const gfx::Rect& bounds) {
900 if (!did_move_or_resize_ || details().window_component != HTCAPTION)
901 return;
903 SnapType last_type = snap_type_;
904 snap_type_ = GetSnapType(location);
905 if (snap_type_ == SNAP_NONE || snap_type_ != last_type) {
906 snap_phantom_window_controller_.reset();
907 edge_cycler_.reset();
908 if (snap_type_ == SNAP_NONE) {
909 SetDraggedWindowDocked(false);
910 return;
914 const bool can_dock = dock_layout_->CanDockWindow(GetTarget(), snap_type_) &&
915 dock_layout_->GetAlignmentOfWindow(GetTarget()) != DOCKED_ALIGNMENT_NONE;
916 if (!can_dock) {
917 // If the window cannot be docked, undock the window. This may change the
918 // workspace bounds and hence |snap_type_|.
919 SetDraggedWindowDocked(false);
920 snap_type_ = GetSnapType(location);
922 const bool can_snap = snap_type_ != SNAP_NONE && window_state()->CanSnap();
923 if (!can_snap && !can_dock) {
924 snap_type_ = SNAP_NONE;
925 snap_phantom_window_controller_.reset();
926 edge_cycler_.reset();
927 return;
929 if (!edge_cycler_)
930 edge_cycler_.reset(new TwoStepEdgeCycler(location));
931 else
932 edge_cycler_->OnMove(location);
934 // Update phantom window with snapped or docked guide bounds.
935 // Windows that cannot be snapped or are less wide than kMaxDockWidth can get
936 // docked without going through a snapping sequence.
937 gfx::Rect phantom_bounds;
938 const bool should_dock = can_dock &&
939 (!can_snap ||
940 GetTarget()->bounds().width() <=
941 DockedWindowLayoutManager::kMaxDockWidth ||
942 edge_cycler_->use_second_mode() ||
943 dock_layout_->is_dragged_window_docked());
944 if (should_dock) {
945 SetDraggedWindowDocked(true);
946 phantom_bounds = ScreenUtil::ConvertRectFromScreen(
947 GetTarget()->parent(), dock_layout_->dragged_bounds());
948 } else {
949 phantom_bounds = (snap_type_ == SNAP_LEFT) ?
950 wm::GetDefaultLeftSnappedWindowBoundsInParent(GetTarget()) :
951 wm::GetDefaultRightSnappedWindowBoundsInParent(GetTarget());
954 if (!snap_phantom_window_controller_) {
955 snap_phantom_window_controller_.reset(
956 new PhantomWindowController(GetTarget()));
958 snap_phantom_window_controller_->Show(ScreenUtil::ConvertRectToScreen(
959 GetTarget()->parent(), phantom_bounds));
962 void WorkspaceWindowResizer::RestackWindows() {
963 if (attached_windows_.empty())
964 return;
965 // Build a map from index in children to window, returning if there is a
966 // window with a different parent.
967 typedef std::map<size_t, aura::Window*> IndexToWindowMap;
968 IndexToWindowMap map;
969 aura::Window* parent = GetTarget()->parent();
970 const aura::Window::Windows& windows(parent->children());
971 map[std::find(windows.begin(), windows.end(), GetTarget()) -
972 windows.begin()] = GetTarget();
973 for (std::vector<aura::Window*>::const_iterator i =
974 attached_windows_.begin(); i != attached_windows_.end(); ++i) {
975 if ((*i)->parent() != parent)
976 return;
977 size_t index =
978 std::find(windows.begin(), windows.end(), *i) - windows.begin();
979 map[index] = *i;
982 // Reorder the windows starting at the topmost.
983 parent->StackChildAtTop(map.rbegin()->second);
984 for (IndexToWindowMap::const_reverse_iterator i = map.rbegin();
985 i != map.rend(); ) {
986 aura::Window* window = i->second;
987 ++i;
988 if (i != map.rend())
989 parent->StackChildBelow(i->second, window);
993 SnapType WorkspaceWindowResizer::GetSnapType(
994 const gfx::Point& location) const {
995 // TODO: this likely only wants total display area, not the area of a single
996 // display.
997 gfx::Rect area(ScreenUtil::GetDisplayWorkAreaBoundsInParent(GetTarget()));
998 if (details().source == aura::client::WINDOW_MOVE_SOURCE_TOUCH) {
999 // Increase tolerance for touch-snapping near the screen edges. This is only
1000 // necessary when the work area left or right edge is same as screen edge.
1001 gfx::Rect display_bounds(ScreenUtil::GetDisplayBoundsInParent(GetTarget()));
1002 int inset_left = 0;
1003 if (area.x() == display_bounds.x())
1004 inset_left = kScreenEdgeInsetForTouchDrag;
1005 int inset_right = 0;
1006 if (area.right() == display_bounds.right())
1007 inset_right = kScreenEdgeInsetForTouchDrag;
1008 area.Inset(inset_left, 0, inset_right, 0);
1010 if (location.x() <= area.x())
1011 return SNAP_LEFT;
1012 if (location.x() >= area.right() - 1)
1013 return SNAP_RIGHT;
1014 return SNAP_NONE;
1017 void WorkspaceWindowResizer::SetDraggedWindowDocked(bool should_dock) {
1018 if (should_dock) {
1019 if (!dock_layout_->is_dragged_window_docked()) {
1020 window_state()->set_bounds_changed_by_user(false);
1021 dock_layout_->DockDraggedWindow(GetTarget());
1023 } else {
1024 if (dock_layout_->is_dragged_window_docked()) {
1025 dock_layout_->UndockDraggedWindow();
1026 window_state()->set_bounds_changed_by_user(true);
1031 bool WorkspaceWindowResizer::AreBoundsValidSnappedBounds(
1032 wm::WindowStateType snapped_type,
1033 const gfx::Rect& bounds_in_parent) const {
1034 DCHECK(snapped_type == wm::WINDOW_STATE_TYPE_LEFT_SNAPPED ||
1035 snapped_type == wm::WINDOW_STATE_TYPE_RIGHT_SNAPPED);
1036 gfx::Rect snapped_bounds = ScreenUtil::GetDisplayWorkAreaBoundsInParent(
1037 GetTarget());
1038 if (snapped_type == wm::WINDOW_STATE_TYPE_RIGHT_SNAPPED)
1039 snapped_bounds.set_x(snapped_bounds.right() - bounds_in_parent.width());
1040 snapped_bounds.set_width(bounds_in_parent.width());
1041 return bounds_in_parent == snapped_bounds;
1044 } // namespace ash