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.
5 #include "ash/wm/window_positioner.h"
7 #include "ash/ash_switches.h"
8 #include "ash/screen_util.h"
10 #include "ash/shell_window_ids.h"
11 #include "ash/wm/mru_window_tracker.h"
12 #include "ash/wm/window_resizer.h"
13 #include "ash/wm/window_state.h"
14 #include "ash/wm/window_util.h"
15 #include "base/command_line.h"
16 #include "ui/aura/window.h"
17 #include "ui/aura/window_delegate.h"
18 #include "ui/aura/window_event_dispatcher.h"
19 #include "ui/compositor/layer.h"
20 #include "ui/compositor/scoped_layer_animation_settings.h"
21 #include "ui/gfx/screen.h"
22 #include "ui/wm/core/window_animations.h"
26 const int WindowPositioner::kMinimumWindowOffset = 32;
28 // The number of pixels which are kept free top, left and right when a window
29 // gets positioned to its default location.
31 const int WindowPositioner::kDesktopBorderSize = 16;
33 // Maximum width of a window even if there is more room on the desktop.
35 const int WindowPositioner::kMaximumWindowWidth = 1100;
39 // When a window gets opened in default mode and the screen is less than or
40 // equal to this width, the window will get opened in maximized mode. This value
41 // can be reduced to a "tame" number if the feature is disabled.
42 const int kForceMaximizeWidthLimit = 1366;
44 // The time in milliseconds which should be used to visually move a window
45 // through an automatic "intelligent" window management option.
46 const int kWindowAutoMoveDurationMS = 125;
48 // If set to true all window repositioning actions will be ignored. Set through
49 // WindowPositioner::SetIgnoreActivations().
50 static bool disable_auto_positioning = false;
52 // If set to true, by default the first window in ASH will be maximized.
53 static bool maximize_first_window = false;
55 // Check if any management should be performed (with a given |window|).
56 bool UseAutoWindowManager(const aura::Window* window) {
57 if (disable_auto_positioning)
59 const wm::WindowState* window_state = wm::GetWindowState(window);
60 return !window_state->is_dragged() && window_state->window_position_managed();
63 // Check if a given |window| can be managed. This includes that it's state is
64 // not minimized/maximized/the user has changed it's size by hand already.
65 // It furthermore checks for the WindowIsManaged status.
66 bool WindowPositionCanBeManaged(const aura::Window* window) {
67 if (disable_auto_positioning)
69 const wm::WindowState* window_state = wm::GetWindowState(window);
70 return window_state->window_position_managed() &&
71 !window_state->IsMinimized() &&
72 !window_state->IsMaximized() &&
73 !window_state->bounds_changed_by_user();
76 // Get the work area for a given |window| in parent coordinates.
77 gfx::Rect GetWorkAreaForWindowInParent(aura::Window* window) {
79 // On Win 8, the host window can't be resized, so
80 // use window's bounds instead.
81 // TODO(oshima): Emulate host window resize on win8.
82 gfx::Rect work_area = gfx::Rect(window->parent()->bounds().size());
83 work_area.Inset(Shell::GetScreen()->GetDisplayMatching(
84 window->parent()->GetBoundsInScreen()).GetWorkAreaInsets());
87 return ScreenUtil::GetDisplayWorkAreaBoundsInParent(window);
91 // Move the given |bounds| on the available |work_area| in the direction
92 // indicated by |move_right|. If |move_right| is true, the rectangle gets moved
93 // to the right edge, otherwise to the left one.
94 bool MoveRectToOneSide(const gfx::Rect& work_area,
98 if (work_area.right() > bounds->right()) {
99 bounds->set_x(work_area.right() - bounds->width());
103 if (work_area.x() < bounds->x()) {
104 bounds->set_x(work_area.x());
111 // Move a |window| to a new |bound|. Animate if desired by user.
112 // Note: The function will do nothing if the bounds did not change.
113 void SetBoundsAnimated(aura::Window* window, const gfx::Rect& bounds) {
114 if (bounds == window->GetTargetBounds())
117 if (::wm::WindowAnimationsDisabled(window)) {
118 window->SetBounds(bounds);
122 ui::ScopedLayerAnimationSettings settings(window->layer()->GetAnimator());
123 settings.SetTransitionDuration(
124 base::TimeDelta::FromMilliseconds(kWindowAutoMoveDurationMS));
125 window->SetBounds(bounds);
128 // Move |window| into the center of the screen - or restore it to the previous
130 void AutoPlaceSingleWindow(aura::Window* window, bool animated) {
131 gfx::Rect work_area = GetWorkAreaForWindowInParent(window);
132 gfx::Rect bounds = window->bounds();
133 const gfx::Rect* user_defined_area =
134 wm::GetWindowState(window)->pre_auto_manage_window_bounds();
135 if (user_defined_area) {
136 bounds = *user_defined_area;
137 ash::wm::AdjustBoundsToEnsureMinimumWindowVisibility(work_area, &bounds);
139 // Center the window (only in x).
140 bounds.set_x(work_area.x() + (work_area.width() - bounds.width()) / 2);
144 SetBoundsAnimated(window, bounds);
146 window->SetBounds(bounds);
149 // Get the first open (non minimized) window which is on the screen defined.
150 aura::Window* GetReferenceWindow(const aura::Window* root_window,
151 const aura::Window* exclude,
152 bool *single_window) {
154 *single_window = true;
155 // Get the active window.
156 aura::Window* active = ash::wm::GetActiveWindow();
157 if (active && active->GetRootWindow() != root_window)
160 // Get a list of all windows.
161 const std::vector<aura::Window*> windows =
162 ash::MruWindowTracker::BuildWindowList(false);
167 aura::Window::Windows::const_iterator iter = windows.begin();
168 // Find the index of the current active window.
170 iter = std::find(windows.begin(), windows.end(), active);
172 int index = (iter == windows.end()) ? 0 : (iter - windows.begin());
174 // Scan the cycle list backwards to see which is the second topmost window
175 // (and so on). Note that we might cycle a few indices twice if there is no
176 // suitable window. However - since the list is fairly small this should be
177 // very fast anyways.
178 aura::Window* found = NULL;
179 for (int i = index + windows.size(); i >= 0; i--) {
180 aura::Window* window = windows[i % windows.size()];
181 if (window != exclude && window->type() == ui::wm::WINDOW_TYPE_NORMAL &&
182 window->GetRootWindow() == root_window && window->TargetVisibility() &&
183 wm::GetWindowState(window)->window_position_managed()) {
184 if (found && found != window) {
185 // no need to check !single_window because the function must have
186 // been already returned in the "if (!single_window)" below.
187 *single_window = false;
191 // If there is no need to check single window, return now.
202 int WindowPositioner::GetForceMaximizedWidthLimit() {
203 return kForceMaximizeWidthLimit;
207 void WindowPositioner::GetBoundsAndShowStateForNewWindow(
208 const gfx::Screen* screen,
209 const aura::Window* new_window,
210 bool is_saved_bounds,
211 ui::WindowShowState show_state_in,
212 gfx::Rect* bounds_in_out,
213 ui::WindowShowState* show_state_out) {
215 // Always open new window in the target display.
216 aura::Window* target = Shell::GetTargetRootWindow();
218 aura::Window* top_window = GetReferenceWindow(target, NULL, NULL);
219 // Our window should not have any impact if we are already on top.
220 if (top_window == new_window)
223 // If there is no valid other window we take and adjust the passed coordinates
226 gfx::Rect work_area = screen->GetDisplayNearestWindow(target).work_area();
228 bounds_in_out->AdjustToFit(work_area);
229 // Use adjusted saved bounds, if there is one.
232 // When using "small screens" we want to always open in full screen mode.
233 if (show_state_in == ui::SHOW_STATE_DEFAULT && (maximize_first_window ||
234 (work_area.width() <= GetForceMaximizedWidthLimit() &&
235 (!new_window || !wm::GetWindowState(new_window)->IsFullscreen())))) {
236 *show_state_out = ui::SHOW_STATE_MAXIMIZED;
240 wm::WindowState* top_window_state = wm::GetWindowState(top_window);
241 bool maximized = top_window_state->IsMaximized();
242 // We ignore the saved show state, but look instead for the top level
243 // window's show state.
244 if (show_state_in == ui::SHOW_STATE_DEFAULT) {
245 *show_state_out = maximized ? ui::SHOW_STATE_MAXIMIZED :
246 ui::SHOW_STATE_DEFAULT;
250 bool has_restore_bounds = top_window_state->HasRestoreBounds();
251 if (has_restore_bounds) {
252 // For a maximized window ignore the real bounds of the top level window
253 // and use its restore bounds instead. Offset the bounds to prevent the
254 // windows from overlapping exactly when restored.
255 *bounds_in_out = top_window_state->GetRestoreBoundsInScreen() +
256 gfx::Vector2d(kMinimumWindowOffset, kMinimumWindowOffset);
258 if (is_saved_bounds || has_restore_bounds) {
259 gfx::Rect work_area = screen->GetDisplayNearestWindow(target).work_area();
260 bounds_in_out->AdjustToFit(work_area);
261 // Use adjusted saved bounds or restore bounds, if there is one.
266 // Use the size of the other window. The window's bound will be rearranged
267 // in ash::WorkspaceLayoutManager using this location.
268 *bounds_in_out = top_window->GetBoundsInScreen();
272 void WindowPositioner::RearrangeVisibleWindowOnHideOrRemove(
273 const aura::Window* removed_window) {
274 if (!UseAutoWindowManager(removed_window))
276 // Find a single open browser window.
278 aura::Window* other_shown_window = GetReferenceWindow(
279 removed_window->GetRootWindow(), removed_window, &single_window);
280 if (!other_shown_window || !single_window ||
281 !WindowPositionCanBeManaged(other_shown_window))
283 AutoPlaceSingleWindow(other_shown_window, true);
287 bool WindowPositioner::DisableAutoPositioning(bool ignore) {
288 bool old_state = disable_auto_positioning;
289 disable_auto_positioning = ignore;
294 void WindowPositioner::RearrangeVisibleWindowOnShow(
295 aura::Window* added_window) {
296 wm::WindowState* added_window_state = wm::GetWindowState(added_window);
297 if (!added_window->TargetVisibility())
300 if (!UseAutoWindowManager(added_window) ||
301 added_window_state->bounds_changed_by_user()) {
302 if (added_window_state->minimum_visibility()) {
303 // Guarante minimum visibility within the work area.
304 gfx::Rect work_area = GetWorkAreaForWindowInParent(added_window);
305 gfx::Rect bounds = added_window->bounds();
306 gfx::Rect new_bounds = bounds;
307 ash::wm::AdjustBoundsToEnsureMinimumWindowVisibility(work_area,
309 if (new_bounds != bounds)
310 added_window->SetBounds(new_bounds);
314 // Find a single open managed window.
316 aura::Window* other_shown_window = GetReferenceWindow(
317 added_window->GetRootWindow(), added_window, &single_window);
319 if (!other_shown_window) {
320 // It could be that this window is the first window joining the workspace.
321 if (!WindowPositionCanBeManaged(added_window) || other_shown_window)
323 // Since we might be going from 0 to 1 window, we have to arrange the new
324 // window to a good default.
325 AutoPlaceSingleWindow(added_window, false);
329 gfx::Rect other_bounds = other_shown_window->bounds();
330 gfx::Rect work_area = GetWorkAreaForWindowInParent(added_window);
331 bool move_other_right =
332 other_bounds.CenterPoint().x() > work_area.x() + work_area.width() / 2;
334 // Push the other window to the size only if there are two windows left.
336 // When going from one to two windows both windows loose their
337 // "positioned by user" flags.
338 added_window_state->set_bounds_changed_by_user(false);
339 wm::WindowState* other_window_state =
340 wm::GetWindowState(other_shown_window);
341 other_window_state->set_bounds_changed_by_user(false);
343 if (WindowPositionCanBeManaged(other_shown_window)) {
344 // Don't override pre auto managed bounds as the current bounds
345 // may not be original.
346 if (!other_window_state->pre_auto_manage_window_bounds())
347 other_window_state->SetPreAutoManageWindowBounds(other_bounds);
349 // Push away the other window after remembering its current position.
350 if (MoveRectToOneSide(work_area, move_other_right, &other_bounds))
351 SetBoundsAnimated(other_shown_window, other_bounds);
355 // Remember the current location of the window if it's new and push
356 // it also to the opposite location if needed. Since it is just
357 // being shown, we do not need to animate it.
358 gfx::Rect added_bounds = added_window->bounds();
359 if (!added_window_state->pre_auto_manage_window_bounds())
360 added_window_state->SetPreAutoManageWindowBounds(added_bounds);
361 if (MoveRectToOneSide(work_area, !move_other_right, &added_bounds))
362 added_window->SetBounds(added_bounds);
365 WindowPositioner::WindowPositioner()
366 : pop_position_offset_increment_x(0),
367 pop_position_offset_increment_y(0),
368 popup_position_offset_from_screen_corner_x(0),
369 popup_position_offset_from_screen_corner_y(0),
370 last_popup_position_x_(0),
371 last_popup_position_y_(0) {
374 WindowPositioner::~WindowPositioner() {
377 gfx::Rect WindowPositioner::GetDefaultWindowBounds(
378 const gfx::Display& display) {
379 const gfx::Rect work_area = display.work_area();
380 // There should be a 'desktop' border around the window at the left and right
382 int default_width = work_area.width() - 2 * kDesktopBorderSize;
383 // There should also be a 'desktop' border around the window at the top.
384 // Since the workspace excludes the tray area we only need one border size.
385 int default_height = work_area.height() - kDesktopBorderSize;
386 int offset_x = kDesktopBorderSize;
387 if (default_width > kMaximumWindowWidth) {
388 // The window should get centered on the screen and not follow the grid.
389 offset_x = (work_area.width() - kMaximumWindowWidth) / 2;
390 default_width = kMaximumWindowWidth;
392 return gfx::Rect(work_area.x() + offset_x,
393 work_area.y() + kDesktopBorderSize,
398 gfx::Rect WindowPositioner::GetPopupPosition(const gfx::Rect& old_pos) {
399 int grid = kMinimumWindowOffset;
400 popup_position_offset_from_screen_corner_x = grid;
401 popup_position_offset_from_screen_corner_y = grid;
402 if (!pop_position_offset_increment_x) {
403 // When the popup position increment is 0, the last popup position
404 // was not yet initialized.
405 last_popup_position_x_ = popup_position_offset_from_screen_corner_x;
406 last_popup_position_y_ = popup_position_offset_from_screen_corner_y;
408 pop_position_offset_increment_x = grid;
409 pop_position_offset_increment_y = grid;
410 // We handle the Multi monitor support by retrieving the active window's
412 aura::Window* window = wm::GetActiveWindow();
413 const gfx::Rect work_area = window && window->IsVisible() ?
414 Shell::GetScreen()->GetDisplayNearestWindow(window).work_area() :
415 Shell::GetScreen()->GetPrimaryDisplay().work_area();
416 // Only try to reposition the popup when it is not spanning the entire
418 if ((old_pos.width() + popup_position_offset_from_screen_corner_x >=
419 work_area.width()) ||
420 (old_pos.height() + popup_position_offset_from_screen_corner_y >=
422 return AlignPopupPosition(old_pos, work_area, grid);
423 const gfx::Rect result = SmartPopupPosition(old_pos, work_area, grid);
424 if (!result.IsEmpty())
425 return AlignPopupPosition(result, work_area, grid);
426 return NormalPopupPosition(old_pos, work_area);
430 void WindowPositioner::SetMaximizeFirstWindow(bool maximize) {
431 maximize_first_window = maximize;
434 gfx::Rect WindowPositioner::NormalPopupPosition(
435 const gfx::Rect& old_pos,
436 const gfx::Rect& work_area) {
437 int w = old_pos.width();
438 int h = old_pos.height();
439 // Note: The 'last_popup_position' is checked and kept relative to the
440 // screen size. The offsetting will be done in the last step when the
441 // target rectangle gets returned.
443 if (last_popup_position_y_ + h > work_area.height() ||
444 last_popup_position_x_ + w > work_area.width()) {
445 // Popup does not fit on screen. Reset to next diagonal row.
446 last_popup_position_x_ -= last_popup_position_y_ -
447 popup_position_offset_from_screen_corner_x -
448 pop_position_offset_increment_x;
449 last_popup_position_y_ = popup_position_offset_from_screen_corner_y;
452 if (last_popup_position_x_ + w > work_area.width()) {
454 last_popup_position_x_ = popup_position_offset_from_screen_corner_x;
455 last_popup_position_y_ = popup_position_offset_from_screen_corner_y;
458 int x = last_popup_position_x_;
459 int y = last_popup_position_y_;
461 last_popup_position_x_ += pop_position_offset_increment_x;
462 last_popup_position_y_ += pop_position_offset_increment_y;
464 return gfx::Rect(x + work_area.x(), y + work_area.y(), w, h);
467 gfx::Rect WindowPositioner::SmartPopupPosition(
468 const gfx::Rect& old_pos,
469 const gfx::Rect& work_area,
471 const std::vector<aura::Window*> windows =
472 MruWindowTracker::BuildWindowList(false);
474 std::vector<const gfx::Rect*> regions;
475 // Process the window list and check if we can bail immediately.
476 for (size_t i = 0; i < windows.size(); i++) {
477 // We only include opaque and visible windows.
478 if (windows[i] && windows[i]->IsVisible() && windows[i]->layer() &&
479 (!windows[i]->transparent() ||
480 windows[i]->layer()->GetTargetOpacity() == 1.0)) {
481 wm::WindowState* window_state = wm::GetWindowState(windows[i]);
482 // When any window is maximized we cannot find any free space.
483 if (window_state->IsMaximizedOrFullscreen())
484 return gfx::Rect(0, 0, 0, 0);
485 if (window_state->IsNormalOrSnapped())
486 regions.push_back(&windows[i]->bounds());
491 return gfx::Rect(0, 0, 0, 0);
493 int w = old_pos.width();
494 int h = old_pos.height();
495 int x_end = work_area.width() / 2;
497 // We parse for a proper location on the screen. We do this in two runs:
498 // The first run will start from the left, parsing down, skipping any
499 // overlapping windows it will encounter until the popup's height can not
500 // be served anymore. Then the next grid position to the right will be
501 // taken, and the same cycle starts again. This will be repeated until we
502 // hit the middle of the screen (or we find a suitable location).
503 // In the second run we parse beginning from the right corner downwards and
505 // When no location was found, an empty rectangle will be returned.
506 for (int run = 0; run < 2; run++) {
507 if (run == 0) { // First run: Start left, parse right till mid screen.
509 x_increment = pop_position_offset_increment_x;
510 } else { // Second run: Start right, parse left till mid screen.
511 x = work_area.width() - w;
512 x_increment = -pop_position_offset_increment_x;
514 // Note: The passing (x,y,w,h) window is always relative to the work area's
516 for (; x_increment > 0 ? (x < x_end) : (x > x_end); x += x_increment) {
518 while (y + h <= work_area.height()) {
520 for (i = 0; i < regions.size(); i++) {
521 if (regions[i]->Intersects(gfx::Rect(x + work_area.x(),
522 y + work_area.y(), w, h))) {
523 y = regions[i]->bottom() - work_area.y();
527 if (i >= regions.size())
528 return gfx::Rect(x + work_area.x(), y + work_area.y(), w, h);
532 return gfx::Rect(0, 0, 0, 0);
535 gfx::Rect WindowPositioner::AlignPopupPosition(
536 const gfx::Rect& pos,
537 const gfx::Rect& work_area,
542 int x = pos.x() - (pos.x() - work_area.x()) % grid;
543 int y = pos.y() - (pos.y() - work_area.y()) % grid;
545 int h = pos.height();
547 // If the alignment was pushing the window out of the screen, we ignore the
548 // alignment for that call.
549 if (abs(pos.right() - work_area.right()) < grid)
550 x = work_area.right() - w;
551 if (abs(pos.bottom() - work_area.bottom()) < grid)
552 y = work_area.bottom() - h;
553 return gfx::Rect(x, y, w, h);