1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/cocoa/nsimage_cache.h"
#include "chrome/browser/cocoa/tab_controller.h"
#include "chrome/browser/cocoa/tab_view.h"
#include "chrome/browser/cocoa/tab_window_controller.h"
// Constants for inset and control points for tab shape.
static const CGFloat kInsetMultiplier = 2.0/3.0;
static const CGFloat kControlPoint1Multiplier = 1.0/3.0;
static const CGFloat kControlPoint2Multiplier = 3.0/8.0;
static const CGFloat kToolbarTopOffset = 12;
static const CGFloat kToolbarMaxHeight = 128;
@implementation TabView
@synthesize state = state_;
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
chromeIsVisible_ = YES;
[self setShowsDivider:NO];
// TODO(alcor): register for theming, either here or the cell
// [self gtm_registerForThemeNotifications];
}
return self;
}
- (void)awakeFromNib {
[self setShowsDivider:NO];
// Set up the tracking rect for the close button mouseover. Add it
// to the |closeButton_| view, but we'll handle the message ourself.
// The mouseover is always enabled, because the close button works
// regardless of key/main/active status.
trackingArea_.reset(
[[NSTrackingArea alloc] initWithRect:[closeButton_ bounds]
options:NSTrackingMouseEnteredAndExited |
NSTrackingActiveAlways
owner:self
userInfo:nil]);
[closeButton_ addTrackingArea:trackingArea_.get()];
}
- (void)dealloc {
// [self gtm_unregisterForThemeNotifications];
[closeButton_ removeTrackingArea:trackingArea_.get()];
[super dealloc];
}
// Overridden so that mouse clicks come to this view (the parent of the
// hierarchy) first. We want to handle clicks and drags in this class and
// leave the background button for display purposes only.
- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent {
return YES;
}
- (void)mouseEntered:(NSEvent *)theEvent {
// We only set up one tracking area, so we know any mouseEntered:
// messages are for close button mouseovers.
[closeButton_ setImage:nsimage_cache::ImageNamed(@"close_bar_h.pdf")];
}
- (void)mouseExited:(NSEvent *)theEvent {
// We only set up one tracking area, so we know any mouseExited:
// messages are for close button mouseovers.
[closeButton_ setImage:nsimage_cache::ImageNamed(@"close_bar.pdf")];
}
// Determines which view a click in our frame actually hit. It's either this
// view or our child close button.
- (NSView *)hitTest:(NSPoint)aPoint {
NSPoint viewPoint = [self convertPoint:aPoint fromView:[self superview]];
NSRect frame = [self frame];
// Reduce the width of the hit rect slightly to remove the overlap
// between adjacent tabs. The drawing code in TabCell has the top
// corners of the tab inset by height*2/3, so we inset by half of
// that here. This doesn't completely eliminate the overlap, but it
// works well enough.
NSRect hitRect = NSInsetRect(frame, frame.size.height / 3.0f, 0);
if (![closeButton_ isHidden])
if (NSPointInRect(viewPoint, [closeButton_ frame])) return closeButton_;
if (NSPointInRect(aPoint, hitRect)) return self;
return nil;
}
// Handle clicks and drags in this button. We get here because we have
// overridden acceptsFirstMouse: and the click is within our bounds.
// TODO(pinkerton/alcor): This routine needs *a lot* of work to marry Cole's
// ideas of dragging cocoa views between windows and how the Browser and
// TabStrip models want to manage tabs.
static const CGFloat kTearDistance = 36.0;
static const NSTimeInterval kTearDuration = 0.333;
static const double kDragStartDistance = 3.0;
- (void)mouseDown:(NSEvent *)theEvent {
// Fire the action to select the tab.
if ([[controller_ target] respondsToSelector:[controller_ action]])
[[controller_ target] performSelector:[controller_ action]
withObject:self];
// Resolve overlay back to original window.
sourceWindow_ = [self window];
if ([sourceWindow_ isKindOfClass:[NSPanel class]]) {
sourceWindow_ = [sourceWindow_ parentWindow];
}
sourceWindowFrame_ = [sourceWindow_ frame];
sourceTabFrame_ = [self frame];
sourceController_ = [sourceWindow_ windowController];
draggedController_ = nil;
dragWindow_ = nil;
dragOverlay_ = nil;
targetController_ = nil;
tabWasDragged_ = NO;
tearTime_ = 0.0;
draggingWithinTabStrip_ = YES;
// We don't want to "tear off" a tab if there's only one in the window. Treat
// it like we're dragging around a tab we've already detached. Note that
// unit tests might have |-numberOfTabs| reporting zero since the model
// won't be fully hooked up. We need to be prepared for that and not send
// them into the "magnetic" codepath.
isTheOnlyTab_ = [sourceController_ numberOfTabs] <= 1;
dragOrigin_ = [NSEvent mouseLocation];
// Because we move views between windows, we need to handle the event loop
// ourselves. Ideally we should use the standard event loop.
while (1) {
theEvent =
[NSApp nextEventMatchingMask:NSLeftMouseUpMask | NSLeftMouseDraggedMask
untilDate:[NSDate distantFuture]
inMode:NSDefaultRunLoopMode dequeue:YES];
NSPoint thisPoint = [NSEvent mouseLocation];
NSEventType type = [theEvent type];
if (type == NSLeftMouseDragged) {
[self mouseDragged:theEvent];
} else { // Mouse Up
[self mouseUp:theEvent];
break;
}
}
}
- (void)mouseDragged:(NSEvent *)theEvent {
// First, go through the magnetic drag cycle. We break out of this if
// "stretchiness" ever exceeds the a set amount.
tabWasDragged_ = YES;
if (isTheOnlyTab_) draggingWithinTabStrip_ = NO;
if (draggingWithinTabStrip_) {
NSRect frame = [self frame];
NSPoint thisPoint = [NSEvent mouseLocation];
CGFloat stretchiness = thisPoint.y - dragOrigin_.y;
stretchiness = copysign(sqrtf(fabs(stretchiness))/sqrtf(kTearDistance),
stretchiness) / 2.0;
CGFloat offset = thisPoint.x - dragOrigin_.x;
if (fabsf(offset) > 100) stretchiness = 0;
[sourceController_ insertPlaceholderForTab:self
frame:NSOffsetRect(sourceTabFrame_,
offset, 0)
yStretchiness:stretchiness];
CGFloat tearForce = fabs(thisPoint.y - dragOrigin_.y);
if (tearForce > kTearDistance) {
draggingWithinTabStrip_ = NO;
// When you finally leave the strip, we treat that as the origin.
dragOrigin_.x = thisPoint.x;
} else {
return;
}
}
NSPoint lastPoint =
[[theEvent window] convertBaseToScreen:[theEvent locationInWindow]];
// Do not start dragging until the user has "torn" the tab off by
// moving more than 3 pixels.
NSDate* targetDwellDate = nil; // The date this target was first chosen
NSMutableArray* targets = [NSMutableArray array];
NSPoint thisPoint = [NSEvent mouseLocation];
// Find all the windows that could be a target. It has to be of the
// appropriate class, and visible (obviously).
if (![targets count]) {
for (NSWindow* window in [NSApp windows]) {
if (window == sourceWindow_ && isTheOnlyTab_) continue;
if (window == dragWindow_) continue;
if (![window isVisible]) continue;
NSWindowController *controller = [window windowController];
if ([controller isKindOfClass:[TabWindowController class]]) {
TabWindowController* realController =
static_cast<TabWindowController*>(controller);
if ([realController canReceiveFrom:sourceController_]) {
[targets addObject:controller];
}
}
}
}
// Iterate over possible targets checking for the one the mouse is in.
// The mouse can be in either the tab or window frame.
TabWindowController* newTarget = nil;
for (TabWindowController* target in targets) {
NSRect windowFrame = [[target window] frame];
if (NSPointInRect(thisPoint, windowFrame)) {
NSRect tabStripFrame = [[target tabStripView] frame];
tabStripFrame = [[target tabStripView] convertRectToBase:tabStripFrame];
tabStripFrame.origin = [[target window]
convertBaseToScreen:tabStripFrame.origin];
if (NSPointInRect(thisPoint, tabStripFrame)) {
newTarget = target;
}
break;
}
}
// If we're now targeting a new window, re-layout the tabs in the old
// target and reset how long we've been hovering over this new one.
if (targetController_ != newTarget) {
targetDwellDate = [NSDate date];
[targetController_ removePlaceholder];
targetController_ = newTarget;
if (!newTarget) {
tearTime_ = [NSDate timeIntervalSinceReferenceDate];
tearOrigin_ = [dragWindow_ frame].origin;
}
}
// Create or identify the dragged controller.
if (!draggedController_) {
if (isTheOnlyTab_) {
draggedController_ = sourceController_;
dragWindow_ = [draggedController_ window];
} else {
// Detach from the current window and put it in a new window.
draggedController_ = [sourceController_ detachTabToNewWindow:self];
dragWindow_ = [draggedController_ window];
[dragWindow_ setAlphaValue:0.0];
}
// Bring the target window to the front and make sure it has a border.
[dragWindow_ setLevel:NSFloatingWindowLevel];
[dragWindow_ orderFront:nil];
[dragWindow_ makeMainWindow];
[draggedController_ showOverlay];
dragOverlay_ = [draggedController_ overlayWindow];
//if (![targets count])
// [dragOverlay_ setHasShadow:NO];
if (!isTheOnlyTab_) {
tearTime_ = [NSDate timeIntervalSinceReferenceDate];
tearOrigin_ = sourceWindowFrame_.origin;
}
}
float tearProgress = [NSDate timeIntervalSinceReferenceDate] - tearTime_;
tearProgress /= kTearDuration;
tearProgress = sqrtf(MAX(MIN(tearProgress, 1.0), 0.0));
// Move the dragged window to the right place on the screen.
NSPoint origin = sourceWindowFrame_.origin;
origin.x += (thisPoint.x - dragOrigin_.x);
origin.y += (thisPoint.y - dragOrigin_.y);
if (tearProgress < 1) {
// If the tear animation is not complete, call back to ourself with the
// same event to animate even if the mouse isn't moving.
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[self performSelector:@selector(mouseDragged:)
withObject:theEvent
afterDelay:1.0f/30.0f];
origin.x = (1 - tearProgress) * tearOrigin_.x + tearProgress * origin.x;
origin.y = (1 - tearProgress) * tearOrigin_.y + tearProgress * origin.y;
}
if (targetController_) {
// In order to "snap" two windows of different sizes together at their
// toolbar, we can't just use the origin of the target frame. We also have
// to take into consideration the difference in height.
NSRect targetFrame = [[targetController_ window] frame];
NSRect sourceFrame = [dragWindow_ frame];
origin.y = NSMinY(targetFrame) +
(NSHeight(targetFrame) - NSHeight(sourceFrame));
}
[dragWindow_ setFrameOrigin:NSMakePoint(origin.x, origin.y)];
// If we're not hovering over any window, make the window is fully
// opaque. Otherwise, find where the tab might be dropped and insert
// a placeholder so it appears like it's part of that window.
if (targetController_) {
if (![[targetController_ window] isKeyWindow]) {
// && ([targetDwellDate timeIntervalSinceNow] < -REQUIRED_DWELL)) {
[[targetController_ window] orderFront:nil];
[targets removeAllObjects];
targetDwellDate = nil;
}
// Compute where placeholder should go and insert it into the
// destination tab strip.
NSRect dropTabFrame = [[targetController_ tabStripView] frame];
TabView *draggedTabView = (TabView *)[draggedController_ selectedTabView];
NSRect tabFrame = [draggedTabView frame];
tabFrame.origin = [dragWindow_ convertBaseToScreen:tabFrame.origin];
tabFrame.origin = [[targetController_ window]
convertScreenToBase:tabFrame.origin];
tabFrame = [[targetController_ tabStripView]
convertRectFromBase:tabFrame];
NSPoint point =
[sourceWindow_ convertBaseToScreen:
[draggedTabView convertPointToBase:NSZeroPoint]];
[targetController_ insertPlaceholderForTab:self
frame:tabFrame
yStretchiness:0];
[targetController_ layoutTabs];
} else {
[dragWindow_ makeKeyAndOrderFront:nil];
}
BOOL chromeShouldBeVisible = targetController_ == nil;
if (chromeIsVisible_ != chromeShouldBeVisible) {
[dragWindow_ setHasShadow:YES];
if (targetController_) {
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.00001];
[[dragWindow_ animator] setAlphaValue:0.0];
[NSAnimationContext endGrouping];
[[draggedController_ overlayWindow] setHasShadow:YES];
[[[draggedController_ overlayWindow] animator] setAlphaValue:1.0];
} else {
[[draggedController_ overlayWindow] setAlphaValue:1.0];
[[draggedController_ overlayWindow] setHasShadow:NO];
[[dragWindow_ animator] setAlphaValue:0.5];
}
chromeIsVisible_ = chromeShouldBeVisible;
}
}
- (void)mouseUp:(NSEvent *)theEvent {
// The drag/click is done. If the user dragged the mouse, finalize the drag
// and clean up.
if (draggingWithinTabStrip_) {
if (tabWasDragged_) {
// Move tab to new location.
TabWindowController* dropController = sourceController_;
[dropController moveTabView:[dropController selectedTabView]
fromController:nil];
}
} else if (targetController_) {
// Move between windows. If |targetController_| is nil, we're not dropping
// into any existing window.
NSView* draggedTabView = [draggedController_ selectedTabView];
[draggedController_ removeOverlay];
[targetController_ moveTabView:draggedTabView
fromController:draggedController_];
[targetController_ showWindow:nil];
} else {
[dragWindow_ setAlphaValue:1.0];
[dragOverlay_ setHasShadow:NO];
[dragWindow_ setHasShadow:YES];
[draggedController_ removeOverlay];
[dragWindow_ makeKeyAndOrderFront:nil];
[[draggedController_ window] setLevel:NSNormalWindowLevel];
[draggedController_ removePlaceholder];
[draggedController_ layoutTabs];
}
[sourceController_ removePlaceholder];
chromeIsVisible_ = YES;
}
- (void)otherMouseUp:(NSEvent*)theEvent {
// Support middle-click-to-close.
if ([theEvent buttonNumber] == 2) {
[controller_ closeTab:self];
}
}
- (NSPoint)patternPhase {
NSPoint phase = NSZeroPoint;
phase.x -= [self convertRect:[self bounds] toView:nil].origin.x;
// offset to start pattern in upper left corner
phase.y += NSHeight([self bounds]) - 1;
return phase;
}
- (void)drawRect:(NSRect)rect {
[[NSGraphicsContext currentContext] saveGraphicsState];
rect = [self bounds];
BOOL active = [[self window] isKeyWindow] || [[self window] isMainWindow];
BOOL selected = [(NSButton *)self state];
// Inset by 0.5 in order to draw on pixels rather than on borders (which would
// cause blurry pixels). Decrease height by 1 in order to move away from the
// edge for the dark shadow.
rect = NSInsetRect(rect, 0.5, -0.5);
rect.origin.y -= 1;
NSPoint bottomLeft = NSMakePoint(NSMinX(rect), NSMinY(rect));
NSPoint bottomRight = NSMakePoint(NSMaxX(rect), NSMinY(rect));
NSPoint topRight =
NSMakePoint(NSMaxX(rect) - kInsetMultiplier * NSHeight(rect),
NSMaxY(rect));
NSPoint topLeft =
NSMakePoint(NSMinX(rect) + kInsetMultiplier * NSHeight(rect),
NSMaxY(rect));
float baseControlPointOutset = NSHeight(rect) * kControlPoint1Multiplier;
float bottomControlPointInset = NSHeight(rect) * kControlPoint2Multiplier;
// Outset many of these values by 1 to cause the fill to bleed outside the
// clip area.
NSBezierPath *path = [NSBezierPath bezierPath];
[path moveToPoint:NSMakePoint(bottomLeft.x - 1, bottomLeft.y + 1)];
[path lineToPoint:NSMakePoint(bottomLeft.x - 1, bottomLeft.y)];
[path lineToPoint:bottomLeft];
[path curveToPoint:topLeft
controlPoint1:NSMakePoint(bottomLeft.x + baseControlPointOutset,
bottomLeft.y)
controlPoint2:NSMakePoint(topLeft.x - bottomControlPointInset,
topLeft.y)];
[path lineToPoint:topRight];
[path curveToPoint:bottomRight
controlPoint1:NSMakePoint(topRight.x + bottomControlPointInset,
topRight.y)
controlPoint2:NSMakePoint(bottomRight.x - baseControlPointOutset,
bottomRight.y)];
[path lineToPoint:NSMakePoint(bottomRight.x + 1, bottomRight.y)];
[path lineToPoint:NSMakePoint(bottomRight.x + 1, bottomRight.y + 1)];
if (selected) {
// Stroke with a translucent black.
[[NSColor colorWithCalibratedWhite:0.0 alpha:active ? 0.5 : 0.3] set];
[[NSGraphicsContext currentContext] saveGraphicsState];
scoped_nsobject<NSShadow> shadow([[NSShadow alloc] init]);
[shadow setShadowOffset:NSMakeSize(2, -1)];
[shadow setShadowBlurRadius:2.0];
[path fill];
[[NSGraphicsContext currentContext] restoreGraphicsState];
} else {
// Stroke with a translucent black.
[[NSBezierPath bezierPathWithRect:NSOffsetRect([self bounds], 0, 1)]
addClip];
[[NSColor colorWithCalibratedWhite:0.0 alpha:active ? 0.3 : 0.1] set];
}
[[NSGraphicsContext currentContext] saveGraphicsState];
[[NSColor colorWithCalibratedWhite:0.0 alpha:0.2] set];
[path setLineWidth:selected ? 2.0 : 1.0];
[path stroke];
[[NSGraphicsContext currentContext] restoreGraphicsState];
GTMTheme *theme = [self gtm_theme];
if (!selected) {
NSColor *windowColor =
[theme backgroundPatternColorForStyle:GTMThemeStyleWindow
state:GTMThemeStateActiveWindow];
if (windowColor) {
NSPoint phase = [self patternPhase];
[windowColor set];
[[NSGraphicsContext currentContext] setPatternPhase:phase];
} else {
[[NSColor colorWithCalibratedWhite:0.6 alpha:1.0] set];
}
[path fill];
}
// Draw the background.
[[NSGraphicsContext currentContext] saveGraphicsState];
CGContextRef context =
(CGContextRef)([[NSGraphicsContext currentContext] graphicsPort]);
CGContextBeginTransparencyLayer(context, 0);
if (!selected)
CGContextSetAlpha(context, 0.5);
[path addClip];
[super drawRect:rect];
CGContextEndTransparencyLayer(context);
[[NSGraphicsContext currentContext] restoreGraphicsState];
// Draw the bottom border.
if (!selected) {
[path addClip];
NSRect borderRect, contentRect;
NSDivideRect(rect, &borderRect, &contentRect, 1, NSMinYEdge);
[[NSColor colorWithCalibratedWhite:0.0 alpha:0.4] set];
NSRectFillUsingOperation(borderRect, NSCompositeSourceOver);
}
[[NSGraphicsContext currentContext] restoreGraphicsState];
}
// Called when the user hits the right mouse button (or control-clicks) to
// show a context menu.
- (void)rightMouseDown:(NSEvent*)theEvent {
[NSMenu popUpContextMenu:[self menu] withEvent:theEvent forView:self];
}
@end
|