Upstream version 7.35.139.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / cocoa / tabs / tab_strip_drag_controller.mm
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
5 #import "chrome/browser/ui/cocoa/tabs/tab_strip_drag_controller.h"
6
7 #import "base/mac/mac_util.h"
8 #include "base/mac/scoped_cftyperef.h"
9 #import "base/mac/sdk_forward_declarations.h"
10 #import "chrome/browser/ui/cocoa/tabs/tab_controller.h"
11 #import "chrome/browser/ui/cocoa/tabs/tab_controller_target.h"
12 #import "chrome/browser/ui/cocoa/tabs/tab_strip_view.h"
13 #import "chrome/browser/ui/cocoa/tabs/tab_view.h"
14 #import "chrome/browser/ui/cocoa/tabs/tab_window_controller.h"
15 #import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
16 #include "ui/gfx/mac/scoped_ns_disable_screen_updates.h"
17
18 const CGFloat kTearDistance = 36.0;
19 const NSTimeInterval kTearDuration = 0.333;
20
21 // Returns whether |screenPoint| is inside the bounds of |view|.
22 static BOOL PointIsInsideView(NSPoint screenPoint, NSView* view) {
23   if ([view window] == nil)
24     return NO;
25   NSPoint windowPoint = [[view window] convertScreenToBase:screenPoint];
26   NSPoint viewPoint = [view convertPoint:windowPoint fromView:nil];
27   return [view mouse:viewPoint inRect:[view bounds]];
28 }
29
30 @interface TabStripDragController (Private)
31 - (void)resetDragControllers;
32 - (NSArray*)dropTargetsForController:(TabWindowController*)dragController;
33 - (void)setWindowBackgroundVisibility:(BOOL)shouldBeVisible;
34 - (void)endDrag:(NSEvent*)event;
35 - (void)continueDrag:(NSEvent*)event;
36 @end
37
38 ////////////////////////////////////////////////////////////////////////////////
39
40 @implementation TabStripDragController
41
42 - (id)initWithTabStripController:(TabStripController*)controller {
43   if ((self = [super init])) {
44     tabStrip_ = controller;
45   }
46   return self;
47 }
48
49 - (void)dealloc {
50   [NSObject cancelPreviousPerformRequestsWithTarget:self];
51   [super dealloc];
52 }
53
54 - (BOOL)tabCanBeDragged:(TabController*)tab {
55   if ([[tab tabView] isClosing])
56     return NO;
57   NSWindowController* controller = [sourceWindow_ windowController];
58   if ([controller isKindOfClass:[TabWindowController class]]) {
59     TabWindowController* realController =
60         static_cast<TabWindowController*>(controller);
61     return [realController isTabDraggable:[tab tabView]];
62   }
63   return YES;
64 }
65
66 - (void)maybeStartDrag:(NSEvent*)theEvent forTab:(TabController*)tab {
67   [self resetDragControllers];
68
69   // Resolve overlay back to original window.
70   sourceWindow_ = [[tab view] window];
71   if ([sourceWindow_ isKindOfClass:[NSPanel class]]) {
72     sourceWindow_ = [sourceWindow_ parentWindow];
73   }
74
75   sourceWindowFrame_ = [sourceWindow_ frame];
76   sourceTabFrame_ = [[tab view] frame];
77   sourceController_ = [sourceWindow_ windowController];
78   draggedTab_ = tab;
79   tabWasDragged_ = NO;
80   tearTime_ = 0.0;
81   draggingWithinTabStrip_ = YES;
82   chromeIsVisible_ = NO;
83
84   // If there's more than one potential window to be a drop target, we want to
85   // treat a drag of a tab just like dragging around a tab that's already
86   // detached. Note that unit tests might have |-numberOfTabs| reporting zero
87   // since the model won't be fully hooked up. We need to be prepared for that
88   // and not send them into the "magnetic" codepath.
89   NSArray* targets = [self dropTargetsForController:sourceController_];
90   moveWindowOnDrag_ =
91       ([sourceController_ numberOfTabs] < 2 && ![targets count]) ||
92       ![self tabCanBeDragged:tab] ||
93       ![sourceController_ tabDraggingAllowed];
94   // If we are dragging a tab, a window with a single tab should immediately
95   // snap off and not drag within the tab strip.
96   if (!moveWindowOnDrag_)
97     draggingWithinTabStrip_ = [sourceController_ numberOfTabs] > 1;
98
99   dragOrigin_ = [NSEvent mouseLocation];
100
101   // When spinning the event loop, a tab can get detached, which could lead to
102   // our own destruction. Keep ourselves around while spinning the loop as well
103   // as the tab controller being dragged.
104   base::scoped_nsobject<TabStripDragController> keepAlive([self retain]);
105   base::scoped_nsobject<TabController> keepAliveTab([tab retain]);
106
107   // Because we move views between windows, we need to handle the event loop
108   // ourselves. Ideally we should use the standard event loop.
109   while (1) {
110     const NSUInteger mask =
111         NSLeftMouseUpMask | NSLeftMouseDraggedMask | NSKeyUpMask;
112     theEvent =
113         [NSApp nextEventMatchingMask:mask
114                            untilDate:[NSDate distantFuture]
115                               inMode:NSDefaultRunLoopMode
116                              dequeue:YES];
117
118     // Ensure that any window changes that happen while handling this event
119     // appear atomically.
120     gfx::ScopedNSDisableScreenUpdates disabler;
121
122     NSEventType type = [theEvent type];
123     if (type == NSKeyUp) {
124       if ([theEvent keyCode] == kVK_Escape) {
125         // Cancel the drag and restore the previous state.
126         if (draggingWithinTabStrip_) {
127           // Simply pretend the tab wasn't dragged (far enough).
128           tabWasDragged_ = NO;
129         } else {
130           [targetController_ removePlaceholder];
131           if ([sourceController_ numberOfTabs] < 2) {
132             // Revert to a single-tab window.
133             targetController_ = nil;
134           } else {
135             // Change the target to the source controller.
136             targetController_ = sourceController_;
137             [targetController_ insertPlaceholderForTab:[tab tabView]
138                                                  frame:sourceTabFrame_];
139           }
140         }
141         // Simply end the drag at this point.
142         [self endDrag:theEvent];
143         break;
144       }
145     } else if (type == NSLeftMouseDragged) {
146       [self continueDrag:theEvent];
147     } else if (type == NSLeftMouseUp) {
148       [tab selectTab:self];
149       [self endDrag:theEvent];
150       break;
151     } else {
152       // TODO(viettrungluu): [crbug.com/23830] We can receive right-mouse-ups
153       // (and maybe even others?) for reasons I don't understand. So we
154       // explicitly check for both events we're expecting, and log others. We
155       // should figure out what's going on.
156       LOG(WARNING) << "Spurious event received of type " << type << ".";
157     }
158   }
159 }
160
161 - (void)continueDrag:(NSEvent*)theEvent {
162   CHECK(draggedTab_);
163
164   // Cancel any delayed -continueDrag: requests that may still be pending.
165   [NSObject cancelPreviousPerformRequestsWithTarget:self];
166
167   // Special-case this to keep the logic below simpler.
168   if (moveWindowOnDrag_) {
169     if ([sourceController_ windowMovementAllowed]) {
170       NSPoint thisPoint = [NSEvent mouseLocation];
171       NSPoint origin = sourceWindowFrame_.origin;
172       origin.x += (thisPoint.x - dragOrigin_.x);
173       origin.y += (thisPoint.y - dragOrigin_.y);
174       [sourceWindow_ setFrameOrigin:NSMakePoint(origin.x, origin.y)];
175     }  // else do nothing.
176     return;
177   }
178
179   // First, go through the magnetic drag cycle. We break out of this if
180   // "stretchiness" ever exceeds a set amount.
181   tabWasDragged_ = YES;
182
183   if (draggingWithinTabStrip_) {
184     NSPoint thisPoint = [NSEvent mouseLocation];
185     CGFloat offset = thisPoint.x - dragOrigin_.x;
186     [sourceController_ insertPlaceholderForTab:[draggedTab_ tabView]
187                                          frame:NSOffsetRect(sourceTabFrame_,
188                                                             offset, 0)];
189     // Check that we haven't pulled the tab too far to start a drag. This
190     // can include either pulling it too far down, or off the side of the tab
191     // strip that would cause it to no longer be fully visible.
192     BOOL stillVisible =
193         [sourceController_ isTabFullyVisible:[draggedTab_ tabView]];
194     CGFloat tearForce = fabs(thisPoint.y - dragOrigin_.y);
195     if ([sourceController_ tabTearingAllowed] &&
196         (tearForce > kTearDistance || !stillVisible)) {
197       draggingWithinTabStrip_ = NO;
198       // When you finally leave the strip, we treat that as the origin.
199       dragOrigin_.x = thisPoint.x;
200     } else {
201       // Still dragging within the tab strip, wait for the next drag event.
202       return;
203     }
204   }
205
206   NSPoint thisPoint = [NSEvent mouseLocation];
207
208   // Iterate over possible targets checking for the one the mouse is in.
209   // If the tab is just in the frame, bring the window forward to make it
210   // easier to drop something there. If it's in the tab strip, set the new
211   // target so that it pops into that window. We can't cache this because we
212   // need the z-order to be correct.
213   NSArray* targets = [self dropTargetsForController:draggedController_];
214   TabWindowController* newTarget = nil;
215   for (TabWindowController* target in targets) {
216     NSRect windowFrame = [[target window] frame];
217     if (NSPointInRect(thisPoint, windowFrame)) {
218       [[target window] orderFront:self];
219       if (PointIsInsideView(thisPoint, [target tabStripView])) {
220         newTarget = target;
221       }
222       break;
223     }
224   }
225
226   // If we're now targeting a new window, re-layout the tabs in the old
227   // target and reset how long we've been hovering over this new one.
228   if (targetController_ != newTarget) {
229     [targetController_ removePlaceholder];
230     targetController_ = newTarget;
231     if (!newTarget) {
232       tearTime_ = [NSDate timeIntervalSinceReferenceDate];
233       tearOrigin_ = [dragWindow_ frame].origin;
234     }
235   }
236
237   // Create or identify the dragged controller.
238   if (!draggedController_) {
239     // Detach from the current window and put it in a new window. If there are
240     // no more tabs remaining after detaching, the source window is about to
241     // go away (it's been autoreleased) so we need to ensure we don't reference
242     // it any more. In that case the new controller becomes our source
243     // controller.
244     NSArray* tabs = [draggedTab_ selected] ? [tabStrip_ selectedViews]
245                                            : @[ [draggedTab_ tabView] ];
246     draggedController_ =
247         [sourceController_ detachTabsToNewWindow:tabs
248                                       draggedTab:[draggedTab_ tabView]];
249
250     dragWindow_ = [draggedController_ window];
251     [dragWindow_ setAlphaValue:0.0];
252     if ([sourceController_ hasLiveTabs]) {
253       if (PointIsInsideView(thisPoint, [sourceController_ tabStripView])) {
254         // We don't want to remove the source window's placeholder here because
255         // the new tab button may briefly flash in and out if we remove and add
256         // back the placeholder.
257         // Instead, we will remove the placeholder later when the target window
258         // actually changes.
259         targetController_ = sourceController_;
260       } else {
261         [sourceController_ removePlaceholder];
262       }
263     } else {
264       [sourceController_ removePlaceholder];
265       sourceController_ = draggedController_;
266       sourceWindow_ = dragWindow_;
267     }
268
269     // Disable window animation before calling |orderFront:| when detaching
270     // to a new window.
271     NSWindowAnimationBehavior savedAnimationBehavior =
272         NSWindowAnimationBehaviorDefault;
273     bool didSaveAnimationBehavior = false;
274     if ([dragWindow_ respondsToSelector:@selector(animationBehavior)] &&
275         [dragWindow_ respondsToSelector:@selector(setAnimationBehavior:)]) {
276       didSaveAnimationBehavior = true;
277       savedAnimationBehavior = [dragWindow_ animationBehavior];
278       [dragWindow_ setAnimationBehavior:NSWindowAnimationBehaviorNone];
279     }
280
281     // If dragging the tab only moves the current window, do not show overlay
282     // so that sheets stay on top of the window.
283     // Bring the target window to the front and make sure it has a border.
284     [dragWindow_ setLevel:NSFloatingWindowLevel];
285     [dragWindow_ setHasShadow:YES];
286     [dragWindow_ orderFront:nil];
287     [dragWindow_ makeMainWindow];
288     [draggedController_ showOverlay];
289     dragOverlay_ = [draggedController_ overlayWindow];
290     // Force the new tab button to be hidden. We'll reset it on mouse up.
291     [draggedController_ showNewTabButton:NO];
292     tearTime_ = [NSDate timeIntervalSinceReferenceDate];
293     tearOrigin_ = sourceWindowFrame_.origin;
294
295     // Restore window animation behavior.
296     if (didSaveAnimationBehavior)
297       [dragWindow_ setAnimationBehavior:savedAnimationBehavior];
298   }
299
300   // TODO(pinkerton): http://crbug.com/25682 demonstrates a way to get here by
301   // some weird circumstance that doesn't first go through mouseDown:. We
302   // really shouldn't go any farther.
303   if (!draggedController_ || !sourceController_)
304     return;
305
306   // When the user first tears off the window, we want slide the window to
307   // the current mouse location (to reduce the jarring appearance). We do this
308   // by calling ourselves back with additional -continueDrag: calls (not actual
309   // events). |tearProgress| is a normalized measure of how far through this
310   // tear "animation" (of length kTearDuration) we are and has values [0..1].
311   // We use sqrt() so the animation is non-linear (slow down near the end
312   // point).
313   NSTimeInterval tearProgress =
314       [NSDate timeIntervalSinceReferenceDate] - tearTime_;
315   tearProgress /= kTearDuration;  // Normalize.
316   tearProgress = sqrtf(MAX(MIN(tearProgress, 1.0), 0.0));
317
318   // Move the dragged window to the right place on the screen.
319   NSPoint origin = sourceWindowFrame_.origin;
320   origin.x += (thisPoint.x - dragOrigin_.x);
321   origin.y += (thisPoint.y - dragOrigin_.y);
322
323   if (tearProgress < 1) {
324     // If the tear animation is not complete, call back to ourself with the
325     // same event to animate even if the mouse isn't moving. We need to make
326     // sure these get cancelled in -endDrag:.
327     [NSObject cancelPreviousPerformRequestsWithTarget:self];
328     [self performSelector:@selector(continueDrag:)
329                withObject:theEvent
330                afterDelay:1.0f/30.0f];
331
332     // Set the current window origin based on how far we've progressed through
333     // the tear animation.
334     origin.x = (1 - tearProgress) * tearOrigin_.x + tearProgress * origin.x;
335     origin.y = (1 - tearProgress) * tearOrigin_.y + tearProgress * origin.y;
336   }
337
338   if (targetController_) {
339     // In order to "snap" two windows of different sizes together at their
340     // toolbar, we can't just use the origin of the target frame. We also have
341     // to take into consideration the difference in height.
342     NSRect targetFrame = [[targetController_ window] frame];
343     NSRect sourceFrame = [dragWindow_ frame];
344     origin.y = NSMinY(targetFrame) +
345                 (NSHeight(targetFrame) - NSHeight(sourceFrame));
346   }
347   [dragWindow_ setFrameOrigin:NSMakePoint(origin.x, origin.y)];
348
349   // If we're not hovering over any window, make the window fully
350   // opaque. Otherwise, find where the tab might be dropped and insert
351   // a placeholder so it appears like it's part of that window.
352   if (targetController_) {
353     if (![[targetController_ window] isKeyWindow])
354       [[targetController_ window] orderFront:nil];
355
356     // Compute where placeholder should go and insert it into the
357     // destination tab strip.
358     // The placeholder frame is the rect that contains all dragged tabs.
359     NSRect tabFrame = NSZeroRect;
360     for (NSView* tabView in [draggedController_ tabViews]) {
361       tabFrame = NSUnionRect(tabFrame, [tabView frame]);
362     }
363     tabFrame.origin = [dragWindow_ convertBaseToScreen:tabFrame.origin];
364     tabFrame.origin = [[targetController_ window]
365                         convertScreenToBase:tabFrame.origin];
366     tabFrame = [[targetController_ tabStripView]
367                 convertRect:tabFrame fromView:nil];
368     [targetController_ insertPlaceholderForTab:[draggedTab_ tabView]
369                                          frame:tabFrame];
370     [targetController_ layoutTabs];
371   } else {
372     [dragWindow_ makeKeyAndOrderFront:nil];
373   }
374
375   // Adjust the visibility of the window background. If there is a drop target,
376   // we want to hide the window background so the tab stands out for
377   // positioning. If not, we want to show it so it looks like a new window will
378   // be realized.
379   BOOL chromeShouldBeVisible = targetController_ == nil;
380   [self setWindowBackgroundVisibility:chromeShouldBeVisible];
381 }
382
383 - (void)endDrag:(NSEvent*)event {
384   // Cancel any delayed -continueDrag: requests that may still be pending.
385   [NSObject cancelPreviousPerformRequestsWithTarget:self];
386
387   // Special-case this to keep the logic below simpler.
388   if (moveWindowOnDrag_) {
389     [self resetDragControllers];
390     return;
391   }
392
393   // TODO(pinkerton): http://crbug.com/25682 demonstrates a way to get here by
394   // some weird circumstance that doesn't first go through mouseDown:. We
395   // really shouldn't go any farther.
396   if (!sourceController_)
397     return;
398
399   // We are now free to re-display the new tab button in the window we're
400   // dragging. It will show when the next call to -layoutTabs (which happens
401   // indirectly by several of the calls below, such as removing the
402   // placeholder).
403   [draggedController_ showNewTabButton:YES];
404
405   if (draggingWithinTabStrip_) {
406     if (tabWasDragged_) {
407       // Move tab to new location.
408       DCHECK([sourceController_ numberOfTabs]);
409       TabWindowController* dropController = sourceController_;
410       [dropController moveTabViews:@[ [dropController activeTabView] ]
411                     fromController:nil];
412     }
413   } else if (targetController_) {
414     // Move between windows. If |targetController_| is nil, we're not dropping
415     // into any existing window.
416     [targetController_ moveTabViews:[draggedController_ tabViews]
417                      fromController:draggedController_];
418     // Force redraw to avoid flashes of old content before returning to event
419     // loop.
420     [[targetController_ window] display];
421     [targetController_ showWindow:nil];
422     [draggedController_ removeOverlay];
423   } else {
424     // Only move the window around on screen. Make sure it's set back to
425     // normal state (fully opaque, has shadow, has key, etc).
426     [draggedController_ removeOverlay];
427     // Don't want to re-show the window if it was closed during the drag.
428     if ([dragWindow_ isVisible]) {
429       [dragWindow_ setAlphaValue:1.0];
430       [dragOverlay_ setHasShadow:NO];
431       [dragWindow_ setHasShadow:YES];
432       [dragWindow_ makeKeyAndOrderFront:nil];
433     }
434     [[draggedController_ window] setLevel:NSNormalWindowLevel];
435     [draggedController_ removePlaceholder];
436   }
437   [sourceController_ removePlaceholder];
438   chromeIsVisible_ = YES;
439
440   [self resetDragControllers];
441 }
442
443 // Private /////////////////////////////////////////////////////////////////////
444
445 // Call to clear out transient weak references we hold during drags.
446 - (void)resetDragControllers {
447   draggedTab_ = nil;
448   draggedController_ = nil;
449   dragWindow_ = nil;
450   dragOverlay_ = nil;
451   sourceController_ = nil;
452   sourceWindow_ = nil;
453   targetController_ = nil;
454 }
455
456 // Returns an array of controllers that could be a drop target, ordered front to
457 // back. It has to be of the appropriate class, and visible (obviously). Note
458 // that the window cannot be a target for itself.
459 - (NSArray*)dropTargetsForController:(TabWindowController*)dragController {
460   NSMutableArray* targets = [NSMutableArray array];
461   NSWindow* dragWindow = [dragController window];
462   for (NSWindow* window in [NSApp orderedWindows]) {
463     if (window == dragWindow) continue;
464     if (![window isVisible]) continue;
465     // Skip windows on the wrong space.
466     if (![window isOnActiveSpace])
467       continue;
468     NSWindowController* controller = [window windowController];
469     if ([controller isKindOfClass:[TabWindowController class]]) {
470       TabWindowController* realController =
471           static_cast<TabWindowController*>(controller);
472       if ([realController canReceiveFrom:dragController])
473         [targets addObject:controller];
474     }
475   }
476   return targets;
477 }
478
479 // Sets whether the window background should be visible or invisible when
480 // dragging a tab. The background should be invisible when the mouse is over a
481 // potential drop target for the tab (the tab strip). It should be visible when
482 // there's no drop target so the window looks more fully realized and ready to
483 // become a stand-alone window.
484 - (void)setWindowBackgroundVisibility:(BOOL)shouldBeVisible {
485   if (chromeIsVisible_ == shouldBeVisible)
486     return;
487
488   // There appears to be a race-condition in CoreAnimation where if we use
489   // animators to set the alpha values, we can't guarantee that we cancel them.
490   // This has the side effect of sometimes leaving the dragged window
491   // translucent or invisible. As a result, don't animate the alpha change.
492   [[draggedController_ overlayWindow] setAlphaValue:1.0];
493   if (targetController_) {
494     [dragWindow_ setAlphaValue:0.0];
495     [[draggedController_ overlayWindow] setHasShadow:YES];
496     [[targetController_ window] makeMainWindow];
497   } else {
498     [dragWindow_ setAlphaValue:0.5];
499     [[draggedController_ overlayWindow] setHasShadow:NO];
500     [[draggedController_ window] makeMainWindow];
501   }
502   chromeIsVisible_ = shouldBeVisible;
503 }
504
505 @end