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