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