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