]> git.saurik.com Git - wxWidgets.git/blob - src/osx/cocoa/textctrl.mm
Define SPI_GETCARETWIDTH ourselves if it's not defined.
[wxWidgets.git] / src / osx / cocoa / textctrl.mm
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/cocoa/textctrl.mm
3 // Purpose: wxTextCtrl
4 // Author: Stefan Csomor
5 // Modified by: Ryan Norton (MLTE GetLineLength and GetLineText)
6 // Created: 1998-01-01
7 // RCS-ID: $Id$
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/wxprec.h"
13
14 #if wxUSE_TEXTCTRL
15
16 #include "wx/textctrl.h"
17
18 #ifndef WX_PRECOMP
19 #include "wx/intl.h"
20 #include "wx/app.h"
21 #include "wx/utils.h"
22 #include "wx/dc.h"
23 #include "wx/button.h"
24 #include "wx/menu.h"
25 #include "wx/settings.h"
26 #include "wx/msgdlg.h"
27 #include "wx/toplevel.h"
28 #endif
29
30 #ifdef __DARWIN__
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #else
34 #include <stat.h>
35 #endif
36
37 #if wxUSE_STD_IOSTREAM
38 #if wxUSE_IOSTREAMH
39 #include <fstream.h>
40 #else
41 #include <fstream>
42 #endif
43 #endif
44
45 #include "wx/filefn.h"
46 #include "wx/sysopt.h"
47 #include "wx/thread.h"
48 #include "wx/textcompleter.h"
49
50 #include "wx/osx/private.h"
51 #include "wx/osx/cocoa/private/textimpl.h"
52
53 @interface NSView(EditableView)
54 - (BOOL)isEditable;
55 - (void)setEditable:(BOOL)flag;
56 - (BOOL)isSelectable;
57 - (void)setSelectable:(BOOL)flag;
58 @end
59
60 // An object of this class is created before the text is modified
61 // programmatically and destroyed as soon as this is done. It does several
62 // things, like ensuring that the control is editable to allow setting its text
63 // at all and eating any unwanted focus loss events from textDidEndEditing:
64 // which don't really correspond to focus change.
65 class wxMacEditHelper
66 {
67 public :
68 wxMacEditHelper( NSView* textView )
69 {
70 m_viewPreviouslyEdited = ms_viewCurrentlyEdited;
71 ms_viewCurrentlyEdited =
72 m_textView = textView;
73 m_formerEditable = YES;
74 if ( textView )
75 {
76 m_formerEditable = [textView isEditable];
77 m_formerSelectable = [textView isSelectable];
78 [textView setEditable:YES];
79 }
80 }
81
82 ~wxMacEditHelper()
83 {
84 if ( m_textView )
85 {
86 [m_textView setEditable:m_formerEditable];
87 [m_textView setSelectable:m_formerSelectable];
88 }
89
90 ms_viewCurrentlyEdited = m_viewPreviouslyEdited;
91 }
92
93 // Returns the last view we were instantiated for or NULL.
94 static NSView *GetCurrentlyEditedView() { return ms_viewCurrentlyEdited; }
95
96 protected :
97 BOOL m_formerEditable ;
98 BOOL m_formerSelectable;
99 NSView* m_textView;
100
101 // The original value of ms_viewCurrentlyEdited when this object was
102 // created.
103 NSView* m_viewPreviouslyEdited;
104
105 static NSView* ms_viewCurrentlyEdited;
106 } ;
107
108 NSView* wxMacEditHelper::ms_viewCurrentlyEdited = nil;
109
110 // a minimal NSFormatter that just avoids getting too long entries
111 @interface wxMaximumLengthFormatter : NSFormatter
112 {
113 int maxLength;
114 }
115
116 @end
117
118 @implementation wxMaximumLengthFormatter
119
120 - (id)init
121 {
122 self = [super init];
123 maxLength = 0;
124 return self;
125 }
126
127 - (void) setMaxLength:(int) maxlen
128 {
129 maxLength = maxlen;
130 }
131
132 - (NSString *)stringForObjectValue:(id)anObject
133 {
134 if(![anObject isKindOfClass:[NSString class]])
135 return nil;
136 return [NSString stringWithString:anObject];
137 }
138
139 - (BOOL)getObjectValue:(id *)obj forString:(NSString *)string errorDescription:(NSString **)error
140 {
141 *obj = [NSString stringWithString:string];
142 return YES;
143 }
144
145 - (BOOL)isPartialStringValid:(NSString **)partialStringPtr proposedSelectedRange:(NSRangePointer)proposedSelRangePtr
146 originalString:(NSString *)origString originalSelectedRange:(NSRange)origSelRange errorDescription:(NSString **)error
147 {
148 int len = [*partialStringPtr length];
149 if ( maxLength > 0 && len > maxLength )
150 {
151 // TODO wxEVT_COMMAND_TEXT_MAXLEN
152 return NO;
153 }
154 return YES;
155 }
156
157 @end
158
159 @implementation wxNSSecureTextField
160
161 + (void)initialize
162 {
163 static BOOL initialized = NO;
164 if (!initialized)
165 {
166 initialized = YES;
167 wxOSXCocoaClassAddWXMethods( self );
168 }
169 }
170
171 - (void)controlTextDidChange:(NSNotification *)aNotification
172 {
173 wxUnusedVar(aNotification);
174 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
175 if ( impl )
176 impl->controlTextDidChange();
177 }
178
179 - (void)controlTextDidEndEditing:(NSNotification *)aNotification
180 {
181 wxUnusedVar(aNotification);
182 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
183 if ( impl )
184 {
185 impl->DoNotifyFocusEvent( false, NULL );
186 }
187 }
188
189 - (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector
190 {
191 wxUnusedVar(textView);
192
193 BOOL handled = NO;
194
195 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( control );
196 if ( impl )
197 {
198 wxWindow* wxpeer = (wxWindow*) impl->GetWXPeer();
199 if ( wxpeer )
200 {
201 if (commandSelector == @selector(insertNewline:))
202 {
203 wxTopLevelWindow *tlw = wxDynamicCast(wxGetTopLevelParent(wxpeer), wxTopLevelWindow);
204 if ( tlw && tlw->GetDefaultItem() )
205 {
206 wxButton *def = wxDynamicCast(tlw->GetDefaultItem(), wxButton);
207 if ( def && def->IsEnabled() )
208 {
209 wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, def->GetId() );
210 event.SetEventObject(def);
211 def->Command(event);
212 handled = YES;
213 }
214 }
215 }
216 }
217 }
218
219 return handled;
220 }
221
222 @end
223
224 @interface wxNSTextScrollView : NSScrollView
225 {
226 }
227 @end
228
229 @implementation wxNSTextScrollView
230
231 + (void)initialize
232 {
233 static BOOL initialized = NO;
234 if (!initialized)
235 {
236 initialized = YES;
237 wxOSXCocoaClassAddWXMethods( self );
238 }
239 }
240
241 @end
242
243 @implementation wxNSTextFieldEditor
244
245 - (void) keyDown:(NSEvent*) event
246 {
247 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
248 lastKeyDownEvent = event;
249 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
250 [super keyDown:event];
251 lastKeyDownEvent = nil;
252 }
253
254 - (void) keyUp:(NSEvent*) event
255 {
256 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
257 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
258 [super keyUp:event];
259 }
260
261 - (void) flagsChanged:(NSEvent*) event
262 {
263 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
264 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
265 [super flagsChanged:event];
266 }
267
268 - (BOOL) performKeyEquivalent:(NSEvent*) event
269 {
270 BOOL retval = [super performKeyEquivalent:event];
271 return retval;
272 }
273
274 - (void) insertText:(id) str
275 {
276 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
277 if ( impl == NULL || lastKeyDownEvent==nil || !impl->DoHandleCharEvent(lastKeyDownEvent, str) )
278 {
279 [super insertText:str];
280 }
281 }
282
283 @end
284
285 @implementation wxNSTextView
286
287 + (void)initialize
288 {
289 static BOOL initialized = NO;
290 if (!initialized)
291 {
292 initialized = YES;
293 wxOSXCocoaClassAddWXMethods( self );
294 }
295 }
296
297 - (void)textDidChange:(NSNotification *)aNotification
298 {
299 wxUnusedVar(aNotification);
300 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
301 if ( impl )
302 impl->controlTextDidChange();
303 }
304
305 - (void) setEnabled:(BOOL) flag
306 {
307 // from Technical Q&A QA1461
308 if (flag) {
309 [self setTextColor: [NSColor controlTextColor]];
310
311 } else {
312 [self setTextColor: [NSColor disabledControlTextColor]];
313 }
314
315 [self setSelectable: flag];
316 [self setEditable: flag];
317 }
318
319 - (BOOL) isEnabled
320 {
321 return [self isEditable];
322 }
323
324 - (void)textDidEndEditing:(NSNotification *)aNotification
325 {
326 wxUnusedVar(aNotification);
327
328 if ( self == wxMacEditHelper::GetCurrentlyEditedView() )
329 {
330 // This notification is generated as the result of calling our own
331 // wxTextCtrl method (e.g. WriteText()) and doesn't correspond to any
332 // real focus loss event so skip generating it.
333 return;
334 }
335
336 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
337 if ( impl )
338 {
339 impl->DoNotifyFocusEvent( false, NULL );
340 }
341 }
342
343 @end
344
345 @implementation wxNSTextField
346
347 + (void)initialize
348 {
349 static BOOL initialized = NO;
350 if (!initialized)
351 {
352 initialized = YES;
353 wxOSXCocoaClassAddWXMethods( self );
354 }
355 }
356
357 - (id) initWithFrame:(NSRect) frame
358 {
359 self = [super initWithFrame:frame];
360 fieldEditor = nil;
361 return self;
362 }
363
364 - (void) dealloc
365 {
366 [fieldEditor release];
367 [super dealloc];
368 }
369
370 - (void) setFieldEditor:(wxNSTextFieldEditor*) editor
371 {
372 if ( editor != fieldEditor )
373 {
374 [editor retain];
375 [fieldEditor release];
376 fieldEditor = editor;
377 }
378 }
379
380 - (wxNSTextFieldEditor*) fieldEditor
381 {
382 return fieldEditor;
383 }
384
385 - (void) setEnabled:(BOOL) flag
386 {
387 [super setEnabled: flag];
388
389 if (![self drawsBackground]) {
390 // Static text is drawn incorrectly when disabled.
391 // For an explanation, see
392 // http://www.cocoabuilder.com/archive/message/cocoa/2006/7/21/168028
393 if (flag) {
394 [self setTextColor: [NSColor controlTextColor]];
395 } else {
396 [self setTextColor: [NSColor secondarySelectedControlColor]];
397 }
398 }
399 }
400
401 - (void)controlTextDidChange:(NSNotification *)aNotification
402 {
403 wxUnusedVar(aNotification);
404 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
405 if ( impl )
406 impl->controlTextDidChange();
407 }
408
409 - (NSArray *)control:(NSControl *)control textView:(NSTextView *)textView completions:(NSArray *)words
410 forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger*)index
411 {
412 NSMutableArray* matches = NULL;
413
414 wxTextWidgetImpl* impl = (wxNSTextFieldControl * ) wxWidgetImpl::FindFromWXWidget( self );
415 wxTextEntry * const entry = impl->GetTextEntry();
416 wxTextCompleter * const completer = entry->OSXGetCompleter();
417 if ( completer )
418 {
419 const wxString prefix = entry->GetValue();
420 if ( completer->Start(prefix) )
421 {
422 const wxString
423 wordStart = wxCFStringRef::AsString(
424 [[textView string] substringWithRange:charRange]
425 );
426
427 matches = [NSMutableArray array];
428 for ( ;; )
429 {
430 const wxString s = completer->GetNext();
431 if ( s.empty() )
432 break;
433
434 // Normally the completer should return only the strings
435 // starting with the prefix, but there could be exceptions
436 // and, for compatibility with MSW which simply ignores all
437 // entries that don't match the current text control contents,
438 // we ignore them as well. Besides, our own wxTextCompleterFixed
439 // doesn't respect this rule and, moreover, we need to extract
440 // just the rest of the string anyhow.
441 wxString completion;
442 if ( s.StartsWith(prefix, &completion) )
443 {
444 // We discarded the entire prefix above but actually we
445 // should include the part of it that consists of the
446 // beginning of the current word, otherwise it would be
447 // lost when completion is accepted as OS X supposes that
448 // our matches do start with the "partial word range"
449 // passed to us.
450 const wxCFStringRef fullWord(wordStart + completion);
451 [matches addObject: fullWord.AsNSString()];
452 }
453 }
454 }
455 }
456
457 return matches;
458 }
459
460 - (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector
461 {
462 wxUnusedVar(textView);
463 wxUnusedVar(control);
464
465 BOOL handled = NO;
466
467 // send back key events wx' common code knows how to handle
468
469 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
470 if ( impl )
471 {
472 wxWindow* wxpeer = (wxWindow*) impl->GetWXPeer();
473 if ( wxpeer )
474 {
475 if (commandSelector == @selector(insertNewline:))
476 {
477 [textView insertNewlineIgnoringFieldEditor:self];
478 handled = YES;
479 }
480 else if ( commandSelector == @selector(insertTab:))
481 {
482 [textView insertTabIgnoringFieldEditor:self];
483 handled = YES;
484 }
485 else if ( commandSelector == @selector(insertBacktab:))
486 {
487 [textView insertTabIgnoringFieldEditor:self];
488 handled = YES;
489 }
490 }
491 }
492
493 return handled;
494 }
495
496 - (void)controlTextDidEndEditing:(NSNotification *)aNotification
497 {
498 wxUnusedVar(aNotification);
499 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
500 if ( impl )
501 {
502 impl->DoNotifyFocusEvent( false, NULL );
503 }
504 }
505 @end
506
507 // wxNSTextViewControl
508
509 wxNSTextViewControl::wxNSTextViewControl( wxTextCtrl *wxPeer, WXWidget w )
510 : wxWidgetCocoaImpl(wxPeer, w),
511 wxTextWidgetImpl(wxPeer)
512 {
513 wxNSTextScrollView* sv = (wxNSTextScrollView*) w;
514 m_scrollView = sv;
515
516 [m_scrollView setHasVerticalScroller:YES];
517 [m_scrollView setHasHorizontalScroller:NO];
518 [m_scrollView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
519 NSSize contentSize = [m_scrollView contentSize];
520
521 wxNSTextView* tv = [[wxNSTextView alloc] initWithFrame: NSMakeRect(0, 0,
522 contentSize.width, contentSize.height)];
523 m_textView = tv;
524 [tv setVerticallyResizable:YES];
525 [tv setHorizontallyResizable:NO];
526 [tv setAutoresizingMask:NSViewWidthSizable];
527
528 [m_scrollView setDocumentView: tv];
529
530 [tv setDelegate: tv];
531
532 InstallEventHandler(tv);
533 }
534
535 wxNSTextViewControl::~wxNSTextViewControl()
536 {
537 if (m_textView)
538 [m_textView setDelegate: nil];
539 }
540
541 bool wxNSTextViewControl::CanFocus() const
542 {
543 // since this doesn't work (return false), we hardcode
544 // if (m_textView)
545 // return [m_textView canBecomeKeyView];
546 return true;
547 }
548
549 wxString wxNSTextViewControl::GetStringValue() const
550 {
551 if (m_textView)
552 {
553 wxString result = wxCFStringRef::AsString([m_textView string], m_wxPeer->GetFont().GetEncoding());
554 wxMacConvertNewlines13To10( &result ) ;
555 return result;
556 }
557 return wxEmptyString;
558 }
559 void wxNSTextViewControl::SetStringValue( const wxString &str)
560 {
561 wxString st = str;
562 wxMacConvertNewlines10To13( &st );
563 wxMacEditHelper helper(m_textView);
564
565 if (m_textView)
566 [m_textView setString: wxCFStringRef( st , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
567 }
568
569 void wxNSTextViewControl::Copy()
570 {
571 if (m_textView)
572 [m_textView copy:nil];
573
574 }
575
576 void wxNSTextViewControl::Cut()
577 {
578 if (m_textView)
579 [m_textView cut:nil];
580 }
581
582 void wxNSTextViewControl::Paste()
583 {
584 if (m_textView)
585 [m_textView paste:nil];
586 }
587
588 bool wxNSTextViewControl::CanPaste() const
589 {
590 return true;
591 }
592
593 void wxNSTextViewControl::SetEditable(bool editable)
594 {
595 if (m_textView)
596 [m_textView setEditable: editable];
597 }
598
599 void wxNSTextViewControl::GetSelection( long* from, long* to) const
600 {
601 if (m_textView)
602 {
603 NSRange range = [m_textView selectedRange];
604 *from = range.location;
605 *to = range.location + range.length;
606 }
607 }
608
609 void wxNSTextViewControl::SetSelection( long from , long to )
610 {
611 long textLength = [[m_textView string] length];
612 if ((from == -1) && (to == -1))
613 {
614 from = 0 ;
615 to = textLength ;
616 }
617 else
618 {
619 from = wxMin(textLength,wxMax(from,0)) ;
620 if ( to == -1 )
621 to = textLength;
622 else
623 to = wxMax(0,wxMin(textLength,to)) ;
624 }
625
626 NSRange selrange = NSMakeRange(from, to-from);
627 [m_textView setSelectedRange:selrange];
628 [m_textView scrollRangeToVisible:selrange];
629 }
630
631 void wxNSTextViewControl::WriteText(const wxString& str)
632 {
633 wxString st = str;
634 wxMacConvertNewlines10To13( &st );
635 wxMacEditHelper helper(m_textView);
636 NSEvent* formerEvent = m_lastKeyDownEvent;
637 m_lastKeyDownEvent = nil;
638 [m_textView insertText:wxCFStringRef( st , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
639 m_lastKeyDownEvent = formerEvent;
640 }
641
642 void wxNSTextViewControl::SetFont( const wxFont & font , const wxColour& WXUNUSED(foreground) , long WXUNUSED(windowStyle), bool WXUNUSED(ignoreBlack) )
643 {
644 if ([m_textView respondsToSelector:@selector(setFont:)])
645 [m_textView setFont: font.OSXGetNSFont()];
646 }
647
648 bool wxNSTextViewControl::GetStyle(long position, wxTextAttr& style)
649 {
650 if (m_textView && position >=0)
651 {
652 NSFont* font = NULL;
653 NSColor* bgcolor = NULL;
654 NSColor* fgcolor = NULL;
655 // NOTE: It appears that other platforms accept GetStyle with the position == length
656 // but that NSTextStorage does not accept length as a valid position.
657 // Therefore we return the default control style in that case.
658 if (position < (long) [[m_textView string] length])
659 {
660 NSTextStorage* storage = [m_textView textStorage];
661 font = [[storage attribute:NSFontAttributeName atIndex:position effectiveRange:NULL] autorelease];
662 bgcolor = [[storage attribute:NSBackgroundColorAttributeName atIndex:position effectiveRange:NULL] autorelease];
663 fgcolor = [[storage attribute:NSForegroundColorAttributeName atIndex:position effectiveRange:NULL] autorelease];
664 }
665 else
666 {
667 NSDictionary* attrs = [m_textView typingAttributes];
668 font = [[attrs objectForKey:NSFontAttributeName] autorelease];
669 bgcolor = [[attrs objectForKey:NSBackgroundColorAttributeName] autorelease];
670 fgcolor = [[attrs objectForKey:NSForegroundColorAttributeName] autorelease];
671 }
672
673 if (font)
674 style.SetFont(wxFont(font));
675
676 if (bgcolor)
677 style.SetBackgroundColour(wxColour(bgcolor));
678
679 if (fgcolor)
680 style.SetTextColour(wxColour(fgcolor));
681 return true;
682 }
683
684 return false;
685 }
686
687 void wxNSTextViewControl::SetStyle(long start,
688 long end,
689 const wxTextAttr& style)
690 {
691 if ( !m_textView )
692 return;
693
694 if ( start == -1 && end == -1 )
695 {
696 NSMutableDictionary* const
697 attrs = [NSMutableDictionary dictionaryWithCapacity:3];
698 if ( style.HasFont() )
699 [attrs setValue:style.GetFont().OSXGetNSFont() forKey:NSFontAttributeName];
700 if ( style.HasBackgroundColour() )
701 [attrs setValue:style.GetBackgroundColour().OSXGetNSColor() forKey:NSBackgroundColorAttributeName];
702 if ( style.HasTextColour() )
703 [attrs setValue:style.GetTextColour().OSXGetNSColor() forKey:NSForegroundColorAttributeName];
704
705 [m_textView setTypingAttributes:attrs];
706 }
707 else // Set the attributes just for this range.
708 {
709 NSRange range = NSMakeRange(start, end-start);
710
711 NSTextStorage* storage = [m_textView textStorage];
712 if ( style.HasFont() )
713 [storage addAttribute:NSFontAttributeName value:style.GetFont().OSXGetNSFont() range:range];
714
715 if ( style.HasBackgroundColour() )
716 [storage addAttribute:NSBackgroundColorAttributeName value:style.GetBackgroundColour().OSXGetNSColor() range:range];
717
718 if ( style.HasTextColour() )
719 [storage addAttribute:NSForegroundColorAttributeName value:style.GetTextColour().OSXGetNSColor() range:range];
720 }
721 }
722
723 void wxNSTextViewControl::CheckSpelling(bool check)
724 {
725 if (m_textView)
726 [m_textView setContinuousSpellCheckingEnabled: check];
727 }
728
729 wxSize wxNSTextViewControl::GetBestSize() const
730 {
731 if (m_textView && [m_textView layoutManager])
732 {
733 NSRect rect = [[m_textView layoutManager] usedRectForTextContainer: [m_textView textContainer]];
734 return wxSize((int)(rect.size.width + [m_textView textContainerInset].width),
735 (int)(rect.size.height + [m_textView textContainerInset].height));
736 }
737 return wxSize(0,0);
738 }
739
740 // wxNSTextFieldControl
741
742 wxNSTextFieldControl::wxNSTextFieldControl( wxTextCtrl *text, WXWidget w )
743 : wxWidgetCocoaImpl(text, w),
744 wxTextWidgetImpl(text)
745 {
746 Init(w);
747 }
748
749 wxNSTextFieldControl::wxNSTextFieldControl(wxWindow *wxPeer,
750 wxTextEntry *entry,
751 WXWidget w)
752 : wxWidgetCocoaImpl(wxPeer, w),
753 wxTextWidgetImpl(entry)
754 {
755 Init(w);
756 }
757
758 void wxNSTextFieldControl::Init(WXWidget w)
759 {
760 NSTextField wxOSX_10_6_AND_LATER(<NSTextFieldDelegate>) *tf = (NSTextField wxOSX_10_6_AND_LATER(<NSTextFieldDelegate>)*) w;
761 m_textField = tf;
762 [m_textField setDelegate: tf];
763 m_selStart = m_selEnd = 0;
764 m_hasEditor = [w isKindOfClass:[NSTextField class]];
765 }
766
767 wxNSTextFieldControl::~wxNSTextFieldControl()
768 {
769 if (m_textField)
770 [m_textField setDelegate: nil];
771 }
772
773 wxString wxNSTextFieldControl::GetStringValue() const
774 {
775 return wxCFStringRef::AsString([m_textField stringValue], m_wxPeer->GetFont().GetEncoding());
776 }
777
778 void wxNSTextFieldControl::SetStringValue( const wxString &str)
779 {
780 wxMacEditHelper helper(m_textField);
781 [m_textField setStringValue: wxCFStringRef( str , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
782 }
783
784 void wxNSTextFieldControl::SetMaxLength(unsigned long len)
785 {
786 wxMaximumLengthFormatter* formatter = [[[wxMaximumLengthFormatter alloc] init] autorelease];
787 [formatter setMaxLength:len];
788 [m_textField setFormatter:formatter];
789 }
790
791 void wxNSTextFieldControl::Copy()
792 {
793 NSText* editor = [m_textField currentEditor];
794 if ( editor )
795 {
796 [editor copy:nil];
797 }
798 }
799
800 void wxNSTextFieldControl::Cut()
801 {
802 NSText* editor = [m_textField currentEditor];
803 if ( editor )
804 {
805 [editor cut:nil];
806 }
807 }
808
809 void wxNSTextFieldControl::Paste()
810 {
811 NSText* editor = [m_textField currentEditor];
812 if ( editor )
813 {
814 [editor paste:nil];
815 }
816 }
817
818 bool wxNSTextFieldControl::CanPaste() const
819 {
820 return true;
821 }
822
823 void wxNSTextFieldControl::SetEditable(bool editable)
824 {
825 [m_textField setEditable:editable];
826 }
827
828 void wxNSTextFieldControl::GetSelection( long* from, long* to) const
829 {
830 NSText* editor = [m_textField currentEditor];
831 if ( editor )
832 {
833 NSRange range = [editor selectedRange];
834 *from = range.location;
835 *to = range.location + range.length;
836 }
837 else
838 {
839 *from = m_selStart;
840 *to = m_selEnd;
841 }
842 }
843
844 void wxNSTextFieldControl::SetSelection( long from , long to )
845 {
846 long textLength = [[m_textField stringValue] length];
847 if ((from == -1) && (to == -1))
848 {
849 from = 0 ;
850 to = textLength ;
851 }
852 else
853 {
854 from = wxMin(textLength,wxMax(from,0)) ;
855 if ( to == -1 )
856 to = textLength;
857 else
858 to = wxMax(0,wxMin(textLength,to)) ;
859 }
860
861 NSText* editor = [m_textField currentEditor];
862 if ( editor )
863 {
864 [editor setSelectedRange:NSMakeRange(from, to-from)];
865 }
866 else
867 {
868 m_selStart = from;
869 m_selEnd = to;
870 }
871 }
872
873 void wxNSTextFieldControl::WriteText(const wxString& str)
874 {
875 NSEvent* formerEvent = m_lastKeyDownEvent;
876 m_lastKeyDownEvent = nil;
877 NSText* editor = [m_textField currentEditor];
878 if ( editor )
879 {
880 wxMacEditHelper helper(m_textField);
881 BOOL hasUndo = [editor respondsToSelector:@selector(setAllowsUndo:)];
882 if ( hasUndo )
883 [(NSTextView*)editor setAllowsUndo:NO];
884 [editor insertText:wxCFStringRef( str , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
885 if ( hasUndo )
886 [(NSTextView*)editor setAllowsUndo:YES];
887 }
888 else
889 {
890 wxString val = GetStringValue() ;
891 long start , end ;
892 GetSelection( &start , &end ) ;
893 val.Remove( start , end - start ) ;
894 val.insert( start , str ) ;
895 SetStringValue( val ) ;
896 SetSelection( start + str.length() , start + str.length() ) ;
897 }
898 m_lastKeyDownEvent = formerEvent;
899 }
900
901 void wxNSTextFieldControl::controlAction(WXWidget WXUNUSED(slf),
902 void* WXUNUSED(_cmd), void *WXUNUSED(sender))
903 {
904 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
905 if ( wxpeer && (wxpeer->GetWindowStyle() & wxTE_PROCESS_ENTER) )
906 {
907 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, wxpeer->GetId());
908 event.SetEventObject( wxpeer );
909 event.SetString( GetTextEntry()->GetValue() );
910 wxpeer->HandleWindowEvent( event );
911 }
912 }
913
914 bool wxNSTextFieldControl::SetHint(const wxString& hint)
915 {
916 wxCFStringRef hintstring(hint);
917 [[m_textField cell] setPlaceholderString:hintstring.AsNSString()];
918 return true;
919 }
920
921 //
922 //
923 //
924
925 wxWidgetImplType* wxWidgetImpl::CreateTextControl( wxTextCtrl* wxpeer,
926 wxWindowMac* WXUNUSED(parent),
927 wxWindowID WXUNUSED(id),
928 const wxString& WXUNUSED(str),
929 const wxPoint& pos,
930 const wxSize& size,
931 long style,
932 long WXUNUSED(extraStyle))
933 {
934 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
935 wxWidgetCocoaImpl* c = NULL;
936
937 if ( style & wxTE_MULTILINE || style & wxTE_RICH || style & wxTE_RICH2 )
938 {
939 wxNSTextScrollView* v = nil;
940 v = [[wxNSTextScrollView alloc] initWithFrame:r];
941 c = new wxNSTextViewControl( wxpeer, v );
942 c->SetNeedsFocusRect( true );
943 }
944 else
945 {
946 NSTextField* v = nil;
947 if ( style & wxTE_PASSWORD )
948 v = [[wxNSSecureTextField alloc] initWithFrame:r];
949 else
950 v = [[wxNSTextField alloc] initWithFrame:r];
951
952 if ( style & wxTE_RIGHT)
953 {
954 [v setAlignment:NSRightTextAlignment];
955 }
956 else if ( style & wxTE_CENTRE)
957 {
958 [v setAlignment:NSCenterTextAlignment];
959 }
960
961 NSTextFieldCell* cell = [v cell];
962 [cell setScrollable:YES];
963 // TODO: Remove if we definitely are sure, it's not needed
964 // as setting scrolling to yes, should turn off any wrapping
965 // [cell setLineBreakMode:NSLineBreakByClipping];
966
967 c = new wxNSTextFieldControl( wxpeer, wxpeer, v );
968
969 if ( (style & wxNO_BORDER) || (style & wxSIMPLE_BORDER) )
970 {
971 // under 10.7 the textcontrol can draw its own focus
972 // even if no border is shown, on previous systems
973 // we have to emulate this
974 [v setBezeled:NO];
975 [v setBordered:NO];
976 if ( UMAGetSystemVersion() < 0x1070 )
977 c->SetNeedsFocusRect( true );
978 }
979 else
980 {
981 // use native border
982 c->SetNeedsFrame(false);
983 }
984 }
985
986 return c;
987 }
988
989
990 #endif // wxUSE_TEXTCTRL