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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
|
// Copyright (c) 2011 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.
#import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_editor.h"
#include "base/strings/string_util.h"
#include "base/strings/sys_string_conversions.h"
#include "chrome/app/chrome_command_ids.h" // IDC_*
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/ui/browser_list.h"
#import "chrome/browser/ui/cocoa/browser_window_controller.h"
#import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.h"
#import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.h"
#import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
#include "chrome/grit/generated_resources.h"
#import "ui/base/cocoa/find_pasteboard.h"
#include "ui/base/l10n/l10n_util_mac.h"
#include "ui/base/material_design/material_design_controller.h"
namespace {
// When too much data is put into a single-line text field, things get
// janky due to the cost of computing the blink rect. Sometimes users
// accidentally paste large amounts, so place a limit on what will be
// accepted.
//
// 10k characters was arbitrarily chosen by seeing how much a text
// field could handle in a single line before it started getting too
// janky to recover from (jankiness was detectable around 5k).
// www.google.com returns an error for searches around 2k characters,
// so this is conservative.
const NSUInteger kMaxPasteLength = 10000;
// Returns |YES| if too much text would be pasted.
BOOL ThePasteboardIsTooDamnBig() {
NSPasteboard* pb = [NSPasteboard generalPasteboard];
NSString* type =
[pb availableTypeFromArray:[NSArray arrayWithObject:NSStringPboardType]];
if (!type)
return NO;
return [[pb stringForType:type] length] > kMaxPasteLength;
}
} // namespace
@implementation AutocompleteTextFieldEditor
- (BOOL)shouldDrawInsertionPoint {
return [super shouldDrawInsertionPoint] &&
![[[self delegate] cell] hideFocusState];
}
- (id)initWithFrame:(NSRect)frameRect {
if ((self = [super initWithFrame:frameRect])) {
dropHandler_.reset([[URLDropTargetHandler alloc] initWithView:self]);
forbiddenCharacters_.reset([[NSCharacterSet controlCharacterSet] retain]);
// Disable all substitutions by default. In regular NSTextFields a user may
// selectively enable them via context menu, but that submenu is not enabled
// for the omnibox. The substitutions are unlikely to be useful in any case.
//
// Also see http://crbug.com/173405 and http://crbug.com/528014.
NSTextCheckingTypes checkingTypes = 0;
[self setEnabledTextCheckingTypes:checkingTypes];
}
return self;
}
- (void)viewDidMoveToWindow {
// Only care about landing in a window when in Material Design mode.
if (![self window] || !ui::MaterialDesignController::IsModeMaterial()) {
return;
}
// Only care about Incognito mode with a non-custom theme.
if (![[self window] inIncognitoModeWithSystemTheme]) {
return;
}
// Draw a light insertion point for MD Incognito.
[self setInsertionPointColor:
[NSColor colorWithCalibratedWhite:1 alpha:0.75]];
// In MD Incognito the text is light gray against a dark background. When
// selected, the light gray text against the selection color is illegible.
// Rather than tweak or change the selection color, make the text black when
// selected.
NSColor* textSelectionColor = [NSColor selectedTextBackgroundColor];
[self setSelectedTextAttributes:@{
NSForegroundColorAttributeName : [NSColor blackColor],
NSBackgroundColorAttributeName : textSelectionColor
}];
}
// If the entire field is selected, drag the same data as would be
// dragged from the field's location icon. In some cases the textual
// contents will not contain relevant data (for instance, "http://" is
// stripped from URLs).
- (BOOL)dragSelectionWithEvent:(NSEvent *)event
offset:(NSSize)mouseOffset
slideBack:(BOOL)slideBack {
AutocompleteTextFieldObserver* observer = [self observer];
DCHECK(observer);
if (observer && observer->CanCopy()) {
NSPasteboard* pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
observer->CopyToPasteboard(pboard);
NSPoint p;
NSImage* image = [self dragImageForSelectionWithEvent:event origin:&p];
[self dragImage:image
at:p
offset:mouseOffset
event:event
pasteboard:pboard
source:self
slideBack:slideBack];
return YES;
}
return [super dragSelectionWithEvent:event
offset:mouseOffset
slideBack:slideBack];
}
- (void)copy:(id)sender {
AutocompleteTextFieldObserver* observer = [self observer];
DCHECK(observer);
if (observer && observer->CanCopy())
observer->CopyToPasteboard([NSPasteboard generalPasteboard]);
}
- (void)cut:(id)sender {
[self copy:sender];
[self delete:nil];
}
- (void)showURL:(id)sender {
AutocompleteTextFieldObserver* observer = [self observer];
DCHECK(observer);
observer->ShowURL();
}
// This class assumes that the delegate is an AutocompleteTextField.
// Enforce that assumption.
- (AutocompleteTextField*)delegate {
AutocompleteTextField* delegate =
static_cast<AutocompleteTextField*>([super delegate]);
DCHECK(delegate == nil ||
[delegate isKindOfClass:[AutocompleteTextField class]]);
return delegate;
}
- (void)setDelegate:(AutocompleteTextField*)delegate {
DCHECK(delegate == nil ||
[delegate isKindOfClass:[AutocompleteTextField class]]);
// Unregister from any previously registered undo and redo notifications.
NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc removeObserver:self
name:NSUndoManagerDidUndoChangeNotification
object:nil];
[nc removeObserver:self
name:NSUndoManagerDidRedoChangeNotification
object:nil];
// Set the delegate.
[super setDelegate:delegate];
// Register for undo and redo notifications from the new |delegate|, if it is
// non-nil.
if ([self delegate]) {
NSUndoManager* undo_manager = [self undoManager];
[nc addObserver:self
selector:@selector(didUndoOrRedo:)
name:NSUndoManagerDidUndoChangeNotification
object:undo_manager];
[nc addObserver:self
selector:@selector(didUndoOrRedo:)
name:NSUndoManagerDidRedoChangeNotification
object:undo_manager];
}
}
- (void)didUndoOrRedo:(NSNotification *)aNotification {
AutocompleteTextFieldObserver* observer = [self observer];
if (observer)
observer->OnDidChange();
}
// Convenience method for retrieving the observer from the delegate.
- (AutocompleteTextFieldObserver*)observer {
return [[self delegate] observer];
}
- (void)paste:(id)sender {
if (ThePasteboardIsTooDamnBig()) {
NSBeep();
return;
}
AutocompleteTextFieldObserver* observer = [self observer];
DCHECK(observer);
if (observer) {
observer->OnPaste();
}
}
- (void)pasteAndMatchStyle:(id)sender {
[self paste:sender];
}
- (void)pasteAndGo:sender {
if (ThePasteboardIsTooDamnBig()) {
NSBeep();
return;
}
AutocompleteTextFieldObserver* observer = [self observer];
DCHECK(observer);
if (observer) {
observer->OnPasteAndGo();
}
}
// We have rich text, but it shouldn't be modified by the user, so
// don't update the font panel. In theory, -setUsesFontPanel: should
// accomplish this, but that gets called frequently with YES when
// NSTextField and NSTextView synchronize their contents. That is
// probably unavoidable because in most cases having rich text in the
// field you probably would expect it to update the font panel.
- (void)updateFontPanel {}
// No ruler bar, so don't update any of that state, either.
- (void)updateRuler {}
- (NSMenu*)menuForEvent:(NSEvent*)event {
// Give the control a chance to provide page-action menus.
// NOTE: Note that page actions aren't even in the editor's
// boundaries! The Cocoa control implementation seems to do a
// blanket forward to here if nothing more specific is returned from
// the control and cell calls.
// TODO(shess): Determine if the page-action part of this can be
// moved to the cell.
NSMenu* actionMenu = [[self delegate] decorationMenuForEvent:event];
if (actionMenu)
return actionMenu;
NSMenu* menu = [[[NSMenu alloc] initWithTitle:@"TITLE"] autorelease];
[menu addItemWithTitle:l10n_util::GetNSStringWithFixup(IDS_CUT)
action:@selector(cut:)
keyEquivalent:@""];
[menu addItemWithTitle:l10n_util::GetNSStringWithFixup(IDS_COPY)
action:@selector(copy:)
keyEquivalent:@""];
[menu addItemWithTitle:l10n_util::GetNSStringWithFixup(IDS_PASTE)
action:@selector(paste:)
keyEquivalent:@""];
// TODO(shess): If the control is not editable, should we show a
// greyed-out "Paste and Go"?
if ([self isEditable]) {
// Paste and go/search.
AutocompleteTextFieldObserver* observer = [self observer];
DCHECK(observer);
if (!ThePasteboardIsTooDamnBig()) {
NSString* pasteAndGoLabel =
l10n_util::GetNSStringWithFixup(observer->GetPasteActionStringId());
DCHECK([pasteAndGoLabel length]);
[menu addItemWithTitle:pasteAndGoLabel
action:@selector(pasteAndGo:)
keyEquivalent:@""];
}
[menu addItem:[NSMenuItem separatorItem]];
// Display a "Show URL" option if search term replacement is active.
if (observer->ShouldEnableShowURL()) {
NSString* showURLLabel =
l10n_util::GetNSStringWithFixup(IDS_SHOW_URL_MAC);
DCHECK([showURLLabel length]);
[menu addItemWithTitle:showURLLabel
action:@selector(showURL:)
keyEquivalent:@""];
}
NSString* searchEngineLabel =
l10n_util::GetNSStringWithFixup(IDS_EDIT_SEARCH_ENGINES);
DCHECK([searchEngineLabel length]);
NSMenuItem* item = [menu addItemWithTitle:searchEngineLabel
action:@selector(commandDispatch:)
keyEquivalent:@""];
[item setTag:IDC_EDIT_SEARCH_ENGINES];
}
return menu;
}
// (Overridden from NSResponder)
- (BOOL)becomeFirstResponder {
BOOL doAccept = [super becomeFirstResponder];
AutocompleteTextField* field = [self delegate];
// Only lock visibility if we've been set up with a delegate (the text field).
if (doAccept && field) {
// Give the text field ownership of the visibility lock. (The first
// responder dance between the field and the field editor is a little
// weird.)
[[BrowserWindowController browserWindowControllerForView:field]
lockBarVisibilityForOwner:field withAnimation:YES delay:NO];
}
return doAccept;
}
// (Overridden from NSResponder)
- (BOOL)resignFirstResponder {
BOOL doResign = [super resignFirstResponder];
AutocompleteTextField* field = [self delegate];
// Only lock visibility if we've been set up with a delegate (the text field).
if (doResign && field) {
// Give the text field ownership of the visibility lock.
[[BrowserWindowController browserWindowControllerForView:field]
releaseBarVisibilityForOwner:field withAnimation:YES delay:YES];
AutocompleteTextFieldObserver* observer = [self observer];
if (observer)
observer->OnKillFocus();
}
return doResign;
}
- (void)mouseDown:(NSEvent*)event {
AutocompleteTextFieldObserver* observer = [self observer];
if (observer)
observer->OnMouseDown([event buttonNumber]);
[super mouseDown:event];
}
- (void)rightMouseDown:(NSEvent *)event {
AutocompleteTextFieldObserver* observer = [self observer];
if (observer)
observer->OnMouseDown([event buttonNumber]);
[super rightMouseDown:event];
}
- (void)otherMouseDown:(NSEvent *)event {
AutocompleteTextFieldObserver* observer = [self observer];
if (observer)
observer->OnMouseDown([event buttonNumber]);
[super otherMouseDown:event];
}
// (URLDropTarget protocol)
- (id<URLDropTargetController>)urlDropController {
BrowserWindowController* windowController =
[BrowserWindowController browserWindowControllerForView:self];
return [windowController toolbarController];
}
// (URLDropTarget protocol)
- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
// Make ourself the first responder (even though we're presumably already the
// first responder), which will select the text to indicate that our contents
// would be replaced by a drop.
[[self window] makeFirstResponder:self];
return [dropHandler_ draggingEntered:sender];
}
// (URLDropTarget protocol)
- (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
return [dropHandler_ draggingUpdated:sender];
}
// (URLDropTarget protocol)
- (void)draggingExited:(id<NSDraggingInfo>)sender {
return [dropHandler_ draggingExited:sender];
}
// (URLDropTarget protocol)
- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
return [dropHandler_ performDragOperation:sender];
}
// Prevent control characters from being entered into the Omnibox.
// This is invoked for keyboard entry, not for pasting.
- (void)insertText:(id)aString {
AutocompleteTextFieldObserver* observer = [self observer];
if (observer)
observer->OnInsertText();
// Repeatedly remove control characters. The loop will only ever
// execute at all when the user enters control characters (using
// Ctrl-Alt- or Ctrl-Q). Making this generally efficient would
// probably be a loss, since the input always seems to be a single
// character.
if ([aString isKindOfClass:[NSAttributedString class]]) {
NSRange range =
[[aString string] rangeOfCharacterFromSet:forbiddenCharacters_];
while (range.location != NSNotFound) {
aString = [[aString mutableCopy] autorelease];
[aString deleteCharactersInRange:range];
range = [[aString string] rangeOfCharacterFromSet:forbiddenCharacters_];
}
DCHECK_EQ(range.length, 0U);
} else {
NSRange range = [aString rangeOfCharacterFromSet:forbiddenCharacters_];
while (range.location != NSNotFound) {
aString =
[aString stringByReplacingCharactersInRange:range withString:@""];
range = [aString rangeOfCharacterFromSet:forbiddenCharacters_];
}
DCHECK_EQ(range.length, 0U);
}
// NOTE: If |aString| is empty, this intentionally replaces the
// selection with empty. This seems consistent with the case where
// the input contained a mixture of characters and the string ended
// up not empty.
[super insertText:aString];
}
- (NSRange)selectionRangeForProposedRange:(NSRange)proposedSelRange
granularity:(NSSelectionGranularity)granularity {
AutocompleteTextFieldObserver* observer = [self observer];
NSRange modifiedRange = [super selectionRangeForProposedRange:proposedSelRange
granularity:granularity];
if (observer)
return observer->SelectionRangeForProposedRange(modifiedRange);
return modifiedRange;
}
- (void)setSelectedRange:(NSRange)charRange
affinity:(NSSelectionAffinity)affinity
stillSelecting:(BOOL)flag {
[super setSelectedRange:charRange affinity:affinity stillSelecting:flag];
// We're only interested in selection changes directly caused by keyboard
// input from the user.
if (interpretingKeyEvents_)
textChangedByKeyEvents_ = YES;
}
- (void)interpretKeyEvents:(NSArray *)eventArray {
DCHECK(!interpretingKeyEvents_);
interpretingKeyEvents_ = YES;
textChangedByKeyEvents_ = NO;
AutocompleteTextFieldObserver* observer = [self observer];
if (observer)
observer->OnBeforeChange();
[super interpretKeyEvents:eventArray];
if (textChangedByKeyEvents_ && observer)
observer->OnDidChange();
DCHECK(interpretingKeyEvents_);
interpretingKeyEvents_ = NO;
}
- (BOOL)shouldChangeTextInRange:(NSRange)affectedCharRange
replacementString:(NSString *)replacementString {
BOOL ret = [super shouldChangeTextInRange:affectedCharRange
replacementString:replacementString];
if (ret && !interpretingKeyEvents_) {
AutocompleteTextFieldObserver* observer = [self observer];
if (observer)
observer->OnBeforeChange();
}
return ret;
}
- (void)didChangeText {
[super didChangeText];
AutocompleteTextFieldObserver* observer = [self observer];
if (observer) {
if (!interpretingKeyEvents_ &&
![[self undoManager] isUndoing] && ![[self undoManager] isRedoing]) {
observer->OnDidChange();
} else if (interpretingKeyEvents_) {
textChangedByKeyEvents_ = YES;
}
}
}
- (void)doCommandBySelector:(SEL)cmd {
// TODO(shess): Review code for cases where we're fruitlessly attempting to
// work in spite of not having an observer.
AutocompleteTextFieldObserver* observer = [self observer];
if (observer && observer->OnDoCommandBySelector(cmd)) {
// The observer should already be aware of any changes to the text, so
// setting |textChangedByKeyEvents_| to NO to prevent its OnDidChange()
// method from being called unnecessarily.
textChangedByKeyEvents_ = NO;
return;
}
// If the escape key was pressed and no revert happened and we're in
// fullscreen mode, give focus to the web contents, which may dismiss the
// overlay.
if (cmd == @selector(cancelOperation:)) {
BrowserWindowController* windowController =
[BrowserWindowController browserWindowControllerForView:self];
if ([windowController isInAnyFullscreenMode]) {
[windowController focusTabContents];
textChangedByKeyEvents_ = NO;
return;
}
}
[super doCommandBySelector:cmd];
}
- (void)setAttributedString:(NSAttributedString*)aString {
NSTextStorage* textStorage = [self textStorage];
DCHECK(textStorage);
[textStorage setAttributedString:aString];
// The text has been changed programmatically. The observer should know
// this change, so setting |textChangedByKeyEvents_| to NO to
// prevent its OnDidChange() method from being called unnecessarily.
textChangedByKeyEvents_ = NO;
}
- (BOOL)validateMenuItem:(NSMenuItem*)item {
if ([item action] == @selector(copyToFindPboard:))
return [self selectedRange].length > 0;
if ([item action] == @selector(pasteAndGo:)) {
// TODO(rohitrao): If the clipboard is empty, should we show a
// greyed-out "Paste and Go" or nothing at all?
AutocompleteTextFieldObserver* observer = [self observer];
DCHECK(observer);
return observer->CanPasteAndGo();
}
if ([item action] == @selector(showURL:)) {
AutocompleteTextFieldObserver* observer = [self observer];
DCHECK(observer);
return observer->ShouldEnableShowURL();
}
return [super validateMenuItem:item];
}
- (void)copyToFindPboard:(id)sender {
NSRange selectedRange = [self selectedRange];
if (selectedRange.length == 0)
return;
NSAttributedString* selection =
[self attributedSubstringForProposedRange:selectedRange
actualRange:NULL];
if (!selection)
return;
[[FindPasteboard sharedInstance] setFindText:[selection string]];
}
- (void)drawRect:(NSRect)rect {
[super drawRect:rect];
autocomplete_text_field::DrawGrayTextAutocompletion(
[self textStorage],
[[self delegate] suggestText],
[[self delegate] suggestColor],
self,
[self bounds]);
AutocompleteTextFieldObserver* observer = [self observer];
if (observer)
observer->OnDidDrawRect();
}
@end
|