workspace_window_resizer.cc 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781
  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. #include "ash/wm/workspace/workspace_window_resizer.h"
  5. #include <algorithm>
  6. #include <cmath>
  7. #include <utility>
  8. #include "ash/constants/app_types.h"
  9. #include "ash/constants/ash_features.h"
  10. #include "ash/metrics/pip_uma.h"
  11. #include "ash/public/cpp/shell_window_ids.h"
  12. #include "ash/root_window_controller.h"
  13. #include "ash/scoped_animation_disabler.h"
  14. #include "ash/screen_util.h"
  15. #include "ash/session/session_controller_impl.h"
  16. #include "ash/shell.h"
  17. #include "ash/utility/haptics_util.h"
  18. #include "ash/wm/default_window_resizer.h"
  19. #include "ash/wm/desks/desks_util.h"
  20. #include "ash/wm/drag_window_resizer.h"
  21. #include "ash/wm/float/tablet_mode_float_window_resizer.h"
  22. #include "ash/wm/overview/overview_controller.h"
  23. #include "ash/wm/pip/pip_window_resizer.h"
  24. #include "ash/wm/tablet_mode/tablet_mode_browser_window_drag_delegate.h"
  25. #include "ash/wm/tablet_mode/tablet_mode_controller.h"
  26. #include "ash/wm/tablet_mode/tablet_mode_window_drag_delegate.h"
  27. #include "ash/wm/tablet_mode/tablet_mode_window_resizer.h"
  28. #include "ash/wm/toplevel_window_event_handler.h"
  29. #include "ash/wm/window_animations.h"
  30. #include "ash/wm/window_positioning_utils.h"
  31. #include "ash/wm/window_state.h"
  32. #include "ash/wm/window_util.h"
  33. #include "ash/wm/wm_event.h"
  34. #include "ash/wm/workspace/phantom_window_controller.h"
  35. #include "base/bind.h"
  36. #include "base/containers/contains.h"
  37. #include "base/metrics/histogram_macros.h"
  38. #include "base/metrics/user_metrics.h"
  39. #include "chromeos/ui/base/window_properties.h"
  40. #include "chromeos/ui/wm/features.h"
  41. #include "ui/aura/client/aura_constants.h"
  42. #include "ui/aura/client/window_types.h"
  43. #include "ui/aura/window.h"
  44. #include "ui/aura/window_delegate.h"
  45. #include "ui/base/class_property.h"
  46. #include "ui/base/hit_test.h"
  47. #include "ui/compositor/layer.h"
  48. #include "ui/display/display.h"
  49. #include "ui/display/screen.h"
  50. #include "ui/events/devices/haptic_touchpad_effects.h"
  51. #include "ui/gfx/geometry/point_conversions.h"
  52. #include "ui/gfx/geometry/transform.h"
  53. #include "ui/wm/core/coordinate_conversion.h"
  54. #include "ui/wm/core/cursor_manager.h"
  55. namespace ash {
  56. namespace {
  57. using ::chromeos::kFrameRestoreLookKey;
  58. using ::chromeos::WindowStateType;
  59. constexpr double kMinHorizVelocityForWindowSwipe = 1100;
  60. constexpr double kMinVertVelocityForWindowMinimize = 1000;
  61. // Snap region when dragging close to the edges. That is, as the window gets
  62. // this close to an edge of the screen it snaps to the edge.
  63. constexpr int kScreenEdgeInset = 8;
  64. // Snapping distance used instead of kScreenEdgeInset when resizing a window
  65. // using touchscreen.
  66. constexpr int kScreenEdgeInsetForTouchDrag = 32;
  67. // If an edge of the work area is at an edge of the display, then you can snap a
  68. // window by dragging to a point within this far inward from that edge. This
  69. // tolerance is helpful in cases where you can drag out of the display. For
  70. // mouse dragging, you may be able to drag out of the display because there is a
  71. // neighboring display. For touch dragging, you may be able to drag out of the
  72. // display because the physical device has a border around the display. Either
  73. // case makes it difficult to drag to the edge without this tolerance.
  74. constexpr int kScreenEdgeInsetForSnappingSides = 32;
  75. // Similar but for snapping to the top. It is less aggressive since users need
  76. // to grab the caption and making it too aggressive will lead to more accidental
  77. // snaps when trying to align windows' top edges to the top of the display.
  78. constexpr int kScreenEdgeInsetForSnappingTop = 8;
  79. // When dragging an attached window this is the min size we'll make sure is
  80. // visible. In the vertical direction we take the max of this and that from
  81. // the delegate.
  82. constexpr int kMinOnscreenSize = 20;
  83. // The amount of pixels that needs to be moved during a caption area drag from a
  84. // snapped window before the window restores.
  85. constexpr int kResizeRestoreDragThresholdDp = 5;
  86. // The UMA histogram that records presentation time for tab dragging between
  87. // windows in clamshell mode.
  88. constexpr char kTabDraggingInClamshellModeHistogram[] =
  89. "Ash.TabDrag.PresentationTime.ClamshellMode";
  90. constexpr char kTabDraggingInClamshellModeMaxLatencyHistogram[] =
  91. "Ash.TabDrag.PresentationTime.MaxLatency.ClamshellMode";
  92. // Name of smoothness histograms of the cross fade animation that happens when
  93. // dragging a maximized window to maximize or unmaximize. Note that for drag
  94. // maximize, this only applies when the window's pre drag state is maximized.
  95. // For dragging from normal state to maximize, we use the regular cross fade
  96. // histogram as its not expected to perform differently. These are measured
  97. // separately from the regular cross fade animation because they have a shorter
  98. // duration and in the case of drag unmaximize, the window bounds are changing
  99. // while animating.
  100. constexpr char kDragUnmaximizeSmoothness[] =
  101. "Ash.Window.AnimationSmoothness.CrossFade.DragUnmaximize";
  102. constexpr char kDragMaximizeSmoothness[] =
  103. "Ash.Window.AnimationSmoothness.CrossFade.DragMaximize";
  104. // Duration of the cross fade animation used when dragging to unmaximize or
  105. // dragging to snap maximize.
  106. constexpr base::TimeDelta kCrossFadeDuration = base::Milliseconds(120);
  107. // The amount of pixels that needs to be moved during a top screen drag to reset
  108. // dwell time.
  109. constexpr int kSnapDragDwellTimeResetThreshold = 8;
  110. // Dwell time before snap to maximize. The countdown starts when window dragged
  111. // into snap region.
  112. constexpr base::TimeDelta kDwellTime = base::Milliseconds(400);
  113. // Dwell time before turning snap top to snap to maximize. The countdown starts
  114. // when window dragged into snap region.
  115. constexpr base::TimeDelta kDwellLongTime = base::Milliseconds(1000);
  116. // The min amount of vertical movement needed for to trigger a snap to
  117. // maximize.
  118. constexpr int kSnapTriggerVerticalMoveThreshold = 64;
  119. // Current instance for use by the WorkspaceWindowResizerTest.
  120. WorkspaceWindowResizer* instance = nullptr;
  121. // Possible areas that can trigger windows snap and maximize.
  122. enum class DragTriggerArea { kLeft, kRight, kBottom, kTop, kInvalid };
  123. // Returns true if the window should stick to the edge.
  124. bool ShouldStickToEdge(int distance_from_edge, int sticky_size) {
  125. return distance_from_edge < sticky_size &&
  126. distance_from_edge > -sticky_size * 2;
  127. }
  128. // Returns the coordinate along the secondary axis to snap to.
  129. int CoordinateAlongSecondaryAxis(SecondaryMagnetismEdge edge,
  130. int leading,
  131. int trailing,
  132. int none) {
  133. switch (edge) {
  134. case SECONDARY_MAGNETISM_EDGE_LEADING:
  135. return leading;
  136. case SECONDARY_MAGNETISM_EDGE_TRAILING:
  137. return trailing;
  138. case SECONDARY_MAGNETISM_EDGE_NONE:
  139. return none;
  140. }
  141. NOTREACHED();
  142. return none;
  143. }
  144. // Returns the origin for |src| when magnetically attaching to |attach_to| along
  145. // the edges |edges|. |edges| is a bitmask of the MagnetismEdges.
  146. gfx::Point OriginForMagneticAttach(const gfx::Rect& src,
  147. const gfx::Rect& attach_to,
  148. const MatchedEdge& edge) {
  149. int x = 0, y = 0;
  150. switch (edge.primary_edge) {
  151. case MAGNETISM_EDGE_TOP:
  152. y = attach_to.bottom();
  153. break;
  154. case MAGNETISM_EDGE_LEFT:
  155. x = attach_to.right();
  156. break;
  157. case MAGNETISM_EDGE_BOTTOM:
  158. y = attach_to.y() - src.height();
  159. break;
  160. case MAGNETISM_EDGE_RIGHT:
  161. x = attach_to.x() - src.width();
  162. break;
  163. }
  164. switch (edge.primary_edge) {
  165. case MAGNETISM_EDGE_TOP:
  166. case MAGNETISM_EDGE_BOTTOM:
  167. x = CoordinateAlongSecondaryAxis(edge.secondary_edge, attach_to.x(),
  168. attach_to.right() - src.width(),
  169. src.x());
  170. break;
  171. case MAGNETISM_EDGE_LEFT:
  172. case MAGNETISM_EDGE_RIGHT:
  173. y = CoordinateAlongSecondaryAxis(edge.secondary_edge, attach_to.y(),
  174. attach_to.bottom() - src.height(),
  175. src.y());
  176. break;
  177. }
  178. return gfx::Point(x, y);
  179. }
  180. // Returns the bounds for a magnetic attach when resizing. |src| is the bounds
  181. // of window being resized, |attach_to| the bounds of the window to attach to
  182. // and |edge| identifies the edge to attach to.
  183. gfx::Rect BoundsForMagneticResizeAttach(const gfx::Rect& src,
  184. const gfx::Rect& attach_to,
  185. const MatchedEdge& edge) {
  186. int x = src.x();
  187. int y = src.y();
  188. int w = src.width();
  189. int h = src.height();
  190. gfx::Point attach_origin(OriginForMagneticAttach(src, attach_to, edge));
  191. switch (edge.primary_edge) {
  192. case MAGNETISM_EDGE_LEFT:
  193. x = attach_origin.x();
  194. w = src.right() - x;
  195. break;
  196. case MAGNETISM_EDGE_RIGHT:
  197. w += attach_origin.x() - src.x();
  198. break;
  199. case MAGNETISM_EDGE_TOP:
  200. y = attach_origin.y();
  201. h = src.bottom() - y;
  202. break;
  203. case MAGNETISM_EDGE_BOTTOM:
  204. h += attach_origin.y() - src.y();
  205. break;
  206. }
  207. switch (edge.primary_edge) {
  208. case MAGNETISM_EDGE_LEFT:
  209. case MAGNETISM_EDGE_RIGHT:
  210. if (edge.secondary_edge == SECONDARY_MAGNETISM_EDGE_LEADING) {
  211. y = attach_origin.y();
  212. h = src.bottom() - y;
  213. } else if (edge.secondary_edge == SECONDARY_MAGNETISM_EDGE_TRAILING) {
  214. h += attach_origin.y() - src.y();
  215. }
  216. break;
  217. case MAGNETISM_EDGE_TOP:
  218. case MAGNETISM_EDGE_BOTTOM:
  219. if (edge.secondary_edge == SECONDARY_MAGNETISM_EDGE_LEADING) {
  220. x = attach_origin.x();
  221. w = src.right() - x;
  222. } else if (edge.secondary_edge == SECONDARY_MAGNETISM_EDGE_TRAILING) {
  223. w += attach_origin.x() - src.x();
  224. }
  225. break;
  226. }
  227. return gfx::Rect(x, y, w, h);
  228. }
  229. // Converts a window component edge to the magnetic edge to snap to.
  230. uint32_t WindowComponentToMagneticEdge(int window_component) {
  231. switch (window_component) {
  232. case HTTOPLEFT:
  233. return MAGNETISM_EDGE_LEFT | MAGNETISM_EDGE_TOP;
  234. case HTTOPRIGHT:
  235. return MAGNETISM_EDGE_TOP | MAGNETISM_EDGE_RIGHT;
  236. case HTBOTTOMLEFT:
  237. return MAGNETISM_EDGE_LEFT | MAGNETISM_EDGE_BOTTOM;
  238. case HTBOTTOMRIGHT:
  239. return MAGNETISM_EDGE_RIGHT | MAGNETISM_EDGE_BOTTOM;
  240. case HTTOP:
  241. return MAGNETISM_EDGE_TOP;
  242. case HTBOTTOM:
  243. return MAGNETISM_EDGE_BOTTOM;
  244. case HTRIGHT:
  245. return MAGNETISM_EDGE_RIGHT;
  246. case HTLEFT:
  247. return MAGNETISM_EDGE_LEFT;
  248. default:
  249. break;
  250. }
  251. return 0;
  252. }
  253. // If |window| has a resize handle and |location_in_parent| occurs within it,
  254. // records UMA for it.
  255. void MaybeRecordResizeHandleUsage(aura::Window* window,
  256. const gfx::PointF& location_in_parent) {
  257. gfx::Rect* resize_bounds_in_pip =
  258. window->GetProperty(kWindowPipResizeHandleBoundsKey);
  259. if (!resize_bounds_in_pip)
  260. return;
  261. gfx::Point point_in_pip = gfx::ToRoundedPoint(location_in_parent);
  262. aura::Window::ConvertPointToTarget(window->parent(), window, &point_in_pip);
  263. if (resize_bounds_in_pip->Contains(point_in_pip)) {
  264. UMA_HISTOGRAM_ENUMERATION(ash::kAshPipEventsHistogramName,
  265. ash::AshPipEvents::CHROME_RESIZE_HANDLE_RESIZE);
  266. }
  267. }
  268. // Returns a WindowResizer if dragging |window| is allowed in tablet mode.
  269. std::unique_ptr<WindowResizer> CreateWindowResizerForTabletMode(
  270. aura::Window* window,
  271. const gfx::PointF& point_in_parent,
  272. int window_component,
  273. wm::WindowMoveSource source) {
  274. WindowState* window_state = WindowState::Get(window);
  275. // Dragging floated windows in tablet mode is allowed.
  276. // TODO(crbug.com/1338715): Investigate if we need to wrap the resizer in a
  277. // DragWindowResizer.
  278. if (window_state->IsFloated() && window_component == HTCAPTION) {
  279. window_state->CreateDragDetails(point_in_parent, HTCAPTION, source);
  280. return std::make_unique<TabletModeFloatWindowResizer>(window_state);
  281. }
  282. // Window dragging from top and tab dragging are disabled if "WebUITabStrip"
  283. // feature is enabled. "WebUITabStrip" will be enabled on 81 for Krane and on
  284. // 82 for all other boards.
  285. if (features::IsWebUITabStripEnabled())
  286. return nullptr;
  287. // Only maximized/fullscreen/snapped window can be dragged from the top of
  288. // the screen.
  289. if (!window_state->IsMaximized() && !window_state->IsFullscreen() &&
  290. !window_state->IsSnapped()) {
  291. return nullptr;
  292. }
  293. AppType app_type =
  294. static_cast<AppType>(window->GetProperty(aura::client::kAppType));
  295. // App windows can be dragged from the client area (see
  296. // ToplevelWindowEventHandler).
  297. if (app_type != AppType::BROWSER && app_type != AppType::LACROS &&
  298. window_component == HTCLIENT) {
  299. DCHECK_EQ(source, ::wm::WINDOW_MOVE_SOURCE_TOUCH);
  300. window_state->CreateDragDetails(point_in_parent, HTCLIENT,
  301. ::wm::WINDOW_MOVE_SOURCE_TOUCH);
  302. std::unique_ptr<WindowResizer> window_resizer =
  303. std::make_unique<TabletModeWindowResizer>(
  304. window_state, std::make_unique<TabletModeWindowDragDelegate>());
  305. return std::make_unique<DragWindowResizer>(std::move(window_resizer),
  306. window_state);
  307. }
  308. // Only allow drag that happens on caption or top area. Note: for a maximized
  309. // or fullscreen window, the window component here is always HTCAPTION, but
  310. // for a snapped window, the window component here can either be HTCAPTION or
  311. // HTTOP.
  312. if (window_component != HTCAPTION && window_component != HTTOP)
  313. return nullptr;
  314. // Note: only browser windows and chrome app windows are included here.
  315. // For browser windows, this piece of codes will be called no matter the
  316. // drag happens on the tab(s) or on the non-tabstrip caption or top area.
  317. // But for app window, this piece of codes will only be called if the chrome
  318. // app window has its customized caption area and can't be hidden in tablet
  319. // mode (and thus the drag for this type of chrome app window always happens
  320. // on caption or top area). The case where the caption area of the chrome app
  321. // window can be hidden is handled above.
  322. if (app_type != AppType::BROWSER && app_type != AppType::CHROME_APP &&
  323. app_type != AppType::LACROS)
  324. return nullptr;
  325. window_state->CreateDragDetails(point_in_parent, window_component, source);
  326. std::unique_ptr<WindowResizer> window_resizer =
  327. std::make_unique<TabletModeWindowResizer>(
  328. window_state,
  329. std::make_unique<TabletModeBrowserWindowDragDelegate>());
  330. return std::make_unique<DragWindowResizer>(std::move(window_resizer),
  331. window_state);
  332. }
  333. // When dragging, drags events have to moved pass this threshold before the
  334. // window bounds start changing.
  335. int GetDraggingThreshold(const DragDetails& details) {
  336. if (details.window_component != HTCAPTION)
  337. return 0;
  338. WindowStateType state = details.initial_state_type;
  339. #if DCHECK_IS_ON()
  340. // Other state types either create a different window resizer, or none at all.
  341. std::vector<WindowStateType> draggable_states = {
  342. WindowStateType::kDefault, WindowStateType::kNormal,
  343. WindowStateType::kPrimarySnapped, WindowStateType::kSecondarySnapped,
  344. WindowStateType::kMaximized, WindowStateType::kFloated};
  345. DCHECK(base::Contains(draggable_states, state));
  346. #endif
  347. // Snapped and maximized windows need to be dragged a certain amount before
  348. // bounds start changing.
  349. return chromeos::IsNormalWindowStateType(state)
  350. ? 0
  351. : kResizeRestoreDragThresholdDp;
  352. }
  353. void ResetFrameRestoreLookKey(WindowState* window_state) {
  354. aura::Window* window = window_state->window();
  355. if (window->GetProperty(kFrameRestoreLookKey))
  356. window->SetProperty(kFrameRestoreLookKey, false);
  357. }
  358. // Returns a work area that excludes area that can trigger snaps.
  359. gfx::Rect GetNonSnapWorkArea(const display::Display& display,
  360. bool is_horizontal) {
  361. gfx::Rect area = display.work_area();
  362. gfx::Insets insets;
  363. // Add tolerance for snapping near each work area edge when there is no
  364. // component reducing work area on that edge.
  365. // 1. Add tolerance to maximize triggering area, which is also shared with
  366. // top snap area for vertical snap.
  367. if (area.y() == display.bounds().y())
  368. insets.set_top(kScreenEdgeInsetForSnappingTop);
  369. // 2. Add tolerance to left and right snap area for horizontal snap, or
  370. // bottom snap area for vertical snap.
  371. if (is_horizontal) {
  372. // Without the left shelf, i.e. the left edge of work area aligns with that
  373. // of the display, add snap area tolerance to the left edge. On contrary,
  374. // users need to drag pass the right edge of the left shelf to trigger snap.
  375. if (area.x() == display.bounds().x())
  376. insets.set_left(kScreenEdgeInsetForSnappingSides);
  377. if (area.right() == display.bounds().right())
  378. insets.set_right(kScreenEdgeInsetForSnappingSides);
  379. } else {
  380. // Always add tolerance for bottom snapping work area regardless of whether
  381. // there is any bottom component that alters work area or not to reduce
  382. // long-distance dragging overhead.
  383. insets.set_bottom(kScreenEdgeInsetForSnappingSides);
  384. }
  385. area.Inset(insets);
  386. return area;
  387. }
  388. // Returns the drag area for snap and maximize that is activated by mouse
  389. // pointing at |location_in_screen| given the |display| and its |orientation|.
  390. // Possible drag area for landscape orientation are left, right, and top
  391. // (maximize), while those for portrait orientation are top and bottom.
  392. DragTriggerArea GetActiveDragAreaForSnapAndMaximize(
  393. const gfx::PointF& location_in_screen,
  394. const display::Display& display,
  395. bool is_horizontal) {
  396. const gfx::Rect non_snap_area = GetNonSnapWorkArea(display, is_horizontal);
  397. // The drag area on one of the four sides of screen is activated for snap and
  398. // maximize when |location_in_screen| is outside non-snap area. For example,
  399. // if the location is far left beyond the left edge of |non_snap_area| of
  400. // landscape display, the drag is in |DragTriggerArea::kLeft| snappable area.
  401. if (is_horizontal) {
  402. if (location_in_screen.x() <= non_snap_area.x())
  403. return DragTriggerArea::kLeft;
  404. if (location_in_screen.x() >= non_snap_area.right() - 1)
  405. return DragTriggerArea::kRight;
  406. } else if (location_in_screen.y() >= non_snap_area.bottom() - 1) {
  407. return DragTriggerArea::kBottom;
  408. }
  409. return location_in_screen.y() <= non_snap_area.y()
  410. ? DragTriggerArea::kTop
  411. : DragTriggerArea::kInvalid;
  412. }
  413. // Returns the snap type based on the |location_in_screen|. In portrait snap,
  414. // maximize happens only after holding snap top, so this function returns
  415. // the initial snap top i.e. type |WorkspaceWindowResizer::SnapType::kPrimary|
  416. // for primary portrait or |kSecondary| for secondary portrait. Then
  417. // |dwell_countdown_timer_| will update to |kMaximize| maximize type once the
  418. // time is out in `Drag()`.
  419. WorkspaceWindowResizer::SnapType GetSnapType(
  420. const display::Display& display,
  421. const gfx::PointF& location_in_screen) {
  422. const chromeos::OrientationType orientation =
  423. GetSnapDisplayOrientation(display);
  424. const bool is_horizontal = chromeos::IsLandscapeOrientation(orientation);
  425. const DragTriggerArea drag_area = GetActiveDragAreaForSnapAndMaximize(
  426. location_in_screen, display, is_horizontal);
  427. // In snap horizontal orientation, i.e. no snap top, triggering top area only
  428. // triggers maximize.
  429. if (is_horizontal && drag_area == DragTriggerArea::kTop)
  430. return WorkspaceWindowResizer::SnapType::kMaximize;
  431. switch (drag_area) {
  432. case DragTriggerArea::kLeft:
  433. DCHECK(is_horizontal);
  434. return orientation == chromeos::OrientationType::kLandscapePrimary
  435. ? WorkspaceWindowResizer::SnapType::kPrimary
  436. : WorkspaceWindowResizer::SnapType::kSecondary;
  437. case DragTriggerArea::kRight:
  438. DCHECK(is_horizontal);
  439. return orientation == chromeos::OrientationType::kLandscapePrimary
  440. ? WorkspaceWindowResizer::SnapType::kSecondary
  441. : WorkspaceWindowResizer::SnapType::kPrimary;
  442. case DragTriggerArea::kTop:
  443. DCHECK(!is_horizontal);
  444. return orientation == chromeos::OrientationType::kPortraitPrimary
  445. ? WorkspaceWindowResizer::SnapType::kPrimary
  446. : WorkspaceWindowResizer::SnapType::kSecondary;
  447. case DragTriggerArea::kBottom:
  448. DCHECK(!is_horizontal);
  449. return orientation == chromeos::OrientationType::kPortraitPrimary
  450. ? WorkspaceWindowResizer::SnapType::kSecondary
  451. : WorkspaceWindowResizer::SnapType::kPrimary;
  452. case DragTriggerArea::kInvalid:
  453. return WorkspaceWindowResizer::SnapType::kNone;
  454. }
  455. }
  456. // If |maximize| is true, this is an animation to maximized bounds and an
  457. // animation from maximized bounds otherwise. This is used to determine which
  458. // metric to record.
  459. void CrossFadeAnimation(aura::Window* window,
  460. const gfx::Rect& target_bounds,
  461. bool maximize) {
  462. CrossFadeAnimationAnimateNewLayerOnly(
  463. window, target_bounds, kCrossFadeDuration, gfx::Tween::LINEAR,
  464. maximize ? kDragMaximizeSmoothness : kDragUnmaximizeSmoothness);
  465. }
  466. bool IsTransitionFromTopToMaximize(WorkspaceWindowResizer::SnapType from_type,
  467. WorkspaceWindowResizer::SnapType to_type,
  468. const display::Display& display) {
  469. if (to_type != WorkspaceWindowResizer::SnapType::kMaximize)
  470. return false;
  471. const chromeos::OrientationType orientation =
  472. GetSnapDisplayOrientation(display);
  473. if (chromeos::IsLandscapeOrientation(orientation))
  474. return false;
  475. const bool is_primary = chromeos::IsPrimaryOrientation(orientation);
  476. return is_primary ? from_type == WorkspaceWindowResizer::SnapType::kPrimary
  477. : from_type == WorkspaceWindowResizer::SnapType::kSecondary;
  478. }
  479. } // namespace
  480. std::unique_ptr<WindowResizer> CreateWindowResizer(
  481. aura::Window* window,
  482. const gfx::PointF& point_in_parent,
  483. int window_component,
  484. wm::WindowMoveSource source) {
  485. DCHECK(window);
  486. WindowState* window_state = WindowState::Get(window);
  487. DCHECK(window_state);
  488. // A resizer already exists; don't create a new one.
  489. if (window_state->drag_details())
  490. return nullptr;
  491. // When running in single app mode or not in an active user session, we
  492. // should not create window resizer.
  493. SessionControllerImpl* session_controller =
  494. Shell::Get()->session_controller();
  495. if (session_controller->IsRunningInAppMode() ||
  496. session_controller->GetSessionState() !=
  497. session_manager::SessionState::ACTIVE) {
  498. return nullptr;
  499. }
  500. if (window_state->IsPip()) {
  501. window_state->CreateDragDetails(point_in_parent, window_component, source);
  502. MaybeRecordResizeHandleUsage(window, point_in_parent);
  503. return std::make_unique<PipWindowResizer>(window_state);
  504. }
  505. if (Shell::Get()->tablet_mode_controller()->InTabletMode()) {
  506. return CreateWindowResizerForTabletMode(window, point_in_parent,
  507. window_component, source);
  508. }
  509. // No need to return a resizer when the window cannot get resized.
  510. if (!window_state->CanResize() && window_component != HTCAPTION)
  511. return nullptr;
  512. const bool maximized = window_state->IsMaximized();
  513. if (!maximized && !window_state->IsNormalOrSnapped() &&
  514. !window_state->IsFloated()) {
  515. return nullptr;
  516. }
  517. // TODO(https://crbug.com/1084695): Disable dragging maximized ARC windows
  518. // from the caption. This is because ARC does not currently handle setting
  519. // bounds on a maximized window well.
  520. if (maximized &&
  521. window_state->window()->GetProperty(aura::client::kAppType) ==
  522. static_cast<int>(AppType::ARC_APP) &&
  523. window_component == HTCAPTION) {
  524. return nullptr;
  525. }
  526. int bounds_change =
  527. WindowResizer::GetBoundsChangeForWindowComponent(window_component);
  528. if (bounds_change == WindowResizer::kBoundsChangeDirection_None)
  529. return nullptr;
  530. window_state->CreateDragDetails(point_in_parent, window_component, source);
  531. // TODO(varkha): The chaining of window resizers causes some of the logic
  532. // to be repeated and the logic flow difficult to control. With some windows
  533. // classes using reparenting during drag operations it becomes challenging to
  534. // implement proper transition from one resizer to another during or at the
  535. // end of the drag. This also causes http://crbug.com/247085.
  536. // We should have a better way of doing this, perhaps by having a way of
  537. // observing drags or having a generic drag window wrapper which informs a
  538. // layout manager that a drag has started or stopped. It may be possible to
  539. // refactor and eliminate chaining.
  540. std::unique_ptr<WindowResizer> window_resizer;
  541. const auto* parent = window->parent();
  542. if (parent &&
  543. // TODO(afakhry): Maybe use switchable containers?
  544. (desks_util::IsDeskContainer(parent) ||
  545. parent->GetId() == kShellWindowId_AlwaysOnTopContainer ||
  546. parent->GetId() == kShellWindowId_FloatContainer)) {
  547. window_resizer = WorkspaceWindowResizer::Create(window_state, {});
  548. } else {
  549. window_resizer = DefaultWindowResizer::Create(window_state);
  550. }
  551. return std::make_unique<DragWindowResizer>(std::move(window_resizer),
  552. window_state);
  553. }
  554. WorkspaceWindowResizer* WorkspaceWindowResizer::GetInstanceForTest() {
  555. return instance;
  556. }
  557. // Represents the width or height of a window with constraints on its minimum
  558. // and maximum size. 0 represents a lack of a constraint.
  559. class WindowSize {
  560. public:
  561. WindowSize(int size, int min, int max) : size_(size), min_(min), max_(max) {
  562. // Grow the min/max bounds to include the starting size.
  563. if (is_underflowing())
  564. min_ = size_;
  565. if (is_overflowing())
  566. max_ = size_;
  567. }
  568. bool is_at_capacity(bool shrinking) const {
  569. return size_ == (shrinking ? min_ : max_);
  570. }
  571. int size() const { return size_; }
  572. bool has_min() const { return min_ != 0; }
  573. bool has_max() const { return max_ != 0; }
  574. bool is_valid() const { return !is_overflowing() && !is_underflowing(); }
  575. bool is_overflowing() const { return has_max() && size_ > max_; }
  576. bool is_underflowing() const { return has_min() && size_ < min_; }
  577. // Add |amount| to this WindowSize not exceeding min or max size constraints.
  578. // Returns by how much |size_| + |amount| exceeds the min/max constraints.
  579. int Add(int amount) {
  580. DCHECK(is_valid());
  581. int new_value = size_ + amount;
  582. if (has_min() && new_value < min_) {
  583. size_ = min_;
  584. return new_value - min_;
  585. }
  586. if (has_max() && new_value > max_) {
  587. size_ = max_;
  588. return new_value - max_;
  589. }
  590. size_ = new_value;
  591. return 0;
  592. }
  593. private:
  594. int size_;
  595. int min_;
  596. int max_;
  597. };
  598. constexpr int WorkspaceWindowResizer::kMinOnscreenHeight;
  599. WorkspaceWindowResizer::~WorkspaceWindowResizer() {
  600. if (did_lock_cursor_)
  601. Shell::Get()->cursor_manager()->UnlockCursor();
  602. if (instance == this)
  603. instance = nullptr;
  604. }
  605. // static
  606. std::unique_ptr<WorkspaceWindowResizer> WorkspaceWindowResizer::Create(
  607. WindowState* window_state,
  608. const std::vector<aura::Window*>& attached_windows) {
  609. return base::WrapUnique(
  610. new WorkspaceWindowResizer(window_state, attached_windows));
  611. }
  612. void WorkspaceWindowResizer::Drag(const gfx::PointF& location_in_parent,
  613. int event_flags) {
  614. // For snapped or maximized windows, do not start resizing or restoring the
  615. // window until a certain threshold has passed.
  616. if (!did_move_or_resize_) {
  617. if ((location_in_parent - details().initial_location_in_parent).Length() <
  618. GetDraggingThreshold(details())) {
  619. return;
  620. }
  621. }
  622. last_location_in_parent_ = location_in_parent;
  623. int sticky_size;
  624. if (event_flags & ui::EF_CONTROL_DOWN) {
  625. sticky_size = 0;
  626. } else if ((details().bounds_change & kBoundsChange_Resizes) &&
  627. details().source == ::wm::WINDOW_MOVE_SOURCE_TOUCH) {
  628. sticky_size = kScreenEdgeInsetForTouchDrag;
  629. } else {
  630. sticky_size = kScreenEdgeInset;
  631. }
  632. // |bounds| is in |GetTarget()->parent()|'s coordinates.
  633. gfx::Rect bounds = CalculateBoundsForDrag(location_in_parent);
  634. AdjustBoundsForMainWindow(sticky_size, &bounds);
  635. if (bounds != GetTarget()->bounds()) {
  636. if (!did_move_or_resize_) {
  637. if (!details().restore_bounds_in_parent.IsEmpty()) {
  638. window_state()->ClearRestoreBounds();
  639. if (details().window_component == HTCAPTION) {
  640. if (window_state()->IsMaximized()) {
  641. // Update the maximized window so that it looks like it has been
  642. // restored (i.e. update the caption buttons and height of the
  643. // browser frame).
  644. // TODO(http://crbug.com/1200599): Speculative, remove if not fixed.
  645. // Change window property kFrameRestoreLookKey or window bounds may
  646. // cause the window being destroyed during the drag and return early
  647. // if that's the case.
  648. base::WeakPtr<WorkspaceWindowResizer> resizer(
  649. weak_ptr_factory_.GetWeakPtr());
  650. window_state()->window()->SetProperty(kFrameRestoreLookKey, true);
  651. if (!resizer)
  652. return;
  653. CrossFadeAnimation(window_state()->window(), bounds,
  654. /*maximize=*/false);
  655. if (!resizer)
  656. return;
  657. base::RecordAction(
  658. base::UserMetricsAction("WindowDrag_Unmaximize"));
  659. } else if (window_state()->IsSnapped()) {
  660. base::RecordAction(base::UserMetricsAction("WindowDrag_Unsnap"));
  661. }
  662. }
  663. }
  664. RestackWindows();
  665. }
  666. did_move_or_resize_ = true;
  667. }
  668. if (!attached_windows_.empty())
  669. LayoutAttachedWindows(&bounds);
  670. if (bounds != GetTarget()->bounds()) {
  671. // SetBounds needs to be called to update the layout which affects where the
  672. // phantom window is drawn. Keep track if the window was destroyed during
  673. // the drag and quit early if so.
  674. base::WeakPtr<WorkspaceWindowResizer> resizer(
  675. weak_ptr_factory_.GetWeakPtr());
  676. SetBoundsDuringResize(bounds);
  677. if (!resizer)
  678. return;
  679. }
  680. if (tab_dragging_recorder_) {
  681. // The recorder only works with a single ui::Compositor. ui::Compositor is
  682. // per display so the recorder does not work correctly across different
  683. // displays. Thus, we give up tab dragging latency data collection if the
  684. // drag touches a different display, i.e. not inside the current parent's
  685. // bounds.
  686. if (!gfx::Rect(GetTarget()->parent()->bounds().size())
  687. .Contains(gfx::ToRoundedPoint(location_in_parent))) {
  688. tab_dragging_recorder_.reset();
  689. } else {
  690. tab_dragging_recorder_->RequestNext();
  691. }
  692. }
  693. // In case of non-dragging action such as resizing, we do not want to
  694. // continue performing any snap or maximize logic. Otherwise, resize top edge
  695. // to the top of display will fire maximize |dwell_countdown_timer_|
  696. // (crbug.com/1251859).
  697. if (details().window_component != HTCAPTION)
  698. return;
  699. gfx::PointF location_in_screen = location_in_parent;
  700. ::wm::ConvertPointToScreen(GetTarget()->parent(), &location_in_screen);
  701. if (!can_snap_to_maximize_) {
  702. gfx::PointF initial_location_in_screen =
  703. details().initial_location_in_parent;
  704. ::wm::ConvertPointToScreen(GetTarget()->parent(),
  705. &initial_location_in_screen);
  706. // When repositioning windows across the top of the screen, only trigger a
  707. // snap when there is significant vertical movement.
  708. can_snap_to_maximize_ =
  709. std::abs(initial_location_in_screen.y() - location_in_screen.y()) >
  710. kSnapTriggerVerticalMoveThreshold;
  711. }
  712. const SnapType snap_type = GetSnapType(GetDisplay(), location_in_screen);
  713. // Start dwell countdown if move window to the top of screen.
  714. if (IsSnapTopOrMaximize(snap_type)) {
  715. if (can_snap_to_maximize_) {
  716. const bool drag_passed_threshold =
  717. dwell_location_in_screen_.has_value() &&
  718. (location_in_screen - dwell_location_in_screen_.value()).Length() >
  719. kSnapDragDwellTimeResetThreshold;
  720. // If vertical snap state is enabled, update phantom window for top/bottom
  721. // snap before setting a timer for maximize phantom to show up.
  722. if (!snap_phantom_window_controller_ &&
  723. snap_type != SnapType::kMaximize) {
  724. UpdateSnapPhantomWindow(snap_type);
  725. }
  726. // Start maximize phantom window dwell time if it is not already running
  727. // or restart timer if user moves the window significantly.
  728. if (!dwell_countdown_timer_.IsRunning() || drag_passed_threshold) {
  729. // Use |kDwellLongTime| when snap top phantom window is shown first
  730. // before it turns into maximize phantom window.
  731. dwell_countdown_timer_.Start(
  732. FROM_HERE,
  733. snap_type != SnapType::kMaximize ? kDwellLongTime : kDwellTime,
  734. base::BindOnce(&WorkspaceWindowResizer::UpdateSnapPhantomWindow,
  735. weak_ptr_factory_.GetWeakPtr(),
  736. SnapType::kMaximize));
  737. // Cancel maximization if drag passed threshold.
  738. // Window can still be maximized in next dwell cycle if stays at top of
  739. // display.
  740. if (drag_passed_threshold) {
  741. snap_type_ = SnapType::kNone;
  742. snap_phantom_window_controller_.reset();
  743. }
  744. }
  745. }
  746. dwell_location_in_screen_ = location_in_screen;
  747. } else {
  748. UpdateSnapPhantomWindow(snap_type);
  749. if (dwell_countdown_timer_.IsRunning()) {
  750. dwell_countdown_timer_.Stop();
  751. }
  752. dwell_location_in_screen_.reset();
  753. }
  754. }
  755. void WorkspaceWindowResizer::CompleteDrag() {
  756. tab_dragging_recorder_.reset();
  757. gfx::PointF last_location_in_screen = last_location_in_parent_;
  758. wm::ConvertPointToScreen(GetTarget()->parent(), &last_location_in_screen);
  759. window_state()->OnCompleteDrag(last_location_in_screen);
  760. EndDragForAttachedWindows(/*revert_drag=*/false);
  761. if (!did_move_or_resize_)
  762. return;
  763. ResetFrameRestoreLookKey(window_state());
  764. window_state()->set_bounds_changed_by_user(true);
  765. snap_phantom_window_controller_.reset();
  766. // If the window's state type changed over the course of the drag do not snap
  767. // the window. This happens when the user minimizes or maximizes the window
  768. // using a keyboard shortcut while dragging it.
  769. if (window_state()->GetStateType() != details().initial_state_type)
  770. return;
  771. // Update window state if the window has been snapped.
  772. if (snap_type_ != SnapType::kNone) {
  773. if (!window_state()->HasRestoreBounds()) {
  774. // Use `restore_bounds_for_gesture_` for touch dragging which is inside
  775. // parent's bounds and would not put window to different display.
  776. gfx::Rect bounds = details().source == ::wm::WINDOW_MOVE_SOURCE_TOUCH
  777. ? restore_bounds_for_gesture_
  778. : details().restore_bounds_in_parent.IsEmpty()
  779. ? details().initial_bounds_in_parent
  780. : details().restore_bounds_in_parent;
  781. window_state()->SetRestoreBoundsInParent(bounds);
  782. }
  783. // TODO(oshima): Add event source type to WMEvent and move
  784. // metrics recording inside WindowState::OnWMEvent.
  785. WMEventType type;
  786. switch (snap_type_) {
  787. case SnapType::kPrimary: {
  788. window_state()->set_snap_action_source(
  789. WindowSnapActionSource::kDragWindowToEdgeToSnap);
  790. base::RecordAction(base::UserMetricsAction("WindowDrag_MaximizeLeft"));
  791. const WindowSnapWMEvent snap_primary_event(WM_EVENT_SNAP_PRIMARY);
  792. window_state()->OnWMEvent(&snap_primary_event);
  793. return;
  794. }
  795. case SnapType::kSecondary: {
  796. window_state()->set_snap_action_source(
  797. WindowSnapActionSource::kDragWindowToEdgeToSnap);
  798. base::RecordAction(base::UserMetricsAction("WindowDrag_MaximizeRight"));
  799. const WindowSnapWMEvent snap_secondary_event(WM_EVENT_SNAP_SECONDARY);
  800. window_state()->OnWMEvent(&snap_secondary_event);
  801. return;
  802. }
  803. case SnapType::kMaximize:
  804. type = WM_EVENT_MAXIMIZE;
  805. base::RecordAction(base::UserMetricsAction("WindowDrag_Maximize"));
  806. // This can happen when a user drags a maximized window from the
  807. // caption, and then later tries to maximize it by snapping. Since the
  808. // window is still maximized, telling window state to maximize will be a
  809. // no-op, so reset the bounds manually here.
  810. if (window_state()->IsMaximized()) {
  811. aura::Window* window = window_state()->window();
  812. CrossFadeAnimation(
  813. window, screen_util::GetMaximizedWindowBoundsInParent(window),
  814. /*maximize=*/true);
  815. }
  816. window_state()->TrackDragToMaximizeBehavior();
  817. break;
  818. default:
  819. NOTREACHED();
  820. type = WM_EVENT_MAXIMIZE;
  821. break;
  822. };
  823. const WMEvent event(type);
  824. window_state()->OnWMEvent(&event);
  825. // If the window has been snapped or maximized we are done here.
  826. return;
  827. }
  828. // Keep the window snapped if the user resizes the window such that the
  829. // window has valid bounds for a snapped window. Always unsnap the window
  830. // if the user dragged the window via the caption area because doing this
  831. // is slightly less confusing.
  832. if (window_state()->IsSnapped()) {
  833. window_state()->UpdateSnapRatio();
  834. if (details().window_component == HTCAPTION ||
  835. !AreBoundsValidSnappedBounds(GetTarget())) {
  836. // Set the window to WindowStateType::kNormal but keep the
  837. // window at the bounds that the user has moved/resized the
  838. // window to.
  839. window_state()->SaveCurrentBoundsForRestore();
  840. // Since we saved the current bounds to the restore bounds, the restore
  841. // animation will use the current bounds as the target bounds, so we can
  842. // disable the animation here.
  843. ScopedAnimationDisabler disabler(window_state()->window());
  844. window_state()->Restore();
  845. }
  846. return;
  847. }
  848. // Maximized to normal. State doesn't change during a drag so restore the
  849. // window here.
  850. if (window_state()->IsMaximized()) {
  851. DCHECK_EQ(HTCAPTION, details().window_component);
  852. // Reaching here the only running animation should be the drag to
  853. // unmaximize animation. Stop animating so that animations that might come
  854. // after because of a gesture swipe or fling look smoother.
  855. window_state()->window()->layer()->GetAnimator()->StopAnimating();
  856. window_state()->SaveCurrentBoundsForRestore();
  857. // Since we saved the current bounds to the restore bounds, the restore
  858. // animation will use the current bounds as the target bounds, so we can
  859. // disable the animation here.
  860. ScopedAnimationDisabler disabler(window_state()->window());
  861. window_state()->Restore();
  862. return;
  863. }
  864. // Drag/Resize a floated window won't change window restore bounds.
  865. if (window_state()->IsFloated()) {
  866. return;
  867. }
  868. DCHECK(window_state()->IsNormalStateType());
  869. // The window was normal and stays normal. This is a user
  870. // resize/drag and so the current bounds should be maintained, clearing
  871. // any prior restore bounds.
  872. window_state()->ClearRestoreBounds();
  873. }
  874. void WorkspaceWindowResizer::RevertDrag() {
  875. tab_dragging_recorder_.reset();
  876. gfx::PointF last_location_in_screen = last_location_in_parent_;
  877. wm::ConvertPointToScreen(GetTarget()->parent(), &last_location_in_screen);
  878. window_state()->OnRevertDrag(last_location_in_screen);
  879. EndDragForAttachedWindows(/*revert_drag=*/true);
  880. window_state()->set_bounds_changed_by_user(initial_bounds_changed_by_user_);
  881. snap_phantom_window_controller_.reset();
  882. if (!did_move_or_resize_)
  883. return;
  884. ResetFrameRestoreLookKey(window_state());
  885. GetTarget()->SetBounds(details().initial_bounds_in_parent);
  886. if (!details().restore_bounds_in_parent.IsEmpty()) {
  887. window_state()->SetRestoreBoundsInParent(
  888. details().restore_bounds_in_parent);
  889. }
  890. if (details().window_component == HTRIGHT) {
  891. int last_x = details().initial_bounds_in_parent.right();
  892. for (size_t i = 0; i < attached_windows_.size(); ++i) {
  893. gfx::Rect bounds(attached_windows_[i]->bounds());
  894. bounds.set_x(last_x);
  895. bounds.set_width(initial_size_[i]);
  896. attached_windows_[i]->SetBounds(bounds);
  897. last_x = attached_windows_[i]->bounds().right();
  898. }
  899. } else {
  900. int last_y = details().initial_bounds_in_parent.bottom();
  901. for (size_t i = 0; i < attached_windows_.size(); ++i) {
  902. gfx::Rect bounds(attached_windows_[i]->bounds());
  903. bounds.set_y(last_y);
  904. bounds.set_height(initial_size_[i]);
  905. attached_windows_[i]->SetBounds(bounds);
  906. last_y = attached_windows_[i]->bounds().bottom();
  907. }
  908. }
  909. }
  910. void WorkspaceWindowResizer::FlingOrSwipe(ui::GestureEvent* event) {
  911. if (event->type() != ui::ET_SCROLL_FLING_START &&
  912. event->type() != ui::ET_GESTURE_SWIPE) {
  913. return;
  914. }
  915. if (event->type() == ui::ET_SCROLL_FLING_START) {
  916. CompleteDrag();
  917. if (details().bounds_change != WindowResizer::kBoundsChange_Repositions ||
  918. !WindowState::Get(GetTarget())->IsNormalOrSnapped()) {
  919. return;
  920. }
  921. if (event->details().velocity_y() > kMinVertVelocityForWindowMinimize) {
  922. SetWindowStateTypeFromGesture(GetTarget(), WindowStateType::kMinimized);
  923. } else if (event->details().velocity_y() <
  924. -kMinVertVelocityForWindowMinimize) {
  925. SetWindowStateTypeFromGesture(GetTarget(), WindowStateType::kMaximized);
  926. } else if (event->details().velocity_x() >
  927. kMinHorizVelocityForWindowSwipe) {
  928. SetWindowStateTypeFromGesture(GetTarget(),
  929. WindowStateType::kSecondarySnapped);
  930. } else if (event->details().velocity_x() <
  931. -kMinHorizVelocityForWindowSwipe) {
  932. SetWindowStateTypeFromGesture(GetTarget(),
  933. WindowStateType::kPrimarySnapped);
  934. }
  935. } else {
  936. DCHECK_EQ(event->type(), ui::ET_GESTURE_SWIPE);
  937. DCHECK_GT(event->details().touch_points(), 0);
  938. if (event->details().touch_points() == 1)
  939. return;
  940. if (!WindowState::Get(GetTarget())->IsNormalOrSnapped())
  941. return;
  942. CompleteDrag();
  943. if (event->details().swipe_down()) {
  944. SetWindowStateTypeFromGesture(GetTarget(), WindowStateType::kMinimized);
  945. } else if (event->details().swipe_up()) {
  946. SetWindowStateTypeFromGesture(GetTarget(), WindowStateType::kMaximized);
  947. } else if (event->details().swipe_right()) {
  948. SetWindowStateTypeFromGesture(GetTarget(),
  949. WindowStateType::kSecondarySnapped);
  950. } else {
  951. SetWindowStateTypeFromGesture(GetTarget(),
  952. WindowStateType::kPrimarySnapped);
  953. }
  954. }
  955. event->StopPropagation();
  956. }
  957. WorkspaceWindowResizer::WorkspaceWindowResizer(
  958. WindowState* window_state,
  959. const std::vector<aura::Window*>& attached_windows)
  960. : WindowResizer(window_state),
  961. attached_windows_(attached_windows),
  962. initial_bounds_changed_by_user_(window_state_->bounds_changed_by_user()) {
  963. DCHECK(details().is_resizable);
  964. // A mousemove should still show the cursor even if the window is
  965. // being moved or resized with touch, so do not lock the cursor.
  966. // If the window state is controlled by a client, which may set the
  967. // cursor by itself, don't lock the cursor.
  968. if (details().source != ::wm::WINDOW_MOVE_SOURCE_TOUCH &&
  969. !window_state->allow_set_bounds_direct()) {
  970. Shell::Get()->cursor_manager()->LockCursor();
  971. did_lock_cursor_ = true;
  972. }
  973. // Only support attaching to the right/bottom.
  974. DCHECK(attached_windows_.empty() || (details().window_component == HTRIGHT ||
  975. details().window_component == HTBOTTOM));
  976. // TODO: figure out how to deal with window going off the edge.
  977. // Calculate sizes so that we can maintain the ratios if we need to resize.
  978. for (size_t i = 0; i < attached_windows_.size(); ++i) {
  979. gfx::Size min(attached_windows_[i]->delegate()
  980. ? attached_windows_[i]->delegate()->GetMinimumSize()
  981. : gfx::Size());
  982. int initial_size = PrimaryAxisSize(attached_windows_[i]->bounds().size());
  983. initial_size_.push_back(initial_size);
  984. // If current size is smaller than the min, use the current size as the min.
  985. // This way we don't snap on resize.
  986. int min_size = std::min(initial_size,
  987. std::max(PrimaryAxisSize(min), kMinOnscreenSize));
  988. total_min_ += min_size;
  989. total_initial_size_ += initial_size;
  990. }
  991. instance = this;
  992. // |restore_bounds_for_gesture_| will be set as the restore bounds if a window
  993. // gets flinged or swiped.
  994. if (details().restore_bounds_in_parent.IsEmpty()) {
  995. // Use |bounds()| instead of |GetTargetBounds()| because that's the position
  996. // a user captured the window.
  997. restore_bounds_for_gesture_ = window_state->window()->bounds();
  998. } else {
  999. restore_bounds_for_gesture_ = details().restore_bounds_in_parent;
  1000. }
  1001. // Ensures |restore_bounds_for_gesture_| touches parent's local bounds so
  1002. // that fling maximize does not move the window to a different display
  1003. // and clear gesture states. See https://crbug.com/1162541.
  1004. const gfx::Rect parent_local_bounds(
  1005. window_state->window()->parent()->bounds().size());
  1006. if (!parent_local_bounds.Intersects(restore_bounds_for_gesture_))
  1007. restore_bounds_for_gesture_.AdjustToFit(parent_local_bounds);
  1008. std::unique_ptr<ash::PresentationTimeRecorder> recorder =
  1009. window_state->OnDragStarted(details().window_component);
  1010. if (recorder) {
  1011. SetPresentationTimeRecorder(std::move(recorder));
  1012. } else {
  1013. // Default to use compositor based recorder.
  1014. SetPresentationTimeRecorder(
  1015. PresentationTimeRecorder::CreateCompositorRecorder(
  1016. GetTarget(), "Ash.InteractiveWindowResize.TimeToPresent",
  1017. "Ash.InteractiveWindowResize.TimeToPresent.MaxLatency"));
  1018. }
  1019. StartDragForAttachedWindows();
  1020. if (window_util::IsDraggingTabs(window_state->window())) {
  1021. tab_dragging_recorder_ = CreatePresentationTimeHistogramRecorder(
  1022. GetTarget()->layer()->GetCompositor(),
  1023. kTabDraggingInClamshellModeHistogram,
  1024. kTabDraggingInClamshellModeMaxLatencyHistogram);
  1025. }
  1026. }
  1027. void WorkspaceWindowResizer::LayoutAttachedWindows(gfx::Rect* bounds) {
  1028. gfx::Rect work_area(
  1029. screen_util::GetDisplayWorkAreaBoundsInParent(GetTarget()));
  1030. int initial_size = PrimaryAxisSize(details().initial_bounds_in_parent.size());
  1031. int current_size = PrimaryAxisSize(bounds->size());
  1032. int start = PrimaryAxisCoordinate(bounds->right(), bounds->bottom());
  1033. int end = PrimaryAxisCoordinate(work_area.right(), work_area.bottom());
  1034. int delta = current_size - initial_size;
  1035. int available_size = end - start;
  1036. std::vector<int> sizes;
  1037. int leftovers = CalculateAttachedSizes(delta, available_size, &sizes);
  1038. // leftovers > 0 means that the attached windows can't grow to compensate for
  1039. // the shrinkage of the main window. This line causes the attached windows to
  1040. // be moved so they are still flush against the main window, rather than the
  1041. // main window being prevented from shrinking.
  1042. leftovers = std::min(0, leftovers);
  1043. // Reallocate any leftover pixels back into the main window. This is
  1044. // necessary when, for example, the main window shrinks, but none of the
  1045. // attached windows can grow without exceeding their max size constraints.
  1046. // Adding the pixels back to the main window effectively prevents the main
  1047. // window from resizing too far.
  1048. if (details().window_component == HTRIGHT)
  1049. bounds->set_width(bounds->width() + leftovers);
  1050. else
  1051. bounds->set_height(bounds->height() + leftovers);
  1052. DCHECK_EQ(attached_windows_.size(), sizes.size());
  1053. int last = PrimaryAxisCoordinate(bounds->right(), bounds->bottom());
  1054. for (size_t i = 0; i < attached_windows_.size(); ++i) {
  1055. gfx::Rect attached_bounds(attached_windows_[i]->bounds());
  1056. if (details().window_component == HTRIGHT) {
  1057. attached_bounds.set_x(last);
  1058. attached_bounds.set_width(sizes[i]);
  1059. } else {
  1060. attached_bounds.set_y(last);
  1061. attached_bounds.set_height(sizes[i]);
  1062. }
  1063. attached_windows_[i]->SetBounds(attached_bounds);
  1064. last += sizes[i];
  1065. }
  1066. }
  1067. int WorkspaceWindowResizer::CalculateAttachedSizes(
  1068. int delta,
  1069. int available_size,
  1070. std::vector<int>* sizes) const {
  1071. std::vector<WindowSize> window_sizes;
  1072. CreateBucketsForAttached(&window_sizes);
  1073. // How much we need to grow the attached by (collectively).
  1074. int grow_attached_by = 0;
  1075. if (delta > 0) {
  1076. // If the attached windows don't fit when at their initial size, we will
  1077. // have to shrink them by how much they overflow.
  1078. if (total_initial_size_ >= available_size)
  1079. grow_attached_by = available_size - total_initial_size_;
  1080. } else {
  1081. // If we're shrinking, we grow the attached so the total size remains
  1082. // constant.
  1083. grow_attached_by = -delta;
  1084. }
  1085. int leftover_pixels = 0;
  1086. while (grow_attached_by != 0) {
  1087. int leftovers = GrowFairly(grow_attached_by, &window_sizes);
  1088. if (leftovers == grow_attached_by) {
  1089. leftover_pixels = leftovers;
  1090. break;
  1091. }
  1092. grow_attached_by = leftovers;
  1093. }
  1094. for (size_t i = 0; i < window_sizes.size(); ++i)
  1095. sizes->push_back(window_sizes[i].size());
  1096. return leftover_pixels;
  1097. }
  1098. int WorkspaceWindowResizer::GrowFairly(int pixels,
  1099. std::vector<WindowSize>* sizes) const {
  1100. bool shrinking = pixels < 0;
  1101. std::vector<WindowSize*> nonfull_windows;
  1102. for (size_t i = 0; i < sizes->size(); ++i) {
  1103. WindowSize& current_window_size = (*sizes)[i];
  1104. if (!current_window_size.is_at_capacity(shrinking))
  1105. nonfull_windows.push_back(&current_window_size);
  1106. }
  1107. std::vector<float> ratios;
  1108. CalculateGrowthRatios(nonfull_windows, &ratios);
  1109. int remaining_pixels = pixels;
  1110. bool add_leftover_pixels_to_last = true;
  1111. for (size_t i = 0; i < nonfull_windows.size(); ++i) {
  1112. int grow_by = pixels * ratios[i];
  1113. // Put any leftover pixels into the last window.
  1114. if (i == nonfull_windows.size() - 1 && add_leftover_pixels_to_last)
  1115. grow_by = remaining_pixels;
  1116. int remainder = nonfull_windows[i]->Add(grow_by);
  1117. int consumed = grow_by - remainder;
  1118. remaining_pixels -= consumed;
  1119. if (nonfull_windows[i]->is_at_capacity(shrinking) && remainder > 0) {
  1120. // Because this window overflowed, some of the pixels in
  1121. // |remaining_pixels| aren't there due to rounding errors. Rather than
  1122. // unfairly giving all those pixels to the last window, we refrain from
  1123. // allocating them so that this function can be called again to distribute
  1124. // the pixels fairly.
  1125. add_leftover_pixels_to_last = false;
  1126. }
  1127. }
  1128. return remaining_pixels;
  1129. }
  1130. void WorkspaceWindowResizer::CalculateGrowthRatios(
  1131. const std::vector<WindowSize*>& sizes,
  1132. std::vector<float>* out_ratios) const {
  1133. DCHECK(out_ratios->empty());
  1134. int total_value = 0;
  1135. for (size_t i = 0; i < sizes.size(); ++i)
  1136. total_value += sizes[i]->size();
  1137. for (size_t i = 0; i < sizes.size(); ++i)
  1138. out_ratios->push_back((static_cast<float>(sizes[i]->size())) / total_value);
  1139. }
  1140. void WorkspaceWindowResizer::CreateBucketsForAttached(
  1141. std::vector<WindowSize>* sizes) const {
  1142. for (size_t i = 0; i < attached_windows_.size(); i++) {
  1143. int initial_size = initial_size_[i];
  1144. aura::WindowDelegate* window_delegate = attached_windows_[i]->delegate();
  1145. int min = PrimaryAxisSize(
  1146. window_delegate ? window_delegate->GetMinimumSize() : gfx::Size());
  1147. int max = PrimaryAxisSize(
  1148. window_delegate ? window_delegate->GetMaximumSize() : gfx::Size());
  1149. sizes->push_back(WindowSize(initial_size, min, max));
  1150. }
  1151. }
  1152. void WorkspaceWindowResizer::MagneticallySnapToOtherWindows(
  1153. const display::Display& display,
  1154. gfx::Rect* bounds) {
  1155. if (UpdateMagnetismWindow(display, *bounds, kAllMagnetismEdges)) {
  1156. gfx::Rect bounds_in_screen = *bounds;
  1157. ::wm::ConvertRectToScreen(GetTarget()->parent(), &bounds_in_screen);
  1158. gfx::Point point = OriginForMagneticAttach(
  1159. bounds_in_screen, magnetism_window_->GetBoundsInScreen(),
  1160. magnetism_edge_);
  1161. ::wm::ConvertPointFromScreen(GetTarget()->parent(), &point);
  1162. bounds->set_origin(point);
  1163. }
  1164. }
  1165. void WorkspaceWindowResizer::MagneticallySnapResizeToOtherWindows(
  1166. const display::Display& display,
  1167. gfx::Rect* bounds) {
  1168. const uint32_t edges =
  1169. WindowComponentToMagneticEdge(details().window_component);
  1170. if (UpdateMagnetismWindow(display, *bounds, edges)) {
  1171. gfx::Rect bounds_in_screen = *bounds;
  1172. ::wm::ConvertRectToScreen(GetTarget()->parent(), &bounds_in_screen);
  1173. *bounds = BoundsForMagneticResizeAttach(
  1174. bounds_in_screen, magnetism_window_->GetBoundsInScreen(),
  1175. magnetism_edge_);
  1176. ::wm::ConvertRectFromScreen(GetTarget()->parent(), bounds);
  1177. }
  1178. }
  1179. bool WorkspaceWindowResizer::UpdateMagnetismWindow(
  1180. const display::Display& display,
  1181. const gfx::Rect& bounds,
  1182. uint32_t edges) {
  1183. DCHECK(display.is_valid());
  1184. // |bounds| are in coordinates of original window's parent.
  1185. gfx::Rect bounds_in_screen = bounds;
  1186. ::wm::ConvertRectToScreen(GetTarget()->parent(), &bounds_in_screen);
  1187. MagnetismMatcher matcher(bounds_in_screen, edges);
  1188. // If we snapped to a window then check it first. That way we don't bounce
  1189. // around when close to multiple edges.
  1190. if (magnetism_window_) {
  1191. if (window_tracker_.Contains(magnetism_window_) &&
  1192. matcher.ShouldAttach(magnetism_window_->GetBoundsInScreen(),
  1193. &magnetism_edge_)) {
  1194. return true;
  1195. }
  1196. window_tracker_.Remove(magnetism_window_);
  1197. magnetism_window_ = NULL;
  1198. }
  1199. // Avoid magnetically snapping windows that are not resizable.
  1200. // TODO(oshima): change this to window.type() == TYPE_NORMAL.
  1201. if (!window_state()->CanResize())
  1202. return false;
  1203. // Check the child windows of the root of the display in which the mouse
  1204. // cursor is. It doesn't make sense to do magnetism with windows on other
  1205. // displays until the cursor enters those displays.
  1206. aura::Window* root_window =
  1207. Shell::Get()->window_tree_host_manager()->GetRootWindowForDisplayId(
  1208. display.id());
  1209. aura::Window* container =
  1210. desks_util::GetActiveDeskContainerForRoot(root_window);
  1211. DCHECK(container);
  1212. const std::vector<aura::Window*>& children = container->children();
  1213. for (auto i = children.rbegin();
  1214. i != children.rend() && !matcher.AreEdgesObscured(); ++i) {
  1215. // Ignore already attached windows.
  1216. if (base::Contains(attached_windows_, *i))
  1217. continue;
  1218. WindowState* other_state = WindowState::Get(*i);
  1219. if (!other_state)
  1220. continue;
  1221. if (other_state->window() == GetTarget() ||
  1222. !other_state->window()->IsVisible() ||
  1223. !other_state->IsNormalOrSnapped() || !other_state->CanResize()) {
  1224. continue;
  1225. }
  1226. if (matcher.ShouldAttach(other_state->window()->GetBoundsInScreen(),
  1227. &magnetism_edge_)) {
  1228. magnetism_window_ = other_state->window();
  1229. window_tracker_.Add(magnetism_window_);
  1230. return true;
  1231. }
  1232. }
  1233. return false;
  1234. }
  1235. void WorkspaceWindowResizer::AdjustBoundsForMainWindow(int sticky_size,
  1236. gfx::Rect* bounds) {
  1237. gfx::Point last_location_in_screen =
  1238. gfx::ToRoundedPoint(last_location_in_parent_);
  1239. wm::ConvertPointToScreen(GetTarget()->parent(), &last_location_in_screen);
  1240. display::Display display =
  1241. display::Screen::GetScreen()->GetDisplayNearestPoint(
  1242. last_location_in_screen);
  1243. gfx::Rect work_area = display.work_area();
  1244. wm::ConvertRectFromScreen(GetTarget()->parent(), &work_area);
  1245. if (details().window_component == HTCAPTION) {
  1246. // Adjust the bounds to the work area where the mouse cursor is located.
  1247. // Always keep kMinOnscreenHeight or the window height (whichever is less)
  1248. // on the bottom.
  1249. int max_y =
  1250. work_area.bottom() - std::min(kMinOnscreenHeight, bounds->height());
  1251. if (bounds->y() > max_y) {
  1252. bounds->set_y(max_y);
  1253. } else if (bounds->y() <= work_area.y()) {
  1254. // Don't allow dragging above the top of the display until the mouse
  1255. // cursor reaches the work area above if any.
  1256. bounds->set_y(work_area.y());
  1257. }
  1258. if (sticky_size > 0) {
  1259. // Possibly stick to edge except when a mouse pointer is outside the
  1260. // work area.
  1261. if (display.work_area().Contains(last_location_in_screen))
  1262. StickToWorkAreaOnMove(work_area, sticky_size, bounds);
  1263. MagneticallySnapToOtherWindows(display, bounds);
  1264. }
  1265. } else if (sticky_size > 0) {
  1266. MagneticallySnapResizeToOtherWindows(display, bounds);
  1267. if (!magnetism_window_ && sticky_size > 0)
  1268. StickToWorkAreaOnResize(work_area, sticky_size, bounds);
  1269. }
  1270. if (attached_windows_.empty())
  1271. return;
  1272. if (details().window_component == HTRIGHT) {
  1273. bounds->set_width(std::min(bounds->width(),
  1274. work_area.right() - total_min_ - bounds->x()));
  1275. } else {
  1276. DCHECK_EQ(HTBOTTOM, details().window_component);
  1277. bounds->set_height(std::min(bounds->height(),
  1278. work_area.bottom() - total_min_ - bounds->y()));
  1279. }
  1280. }
  1281. bool WorkspaceWindowResizer::StickToWorkAreaOnMove(const gfx::Rect& work_area,
  1282. int sticky_size,
  1283. gfx::Rect* bounds) const {
  1284. const int left_edge = work_area.x();
  1285. const int right_edge = work_area.right();
  1286. const int top_edge = work_area.y();
  1287. const int bottom_edge = work_area.bottom();
  1288. bool updated = false;
  1289. if (ShouldStickToEdge(bounds->x() - left_edge, sticky_size)) {
  1290. bounds->set_x(left_edge);
  1291. updated = true;
  1292. } else if (ShouldStickToEdge(right_edge - bounds->right(), sticky_size)) {
  1293. bounds->set_x(right_edge - bounds->width());
  1294. updated = true;
  1295. }
  1296. if (ShouldStickToEdge(bounds->y() - top_edge, sticky_size)) {
  1297. bounds->set_y(top_edge);
  1298. updated = true;
  1299. } else if (ShouldStickToEdge(bottom_edge - bounds->bottom(), sticky_size) &&
  1300. bounds->height() < (bottom_edge - top_edge)) {
  1301. // Only snap to the bottom if the window is smaller than the work area.
  1302. // Doing otherwise can lead to window snapping in weird ways as it bounces
  1303. // between snapping to top then bottom.
  1304. bounds->set_y(bottom_edge - bounds->height());
  1305. updated = true;
  1306. }
  1307. return updated;
  1308. }
  1309. void WorkspaceWindowResizer::StickToWorkAreaOnResize(const gfx::Rect& work_area,
  1310. int sticky_size,
  1311. gfx::Rect* bounds) const {
  1312. const uint32_t edges =
  1313. WindowComponentToMagneticEdge(details().window_component);
  1314. const int left_edge = work_area.x();
  1315. const int right_edge = work_area.right();
  1316. const int top_edge = work_area.y();
  1317. const int bottom_edge = work_area.bottom();
  1318. if (edges & MAGNETISM_EDGE_TOP &&
  1319. ShouldStickToEdge(bounds->y() - top_edge, sticky_size)) {
  1320. bounds->set_height(bounds->bottom() - top_edge);
  1321. bounds->set_y(top_edge);
  1322. }
  1323. if (edges & MAGNETISM_EDGE_LEFT &&
  1324. ShouldStickToEdge(bounds->x() - left_edge, sticky_size)) {
  1325. bounds->set_width(bounds->right() - left_edge);
  1326. bounds->set_x(left_edge);
  1327. }
  1328. if (edges & MAGNETISM_EDGE_BOTTOM &&
  1329. ShouldStickToEdge(bottom_edge - bounds->bottom(), sticky_size)) {
  1330. bounds->set_height(bottom_edge - bounds->y());
  1331. }
  1332. if (edges & MAGNETISM_EDGE_RIGHT &&
  1333. ShouldStickToEdge(right_edge - bounds->right(), sticky_size)) {
  1334. bounds->set_width(right_edge - bounds->x());
  1335. }
  1336. }
  1337. int WorkspaceWindowResizer::PrimaryAxisSize(const gfx::Size& size) const {
  1338. return PrimaryAxisCoordinate(size.width(), size.height());
  1339. }
  1340. int WorkspaceWindowResizer::PrimaryAxisCoordinate(int x, int y) const {
  1341. switch (details().window_component) {
  1342. case HTRIGHT:
  1343. return x;
  1344. case HTBOTTOM:
  1345. return y;
  1346. default:
  1347. NOTREACHED();
  1348. }
  1349. return 0;
  1350. }
  1351. bool WorkspaceWindowResizer::IsSnapTopOrMaximize(SnapType type) const {
  1352. if (type == SnapType::kMaximize)
  1353. return true;
  1354. switch (GetSnapDisplayOrientation(GetDisplay())) {
  1355. case chromeos::OrientationType::kPortraitPrimary:
  1356. return type == SnapType::kPrimary;
  1357. case chromeos::OrientationType::kPortraitSecondary:
  1358. return type == SnapType::kSecondary;
  1359. default:
  1360. return false;
  1361. }
  1362. }
  1363. void WorkspaceWindowResizer::UpdateSnapPhantomWindow(
  1364. const SnapType target_snap_type) {
  1365. if (snap_type_ == target_snap_type)
  1366. return;
  1367. if (!did_move_or_resize_ || details().window_component != HTCAPTION)
  1368. return;
  1369. SnapType last_type = snap_type_;
  1370. snap_type_ = target_snap_type;
  1371. // Reset the controller if no snap.
  1372. if (snap_type_ == SnapType::kNone) {
  1373. // TODO(crbug/1258197): Don't destroy phantom controller and add exit
  1374. // animation.
  1375. snap_phantom_window_controller_.reset();
  1376. return;
  1377. }
  1378. const bool is_top_to_maximize =
  1379. IsTransitionFromTopToMaximize(last_type, snap_type_, GetDisplay());
  1380. // Reset the controller if switching snap types unless we want to transform
  1381. // snap top to maximize so that we can have a fade in show animation when
  1382. // switching to the new snap type.
  1383. if (snap_type_ != last_type && !is_top_to_maximize)
  1384. snap_phantom_window_controller_.reset();
  1385. // Update phantom window with snapped guide bounds.
  1386. if (!snap_phantom_window_controller_) {
  1387. snap_phantom_window_controller_ =
  1388. std::make_unique<PhantomWindowController>(GetTarget());
  1389. }
  1390. gfx::Rect phantom_bounds;
  1391. const display::Display display = GetDisplay();
  1392. switch (snap_type_) {
  1393. case SnapType::kPrimary:
  1394. phantom_bounds = GetSnappedWindowBounds(
  1395. display.work_area(), display, GetTarget(),
  1396. ash::SnapViewType::kPrimary, kDefaultSnapRatio);
  1397. break;
  1398. case SnapType::kSecondary:
  1399. phantom_bounds = GetSnappedWindowBounds(
  1400. display.work_area(), display, GetTarget(),
  1401. ash::SnapViewType::kSecondary, kDefaultSnapRatio);
  1402. break;
  1403. case SnapType::kMaximize:
  1404. phantom_bounds = display.work_area();
  1405. break;
  1406. case SnapType::kNone:
  1407. NOTREACHED();
  1408. break;
  1409. }
  1410. const bool need_haptic_feedback =
  1411. snap_phantom_window_controller_->GetTargetWindowBounds() !=
  1412. phantom_bounds &&
  1413. !Shell::Get()->toplevel_window_event_handler()->in_gesture_drag();
  1414. if (is_top_to_maximize) {
  1415. snap_phantom_window_controller_
  1416. ->TransformPhantomWidgetFromSnapTopToMaximize(phantom_bounds);
  1417. // Hide maximize cue once the top-snap phantom turns into maximize phantom.
  1418. snap_phantom_window_controller_->HideMaximizeCue();
  1419. } else {
  1420. snap_phantom_window_controller_->Show(phantom_bounds);
  1421. // Show the maximize cue on top-snap phantom.
  1422. if (IsSnapTopOrMaximize(snap_type_) && snap_type_ != SnapType::kMaximize &&
  1423. snap_type_ != last_type) {
  1424. snap_phantom_window_controller_->ShowMaximizeCue();
  1425. }
  1426. }
  1427. // Fire a haptic event if necessary.
  1428. if (need_haptic_feedback) {
  1429. haptics_util::PlayHapticTouchpadEffect(
  1430. ui::HapticTouchpadEffect::kSnap,
  1431. ui::HapticTouchpadEffectStrength::kMedium);
  1432. }
  1433. }
  1434. void WorkspaceWindowResizer::RestackWindows() {
  1435. if (attached_windows_.empty())
  1436. return;
  1437. // Build a map from index in children to window, returning if there is a
  1438. // window with a different parent.
  1439. using IndexToWindowMap = std::map<size_t, aura::Window*>;
  1440. IndexToWindowMap map;
  1441. aura::Window* parent = GetTarget()->parent();
  1442. const std::vector<aura::Window*>& windows(parent->children());
  1443. map[std::find(windows.begin(), windows.end(), GetTarget()) -
  1444. windows.begin()] = GetTarget();
  1445. for (auto i = attached_windows_.begin(); i != attached_windows_.end(); ++i) {
  1446. if ((*i)->parent() != parent)
  1447. return;
  1448. size_t index =
  1449. std::find(windows.begin(), windows.end(), *i) - windows.begin();
  1450. map[index] = *i;
  1451. }
  1452. // Reorder the windows starting at the topmost.
  1453. parent->StackChildAtTop(map.rbegin()->second);
  1454. for (auto i = map.rbegin(); i != map.rend();) {
  1455. aura::Window* window = i->second;
  1456. ++i;
  1457. if (i != map.rend())
  1458. parent->StackChildBelow(i->second, window);
  1459. }
  1460. }
  1461. WorkspaceWindowResizer::SnapType WorkspaceWindowResizer::GetSnapType(
  1462. const display::Display& display,
  1463. const gfx::PointF& location_in_screen) const {
  1464. SnapType snap_type = ::ash::GetSnapType(display, location_in_screen);
  1465. // Change |snap_type| to none if the requested snap type is not compatible
  1466. // with the window.
  1467. switch (snap_type) {
  1468. case SnapType::kPrimary:
  1469. case SnapType::kSecondary:
  1470. if (!window_state()->CanSnapOnDisplay(display))
  1471. snap_type = SnapType::kNone;
  1472. break;
  1473. case SnapType::kMaximize:
  1474. if (!window_state()->CanMaximize() || !can_snap_to_maximize_)
  1475. snap_type = SnapType::kNone;
  1476. break;
  1477. case SnapType::kNone:
  1478. break;
  1479. };
  1480. return snap_type;
  1481. }
  1482. bool WorkspaceWindowResizer::AreBoundsValidSnappedBounds(
  1483. aura::Window* window) const {
  1484. const gfx::Rect bounds_in_parent = window->bounds();
  1485. const WindowState* state = window_state();
  1486. const WindowStateType state_type = state->GetStateType();
  1487. DCHECK(state_type == WindowStateType::kPrimarySnapped ||
  1488. state_type == WindowStateType::kSecondarySnapped);
  1489. SnapViewType snapped_type = state_type == WindowStateType::kPrimarySnapped
  1490. ? SnapViewType::kPrimary
  1491. : SnapViewType::kSecondary;
  1492. const float snap_ratio = state->snap_ratio().value_or(kDefaultSnapRatio);
  1493. gfx::Rect snapped_bounds = GetSnappedWindowBounds(
  1494. screen_util::GetDisplayWorkAreaBoundsInParent(window),
  1495. display::Screen::GetScreen()->GetDisplayNearestWindow(window), window,
  1496. snapped_type, snap_ratio);
  1497. return bounds_in_parent.ApproximatelyEqual(snapped_bounds, 1);
  1498. }
  1499. void WorkspaceWindowResizer::SetWindowStateTypeFromGesture(
  1500. aura::Window* window,
  1501. WindowStateType new_state_type) {
  1502. WindowState* window_state = WindowState::Get(window);
  1503. // TODO(oshima): Move extra logic (set_unminimize_to_restore_bounds,
  1504. // SetRestoreBoundsInParent) that modifies the window state
  1505. // into WindowState.
  1506. switch (new_state_type) {
  1507. case WindowStateType::kMinimized:
  1508. if (window_state->CanMinimize()) {
  1509. window_state->Minimize();
  1510. window_state->set_unminimize_to_restore_bounds(true);
  1511. window_state->SetRestoreBoundsInParent(restore_bounds_for_gesture_);
  1512. }
  1513. break;
  1514. case WindowStateType::kMaximized:
  1515. if (window_state->CanMaximize()) {
  1516. window_state->SetRestoreBoundsInParent(restore_bounds_for_gesture_);
  1517. window_state->Maximize();
  1518. }
  1519. break;
  1520. case WindowStateType::kPrimarySnapped:
  1521. if (window_state->CanSnap()) {
  1522. window_state->SetRestoreBoundsInParent(restore_bounds_for_gesture_);
  1523. window_state->set_snap_action_source(
  1524. WindowSnapActionSource::kDragWindowToEdgeToSnap);
  1525. const WindowSnapWMEvent event(WM_EVENT_SNAP_PRIMARY);
  1526. window_state->OnWMEvent(&event);
  1527. }
  1528. break;
  1529. case WindowStateType::kSecondarySnapped:
  1530. if (window_state->CanSnap()) {
  1531. window_state->SetRestoreBoundsInParent(restore_bounds_for_gesture_);
  1532. window_state->set_snap_action_source(
  1533. WindowSnapActionSource::kDragWindowToEdgeToSnap);
  1534. const WindowSnapWMEvent event(WM_EVENT_SNAP_SECONDARY);
  1535. window_state->OnWMEvent(&event);
  1536. }
  1537. break;
  1538. default:
  1539. NOTREACHED();
  1540. }
  1541. }
  1542. void WorkspaceWindowResizer::StartDragForAttachedWindows() {
  1543. if (attached_windows_.empty())
  1544. return;
  1545. // The component of the attached windows is always the opposite component of
  1546. // the main window.
  1547. const int main_window_component = details().window_component;
  1548. DCHECK(main_window_component == HTRIGHT || main_window_component == HTBOTTOM);
  1549. int window_component = HTNOWHERE;
  1550. if (main_window_component == HTRIGHT)
  1551. window_component = HTLEFT;
  1552. else if (main_window_component == HTBOTTOM)
  1553. window_component = HTTOP;
  1554. DCHECK(window_component == HTLEFT || window_component == HTTOP);
  1555. for (auto* window : attached_windows_) {
  1556. WindowState* window_state = WindowState::Get(window);
  1557. window_state->CreateDragDetails(details().initial_location_in_parent,
  1558. window_component,
  1559. ::wm::WINDOW_MOVE_SOURCE_MOUSE);
  1560. window_state->OnDragStarted(window_component);
  1561. }
  1562. }
  1563. void WorkspaceWindowResizer::EndDragForAttachedWindows(bool revert_drag) {
  1564. if (attached_windows_.empty())
  1565. return;
  1566. for (auto* window : attached_windows_) {
  1567. WindowState* window_state = WindowState::Get(window);
  1568. if (revert_drag)
  1569. window_state->OnRevertDrag(last_location_in_parent_);
  1570. else
  1571. window_state->OnCompleteDrag(last_location_in_parent_);
  1572. window_state->DeleteDragDetails();
  1573. }
  1574. }
  1575. display::Display WorkspaceWindowResizer::GetDisplay() const {
  1576. display::Screen* screen = display::Screen::GetScreen();
  1577. display::Display display;
  1578. if (details().source == ::wm::WINDOW_MOVE_SOURCE_TOUCH) {
  1579. display = screen->GetDisplayNearestWindow(GetTarget());
  1580. } else {
  1581. // The |Display| object returned by |CursorManager::GetDisplay| may be
  1582. // stale, but will have the correct id.
  1583. // TODO(oshima): Change the API so |GetDisplay| just returns a display id.
  1584. screen->GetDisplayWithDisplayId(
  1585. Shell::Get()->cursor_manager()->GetDisplay().id(), &display);
  1586. }
  1587. DCHECK(display.is_valid());
  1588. return display;
  1589. }
  1590. } // namespace ash