Home | History | Annotate | Download | only in workspace
      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/ash_switches.h"
     13 #include "ash/root_window_controller.h"
     14 #include "ash/screen_ash.h"
     15 #include "ash/shell.h"
     16 #include "ash/shell_window_ids.h"
     17 #include "ash/wm/coordinate_conversion.h"
     18 #include "ash/wm/default_window_resizer.h"
     19 #include "ash/wm/dock/docked_window_resizer.h"
     20 #include "ash/wm/drag_window_resizer.h"
     21 #include "ash/wm/panels/panel_window_resizer.h"
     22 #include "ash/wm/property_util.h"
     23 #include "ash/wm/window_properties.h"
     24 #include "ash/wm/window_util.h"
     25 #include "ash/wm/workspace/phantom_window_controller.h"
     26 #include "ash/wm/workspace/snap_sizer.h"
     27 #include "base/command_line.h"
     28 #include "ui/aura/client/aura_constants.h"
     29 #include "ui/aura/client/screen_position_client.h"
     30 #include "ui/aura/client/window_types.h"
     31 #include "ui/aura/root_window.h"
     32 #include "ui/aura/window.h"
     33 #include "ui/aura/window_delegate.h"
     34 #include "ui/base/hit_test.h"
     35 #include "ui/compositor/layer.h"
     36 #include "ui/gfx/screen.h"
     37 #include "ui/gfx/transform.h"
     38 
     39 namespace ash {
     40 
     41 scoped_ptr<WindowResizer> CreateWindowResizer(
     42     aura::Window* window,
     43     const gfx::Point& point_in_parent,
     44     int window_component,
     45     aura::client::WindowMoveSource source) {
     46   DCHECK(window);
     47   // No need to return a resizer when the window cannot get resized.
     48   if (!wm::CanResizeWindow(window) && window_component != HTCAPTION)
     49     return scoped_ptr<WindowResizer>();
     50 
     51   // TODO(varkha): The chaining of window resizers causes some of the logic
     52   // to be repeated and the logic flow difficult to control. With some windows
     53   // classes using reparenting during drag operations it becomes challenging to
     54   // implement proper transition from one resizer to another during or at the
     55   // end of the drag. This also causes http://crbug.com/247085.
     56   // It seems the only thing the panel or dock resizer needs to do is notify the
     57   // layout manager when a docked window is being dragged. We should have a
     58   // better way of doing this, perhaps by having a way of observing drags or
     59   // having a generic drag window wrapper which informs a layout manager that a
     60   // drag has started or stopped.
     61   // It may be possible to refactor and eliminate chaining.
     62   WindowResizer* window_resizer = NULL;
     63   if (window->parent() &&
     64       (window->parent()->id() == internal::kShellWindowId_DefaultContainer ||
     65        window->parent()->id() == internal::kShellWindowId_DockedContainer ||
     66        window->parent()->id() == internal::kShellWindowId_PanelContainer)) {
     67     // Allow dragging maximized windows if it's not tracked by workspace. This
     68     // is set by tab dragging code.
     69     if (!wm::IsWindowNormal(window) &&
     70         (window_component != HTCAPTION || GetTrackedByWorkspace(window)))
     71       return scoped_ptr<WindowResizer>();
     72     window_resizer = internal::WorkspaceWindowResizer::Create(
     73         window,
     74         point_in_parent,
     75         window_component,
     76         source,
     77         std::vector<aura::Window*>());
     78   } else if (wm::IsWindowNormal(window)) {
     79     window_resizer = DefaultWindowResizer::Create(
     80         window, point_in_parent, window_component, source);
     81   }
     82   if (window_resizer) {
     83     window_resizer = internal::DragWindowResizer::Create(
     84         window_resizer, window, point_in_parent, window_component, source);
     85   }
     86   if (window_resizer && window->type() == aura::client::WINDOW_TYPE_PANEL) {
     87     window_resizer = PanelWindowResizer::Create(
     88         window_resizer, window, point_in_parent, window_component, source);
     89   }
     90   if (window_resizer) {
     91     window_resizer = DockedWindowResizer::Create(
     92         window_resizer, window, point_in_parent, window_component, source);
     93   }
     94   return make_scoped_ptr<WindowResizer>(window_resizer);
     95 }
     96 
     97 namespace internal {
     98 
     99 namespace {
    100 
    101 // Distance in pixels that the cursor must move past an edge for a window
    102 // to move or resize beyond that edge.
    103 const int kStickyDistancePixels = 64;
    104 
    105 // Snapping distance used instead of WorkspaceWindowResizer::kScreenEdgeInset
    106 // when resizing a window using touchscreen.
    107 const int kScreenEdgeInsetForTouchResize = 32;
    108 
    109 // Returns true if the window should stick to the edge.
    110 bool ShouldStickToEdge(int distance_from_edge, int sticky_size) {
    111   if (CommandLine::ForCurrentProcess()->HasSwitch(
    112           switches::kAshEnableStickyEdges) ||
    113       CommandLine::ForCurrentProcess()->HasSwitch(
    114           switches::kAshEnableDockedWindows)) {
    115     return distance_from_edge < 0 &&
    116            distance_from_edge > -sticky_size;
    117   }
    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.
    123 int 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.
    141 gfx::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.
    179 gfx::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.
    227 uint32 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
    254 const int WorkspaceWindowResizer::kMinOnscreenSize = 20;
    255 
    256 // static
    257 const int WorkspaceWindowResizer::kMinOnscreenHeight = 32;
    258 
    259 // static
    260 const int WorkspaceWindowResizer::kScreenEdgeInset = 8;
    261 
    262 // Represents the width or height of a window with constraints on its minimum
    263 // and maximum size. 0 represents a lack of a constraint.
    264 class WindowSize {
    265  public:
    266   WindowSize(int size, int min, int max)
    267       : size_(size),
    268         min_(min),
    269         max_(max) {
    270     // Grow the min/max bounds to include the starting size.
    271     if (is_underflowing())
    272       min_ = size_;
    273     if (is_overflowing())
    274       max_ = size_;
    275   }
    276 
    277   bool is_at_capacity(bool shrinking) {
    278     return size_ == (shrinking ? min_ : max_);
    279   }
    280 
    281   int size() const {
    282     return size_;
    283   }
    284 
    285   bool has_min() const {
    286     return min_ != 0;
    287   }
    288 
    289   bool has_max() const {
    290     return max_ != 0;
    291   }
    292 
    293   bool is_valid() const {
    294     return !is_overflowing() && !is_underflowing();
    295   }
    296 
    297   bool is_overflowing() const {
    298     return has_max() && size_ > max_;
    299   }
    300 
    301   bool is_underflowing() const {
    302     return has_min() && size_ < min_;
    303   }
    304 
    305   // Add |amount| to this WindowSize not exceeding min or max size constraints.
    306   // Returns by how much |size_| + |amount| exceeds the min/max constraints.
    307   int Add(int amount) {
    308     DCHECK(is_valid());
    309     int new_value = size_ + amount;
    310 
    311     if (has_min() && new_value < min_) {
    312       size_ = min_;
    313       return new_value - min_;
    314     }
    315 
    316     if (has_max() && new_value > max_) {
    317       size_ = max_;
    318       return new_value - max_;
    319     }
    320 
    321     size_ = new_value;
    322     return 0;
    323   }
    324 
    325  private:
    326   int size_;
    327   int min_;
    328   int max_;
    329 };
    330 
    331 WorkspaceWindowResizer::~WorkspaceWindowResizer() {
    332   Shell* shell = Shell::GetInstance();
    333   shell->cursor_manager()->UnlockCursor();
    334 }
    335 
    336 // static
    337 WorkspaceWindowResizer* WorkspaceWindowResizer::Create(
    338     aura::Window* window,
    339     const gfx::Point& location_in_parent,
    340     int window_component,
    341     aura::client::WindowMoveSource source,
    342     const std::vector<aura::Window*>& attached_windows) {
    343   Details details(window, location_in_parent, window_component, source);
    344   return details.is_resizable ?
    345       new WorkspaceWindowResizer(details, attached_windows) : NULL;
    346 }
    347 
    348 void WorkspaceWindowResizer::Drag(const gfx::Point& location_in_parent,
    349                                   int event_flags) {
    350   last_mouse_location_ = location_in_parent;
    351 
    352   int sticky_size;
    353   if (event_flags & ui::EF_CONTROL_DOWN) {
    354     sticky_size = 0;
    355   } else if (CommandLine::ForCurrentProcess()->HasSwitch(
    356       switches::kAshEnableStickyEdges) ||
    357       CommandLine::ForCurrentProcess()->HasSwitch(
    358           switches::kAshEnableDockedWindows)) {
    359     sticky_size = kStickyDistancePixels;
    360   } else if ((details_.bounds_change & kBoundsChange_Resizes) &&
    361       details_.source == aura::client::WINDOW_MOVE_SOURCE_TOUCH) {
    362     sticky_size = kScreenEdgeInsetForTouchResize;
    363   } else {
    364     sticky_size = kScreenEdgeInset;
    365   }
    366   // |bounds| is in |window()->parent()|'s coordinates.
    367   gfx::Rect bounds = CalculateBoundsForDrag(details_, location_in_parent);
    368 
    369   if (wm::IsWindowNormal(window()))
    370     AdjustBoundsForMainWindow(sticky_size, &bounds);
    371 
    372   if (bounds != window()->bounds()) {
    373     if (!did_move_or_resize_) {
    374       if (!details_.restore_bounds.IsEmpty())
    375         ClearRestoreBounds(window());
    376       RestackWindows();
    377     }
    378     did_move_or_resize_ = true;
    379   }
    380 
    381   gfx::Point location_in_screen = location_in_parent;
    382   wm::ConvertPointToScreen(window()->parent(), &location_in_screen);
    383   const bool in_original_root =
    384       wm::GetRootWindowAt(location_in_screen) == window()->GetRootWindow();
    385   // Hide a phantom window for snapping if the cursor is in another root window.
    386   if (in_original_root && wm::CanResizeWindow(window())) {
    387     UpdateSnapPhantomWindow(location_in_parent, bounds);
    388   } else {
    389     snap_type_ = SNAP_NONE;
    390     snap_phantom_window_controller_.reset();
    391   }
    392 
    393   if (!attached_windows_.empty())
    394     LayoutAttachedWindows(&bounds);
    395   if (bounds != window()->bounds())
    396     window()->SetBounds(bounds);
    397 }
    398 
    399 void WorkspaceWindowResizer::CompleteDrag(int event_flags) {
    400   wm::SetUserHasChangedWindowPositionOrSize(details_.window, true);
    401   snap_phantom_window_controller_.reset();
    402   if (!did_move_or_resize_ || details_.window_component != HTCAPTION)
    403     return;
    404 
    405   // When the window is not in the normal show state, we do not snap the window.
    406   // This happens when the user minimizes or maximizes the window by keyboard
    407   // shortcut while dragging it. If the window is the result of dragging a tab
    408   // out of a maximized window, it's already in the normal show state when this
    409   // is called, so it does not matter.
    410   if (wm::IsWindowNormal(window()) &&
    411       (window()->type() != aura::client::WINDOW_TYPE_PANEL ||
    412        !window()->GetProperty(kPanelAttachedKey)) &&
    413       (snap_type_ == SNAP_LEFT_EDGE || snap_type_ == SNAP_RIGHT_EDGE)) {
    414     if (!GetRestoreBoundsInScreen(window())) {
    415       gfx::Rect initial_bounds = ScreenAsh::ConvertRectToScreen(
    416           window()->parent(), details_.initial_bounds_in_parent);
    417       SetRestoreBoundsInScreen(window(), details_.restore_bounds.IsEmpty() ?
    418                                initial_bounds :
    419                                details_.restore_bounds);
    420     }
    421     window()->SetBounds(snap_sizer_->target_bounds());
    422     return;
    423   }
    424 }
    425 
    426 void WorkspaceWindowResizer::RevertDrag() {
    427   snap_phantom_window_controller_.reset();
    428 
    429   if (!did_move_or_resize_)
    430     return;
    431 
    432   window()->SetBounds(details_.initial_bounds_in_parent);
    433   if (!details_.restore_bounds.IsEmpty())
    434     SetRestoreBoundsInScreen(details_.window, details_.restore_bounds);
    435 
    436   if (details_.window_component == HTRIGHT) {
    437     int last_x = details_.initial_bounds_in_parent.right();
    438     for (size_t i = 0; i < attached_windows_.size(); ++i) {
    439       gfx::Rect bounds(attached_windows_[i]->bounds());
    440       bounds.set_x(last_x);
    441       bounds.set_width(initial_size_[i]);
    442       attached_windows_[i]->SetBounds(bounds);
    443       last_x = attached_windows_[i]->bounds().right();
    444     }
    445   } else {
    446     int last_y = details_.initial_bounds_in_parent.bottom();
    447     for (size_t i = 0; i < attached_windows_.size(); ++i) {
    448       gfx::Rect bounds(attached_windows_[i]->bounds());
    449       bounds.set_y(last_y);
    450       bounds.set_height(initial_size_[i]);
    451       attached_windows_[i]->SetBounds(bounds);
    452       last_y = attached_windows_[i]->bounds().bottom();
    453     }
    454   }
    455 }
    456 
    457 aura::Window* WorkspaceWindowResizer::GetTarget() {
    458   return details_.window;
    459 }
    460 
    461 const gfx::Point& WorkspaceWindowResizer::GetInitialLocation() const {
    462   return details_.initial_location_in_parent;
    463 }
    464 
    465 WorkspaceWindowResizer::WorkspaceWindowResizer(
    466     const Details& details,
    467     const std::vector<aura::Window*>& attached_windows)
    468     : details_(details),
    469       attached_windows_(attached_windows),
    470       did_move_or_resize_(false),
    471       total_min_(0),
    472       total_initial_size_(0),
    473       snap_type_(SNAP_NONE),
    474       num_mouse_moves_since_bounds_change_(0),
    475       magnetism_window_(NULL) {
    476   DCHECK(details_.is_resizable);
    477 
    478   Shell* shell = Shell::GetInstance();
    479   shell->cursor_manager()->LockCursor();
    480 
    481   // Only support attaching to the right/bottom.
    482   DCHECK(attached_windows_.empty() ||
    483          (details.window_component == HTRIGHT ||
    484           details.window_component == HTBOTTOM));
    485 
    486   // TODO: figure out how to deal with window going off the edge.
    487 
    488   // Calculate sizes so that we can maintain the ratios if we need to resize.
    489   int total_available = 0;
    490   for (size_t i = 0; i < attached_windows_.size(); ++i) {
    491     gfx::Size min(attached_windows_[i]->delegate()->GetMinimumSize());
    492     int initial_size = PrimaryAxisSize(attached_windows_[i]->bounds().size());
    493     initial_size_.push_back(initial_size);
    494     // If current size is smaller than the min, use the current size as the min.
    495     // This way we don't snap on resize.
    496     int min_size = std::min(initial_size,
    497                             std::max(PrimaryAxisSize(min), kMinOnscreenSize));
    498     total_min_ += min_size;
    499     total_initial_size_ += initial_size;
    500     total_available += std::max(min_size, initial_size) - min_size;
    501   }
    502 }
    503 
    504 gfx::Rect WorkspaceWindowResizer::GetFinalBounds(
    505     const gfx::Rect& bounds) const {
    506   if (snap_phantom_window_controller_.get() &&
    507       snap_phantom_window_controller_->IsShowing()) {
    508     return snap_phantom_window_controller_->bounds();
    509   }
    510   return bounds;
    511 }
    512 
    513 void WorkspaceWindowResizer::LayoutAttachedWindows(
    514     gfx::Rect* bounds) {
    515   gfx::Rect work_area(ScreenAsh::GetDisplayWorkAreaBoundsInParent(window()));
    516   int initial_size = PrimaryAxisSize(details_.initial_bounds_in_parent.size());
    517   int current_size = PrimaryAxisSize(bounds->size());
    518   int start = PrimaryAxisCoordinate(bounds->right(), bounds->bottom());
    519   int end = PrimaryAxisCoordinate(work_area.right(), work_area.bottom());
    520 
    521   int delta = current_size - initial_size;
    522   int available_size = end - start;
    523   std::vector<int> sizes;
    524   int leftovers = CalculateAttachedSizes(delta, available_size, &sizes);
    525 
    526   // leftovers > 0 means that the attached windows can't grow to compensate for
    527   // the shrinkage of the main window. This line causes the attached windows to
    528   // be moved so they are still flush against the main window, rather than the
    529   // main window being prevented from shrinking.
    530   leftovers = std::min(0, leftovers);
    531   // Reallocate any leftover pixels back into the main window. This is
    532   // necessary when, for example, the main window shrinks, but none of the
    533   // attached windows can grow without exceeding their max size constraints.
    534   // Adding the pixels back to the main window effectively prevents the main
    535   // window from resizing too far.
    536   if (details_.window_component == HTRIGHT)
    537     bounds->set_width(bounds->width() + leftovers);
    538   else
    539     bounds->set_height(bounds->height() + leftovers);
    540 
    541   DCHECK_EQ(attached_windows_.size(), sizes.size());
    542   int last = PrimaryAxisCoordinate(bounds->right(), bounds->bottom());
    543   for (size_t i = 0; i < attached_windows_.size(); ++i) {
    544     gfx::Rect attached_bounds(attached_windows_[i]->bounds());
    545     if (details_.window_component == HTRIGHT) {
    546       attached_bounds.set_x(last);
    547       attached_bounds.set_width(sizes[i]);
    548     } else {
    549       attached_bounds.set_y(last);
    550       attached_bounds.set_height(sizes[i]);
    551     }
    552     attached_windows_[i]->SetBounds(attached_bounds);
    553     last += sizes[i];
    554   }
    555 }
    556 
    557 int WorkspaceWindowResizer::CalculateAttachedSizes(
    558     int delta,
    559     int available_size,
    560     std::vector<int>* sizes) const {
    561   std::vector<WindowSize> window_sizes;
    562   CreateBucketsForAttached(&window_sizes);
    563 
    564   // How much we need to grow the attached by (collectively).
    565   int grow_attached_by = 0;
    566   if (delta > 0) {
    567     // If the attached windows don't fit when at their initial size, we will
    568     // have to shrink them by how much they overflow.
    569     if (total_initial_size_ >= available_size)
    570       grow_attached_by = available_size - total_initial_size_;
    571   } else {
    572     // If we're shrinking, we grow the attached so the total size remains
    573     // constant.
    574     grow_attached_by = -delta;
    575   }
    576 
    577   int leftover_pixels = 0;
    578   while (grow_attached_by != 0) {
    579     int leftovers = GrowFairly(grow_attached_by, window_sizes);
    580     if (leftovers == grow_attached_by) {
    581       leftover_pixels = leftovers;
    582       break;
    583     }
    584     grow_attached_by = leftovers;
    585   }
    586 
    587   for (size_t i = 0; i < window_sizes.size(); ++i)
    588     sizes->push_back(window_sizes[i].size());
    589 
    590   return leftover_pixels;
    591 }
    592 
    593 int WorkspaceWindowResizer::GrowFairly(
    594     int pixels,
    595     std::vector<WindowSize>& sizes) const {
    596   bool shrinking = pixels < 0;
    597   std::vector<WindowSize*> nonfull_windows;
    598   for (size_t i = 0; i < sizes.size(); ++i) {
    599     if (!sizes[i].is_at_capacity(shrinking))
    600       nonfull_windows.push_back(&sizes[i]);
    601   }
    602   std::vector<float> ratios;
    603   CalculateGrowthRatios(nonfull_windows, &ratios);
    604 
    605   int remaining_pixels = pixels;
    606   bool add_leftover_pixels_to_last = true;
    607   for (size_t i = 0; i < nonfull_windows.size(); ++i) {
    608     int grow_by = pixels * ratios[i];
    609     // Put any leftover pixels into the last window.
    610     if (i == nonfull_windows.size() - 1 && add_leftover_pixels_to_last)
    611       grow_by = remaining_pixels;
    612     int remainder = nonfull_windows[i]->Add(grow_by);
    613     int consumed = grow_by - remainder;
    614     remaining_pixels -= consumed;
    615     if (nonfull_windows[i]->is_at_capacity(shrinking) && remainder > 0) {
    616       // Because this window overflowed, some of the pixels in
    617       // |remaining_pixels| aren't there due to rounding errors. Rather than
    618       // unfairly giving all those pixels to the last window, we refrain from
    619       // allocating them so that this function can be called again to distribute
    620       // the pixels fairly.
    621       add_leftover_pixels_to_last = false;
    622     }
    623   }
    624   return remaining_pixels;
    625 }
    626 
    627 void WorkspaceWindowResizer::CalculateGrowthRatios(
    628     const std::vector<WindowSize*>& sizes,
    629     std::vector<float>* out_ratios) const {
    630   DCHECK(out_ratios->empty());
    631   int total_value = 0;
    632   for (size_t i = 0; i < sizes.size(); ++i)
    633     total_value += sizes[i]->size();
    634 
    635   for (size_t i = 0; i < sizes.size(); ++i)
    636     out_ratios->push_back(
    637         (static_cast<float>(sizes[i]->size())) / total_value);
    638 }
    639 
    640 void WorkspaceWindowResizer::CreateBucketsForAttached(
    641     std::vector<WindowSize>* sizes) const {
    642   for (size_t i = 0; i < attached_windows_.size(); i++) {
    643     int initial_size = initial_size_[i];
    644     aura::WindowDelegate* delegate = attached_windows_[i]->delegate();
    645     int min = PrimaryAxisSize(delegate->GetMinimumSize());
    646     int max = PrimaryAxisSize(delegate->GetMaximumSize());
    647 
    648     sizes->push_back(WindowSize(initial_size, min, max));
    649   }
    650 }
    651 
    652 void WorkspaceWindowResizer::MagneticallySnapToOtherWindows(gfx::Rect* bounds) {
    653   if (UpdateMagnetismWindow(*bounds, kAllMagnetismEdges)) {
    654     gfx::Point point = OriginForMagneticAttach(
    655         ScreenAsh::ConvertRectToScreen(window()->parent(), *bounds),
    656         magnetism_window_->GetBoundsInScreen(),
    657         magnetism_edge_);
    658     aura::client::GetScreenPositionClient(window()->GetRootWindow())->
    659         ConvertPointFromScreen(window()->parent(), &point);
    660     bounds->set_origin(point);
    661   }
    662 }
    663 
    664 void WorkspaceWindowResizer::MagneticallySnapResizeToOtherWindows(
    665     gfx::Rect* bounds) {
    666   const uint32 edges = WindowComponentToMagneticEdge(details_.window_component);
    667   if (UpdateMagnetismWindow(*bounds, edges)) {
    668     *bounds = ScreenAsh::ConvertRectFromScreen(
    669         window()->parent(),
    670         BoundsForMagneticResizeAttach(
    671             ScreenAsh::ConvertRectToScreen(window()->parent(), *bounds),
    672             magnetism_window_->GetBoundsInScreen(),
    673             magnetism_edge_));
    674   }
    675 }
    676 
    677 bool WorkspaceWindowResizer::UpdateMagnetismWindow(const gfx::Rect& bounds,
    678                                                    uint32 edges) {
    679   // |bounds| are in coordinates of original window's parent.
    680   gfx::Rect bounds_in_screen =
    681       ScreenAsh::ConvertRectToScreen(window()->parent(), bounds);
    682   MagnetismMatcher matcher(bounds_in_screen, edges);
    683 
    684   // If we snapped to a window then check it first. That way we don't bounce
    685   // around when close to multiple edges.
    686   if (magnetism_window_) {
    687     if (window_tracker_.Contains(magnetism_window_) &&
    688         matcher.ShouldAttach(magnetism_window_->GetBoundsInScreen(),
    689                              &magnetism_edge_)) {
    690       return true;
    691     }
    692     window_tracker_.Remove(magnetism_window_);
    693     magnetism_window_ = NULL;
    694   }
    695 
    696   // Avoid magnetically snapping to popups, menus, tooltips, controls and
    697   // windows that are not tracked by workspace.
    698   if (!wm::CanResizeWindow(window()) || !GetTrackedByWorkspace(window()))
    699     return false;
    700 
    701   Shell::RootWindowList root_windows = Shell::GetAllRootWindows();
    702   for (Shell::RootWindowList::iterator iter = root_windows.begin();
    703        iter != root_windows.end(); ++iter) {
    704     const aura::RootWindow* root_window = *iter;
    705     // Test all children from the desktop in each root window.
    706     const aura::Window::Windows& children = Shell::GetContainer(
    707         root_window, kShellWindowId_DefaultContainer)->children();
    708     for (aura::Window::Windows::const_reverse_iterator i = children.rbegin();
    709          i != children.rend() && !matcher.AreEdgesObscured(); ++i) {
    710       aura::Window* other = *i;
    711       if (other == window() ||
    712           !other->IsVisible() ||
    713           !wm::IsWindowNormal(other) ||
    714           !wm::CanResizeWindow(other)) {
    715         continue;
    716       }
    717       if (matcher.ShouldAttach(other->GetBoundsInScreen(), &magnetism_edge_)) {
    718         magnetism_window_ = other;
    719         window_tracker_.Add(magnetism_window_);
    720         return true;
    721       }
    722     }
    723   }
    724   return false;
    725 }
    726 
    727 void WorkspaceWindowResizer::AdjustBoundsForMainWindow(
    728     int sticky_size,
    729     gfx::Rect* bounds) {
    730   gfx::Point last_mouse_location_in_screen = last_mouse_location_;
    731   wm::ConvertPointToScreen(window()->parent(), &last_mouse_location_in_screen);
    732   gfx::Display display = Shell::GetScreen()->GetDisplayNearestPoint(
    733       last_mouse_location_in_screen);
    734   gfx::Rect work_area =
    735       ScreenAsh::ConvertRectFromScreen(window()->parent(), display.work_area());
    736   if (details_.window_component == HTCAPTION) {
    737     // Adjust the bounds to the work area where the mouse cursor is located.
    738     // Always keep kMinOnscreenHeight on the bottom.
    739     int max_y = work_area.bottom() - kMinOnscreenHeight;
    740     if (bounds->y() > max_y) {
    741       bounds->set_y(max_y);
    742     } else if (bounds->y() <= work_area.y()) {
    743       // Don't allow dragging above the top of the display until the mouse
    744       // cursor reaches the work area above if any.
    745       bounds->set_y(work_area.y());
    746     }
    747 
    748     if (sticky_size > 0) {
    749       if (!StickToWorkAreaOnMove(work_area, sticky_size, bounds))
    750         MagneticallySnapToOtherWindows(bounds);
    751     }
    752   } else if (sticky_size > 0) {
    753     MagneticallySnapResizeToOtherWindows(bounds);
    754     if (!magnetism_window_ && sticky_size > 0)
    755       StickToWorkAreaOnResize(work_area, sticky_size, bounds);
    756   }
    757 
    758   if (attached_windows_.empty())
    759     return;
    760 
    761   if (details_.window_component == HTRIGHT) {
    762     bounds->set_width(std::min(bounds->width(),
    763                                work_area.right() - total_min_ - bounds->x()));
    764   } else {
    765     DCHECK_EQ(HTBOTTOM, details_.window_component);
    766     bounds->set_height(std::min(bounds->height(),
    767                                 work_area.bottom() - total_min_ - bounds->y()));
    768   }
    769 }
    770 
    771 bool WorkspaceWindowResizer::StickToWorkAreaOnMove(
    772     const gfx::Rect& work_area,
    773     int sticky_size,
    774     gfx::Rect* bounds) const {
    775   const int left_edge = work_area.x();
    776   const int right_edge = work_area.right();
    777   const int top_edge = work_area.y();
    778   const int bottom_edge = work_area.bottom();
    779   if (ShouldStickToEdge(bounds->x() - left_edge, sticky_size)) {
    780     bounds->set_x(left_edge);
    781     return true;
    782   } else if (ShouldStickToEdge(right_edge - bounds->right(), sticky_size)) {
    783     bounds->set_x(right_edge - bounds->width());
    784     return true;
    785   }
    786   if (ShouldStickToEdge(bounds->y() - top_edge, sticky_size)) {
    787     bounds->set_y(top_edge);
    788     return true;
    789   } else if (ShouldStickToEdge(bottom_edge - bounds->bottom(), sticky_size) &&
    790              bounds->height() < (bottom_edge - top_edge)) {
    791     // Only snap to the bottom if the window is smaller than the work area.
    792     // Doing otherwise can lead to window snapping in weird ways as it bounces
    793     // between snapping to top then bottom.
    794     bounds->set_y(bottom_edge - bounds->height());
    795     return true;
    796   }
    797   return false;
    798 }
    799 
    800 void WorkspaceWindowResizer::StickToWorkAreaOnResize(
    801     const gfx::Rect& work_area,
    802     int sticky_size,
    803     gfx::Rect* bounds) const {
    804   const uint32 edges = WindowComponentToMagneticEdge(details_.window_component);
    805   const int left_edge = work_area.x();
    806   const int right_edge = work_area.right();
    807   const int top_edge = work_area.y();
    808   const int bottom_edge = work_area.bottom();
    809   if (edges & MAGNETISM_EDGE_TOP &&
    810       ShouldStickToEdge(bounds->y() - top_edge, sticky_size)) {
    811     bounds->set_height(bounds->bottom() - top_edge);
    812     bounds->set_y(top_edge);
    813   }
    814   if (edges & MAGNETISM_EDGE_LEFT &&
    815       ShouldStickToEdge(bounds->x() - left_edge, sticky_size)) {
    816     bounds->set_width(bounds->right() - left_edge);
    817     bounds->set_x(left_edge);
    818   }
    819   if (edges & MAGNETISM_EDGE_BOTTOM &&
    820       ShouldStickToEdge(bottom_edge - bounds->bottom(), sticky_size)) {
    821     bounds->set_height(bottom_edge - bounds->y());
    822   }
    823   if (edges & MAGNETISM_EDGE_RIGHT &&
    824       ShouldStickToEdge(right_edge - bounds->right(), sticky_size)) {
    825     bounds->set_width(right_edge - bounds->x());
    826   }
    827 }
    828 
    829 int WorkspaceWindowResizer::PrimaryAxisSize(const gfx::Size& size) const {
    830   return PrimaryAxisCoordinate(size.width(), size.height());
    831 }
    832 
    833 int WorkspaceWindowResizer::PrimaryAxisCoordinate(int x, int y) const {
    834   switch (details_.window_component) {
    835     case HTRIGHT:
    836       return x;
    837     case HTBOTTOM:
    838       return y;
    839     default:
    840       NOTREACHED();
    841   }
    842   return 0;
    843 }
    844 
    845 void WorkspaceWindowResizer::UpdateSnapPhantomWindow(const gfx::Point& location,
    846                                                      const gfx::Rect& bounds) {
    847   if (!did_move_or_resize_ || details_.window_component != HTCAPTION)
    848     return;
    849 
    850   if (!wm::CanSnapWindow(window()))
    851     return;
    852 
    853   if (window()->type() == aura::client::WINDOW_TYPE_PANEL &&
    854       window()->GetProperty(kPanelAttachedKey)) {
    855     return;
    856   }
    857 
    858   SnapType last_type = snap_type_;
    859   snap_type_ = GetSnapType(location);
    860   if (snap_type_ == SNAP_NONE || snap_type_ != last_type) {
    861     snap_phantom_window_controller_.reset();
    862     snap_sizer_.reset();
    863     if (snap_type_ == SNAP_NONE)
    864       return;
    865   }
    866   if (!snap_sizer_) {
    867     SnapSizer::Edge edge = (snap_type_ == SNAP_LEFT_EDGE) ?
    868         SnapSizer::LEFT_EDGE : SnapSizer::RIGHT_EDGE;
    869     snap_sizer_.reset(new SnapSizer(window(),
    870                                     location,
    871                                     edge,
    872                                     internal::SnapSizer::OTHER_INPUT));
    873   } else {
    874     snap_sizer_->Update(location);
    875   }
    876   if (!snap_phantom_window_controller_) {
    877     snap_phantom_window_controller_.reset(
    878         new PhantomWindowController(window()));
    879   }
    880   snap_phantom_window_controller_->Show(ScreenAsh::ConvertRectToScreen(
    881       window()->parent(), snap_sizer_->target_bounds()));
    882 }
    883 
    884 void WorkspaceWindowResizer::RestackWindows() {
    885   if (attached_windows_.empty())
    886     return;
    887   // Build a map from index in children to window, returning if there is a
    888   // window with a different parent.
    889   typedef std::map<size_t, aura::Window*> IndexToWindowMap;
    890   IndexToWindowMap map;
    891   aura::Window* parent = window()->parent();
    892   const aura::Window::Windows& windows(parent->children());
    893   map[std::find(windows.begin(), windows.end(), window()) -
    894       windows.begin()] = window();
    895   for (std::vector<aura::Window*>::const_iterator i =
    896            attached_windows_.begin(); i != attached_windows_.end(); ++i) {
    897     if ((*i)->parent() != parent)
    898       return;
    899     size_t index =
    900         std::find(windows.begin(), windows.end(), *i) - windows.begin();
    901     map[index] = *i;
    902   }
    903 
    904   // Reorder the windows starting at the topmost.
    905   parent->StackChildAtTop(map.rbegin()->second);
    906   for (IndexToWindowMap::const_reverse_iterator i = map.rbegin();
    907        i != map.rend(); ) {
    908     aura::Window* window = i->second;
    909     ++i;
    910     if (i != map.rend())
    911       parent->StackChildBelow(i->second, window);
    912   }
    913 }
    914 
    915 WorkspaceWindowResizer::SnapType WorkspaceWindowResizer::GetSnapType(
    916     const gfx::Point& location) const {
    917   // TODO: this likely only wants total display area, not the area of a single
    918   // display.
    919   gfx::Rect area(ScreenAsh::GetDisplayBoundsInParent(window()));
    920   if (location.x() <= area.x())
    921     return SNAP_LEFT_EDGE;
    922   if (location.x() >= area.right() - 1)
    923     return SNAP_RIGHT_EDGE;
    924   return SNAP_NONE;
    925 }
    926 
    927 }  // namespace internal
    928 }  // namespace ash
    929