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.
5 #import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.h"
7 #include "base/logging.h"
8 #include "base/mac/foundation_util.h"
9 #include "base/mac/mac_logging.h"
10 #include "chrome/browser/search/search.h"
11 #import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.h"
12 #import "chrome/browser/ui/cocoa/location_bar/button_decoration.h"
13 #import "chrome/browser/ui/cocoa/location_bar/location_bar_decoration.h"
14 #import "chrome/browser/ui/cocoa/nsview_additions.h"
15 #import "extensions/common/feature_switch.h"
16 #include "grit/theme_resources.h"
17 #import "third_party/mozilla/NSPasteboard+Utils.h"
18 #import "ui/base/cocoa/appkit_utils.h"
19 #import "ui/base/cocoa/tracking_area.h"
20 #include "ui/base/resource/resource_bundle.h"
22 using extensions::FeatureSwitch;
26 // Matches the clipping radius of |GradientButtonCell|.
27 const CGFloat kCornerRadius = 3.0;
29 // How far to inset the left- and right-hand decorations from the field's
31 const CGFloat kLeftDecorationXOffset = 5.0;
32 const CGFloat kRightDecorationXOffset = 5.0;
34 // The amount of padding on either side reserved for drawing
35 // decorations. [Views has |kItemPadding| == 3.]
36 const CGFloat kDecorationHorizontalPad = 3.0;
38 NSString* const kButtonDecorationKey = @"ButtonDecoration";
40 const ui::NinePartImageIds kPopupBorderImageIds =
41 IMAGE_GRID(IDR_OMNIBOX_POPUP_BORDER_AND_SHADOW);
43 const ui::NinePartImageIds kNormalBorderImageIds =
44 IMAGE_GRID(IDR_OMNIBOX_BORDER_AND_SHADOW);
46 // How long to wait for mouse-up on the location icon before assuming
47 // that the user wants to drag.
48 const NSTimeInterval kLocationIconDragTimeout = 0.25;
50 // Calculate the positions for a set of decorations. |frame| is the
51 // overall frame to do layout in, |remaining_frame| will get the
52 // left-over space. |all_decorations| is the set of decorations to
53 // lay out, |decorations| will be set to the decorations which are
54 // visible and which fit, in the same order as |all_decorations|,
55 // while |decoration_frames| will be the corresponding frames.
56 // |x_edge| describes the edge to layout the decorations against
57 // (|NSMinXEdge| or |NSMaxXEdge|). |regular_padding| is the padding
58 // from the edge of |cell_frame| to use when the first visible decoration
59 // is a regular decoration. |action_padding| is the padding to use when the
60 // first decoration is a button decoration, ie. the action box button.
61 // (|kDecorationHorizontalPad| is used between decorations).
62 void CalculatePositionsHelper(
64 const std::vector<LocationBarDecoration*>& all_decorations,
66 CGFloat regular_padding,
67 CGFloat action_padding,
68 std::vector<LocationBarDecoration*>* decorations,
69 std::vector<NSRect>* decoration_frames,
70 NSRect* remaining_frame) {
71 DCHECK(x_edge == NSMinXEdge || x_edge == NSMaxXEdge);
72 DCHECK_EQ(decorations->size(), decoration_frames->size());
74 // The initial padding depends on whether the first visible decoration is
76 bool is_first_visible_decoration = true;
78 for (size_t i = 0; i < all_decorations.size(); ++i) {
79 if (all_decorations[i]->IsVisible()) {
80 CGFloat padding = kDecorationHorizontalPad;
81 if (is_first_visible_decoration) {
82 padding = all_decorations[i]->AsButtonDecoration() ?
83 action_padding : regular_padding;
84 is_first_visible_decoration = false;
87 NSRect padding_rect, available;
89 // Peel off the outside padding.
90 NSDivideRect(frame, &padding_rect, &available, padding, x_edge);
92 // Find out how large the decoration will be in the remaining
94 const CGFloat used_width =
95 all_decorations[i]->GetWidthForSpace(NSWidth(available));
97 if (used_width != LocationBarDecoration::kOmittedWidth) {
98 DCHECK_GT(used_width, 0.0);
99 NSRect decoration_frame;
101 // Peel off the desired width, leaving the remainder in
103 NSDivideRect(available, &decoration_frame, &frame,
106 decorations->push_back(all_decorations[i]);
107 decoration_frames->push_back(decoration_frame);
108 DCHECK_EQ(decorations->size(), decoration_frames->size());
110 // Adjust padding for between decorations.
111 padding = kDecorationHorizontalPad;
116 DCHECK_EQ(decorations->size(), decoration_frames->size());
117 *remaining_frame = frame;
120 // Helper function for calculating placement of decorations w/in the cell.
121 // |frame| is the cell's boundary rectangle, |remaining_frame| will get any
122 // space left after decorations are laid out (for text). |left_decorations| is
123 // a set of decorations for the left-hand side of the cell, |right_decorations|
124 // for the right-hand side. |edge_width| is the width of one vertical edge of
125 // the omnibox, this depends on whether the display is low DPI or high DPI.
126 // |decorations| will contain the resulting visible decorations, and
127 // |decoration_frames| will contain their frames in the same coordinates as
128 // |frame|. Decorations will be ordered left to right. As a convenience returns
129 // the index of the first right-hand decoration.
130 size_t CalculatePositionsInFrame(
132 const std::vector<LocationBarDecoration*>& left_decorations,
133 const std::vector<LocationBarDecoration*>& right_decorations,
135 std::vector<LocationBarDecoration*>* decorations,
136 std::vector<NSRect>* decoration_frames,
137 NSRect* remaining_frame) {
138 decorations->clear();
139 decoration_frames->clear();
141 // Layout |left_decorations| against the LHS.
142 CalculatePositionsHelper(frame, left_decorations, NSMinXEdge,
143 kLeftDecorationXOffset, edge_width,
144 decorations, decoration_frames, &frame);
145 DCHECK_EQ(decorations->size(), decoration_frames->size());
147 // Capture the number of visible left-hand decorations.
148 const size_t left_count = decorations->size();
150 // Layout |right_decorations| against the RHS.
151 CalculatePositionsHelper(frame, right_decorations, NSMaxXEdge,
152 kRightDecorationXOffset, edge_width, decorations,
153 decoration_frames, &frame);
154 DCHECK_EQ(decorations->size(), decoration_frames->size());
156 // Reverse the right-hand decorations so that overall everything is
157 // sorted left to right.
158 std::reverse(decorations->begin() + left_count, decorations->end());
159 std::reverse(decoration_frames->begin() + left_count,
160 decoration_frames->end());
162 *remaining_frame = frame;
168 @interface AutocompleteTextFieldCell ()
169 // Post an OnSetFocus notification to the observer of |controlView|.
170 - (void)focusNotificationFor:(NSEvent*)event
171 ofView:(AutocompleteTextField*)controlView;
174 @implementation AutocompleteTextFieldCell
176 @synthesize isPopupMode = isPopupMode_;
178 - (CGFloat)topTextFrameOffset {
182 - (CGFloat)bottomTextFrameOffset {
186 - (CGFloat)cornerRadius {
187 return kCornerRadius;
190 - (CGFloat)edgeWidth {
191 // The omnibox vertical edge width is 1 pixel both in low DPI and high DPI.
192 return [[self controlView] cr_lineWidth];
195 - (BOOL)shouldDrawBezel {
199 - (CGFloat)lineHeight {
203 - (void)clearDecorations {
204 leftDecorations_.clear();
205 rightDecorations_.clear();
208 - (void)addLeftDecoration:(LocationBarDecoration*)decoration {
209 leftDecorations_.push_back(decoration);
212 - (void)addRightDecoration:(LocationBarDecoration*)decoration {
213 rightDecorations_.push_back(decoration);
216 - (CGFloat)availableWidthInFrame:(const NSRect)frame {
217 std::vector<LocationBarDecoration*> decorations;
218 std::vector<NSRect> decorationFrames;
220 CalculatePositionsInFrame(frame, leftDecorations_, rightDecorations_,
221 [self edgeWidth], &decorations, &decorationFrames,
224 return NSWidth(textFrame);
227 - (NSRect)frameForDecoration:(const LocationBarDecoration*)aDecoration
228 inFrame:(NSRect)cellFrame {
229 // Short-circuit if the decoration is known to be not visible.
230 if (aDecoration && !aDecoration->IsVisible())
233 // Layout the decorations.
234 std::vector<LocationBarDecoration*> decorations;
235 std::vector<NSRect> decorationFrames;
237 CalculatePositionsInFrame(cellFrame, leftDecorations_, rightDecorations_,
238 [self edgeWidth], &decorations, &decorationFrames,
241 // Find our decoration and return the corresponding frame.
242 std::vector<LocationBarDecoration*>::const_iterator iter =
243 std::find(decorations.begin(), decorations.end(), aDecoration);
244 if (iter != decorations.end()) {
245 const size_t index = iter - decorations.begin();
246 return decorationFrames[index];
249 // Decorations which are not visible should have been filtered out
250 // at the top, but return |NSZeroRect| rather than a 0-width rect
256 // Overriden to account for the decorations.
257 - (NSRect)textFrameForFrame:(NSRect)cellFrame {
258 // Get the frame adjusted for decorations.
259 std::vector<LocationBarDecoration*> decorations;
260 std::vector<NSRect> decorationFrames;
261 NSRect textFrame = [super textFrameForFrame:cellFrame];
262 CalculatePositionsInFrame(textFrame, leftDecorations_, rightDecorations_,
263 [self edgeWidth], &decorations, &decorationFrames,
266 // NOTE: This function must closely match the logic in
267 // |-drawInteriorWithFrame:inView:|.
272 // Returns the sub-frame where clicks can happen within the cell.
273 - (NSRect)clickableFrameForFrame:(NSRect)cellFrame {
274 return [super textFrameForFrame:cellFrame];
277 - (NSRect)textCursorFrameForFrame:(NSRect)cellFrame {
278 std::vector<LocationBarDecoration*> decorations;
279 std::vector<NSRect> decorationFrames;
282 CalculatePositionsInFrame(cellFrame, leftDecorations_, rightDecorations_,
283 [self edgeWidth], &decorations,
284 &decorationFrames, &textFrame);
286 // Determine the left-most extent for the i-beam cursor.
287 CGFloat minX = NSMinX(textFrame);
288 for (size_t index = left_count; index--; ) {
289 if (decorations[index]->AcceptsMousePress())
292 // If at leftmost decoration, expand to edge of cell.
294 minX = NSMinX(cellFrame);
296 minX = NSMinX(decorationFrames[index]) - kDecorationHorizontalPad;
300 // Determine the right-most extent for the i-beam cursor.
301 CGFloat maxX = NSMaxX(textFrame);
302 for (size_t index = left_count; index < decorations.size(); ++index) {
303 if (decorations[index]->AcceptsMousePress())
306 // If at rightmost decoration, expand to edge of cell.
307 if (index == decorations.size() - 1) {
308 maxX = NSMaxX(cellFrame);
310 maxX = NSMaxX(decorationFrames[index]) + kDecorationHorizontalPad;
314 // I-beam cursor covers left-most to right-most.
315 return NSMakeRect(minX, NSMinY(textFrame), maxX - minX, NSHeight(textFrame));
318 - (void)drawWithFrame:(NSRect)frame inView:(NSView*)controlView {
320 const CGFloat lineWidth = [controlView cr_lineWidth];
322 [[self backgroundColor] set];
323 NSRectFillUsingOperation(NSInsetRect(frame, 1, 1), NSCompositeSourceOver);
325 CGFloat insetSize = lineWidth == 0.5 ? 1.5 : 2.0;
326 NSRect fillRect = NSInsetRect(frame, insetSize, insetSize);
327 [[self backgroundColor] set];
328 [[NSBezierPath bezierPathWithRoundedRect:fillRect
329 xRadius:kCornerRadius
330 yRadius:kCornerRadius] fill];
334 ui::DrawNinePartImage(frame,
335 isPopupMode_ ? kPopupBorderImageIds
336 : kNormalBorderImageIds,
337 NSCompositeSourceOver,
341 // Interior contents. Drawn after the border as some of the interior controls
342 // draw over the border.
343 [self drawInteriorWithFrame:frame inView:controlView];
346 if ([self showsFirstResponder]) {
347 NSRect focusRingRect = NSInsetRect(frame, lineWidth, lineWidth);
348 [[[NSColor keyboardFocusIndicatorColor]
349 colorWithAlphaComponent:0.5 / lineWidth] set];
350 NSBezierPath* path = [NSBezierPath bezierPathWithRoundedRect:focusRingRect
351 xRadius:kCornerRadius
352 yRadius:kCornerRadius];
353 [path setLineWidth:lineWidth * 2.0];
358 - (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView*)controlView {
359 std::vector<LocationBarDecoration*> decorations;
360 std::vector<NSRect> decorationFrames;
363 CalculatePositionsInFrame(cellFrame, leftDecorations_, rightDecorations_,
364 [self edgeWidth], &decorations, &decorationFrames,
367 // Draw the decorations.
368 for (size_t i = 0; i < decorations.size(); ++i) {
369 if (decorations[i]) {
370 NSRect background_frame = NSInsetRect(
371 decorationFrames[i], -(kDecorationHorizontalPad + 1) / 2, 2);
372 decorations[i]->DrawWithBackgroundInFrame(
373 background_frame, decorationFrames[i], controlView);
377 // NOTE: This function must closely match the logic in
378 // |-textFrameForFrame:|.
380 // Superclass draws text portion WRT original |cellFrame|.
381 [super drawInteriorWithFrame:cellFrame inView:controlView];
384 - (LocationBarDecoration*)decorationForEvent:(NSEvent*)theEvent
385 inRect:(NSRect)cellFrame
386 ofView:(AutocompleteTextField*)controlView
388 const BOOL flipped = [controlView isFlipped];
389 const NSPoint location =
390 [controlView convertPoint:[theEvent locationInWindow] fromView:nil];
392 std::vector<LocationBarDecoration*> decorations;
393 std::vector<NSRect> decorationFrames;
395 CalculatePositionsInFrame(cellFrame, leftDecorations_, rightDecorations_,
396 [self edgeWidth], &decorations, &decorationFrames,
399 for (size_t i = 0; i < decorations.size(); ++i) {
400 if (NSMouseInRect(location, decorationFrames[i], flipped))
401 return decorations[i];
407 - (NSMenu*)decorationMenuForEvent:(NSEvent*)theEvent
408 inRect:(NSRect)cellFrame
409 ofView:(AutocompleteTextField*)controlView {
410 LocationBarDecoration* decoration =
411 [self decorationForEvent:theEvent inRect:cellFrame ofView:controlView];
413 return decoration->GetMenu();
417 - (BOOL)mouseDown:(NSEvent*)theEvent
418 inRect:(NSRect)cellFrame
419 ofView:(AutocompleteTextField*)controlView {
420 // TODO(groby): Factor this into three pieces - find target for event, handle
421 // delayed focus (for any and all events), execute mouseDown for target.
423 // Check if this mouseDown was the reason the control became firstResponder.
424 // If not, discard focus event.
425 base::scoped_nsobject<NSEvent> focusEvent(focusEvent_.release());
426 if (![theEvent isEqual:focusEvent])
429 LocationBarDecoration* decoration =
430 [self decorationForEvent:theEvent inRect:cellFrame ofView:controlView];
431 if (!decoration || !decoration->AcceptsMousePress())
434 NSRect decorationRect =
435 [self frameForDecoration:decoration inFrame:cellFrame];
437 // If the decoration is draggable, then initiate a drag if the user
438 // drags or holds the mouse down for awhile.
439 if (decoration->IsDraggable()) {
441 [NSDate dateWithTimeIntervalSinceNow:kLocationIconDragTimeout];
442 NSEvent* event = [NSApp nextEventMatchingMask:(NSLeftMouseDraggedMask |
445 inMode:NSEventTrackingRunLoopMode
447 if (!event || [event type] == NSLeftMouseDragged) {
448 NSPasteboard* pboard = decoration->GetDragPasteboard();
451 NSImage* image = decoration->GetDragImage();
454 NSRect dragImageRect = decoration->GetDragImageFrame(decorationRect);
456 // Center under mouse horizontally, with cursor below so the image
458 const NSPoint mousePoint =
459 [controlView convertPoint:[theEvent locationInWindow] fromView:nil];
460 dragImageRect.origin =
461 NSMakePoint(mousePoint.x - NSWidth(dragImageRect) / 2.0,
462 mousePoint.y - NSHeight(dragImageRect));
464 // -[NSView dragImage:at:*] wants the images lower-left point,
465 // regardless of -isFlipped. Converting the rect to window base
466 // coordinates doesn't require any special-casing. Note that
467 // -[NSView dragFile:fromRect:*] takes a rect rather than a
468 // point, likely for this exact reason.
469 const NSPoint dragPoint =
470 [controlView convertRect:dragImageRect toView:nil].origin;
471 [[controlView window] dragImage:image
482 // On mouse-up fall through to mouse-pressed case.
483 DCHECK_EQ([event type], NSLeftMouseUp);
487 if (decoration->AsButtonDecoration()) {
488 ButtonDecoration* button = decoration->AsButtonDecoration();
490 button->SetButtonState(ButtonDecoration::kButtonStatePressed);
491 [controlView setNeedsDisplay:YES];
493 // Track the mouse until the user releases the button.
494 [self trackMouse:theEvent
499 // Post delayed focus notification, if necessary.
500 if (focusEvent.get())
501 [self focusNotificationFor:focusEvent ofView:controlView];
503 // Set the proper state (hover or normal) once the mouse has been released,
504 // and call |OnMousePressed| if the button was released while the mouse was
505 // within the bounds of the button.
506 const NSPoint mouseLocation = [[NSApp currentEvent] locationInWindow];
507 const NSPoint point = [controlView convertPoint:mouseLocation fromView:nil];
508 if (NSMouseInRect(point, decorationRect, [controlView isFlipped])) {
509 button->SetButtonState(ButtonDecoration::kButtonStateHover);
510 [controlView setNeedsDisplay:YES];
511 handled = decoration->AsButtonDecoration()->OnMousePressed(
512 [self frameForDecoration:decoration inFrame:cellFrame]);
514 button->SetButtonState(ButtonDecoration::kButtonStateNormal);
515 [controlView setNeedsDisplay:YES];
519 handled = decoration->OnMousePressed(decorationRect);
522 return handled ? YES : NO;
525 // Helper method for the |mouseEntered:inView:| and |mouseExited:inView:|
526 // messages. Retrieves the |ButtonDecoration| for the specified event (received
527 // from a tracking area), and returns |NULL| if no decoration matches.
528 - (ButtonDecoration*)getButtonDecorationForEvent:(NSEvent*)theEvent {
529 ButtonDecoration* bd = static_cast<ButtonDecoration*>(
530 [[[[theEvent trackingArea] userInfo] valueForKey:kButtonDecorationKey]
534 std::count(leftDecorations_.begin(), leftDecorations_.end(), bd) ||
535 std::count(rightDecorations_.begin(), rightDecorations_.end(), bd));
540 // Helper method for |setUpTrackingAreasInView|. Creates an |NSDictionary| to
541 // be used as user information to identify which decoration is the source of an
542 // event (from a tracking area).
543 - (NSDictionary*)getDictionaryForButtonDecoration:
544 (ButtonDecoration*)decoration {
549 std::count(leftDecorations_.begin(), leftDecorations_.end(), decoration) ||
550 std::count(rightDecorations_.begin(), rightDecorations_.end(), decoration));
553 dictionaryWithObject:[NSValue valueWithPointer:decoration]
554 forKey:kButtonDecorationKey];
557 - (void)mouseEntered:(NSEvent*)theEvent
558 inView:(AutocompleteTextField*)controlView {
559 ButtonDecoration* decoration = [self getButtonDecorationForEvent:theEvent];
561 decoration->SetButtonState(ButtonDecoration::kButtonStateHover);
562 [controlView setNeedsDisplay:YES];
566 - (void)mouseExited:(NSEvent*)theEvent
567 inView:(AutocompleteTextField*)controlView {
568 ButtonDecoration* decoration = [self getButtonDecorationForEvent:theEvent];
570 decoration->SetButtonState(ButtonDecoration::kButtonStateNormal);
571 [controlView setNeedsDisplay:YES];
575 - (void)setUpTrackingAreasInRect:(NSRect)frame
576 ofView:(AutocompleteTextField*)view {
577 std::vector<LocationBarDecoration*> decorations;
578 std::vector<NSRect> decorationFrames;
580 NSRect cellRect = [self clickableFrameForFrame:[view bounds]];
581 CalculatePositionsInFrame(cellRect, leftDecorations_, rightDecorations_,
582 [self edgeWidth], &decorations, &decorationFrames,
585 // Remove previously-registered tracking areas, since we'll update them below.
586 for (CrTrackingArea* area in [view trackingAreas]) {
587 if ([[area userInfo] objectForKey:kButtonDecorationKey])
588 [view removeTrackingArea:area];
591 // Setup new tracking areas for the buttons.
592 for (size_t i = 0; i < decorations.size(); ++i) {
593 ButtonDecoration* button = decorations[i]->AsButtonDecoration();
595 // If the button isn't pressed (in which case we want to leave it as-is),
596 // update it's state since we might have missed some entered/exited events
597 // because of the removing/adding of the tracking areas.
598 if (button->GetButtonState() !=
599 ButtonDecoration::kButtonStatePressed) {
600 const NSPoint mouseLocationWindow =
601 [[view window] mouseLocationOutsideOfEventStream];
602 const NSPoint mouseLocation =
603 [view convertPoint:mouseLocationWindow fromView:nil];
604 const BOOL mouseInRect = NSMouseInRect(
605 mouseLocation, decorationFrames[i], [view isFlipped]);
606 button->SetButtonState(mouseInRect ?
607 ButtonDecoration::kButtonStateHover :
608 ButtonDecoration::kButtonStateNormal);
609 [view setNeedsDisplay:YES];
612 NSDictionary* info = [self getDictionaryForButtonDecoration:button];
613 base::scoped_nsobject<CrTrackingArea> area(
614 [[CrTrackingArea alloc] initWithRect:decorationFrames[i]
615 options:NSTrackingMouseEnteredAndExited |
616 NSTrackingActiveAlways
619 [view addTrackingArea:area];
624 // Given a newly created .webloc plist url file, also give it a resource
625 // fork and insert 'TEXT and 'url ' resources holding further copies of the
626 // url data. This is required for apps such as Terminal and Safari to accept it
627 // as a real webloc file when dragged in.
628 // It's expected that the resource fork requirement will go away at some
629 // point and this code can then be deleted.
630 OSErr WriteURLToNewWebLocFileResourceFork(NSURL* file, NSString* urlStr) {
631 ResFileRefNum refNum = kResFileNotOpened;
632 ResFileRefNum prevResRef = CurResFile();
635 HFSUniStr255 resourceForkName;
636 FSGetResourceForkName(&resourceForkName);
638 if (![[NSFileManager defaultManager] fileExistsAtPath:[file path]])
641 if (!CFURLGetFSRef((CFURLRef)file, &fsRef))
644 err = FSCreateResourceFork(&fsRef,
645 resourceForkName.length,
646 resourceForkName.unicode,
650 err = FSOpenResourceFile(&fsRef,
651 resourceForkName.length,
652 resourceForkName.unicode,
653 fsRdWrPerm, &refNum);
657 const char* utf8URL = [urlStr UTF8String];
658 int urlChars = strlen(utf8URL);
660 Handle urlHandle = NewHandle(urlChars);
661 memcpy(*urlHandle, utf8URL, urlChars);
663 Handle textHandle = NewHandle(urlChars);
664 memcpy(*textHandle, utf8URL, urlChars);
666 // Data for the 'drag' resource.
667 // This comes from derezzing webloc files made by the Finder.
668 // It's bigendian data, so it's represented here as chars to preserve
671 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, // Header.
672 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
673 0x54, 0x45, 0x58, 0x54, 0x00, 0x00, 0x01, 0x00, // 'TEXT', 0, 256
674 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
675 0x75, 0x72, 0x6C, 0x20, 0x00, 0x00, 0x01, 0x00, // 'url ', 0, 256
676 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
678 Handle dragHandle = NewHandleClear(sizeof(dragData));
679 memcpy(*dragHandle, &dragData[0], sizeof(dragData));
681 // Save the resources to the file.
682 ConstStr255Param noName = {0};
683 AddResource(dragHandle, 'drag', 128, noName);
684 AddResource(textHandle, 'TEXT', 256, noName);
685 AddResource(urlHandle, 'url ', 256, noName);
687 CloseResFile(refNum);
688 UseResFile(prevResRef);
692 // Returns the file path for file |name| if saved at NSURL |base|.
693 static NSString* PathWithBaseURLAndName(NSURL* base, NSString* name) {
694 NSString* filteredName =
695 [name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
696 return [[NSURL URLWithString:filteredName relativeToURL:base] path];
699 // Returns if there is already a file |name| at dir NSURL |base|.
700 static BOOL FileAlreadyExists(NSURL* base, NSString* name) {
701 NSString* path = PathWithBaseURLAndName(base, name);
702 DCHECK([path hasSuffix:name]);
703 return [[NSFileManager defaultManager] fileExistsAtPath:path];
706 // Takes a destination URL, a suggested file name, & an extension (eg .webloc).
707 // Returns the complete file name with extension you should use.
708 // The name returned will not contain /, : or ?, will not be longer than
709 // kMaxNameLength + length of extension, and will not be a file name that
710 // already exists in that directory. If necessary it will try appending a space
711 // and a number to the name (but before the extension) trying numbers up to and
712 // including kMaxIndex.
713 // If the function gives up it returns nil.
714 static NSString* UnusedLegalNameForNewDropFile(NSURL* saveLocation,
716 NSString *extension) {
718 const int kMaxIndex = 20;
719 const unsigned kMaxNameLength = 64; // Arbitrary.
721 NSString* filteredName = [fileName stringByReplacingOccurrencesOfString:@"/"
723 filteredName = [filteredName stringByReplacingOccurrencesOfString:@":"
725 filteredName = [filteredName stringByReplacingOccurrencesOfString:@"?"
728 if ([filteredName length] > kMaxNameLength)
729 filteredName = [filteredName substringToIndex:kMaxNameLength];
731 NSString* candidateName = [filteredName stringByAppendingString:extension];
733 while (FileAlreadyExists(saveLocation, candidateName)) {
734 if (number > kMaxIndex)
737 candidateName = [filteredName stringByAppendingFormat:@" %d%@",
738 number++, extension];
741 return candidateName;
744 - (NSArray*)namesOfPromisedFilesDroppedAtDestination:(NSURL*)dropDestination {
745 NSPasteboard* pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
746 NSFileManager* fileManager = [NSFileManager defaultManager];
748 if (![pboard containsURLData])
751 NSArray *urls = NULL;
752 NSArray* titles = NULL;
753 [pboard getURLs:&urls andTitles:&titles convertingFilenames:YES];
755 NSString* urlStr = [urls objectAtIndex:0];
756 NSString* nameStr = [titles objectAtIndex:0];
758 NSString* nameWithExtensionStr =
759 UnusedLegalNameForNewDropFile(dropDestination, nameStr, @".webloc");
760 if (!nameWithExtensionStr)
763 NSDictionary* urlDict = [NSDictionary dictionaryWithObject:urlStr
766 [NSURL fileURLWithPath:PathWithBaseURLAndName(dropDestination,
767 nameWithExtensionStr)];
768 [urlDict writeToURL:outputURL
771 if (![fileManager fileExistsAtPath:[outputURL path]])
774 NSDictionary* attr = [NSDictionary dictionaryWithObjectsAndKeys:
775 [NSNumber numberWithBool:YES], NSFileExtensionHidden,
776 [NSNumber numberWithUnsignedLong:'ilht'], NSFileHFSTypeCode,
777 [NSNumber numberWithUnsignedLong:'MACS'], NSFileHFSCreatorCode,
779 [fileManager setAttributes:attr
780 ofItemAtPath:[outputURL path]
782 // Add resource data.
783 OSErr resStatus = WriteURLToNewWebLocFileResourceFork(outputURL, urlStr);
784 OSSTATUS_DCHECK(resStatus == noErr, resStatus);
786 return [NSArray arrayWithObject:nameWithExtensionStr];
789 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal {
790 return NSDragOperationCopy;
793 - (void)updateToolTipsInRect:(NSRect)cellFrame
794 ofView:(AutocompleteTextField*)controlView {
795 std::vector<LocationBarDecoration*> decorations;
796 std::vector<NSRect> decorationFrames;
798 CalculatePositionsInFrame(cellFrame, leftDecorations_, rightDecorations_,
799 [self edgeWidth], &decorations, &decorationFrames,
802 for (size_t i = 0; i < decorations.size(); ++i) {
803 NSString* tooltip = decorations[i]->GetToolTip();
804 if ([tooltip length] > 0)
805 [controlView addToolTip:tooltip forRect:decorationFrames[i]];
809 - (BOOL)hideFocusState {
810 return hideFocusState_;
813 - (void)setHideFocusState:(BOOL)hideFocusState
814 ofView:(AutocompleteTextField*)controlView {
815 if (hideFocusState_ == hideFocusState)
817 hideFocusState_ = hideFocusState;
818 [controlView setNeedsDisplay:YES];
819 NSTextView* fieldEditor =
820 base::mac::ObjCCastStrict<NSTextView>([controlView currentEditor]);
821 [fieldEditor updateInsertionPointStateAndRestartTimer:YES];
824 - (BOOL)showsFirstResponder {
825 return [super showsFirstResponder] && !hideFocusState_;
828 - (void)focusNotificationFor:(NSEvent*)event
829 ofView:(AutocompleteTextField*)controlView {
830 if ([controlView observer]) {
831 const bool controlDown = ([event modifierFlags] & NSControlKeyMask) != 0;
832 [controlView observer]->OnSetFocus(controlDown);
836 - (void)handleFocusEvent:(NSEvent*)event
837 ofView:(AutocompleteTextField*)controlView {
838 // Only intercept left button click. All other events cause immediate focus.
839 if ([event type] == NSLeftMouseDown) {
840 LocationBarDecoration* decoration =
841 [self decorationForEvent:event
842 inRect:[controlView bounds]
844 // Only ButtonDecorations need a delayed focus handling.
845 if (decoration && decoration->AsButtonDecoration()) {
846 focusEvent_.reset([event retain]);
851 // Handle event immediately.
852 [self focusNotificationFor:event ofView:controlView];