1// Copyright 2013 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/window_positioner.h"
6
7#include "ash/screen_util.h"
8#include "ash/shell.h"
9#include "ash/shell_window_ids.h"
10#include "ash/wm/mru_window_tracker.h"
11#include "ash/wm/window_resizer.h"
12#include "ash/wm/window_state.h"
13#include "ash/wm/window_util.h"
14#include "ui/aura/window.h"
15#include "ui/aura/window_delegate.h"
16#include "ui/aura/window_event_dispatcher.h"
17#include "ui/compositor/layer.h"
18#include "ui/compositor/scoped_layer_animation_settings.h"
19#include "ui/gfx/screen.h"
20#include "ui/wm/core/window_animations.h"
21#include "ui/wm/core/window_util.h"
22
23namespace ash {
24
25const int WindowPositioner::kMinimumWindowOffset = 32;
26
27// The number of pixels which are kept free top, left and right when a window
28// gets positioned to its default location.
29// static
30const int WindowPositioner::kDesktopBorderSize = 16;
31
32// Maximum width of a window even if there is more room on the desktop.
33// static
34const int WindowPositioner::kMaximumWindowWidth = 1100;
35
36namespace {
37
38// When a window gets opened in default mode and the screen is less than or
39// equal to this width, the window will get opened in maximized mode. This value
40// can be reduced to a "tame" number if the feature is disabled.
41const int kForceMaximizeWidthLimit = 1366;
42
43// The time in milliseconds which should be used to visually move a window
44// through an automatic "intelligent" window management option.
45const int kWindowAutoMoveDurationMS = 125;
46
47// If set to true all window repositioning actions will be ignored. Set through
48// WindowPositioner::SetIgnoreActivations().
49static bool disable_auto_positioning = false;
50
51// If set to true, by default the first window in ASH will be maximized.
52static bool maximize_first_window = false;
53
54// Check if any management should be performed (with a given |window|).
55bool UseAutoWindowManager(const aura::Window* window) {
56  if (disable_auto_positioning)
57    return false;
58  const wm::WindowState* window_state = wm::GetWindowState(window);
59  return !window_state->is_dragged() && window_state->window_position_managed();
60}
61
62// Check if a given |window| can be managed. This includes that it's state is
63// not minimized/maximized/the user has changed it's size by hand already.
64// It furthermore checks for the WindowIsManaged status.
65bool WindowPositionCanBeManaged(const aura::Window* window) {
66  if (disable_auto_positioning)
67    return false;
68  const wm::WindowState* window_state = wm::GetWindowState(window);
69  return window_state->window_position_managed() &&
70      !window_state->IsMinimized() &&
71      !window_state->IsMaximized() &&
72      !window_state->bounds_changed_by_user();
73}
74
75// Get the work area for a given |window| in parent coordinates.
76gfx::Rect GetWorkAreaForWindowInParent(aura::Window* window) {
77#if defined(OS_WIN)
78  // On Win 8, the host window can't be resized, so
79  // use window's bounds instead.
80  // TODO(oshima): Emulate host window resize on win8.
81  gfx::Rect work_area = gfx::Rect(window->parent()->bounds().size());
82  work_area.Inset(Shell::GetScreen()->GetDisplayMatching(
83      window->parent()->GetBoundsInScreen()).GetWorkAreaInsets());
84  return work_area;
85#else
86  return ScreenUtil::GetDisplayWorkAreaBoundsInParent(window);
87#endif
88}
89
90// Move the given |bounds| on the available |work_area| in the direction
91// indicated by |move_right|. If |move_right| is true, the rectangle gets moved
92// to the right edge, otherwise to the left one.
93bool MoveRectToOneSide(const gfx::Rect& work_area,
94                       bool move_right,
95                       gfx::Rect* bounds) {
96  if (move_right) {
97    if (work_area.right() > bounds->right()) {
98      bounds->set_x(work_area.right() - bounds->width());
99      return true;
100    }
101  } else {
102    if (work_area.x() < bounds->x()) {
103      bounds->set_x(work_area.x());
104      return true;
105    }
106  }
107  return false;
108}
109
110// Move a |window| to new |bounds|. Animate if desired by user.
111// Moves the transient children of the |window| as well by the same |offset| as
112// the parent |window|.
113void SetBoundsAndOffsetTransientChildren(aura::Window* window,
114                                         const gfx::Rect& bounds,
115                                         const gfx::Rect& work_area,
116                                         const gfx::Vector2d& offset) {
117  aura::Window::Windows transient_children =
118      ::wm::GetTransientChildren(window);
119  for (aura::Window::Windows::iterator iter = transient_children.begin();
120      iter != transient_children.end(); ++iter) {
121    aura::Window* transient_child = *iter;
122    gfx::Rect child_bounds = transient_child->bounds();
123    gfx::Rect new_child_bounds = child_bounds + offset;
124    if ((child_bounds.x() <= work_area.x() &&
125         new_child_bounds.x() <= work_area.x()) ||
126        (child_bounds.right() >= work_area.right() &&
127         new_child_bounds.right() >= work_area.right())) {
128      continue;
129    }
130    if (new_child_bounds.right() > work_area.right())
131      new_child_bounds.set_x(work_area.right() - bounds.width());
132    else if (new_child_bounds.x() < work_area.x())
133      new_child_bounds.set_x(work_area.x());
134    SetBoundsAndOffsetTransientChildren(transient_child,
135                                        new_child_bounds, work_area, offset);
136  }
137
138  if (::wm::WindowAnimationsDisabled(window)) {
139    window->SetBounds(bounds);
140    return;
141  }
142
143  ui::ScopedLayerAnimationSettings settings(window->layer()->GetAnimator());
144  settings.SetTransitionDuration(
145      base::TimeDelta::FromMilliseconds(kWindowAutoMoveDurationMS));
146  window->SetBounds(bounds);
147}
148
149// Move a |window| to new |bounds|. Animate if desired by user.
150// Note: The function will do nothing if the bounds did not change.
151void SetBoundsAnimated(aura::Window* window,
152                       const gfx::Rect& bounds,
153                       const gfx::Rect& work_area) {
154  gfx::Rect old_bounds = window->GetTargetBounds();
155  if (bounds == old_bounds)
156    return;
157  gfx::Vector2d offset(bounds.origin() - old_bounds.origin());
158  SetBoundsAndOffsetTransientChildren(window, bounds, work_area, offset);
159}
160
161// Move |window| into the center of the screen - or restore it to the previous
162// position.
163void AutoPlaceSingleWindow(aura::Window* window, bool animated) {
164  gfx::Rect work_area = GetWorkAreaForWindowInParent(window);
165  gfx::Rect bounds = window->bounds();
166  const gfx::Rect* user_defined_area =
167      wm::GetWindowState(window)->pre_auto_manage_window_bounds();
168  if (user_defined_area) {
169    bounds = *user_defined_area;
170    ash::wm::AdjustBoundsToEnsureMinimumWindowVisibility(work_area, &bounds);
171  } else {
172    // Center the window (only in x).
173    bounds.set_x(work_area.x() + (work_area.width() - bounds.width()) / 2);
174  }
175
176  if (animated)
177    SetBoundsAnimated(window, bounds, work_area);
178  else
179    window->SetBounds(bounds);
180}
181
182// Get the first open (non minimized) window which is on the screen defined.
183aura::Window* GetReferenceWindow(const aura::Window* root_window,
184                                 const aura::Window* exclude,
185                                 bool *single_window) {
186  if (single_window)
187    *single_window = true;
188  // Get the active window.
189  aura::Window* active = ash::wm::GetActiveWindow();
190  if (active && active->GetRootWindow() != root_window)
191    active = NULL;
192
193  // Get a list of all windows.
194  const std::vector<aura::Window*> windows =
195      ash::MruWindowTracker::BuildWindowList(false);
196
197  if (windows.empty())
198    return NULL;
199
200  aura::Window::Windows::const_iterator iter = windows.begin();
201  // Find the index of the current active window.
202  if (active)
203    iter = std::find(windows.begin(), windows.end(), active);
204
205  int index = (iter == windows.end()) ? 0 : (iter - windows.begin());
206
207  // Scan the cycle list backwards to see which is the second topmost window
208  // (and so on). Note that we might cycle a few indices twice if there is no
209  // suitable window. However - since the list is fairly small this should be
210  // very fast anyways.
211  aura::Window* found = NULL;
212  for (int i = index + windows.size(); i >= 0; i--) {
213    aura::Window* window = windows[i % windows.size()];
214    while (::wm::GetTransientParent(window))
215      window = ::wm::GetTransientParent(window);
216    if (window != exclude && window->type() == ui::wm::WINDOW_TYPE_NORMAL &&
217        window->GetRootWindow() == root_window && window->TargetVisibility() &&
218        wm::GetWindowState(window)->window_position_managed()) {
219      if (found && found != window) {
220        // no need to check !single_window because the function must have
221        // been already returned in the "if (!single_window)" below.
222        *single_window = false;
223        return found;
224      }
225      found = window;
226      // If there is no need to check single window, return now.
227      if (!single_window)
228        return found;
229    }
230  }
231  return found;
232}
233
234}  // namespace
235
236// static
237int WindowPositioner::GetForceMaximizedWidthLimit() {
238  return kForceMaximizeWidthLimit;
239}
240
241// static
242void WindowPositioner::GetBoundsAndShowStateForNewWindow(
243    const gfx::Screen* screen,
244    const aura::Window* new_window,
245    bool is_saved_bounds,
246    ui::WindowShowState show_state_in,
247    gfx::Rect* bounds_in_out,
248    ui::WindowShowState* show_state_out) {
249
250  // Always open new window in the target display.
251  aura::Window* target = Shell::GetTargetRootWindow();
252
253  aura::Window* top_window = GetReferenceWindow(target, NULL, NULL);
254  // Our window should not have any impact if we are already on top.
255  if (top_window == new_window)
256    top_window = NULL;
257
258  // If there is no valid other window we take and adjust the passed coordinates
259  // and show state.
260  if (!top_window) {
261    gfx::Rect work_area = screen->GetDisplayNearestWindow(target).work_area();
262
263    bounds_in_out->AdjustToFit(work_area);
264    // Use adjusted saved bounds, if there is one.
265    if (is_saved_bounds)
266      return;
267    // When using "small screens" we want to always open in full screen mode.
268    if (show_state_in == ui::SHOW_STATE_DEFAULT && (maximize_first_window ||
269         (work_area.width() <= GetForceMaximizedWidthLimit() &&
270         (!new_window || !wm::GetWindowState(new_window)->IsFullscreen())))) {
271      *show_state_out = ui::SHOW_STATE_MAXIMIZED;
272    }
273    return;
274  }
275  wm::WindowState* top_window_state = wm::GetWindowState(top_window);
276  bool maximized = top_window_state->IsMaximized();
277  // We ignore the saved show state, but look instead for the top level
278  // window's show state.
279  if (show_state_in == ui::SHOW_STATE_DEFAULT) {
280    *show_state_out = maximized ? ui::SHOW_STATE_MAXIMIZED :
281        ui::SHOW_STATE_DEFAULT;
282  }
283
284  if (maximized) {
285    bool has_restore_bounds = top_window_state->HasRestoreBounds();
286    if (has_restore_bounds) {
287      // For a maximized window ignore the real bounds of the top level window
288      // and use its restore bounds instead. Offset the bounds to prevent the
289      // windows from overlapping exactly when restored.
290      *bounds_in_out = top_window_state->GetRestoreBoundsInScreen() +
291          gfx::Vector2d(kMinimumWindowOffset, kMinimumWindowOffset);
292    }
293    if (is_saved_bounds || has_restore_bounds) {
294      gfx::Rect work_area = screen->GetDisplayNearestWindow(target).work_area();
295      bounds_in_out->AdjustToFit(work_area);
296      // Use adjusted saved bounds or restore bounds, if there is one.
297      return;
298    }
299  }
300
301  // Use the size of the other window. The window's bound will be rearranged
302  // in ash::WorkspaceLayoutManager using this location.
303  *bounds_in_out = top_window->GetBoundsInScreen();
304}
305
306// static
307void WindowPositioner::RearrangeVisibleWindowOnHideOrRemove(
308    const aura::Window* removed_window) {
309  if (!UseAutoWindowManager(removed_window))
310    return;
311  // Find a single open browser window.
312  bool single_window;
313  aura::Window* other_shown_window = GetReferenceWindow(
314      removed_window->GetRootWindow(), removed_window, &single_window);
315  if (!other_shown_window || !single_window ||
316      !WindowPositionCanBeManaged(other_shown_window))
317    return;
318  AutoPlaceSingleWindow(other_shown_window, true);
319}
320
321// static
322bool WindowPositioner::DisableAutoPositioning(bool ignore) {
323  bool old_state = disable_auto_positioning;
324  disable_auto_positioning = ignore;
325  return old_state;
326}
327
328// static
329void WindowPositioner::RearrangeVisibleWindowOnShow(
330    aura::Window* added_window) {
331  wm::WindowState* added_window_state = wm::GetWindowState(added_window);
332  if (!added_window->TargetVisibility())
333    return;
334
335  if (!UseAutoWindowManager(added_window) ||
336      added_window_state->bounds_changed_by_user()) {
337    if (added_window_state->minimum_visibility()) {
338      // Guarantee minimum visibility within the work area.
339      gfx::Rect work_area = GetWorkAreaForWindowInParent(added_window);
340      gfx::Rect bounds = added_window->bounds();
341      gfx::Rect new_bounds = bounds;
342      ash::wm::AdjustBoundsToEnsureMinimumWindowVisibility(work_area,
343                                                           &new_bounds);
344      if (new_bounds != bounds)
345        added_window->SetBounds(new_bounds);
346    }
347    return;
348  }
349  // Find a single open managed window.
350  bool single_window;
351  aura::Window* other_shown_window = GetReferenceWindow(
352      added_window->GetRootWindow(), added_window, &single_window);
353
354  if (!other_shown_window) {
355    // It could be that this window is the first window joining the workspace.
356    if (!WindowPositionCanBeManaged(added_window) || other_shown_window)
357      return;
358    // Since we might be going from 0 to 1 window, we have to arrange the new
359    // window to a good default.
360    AutoPlaceSingleWindow(added_window, false);
361    return;
362  }
363
364  gfx::Rect other_bounds = other_shown_window->bounds();
365  gfx::Rect work_area = GetWorkAreaForWindowInParent(added_window);
366  bool move_other_right =
367      other_bounds.CenterPoint().x() > work_area.x() + work_area.width() / 2;
368
369  // Push the other window to the size only if there are two windows left.
370  if (single_window) {
371    // When going from one to two windows both windows loose their
372    // "positioned by user" flags.
373    added_window_state->set_bounds_changed_by_user(false);
374    wm::WindowState* other_window_state =
375        wm::GetWindowState(other_shown_window);
376    other_window_state->set_bounds_changed_by_user(false);
377
378    if (WindowPositionCanBeManaged(other_shown_window)) {
379      // Don't override pre auto managed bounds as the current bounds
380      // may not be original.
381      if (!other_window_state->pre_auto_manage_window_bounds())
382        other_window_state->SetPreAutoManageWindowBounds(other_bounds);
383
384      // Push away the other window after remembering its current position.
385      if (MoveRectToOneSide(work_area, move_other_right, &other_bounds))
386        SetBoundsAnimated(other_shown_window, other_bounds, work_area);
387    }
388  }
389
390  // Remember the current location of the window if it's new and push
391  // it also to the opposite location if needed.  Since it is just
392  // being shown, we do not need to animate it.
393  gfx::Rect added_bounds = added_window->bounds();
394  if (!added_window_state->pre_auto_manage_window_bounds())
395    added_window_state->SetPreAutoManageWindowBounds(added_bounds);
396  if (MoveRectToOneSide(work_area, !move_other_right, &added_bounds))
397    added_window->SetBounds(added_bounds);
398}
399
400WindowPositioner::WindowPositioner()
401    : pop_position_offset_increment_x(0),
402      pop_position_offset_increment_y(0),
403      popup_position_offset_from_screen_corner_x(0),
404      popup_position_offset_from_screen_corner_y(0),
405      last_popup_position_x_(0),
406      last_popup_position_y_(0) {
407}
408
409WindowPositioner::~WindowPositioner() {
410}
411
412gfx::Rect WindowPositioner::GetDefaultWindowBounds(
413    const gfx::Display& display) {
414  const gfx::Rect work_area = display.work_area();
415  // There should be a 'desktop' border around the window at the left and right
416  // side.
417  int default_width = work_area.width() - 2 * kDesktopBorderSize;
418  // There should also be a 'desktop' border around the window at the top.
419  // Since the workspace excludes the tray area we only need one border size.
420  int default_height = work_area.height() - kDesktopBorderSize;
421  int offset_x = kDesktopBorderSize;
422  if (default_width > kMaximumWindowWidth) {
423    // The window should get centered on the screen and not follow the grid.
424    offset_x = (work_area.width() - kMaximumWindowWidth) / 2;
425    default_width = kMaximumWindowWidth;
426  }
427  return gfx::Rect(work_area.x() + offset_x,
428                   work_area.y() + kDesktopBorderSize,
429                   default_width,
430                   default_height);
431}
432
433gfx::Rect WindowPositioner::GetPopupPosition(const gfx::Rect& old_pos) {
434  int grid = kMinimumWindowOffset;
435  popup_position_offset_from_screen_corner_x = grid;
436  popup_position_offset_from_screen_corner_y = grid;
437  if (!pop_position_offset_increment_x) {
438    // When the popup position increment is 0, the last popup position
439    // was not yet initialized.
440    last_popup_position_x_ = popup_position_offset_from_screen_corner_x;
441    last_popup_position_y_ = popup_position_offset_from_screen_corner_y;
442  }
443  pop_position_offset_increment_x = grid;
444  pop_position_offset_increment_y = grid;
445  // We handle the Multi monitor support by retrieving the active window's
446  // work area.
447  aura::Window* window = wm::GetActiveWindow();
448  const gfx::Rect work_area = window && window->IsVisible() ?
449      Shell::GetScreen()->GetDisplayNearestWindow(window).work_area() :
450      Shell::GetScreen()->GetPrimaryDisplay().work_area();
451  // Only try to reposition the popup when it is not spanning the entire
452  // screen.
453  if ((old_pos.width() + popup_position_offset_from_screen_corner_x >=
454      work_area.width()) ||
455      (old_pos.height() + popup_position_offset_from_screen_corner_y >=
456       work_area.height()))
457    return AlignPopupPosition(old_pos, work_area, grid);
458  const gfx::Rect result = SmartPopupPosition(old_pos, work_area, grid);
459  if (!result.IsEmpty())
460    return AlignPopupPosition(result, work_area, grid);
461  return NormalPopupPosition(old_pos, work_area);
462}
463
464// static
465void WindowPositioner::SetMaximizeFirstWindow(bool maximize) {
466  maximize_first_window = maximize;
467}
468
469gfx::Rect WindowPositioner::NormalPopupPosition(
470    const gfx::Rect& old_pos,
471    const gfx::Rect& work_area) {
472  int w = old_pos.width();
473  int h = old_pos.height();
474  // Note: The 'last_popup_position' is checked and kept relative to the
475  // screen size. The offsetting will be done in the last step when the
476  // target rectangle gets returned.
477  bool reset = false;
478  if (last_popup_position_y_ + h > work_area.height() ||
479      last_popup_position_x_ + w > work_area.width()) {
480    // Popup does not fit on screen. Reset to next diagonal row.
481    last_popup_position_x_ -= last_popup_position_y_ -
482                              popup_position_offset_from_screen_corner_x -
483                              pop_position_offset_increment_x;
484    last_popup_position_y_ = popup_position_offset_from_screen_corner_y;
485    reset = true;
486  }
487  if (last_popup_position_x_ + w > work_area.width()) {
488    // Start again over.
489    last_popup_position_x_ = popup_position_offset_from_screen_corner_x;
490    last_popup_position_y_ = popup_position_offset_from_screen_corner_y;
491    reset = true;
492  }
493  int x = last_popup_position_x_;
494  int y = last_popup_position_y_;
495  if (!reset) {
496    last_popup_position_x_ += pop_position_offset_increment_x;
497    last_popup_position_y_ += pop_position_offset_increment_y;
498  }
499  return gfx::Rect(x + work_area.x(), y + work_area.y(), w, h);
500}
501
502gfx::Rect WindowPositioner::SmartPopupPosition(
503    const gfx::Rect& old_pos,
504    const gfx::Rect& work_area,
505    int grid) {
506  const std::vector<aura::Window*> windows =
507      MruWindowTracker::BuildWindowList(false);
508
509  std::vector<const gfx::Rect*> regions;
510  // Process the window list and check if we can bail immediately.
511  for (size_t i = 0; i < windows.size(); i++) {
512    // We only include opaque and visible windows.
513    if (windows[i] && windows[i]->IsVisible() && windows[i]->layer() &&
514        (!windows[i]->transparent() ||
515         windows[i]->layer()->GetTargetOpacity() == 1.0)) {
516      wm::WindowState* window_state = wm::GetWindowState(windows[i]);
517      // When any window is maximized we cannot find any free space.
518      if (window_state->IsMaximizedOrFullscreen())
519        return gfx::Rect(0, 0, 0, 0);
520      if (window_state->IsNormalOrSnapped())
521        regions.push_back(&windows[i]->bounds());
522    }
523  }
524
525  if (regions.empty())
526    return gfx::Rect(0, 0, 0, 0);
527
528  int w = old_pos.width();
529  int h = old_pos.height();
530  int x_end = work_area.width() / 2;
531  int x, x_increment;
532  // We parse for a proper location on the screen. We do this in two runs:
533  // The first run will start from the left, parsing down, skipping any
534  // overlapping windows it will encounter until the popup's height can not
535  // be served anymore. Then the next grid position to the right will be
536  // taken, and the same cycle starts again. This will be repeated until we
537  // hit the middle of the screen (or we find a suitable location).
538  // In the second run we parse beginning from the right corner downwards and
539  // then to the left.
540  // When no location was found, an empty rectangle will be returned.
541  for (int run = 0; run < 2; run++) {
542    if (run == 0) { // First run: Start left, parse right till mid screen.
543      x = 0;
544      x_increment = pop_position_offset_increment_x;
545    } else { // Second run: Start right, parse left till mid screen.
546      x = work_area.width() - w;
547      x_increment = -pop_position_offset_increment_x;
548    }
549    // Note: The passing (x,y,w,h) window is always relative to the work area's
550    // origin.
551    for (; x_increment > 0 ? (x < x_end) : (x > x_end); x += x_increment) {
552      int y = 0;
553      while (y + h <= work_area.height()) {
554        size_t i;
555        for (i = 0; i < regions.size(); i++) {
556          if (regions[i]->Intersects(gfx::Rect(x + work_area.x(),
557                                               y + work_area.y(), w, h))) {
558            y = regions[i]->bottom() - work_area.y();
559            break;
560          }
561        }
562        if (i >= regions.size())
563          return gfx::Rect(x + work_area.x(), y + work_area.y(), w, h);
564      }
565    }
566  }
567  return gfx::Rect(0, 0, 0, 0);
568}
569
570gfx::Rect WindowPositioner::AlignPopupPosition(
571    const gfx::Rect& pos,
572    const gfx::Rect& work_area,
573    int grid) {
574  if (grid <= 1)
575    return pos;
576
577  int x = pos.x() - (pos.x() - work_area.x()) % grid;
578  int y = pos.y() - (pos.y() - work_area.y()) % grid;
579  int w = pos.width();
580  int h = pos.height();
581
582  // If the alignment was pushing the window out of the screen, we ignore the
583  // alignment for that call.
584  if (abs(pos.right() - work_area.right()) < grid)
585    x = work_area.right() - w;
586  if (abs(pos.bottom() - work_area.bottom()) < grid)
587    y = work_area.bottom() - h;
588  return gfx::Rect(x, y, w, h);
589}
590
591}  // namespace ash
592