forked from amaxwell/tlutility
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTLMAddressTextField.m
431 lines (357 loc) · 16.7 KB
/
TLMAddressTextField.m
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
//
// TLMAddressTextField.m
// TeX Live Utility
//
// Created by Adam R. Maxwell on 07/24/11.
/*
This software is Copyright (c) 2011-2016
Adam Maxwell. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
- Neither the name of Adam Maxwell nor the names of any
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "TLMAddressTextField.h"
#import "TLMAddressTextFieldCell.h"
#import "TLMMirrorCell.h"
#import "BDSKTextViewCompletionController.h"
static NSArray * __TLMAddressDragTypes()
{
/*
A webloc has a file: URL pointing to the webloc itself, and it also has a URL
embedded in it. Guess which one NSURLPboardType gives us? That's right, it
gives the file: URL pointing to the webloc file. Never mind that when you drop
a webloc on something you're generally interested in what's inside the webloc.
Fortunately, Apple's inconsistent or broken pasteboard APIs provide a workaround,
as asking for kUTTypeURL first will give us the embedded URL. Yay. (as of10.6.8)
*/
return [NSArray arrayWithObjects:(id)kUTTypeURL, NSURLPboardType, NSStringPboardType, nil];
}
@implementation TLMMirrorFieldEditor
- (void)handleTextDidBeginEditingNotification:(NSNotification *)note { _isEditing = YES; }
- (void)handleTextDidEndEditingNotification:(NSNotification *)note { _isEditing = NO; }
- (void)viewWillMoveToWindow:(NSWindow *)newWindow
{
[super viewWillMoveToWindow:newWindow];
if (newWindow) {
[self registerForDraggedTypes:__TLMAddressDragTypes()];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleTextDidBeginEditingNotification:)
name:NSTextDidBeginEditingNotification
object:self];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleTextDidEndEditingNotification:)
name:NSTextDidEndEditingNotification
object:self];
}
else {
[self unregisterDraggedTypes];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSTextDidBeginEditingNotification object:self];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSTextDidEndEditingNotification object:self];
}
}
- (BOOL)isFieldEditor { return YES; }
- (BOOL)dragChangedText { return _dragChangedText; }
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender {
_dragChangedText = NO;
return [sender draggingSource] == [self delegate] ? NSDragOperationNone : NSDragOperationCopy;
}
- (void)concludeDragOperation:(id <NSDraggingInfo>)sender {
[[self window] makeFirstResponder:nil];
_dragChangedText = NO;
}
- (BOOL)setStringFromDragOperation:(NSString *)aString
{
if ([[self string] isEqualToString:aString])
return NO;
[self setString:aString];
_dragChangedText = YES;
return YES;
}
- (BOOL)performDragOperation:(id < NSDraggingInfo >)sender
{
NSPasteboard *pboard = [sender draggingPasteboard];
NSString *type = [pboard availableTypeFromArray:__TLMAddressDragTypes()];
BOOL rv = NO;
if ([type isEqualToString:NSURLPboardType]) {
rv = [self setStringFromDragOperation:[[NSURL URLFromPasteboard:pboard] absoluteString]];
}
else if ([type isEqualToString:(id)kUTTypeURL]) {
rv = [self setStringFromDragOperation:[pboard stringForType:type]];
}
else if ([type isEqualToString:NSStringPboardType] && [NSURL URLWithString:[pboard stringForType:type]]) {
rv = [self setStringFromDragOperation:[pboard stringForType:type]];
}
return rv;
}
- (BOOL)prepareForDragOperation:(id < NSDraggingInfo >)sender { return YES; }
#pragma mark Completion methods
static inline BOOL completionWindowIsVisibleForTextView(NSTextView *textView)
{
BDSKTextViewCompletionController *controller = [BDSKTextViewCompletionController sharedController];
return ([[controller completionWindow] isVisible] && [[controller currentTextView] isEqual:textView]);
}
static inline BOOL forwardSelectorForCompletionInTextView(SEL selector, NSTextView *textView)
{
if(completionWindowIsVisibleForTextView(textView)){
[[BDSKTextViewCompletionController sharedController] performSelector:selector withObject:nil];
return YES;
}
return NO;
}
- (void)doAutoCompleteIfPossible {
if (completionWindowIsVisibleForTextView(self) == NO && _isEditing) {
if ([[self delegate] respondsToSelector:@selector(textViewShouldAutoComplete:)] &&
[(id <BDSKFieldEditorDelegate>)[self delegate] textViewShouldAutoComplete:self])
[self complete:self]; // NB: the self argument is critical here (see comment in complete:)
}
}
// insertText: and deleteBackward: affect the text content, so we send to super first, then autocomplete unconditionally since the completion controller needs to see the changes
- (void)insertText:(id)insertString {
[super insertText:insertString];
[self doAutoCompleteIfPossible];
// passing a nil argument to the completion controller's insertText: is safe, and we can ensure the completion window is visible this way
forwardSelectorForCompletionInTextView(_cmd, self);
}
- (void)deleteBackward:(id)sender {
[super deleteBackward:(id)sender];
// deleting a spelling error should also show the completions again
[self doAutoCompleteIfPossible];
forwardSelectorForCompletionInTextView(_cmd, self);
}
// moveLeft and moveRight should happen regardless of completion, or you can't navigate the line with arrow keys
- (void)moveLeft:(id)sender {
forwardSelectorForCompletionInTextView(_cmd, self);
[super moveLeft:sender];
}
- (void)moveRight:(id)sender {
forwardSelectorForCompletionInTextView(_cmd, self);
[super moveRight:sender];
}
// the following movement methods are conditional based on whether the autocomplete window is visible
- (void)moveUp:(id)sender {
if(forwardSelectorForCompletionInTextView(_cmd, self) == NO)
[super moveUp:sender];
}
- (void)moveDown:(id)sender {
if(forwardSelectorForCompletionInTextView(_cmd, self) == NO)
[super moveDown:sender];
}
- (void)insertTab:(id)sender {
if(forwardSelectorForCompletionInTextView(_cmd, self) == NO)
[super insertTab:sender];
}
- (void)insertNewline:(id)sender {
if(forwardSelectorForCompletionInTextView(_cmd, self) == NO)
[super insertNewline:sender];
}
- (NSRange)rangeForUserCompletion {
// @@ check this if we have problems inserting accented characters; super's implementation can mess that up
NSParameterAssert([self markedRange].length == 0);
NSRange charRange = [super rangeForUserCompletion];
if ([[self delegate] respondsToSelector:@selector(textView:rangeForUserCompletion:)])
return [(id <BDSKFieldEditorDelegate>)[self delegate] textView:self rangeForUserCompletion:charRange];
return charRange;
}
#pragma mark Auto-completion methods
- (NSArray *)completionsForPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger *)idx;
{
id delegate = [self delegate];
SEL delegateSEL = @selector(control:textView:completions:forPartialWordRange:indexOfSelectedItem:);
NSParameterAssert(delegate == nil || [delegate isKindOfClass:[NSControl class]]); // typically the NSForm
NSArray *completions = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
if([delegate respondsToSelector:delegateSEL])
completions = [delegate control:delegate textView:self completions:nil forPartialWordRange:charRange indexOfSelectedItem:idx];
else if([[[self window] delegate] respondsToSelector:delegateSEL])
completions = [(id)[[self window] delegate] control:delegate textView:self completions:nil forPartialWordRange:charRange indexOfSelectedItem:idx];
#pragma clang diagnostic pop
// Default is to call -[NSSpellChecker completionsForPartialWordRange:inString:language:inSpellDocumentWithTag:], but this apparently sends a DO message to CocoAspell (in a separate process), and we block the main runloop until it returns a long time later. Lacking a way to determine whether the system speller (which works fine) or CocoAspell is in use, we'll just return our own completions.
return completions;
}
- (void)complete:(id)sender;
{
// forward this method so the controller can handle cancellation and undo
if(forwardSelectorForCompletionInTextView(_cmd, self))
return;
NSRange selRange = [self rangeForUserCompletion];
NSString *string = [self string];
if(selRange.location == NSNotFound || [string isEqualToString:@""] || selRange.length == 0)
return;
// make sure to initialize this
NSInteger idx = 0;
NSArray *completions = [self completionsForPartialWordRange:selRange indexOfSelectedItem:&idx];
if(sender == self) // auto-complete, don't select an item
idx = -1;
[[BDSKTextViewCompletionController sharedController] displayCompletions:completions indexOfSelectedItem:idx forPartialWordRange:selRange originalString:[string substringWithRange:selRange] atPoint:[self locationForCompletionWindow] forTextView:self];
}
- (NSRange)selectionRangeForProposedRange:(NSRange)proposedSelRange granularity:(NSSelectionGranularity)granularity {
if(completionWindowIsVisibleForTextView(self))
[[BDSKTextViewCompletionController sharedController] endDisplayNoComplete];
return [super selectionRangeForProposedRange:proposedSelRange granularity:granularity];
}
- (BOOL)becomeFirstResponder {
if(completionWindowIsVisibleForTextView(self))
[[BDSKTextViewCompletionController sharedController] endDisplayNoComplete];
return [super becomeFirstResponder];
}
- (BOOL)resignFirstResponder {
if(completionWindowIsVisibleForTextView(self))
[[BDSKTextViewCompletionController sharedController] endDisplayNoComplete];
return [super resignFirstResponder];
}
@end
@implementation TLMAddressTextField
- (void)setProgressValue:(double)val
{
[[self cell] setProgressValue:val];
[self setNeedsDisplay:YES];
}
- (double)progressValue { return [[self cell] progressValue]; }
- (void)setMaximumProgressValue:(double)val { [[self cell] setMaximumProgressValue:val]; }
- (double)maximumProgressValue { return [[self cell] maximumProgressValue]; }
- (void)setMinimumProgressValue:(double)val { [[self cell] setMinimumProgressValue:val]; }
- (double)minimumProgressValue { return [[self cell] minimumProgressValue]; }
- (void)incrementProgressBy:(double)value;
{
[[self cell] incrementProgressBy:value];
[self setNeedsDisplay:YES];
}
/*
I tried NSTrackingArea, but it only works on the fringes of the icon, or if you enter the
icon area from inside the cell. Entering from the bottom, left, or top of the icon did
not work. Since this works and is a single line of code instead of multiple overrides
and an ivar to get something partially functional...I say NSTrackingArea officially sucks.
*/
- (void)resetCursorRects
{
[self addCursorRect:[[self cell] iconRectForBounds:[self bounds]] cursor:[NSCursor arrowCursor]];
}
- (void)viewWillMoveToWindow:(NSWindow *)newWindow
{
[super viewWillMoveToWindow:newWindow];
if (newWindow) {
[self registerForDraggedTypes:__TLMAddressDragTypes()];
}
else {
[self unregisterDraggedTypes];
}
}
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender {
_dragChangedText = NO;
return [sender draggingSource] == self ? NSDragOperationNone : NSDragOperationCopy;
}
- (void)concludeDragOperation:(id <NSDraggingInfo>)sender {
if ([[self window] makeFirstResponder:nil])
[self sendAction:[self action] to:[self target]];
_dragChangedText = NO;
}
- (BOOL)setStringFromDragOperation:(NSString *)aString
{
if ([[self stringValue] isEqualToString:aString])
return NO;
[self setStringValue:aString];
_dragChangedText = YES;
return YES;
}
- (BOOL)performDragOperation:(id < NSDraggingInfo >)sender
{
NSPasteboard *pboard = [sender draggingPasteboard];
NSString *type = [pboard availableTypeFromArray:__TLMAddressDragTypes()];
BOOL rv = NO;
if ([type isEqualToString:NSURLPboardType]) {
rv = [self setStringFromDragOperation:[[NSURL URLFromPasteboard:pboard] absoluteString]];
}
else if ([type isEqualToString:(id)kUTTypeURL]) {
rv = [self setStringFromDragOperation:[pboard stringForType:type]];
}
else if ([type isEqualToString:NSStringPboardType]) {
rv = [self setStringFromDragOperation:[pboard stringForType:type]];
}
return rv;
}
- (BOOL)prepareForDragOperation:(id < NSDraggingInfo >)sender { return YES; }
- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)flag { return NSDragOperationCopy; }
- (void)textDidChange:(NSNotification *)notification
{
[super textDidChange:notification];
_dragChangedText = YES;
}
- (BOOL)becomeFirstResponder
{
/*
Don't become first responder on a mouse down unless the user clicks inside the text area,
or else the field editor ends up selecting all text. This messes up the progress bar
drawing, and irritates me since clicking a button cell shouldn't affect selection in
the textfield. In fact, it might be better if clicking the button to reload/cancel
would deselect text.
Note that mouseDown: is implemented for the same purpose; it looks like there are a
couple of different paths on which the field editor will select all.
*/
NSEvent *evt = [NSApp currentEvent];
if ([evt type] == NSLeftMouseDown || [evt type] == NSRightMouseDown) {
NSPoint mouseLoc = [self convertPoint:[evt locationInWindow] fromView:nil];
if (NSMouseInRect(mouseLoc, [[self cell] textRectForBounds:[self bounds]], [self isFlipped]) == NO)
return NO;
}
return [super becomeFirstResponder];
}
- (void)mouseDown:(NSEvent *)evt
{
if ([evt type] == NSLeftMouseDown || [evt type] == NSRightMouseDown) {
NSPoint mouseLoc = [self convertPoint:[evt locationInWindow] fromView:nil];
if (NSMouseInRect(mouseLoc, [[self cell] textRectForBounds:[self bounds]], [self isFlipped]))
[super mouseDown:evt];
else
[[self cell] trackMouse:evt inRect:[self bounds] ofView:self untilMouseUp:YES];
}
else {
[super mouseDown:evt];
}
}
/*
The _dragChangedText business is to avoid sending spurious action messages
when text hasn't actually changed due to drag-and-drop or direct editing.
By default, it sends it every time you click on the icon, which is a bit
much if the action does anything nontrivial.
*/
- (void)textDidEndEditing:(NSNotification *)notification
{
TLMMirrorFieldEditor *editor = [notification object];
if ([editor dragChangedText] || _dragChangedText)
[super textDidEndEditing:notification];
}
- (NSRange)textView:(NSTextView *)textView rangeForUserCompletion:(NSRange)charRange {
if (textView == [self currentEditor] && [[self delegate] respondsToSelector:@selector(control:textView:rangeForUserCompletion:)])
return [(id)[self delegate] control:self textView:textView rangeForUserCompletion:charRange];
return charRange;
}
- (BOOL)textViewShouldAutoComplete:(NSTextView *)textView {
if (textView == [self currentEditor] && [[self delegate] respondsToSelector:@selector(control:textViewShouldAutoComplete:)])
return [(id)[self delegate] control:self textViewShouldAutoComplete:textView];
return NO;
}
- (void)setButtonImage:(NSImage *)image { [[self cell] setButtonImage:image]; }
- (void)setButtonAction:(SEL)action { [[self cell] setButtonAction:action]; }
- (void)setButtonTarget:(id)target { [[self cell] setButtonTarget:target]; }
@end