1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/cocoa/textctrl.mm
4 // Author: Stefan Csomor
5 // Modified by: Ryan Norton (MLTE GetLineLength and GetLineText)
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
16 #include "wx/textctrl.h"
23 #include "wx/button.h"
25 #include "wx/settings.h"
26 #include "wx/msgdlg.h"
27 #include "wx/toplevel.h"
31 #include <sys/types.h>
37 #if wxUSE_STD_IOSTREAM
45 #include "wx/filefn.h"
46 #include "wx/sysopt.h"
47 #include "wx/thread.h"
48 #include "wx/textcompleter.h"
50 #include "wx/osx/private.h"
51 #include "wx/osx/cocoa/private/textimpl.h"
53 @interface NSView(EditableView)
55 - (void)setEditable:(BOOL)flag;
57 - (void)setSelectable:(BOOL)flag;
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.
68 wxMacEditHelper( NSView* textView )
70 m_viewPreviouslyEdited = ms_viewCurrentlyEdited;
71 ms_viewCurrentlyEdited =
72 m_textView = textView;
73 m_formerEditable = YES;
76 m_formerEditable = [textView isEditable];
77 m_formerSelectable = [textView isSelectable];
78 [textView setEditable:YES];
86 [m_textView setEditable:m_formerEditable];
87 [m_textView setSelectable:m_formerSelectable];
90 ms_viewCurrentlyEdited = m_viewPreviouslyEdited;
93 // Returns the last view we were instantiated for or NULL.
94 static NSView *GetCurrentlyEditedView() { return ms_viewCurrentlyEdited; }
97 BOOL m_formerEditable ;
98 BOOL m_formerSelectable;
101 // The original value of ms_viewCurrentlyEdited when this object was
103 NSView* m_viewPreviouslyEdited;
105 static NSView* ms_viewCurrentlyEdited;
108 NSView* wxMacEditHelper::ms_viewCurrentlyEdited = nil;
110 // a minimal NSFormatter that just avoids getting too long entries
111 @interface wxMaximumLengthFormatter : NSFormatter
118 @implementation wxMaximumLengthFormatter
127 - (void) setMaxLength:(int) maxlen
132 - (NSString *)stringForObjectValue:(id)anObject
134 if(![anObject isKindOfClass:[NSString class]])
136 return [NSString stringWithString:anObject];
139 - (BOOL)getObjectValue:(id *)obj forString:(NSString *)string errorDescription:(NSString **)error
141 *obj = [NSString stringWithString:string];
145 - (BOOL)isPartialStringValid:(NSString **)partialStringPtr proposedSelectedRange:(NSRangePointer)proposedSelRangePtr
146 originalString:(NSString *)origString originalSelectedRange:(NSRange)origSelRange errorDescription:(NSString **)error
148 int len = [*partialStringPtr length];
149 if ( maxLength > 0 && len > maxLength )
151 // TODO wxEVT_COMMAND_TEXT_MAXLEN
159 @implementation wxNSSecureTextField
163 static BOOL initialized = NO;
167 wxOSXCocoaClassAddWXMethods( self );
171 - (void)controlTextDidChange:(NSNotification *)aNotification
173 wxUnusedVar(aNotification);
174 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
176 impl->controlTextDidChange();
179 - (void)controlTextDidEndEditing:(NSNotification *)aNotification
181 wxUnusedVar(aNotification);
182 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
185 impl->DoNotifyFocusEvent( false, NULL );
191 @interface wxNSTextScrollView : NSScrollView
196 @implementation wxNSTextScrollView
200 static BOOL initialized = NO;
204 wxOSXCocoaClassAddWXMethods( self );
210 @implementation wxNSTextFieldEditor
212 - (void) keyDown:(NSEvent*) event
214 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
215 lastKeyDownEvent = event;
216 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
217 [super keyDown:event];
218 lastKeyDownEvent = nil;
221 - (void) keyUp:(NSEvent*) event
223 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
224 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
228 - (void) flagsChanged:(NSEvent*) event
230 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
231 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
232 [super flagsChanged:event];
235 - (BOOL) performKeyEquivalent:(NSEvent*) event
237 BOOL retval = [super performKeyEquivalent:event];
241 - (void) insertText:(id) str
243 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
244 if ( impl == NULL || lastKeyDownEvent==nil || !impl->DoHandleCharEvent(lastKeyDownEvent, str) )
246 [super insertText:str];
252 @implementation wxNSTextView
256 static BOOL initialized = NO;
260 wxOSXCocoaClassAddWXMethods( self );
264 - (void)textDidChange:(NSNotification *)aNotification
266 wxUnusedVar(aNotification);
267 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
269 impl->controlTextDidChange();
272 - (void) setEnabled:(BOOL) flag
274 // from Technical Q&A QA1461
276 [self setTextColor: [NSColor controlTextColor]];
279 [self setTextColor: [NSColor disabledControlTextColor]];
282 [self setSelectable: flag];
283 [self setEditable: flag];
288 return [self isEditable];
291 - (void)textDidEndEditing:(NSNotification *)aNotification
293 wxUnusedVar(aNotification);
295 if ( self == wxMacEditHelper::GetCurrentlyEditedView() )
297 // This notification is generated as the result of calling our own
298 // wxTextCtrl method (e.g. WriteText()) and doesn't correspond to any
299 // real focus loss event so skip generating it.
303 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
306 impl->DoNotifyFocusEvent( false, NULL );
312 @implementation wxNSTextField
316 static BOOL initialized = NO;
320 wxOSXCocoaClassAddWXMethods( self );
324 - (id) initWithFrame:(NSRect) frame
326 self = [super initWithFrame:frame];
333 [fieldEditor release];
337 - (void) setFieldEditor:(wxNSTextFieldEditor*) editor
339 if ( editor != fieldEditor )
342 [fieldEditor release];
343 fieldEditor = editor;
347 - (wxNSTextFieldEditor*) fieldEditor
352 - (void) setEnabled:(BOOL) flag
354 [super setEnabled: flag];
356 if (![self drawsBackground]) {
357 // Static text is drawn incorrectly when disabled.
358 // For an explanation, see
359 // http://www.cocoabuilder.com/archive/message/cocoa/2006/7/21/168028
361 [self setTextColor: [NSColor controlTextColor]];
363 [self setTextColor: [NSColor secondarySelectedControlColor]];
368 - (void)controlTextDidChange:(NSNotification *)aNotification
370 wxUnusedVar(aNotification);
371 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
373 impl->controlTextDidChange();
376 - (NSArray *)control:(NSControl *)control textView:(NSTextView *)textView completions:(NSArray *)words
377 forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger*)index
379 NSMutableArray* matches = NULL;
381 wxTextWidgetImpl* impl = (wxNSTextFieldControl * ) wxWidgetImpl::FindFromWXWidget( self );
382 wxTextEntry * const entry = impl->GetTextEntry();
383 wxTextCompleter * const completer = entry->OSXGetCompleter();
386 const wxString prefix = entry->GetValue();
387 if ( completer->Start(prefix) )
390 wordStart = wxCFStringRef::AsString(
391 [[textView string] substringWithRange:charRange]
394 matches = [NSMutableArray array];
397 const wxString s = completer->GetNext();
401 // Normally the completer should return only the strings
402 // starting with the prefix, but there could be exceptions
403 // and, for compatibility with MSW which simply ignores all
404 // entries that don't match the current text control contents,
405 // we ignore them as well. Besides, our own wxTextCompleterFixed
406 // doesn't respect this rule and, moreover, we need to extract
407 // just the rest of the string anyhow.
409 if ( s.StartsWith(prefix, &completion) )
411 // We discarded the entire prefix above but actually we
412 // should include the part of it that consists of the
413 // beginning of the current word, otherwise it would be
414 // lost when completion is accepted as OS X supposes that
415 // our matches do start with the "partial word range"
417 const wxCFStringRef fullWord(wordStart + completion);
418 [matches addObject: fullWord.AsNSString()];
427 - (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector
429 wxUnusedVar(textView);
430 wxUnusedVar(control);
434 // send back key events wx' common code knows how to handle
436 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
439 wxWindow* wxpeer = (wxWindow*) impl->GetWXPeer();
442 if (commandSelector == @selector(insertNewline:))
444 [textView insertNewlineIgnoringFieldEditor:self];
447 else if ( commandSelector == @selector(insertTab:))
449 [textView insertTabIgnoringFieldEditor:self];
452 else if ( commandSelector == @selector(insertBacktab:))
454 [textView insertTabIgnoringFieldEditor:self];
463 - (void)controlTextDidEndEditing:(NSNotification *)aNotification
465 wxUnusedVar(aNotification);
466 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
469 impl->DoNotifyFocusEvent( false, NULL );
474 // wxNSTextViewControl
476 wxNSTextViewControl::wxNSTextViewControl( wxTextCtrl *wxPeer, WXWidget w )
477 : wxWidgetCocoaImpl(wxPeer, w),
478 wxTextWidgetImpl(wxPeer)
480 wxNSTextScrollView* sv = (wxNSTextScrollView*) w;
483 [m_scrollView setHasVerticalScroller:YES];
484 [m_scrollView setHasHorizontalScroller:NO];
485 [m_scrollView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
486 NSSize contentSize = [m_scrollView contentSize];
488 wxNSTextView* tv = [[wxNSTextView alloc] initWithFrame: NSMakeRect(0, 0,
489 contentSize.width, contentSize.height)];
491 [tv setVerticallyResizable:YES];
492 [tv setHorizontallyResizable:NO];
493 [tv setAutoresizingMask:NSViewWidthSizable];
495 [m_scrollView setDocumentView: tv];
497 [tv setDelegate: tv];
499 InstallEventHandler(tv);
502 wxNSTextViewControl::~wxNSTextViewControl()
505 [m_textView setDelegate: nil];
508 bool wxNSTextViewControl::CanFocus() const
510 // since this doesn't work (return false), we hardcode
512 // return [m_textView canBecomeKeyView];
516 wxString wxNSTextViewControl::GetStringValue() const
520 wxString result = wxCFStringRef::AsString([m_textView string], m_wxPeer->GetFont().GetEncoding());
521 wxMacConvertNewlines13To10( &result ) ;
524 return wxEmptyString;
526 void wxNSTextViewControl::SetStringValue( const wxString &str)
529 wxMacConvertNewlines10To13( &st );
530 wxMacEditHelper helper(m_textView);
533 [m_textView setString: wxCFStringRef( st , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
536 void wxNSTextViewControl::Copy()
539 [m_textView copy:nil];
543 void wxNSTextViewControl::Cut()
546 [m_textView cut:nil];
549 void wxNSTextViewControl::Paste()
552 [m_textView paste:nil];
555 bool wxNSTextViewControl::CanPaste() const
560 void wxNSTextViewControl::SetEditable(bool editable)
563 [m_textView setEditable: editable];
566 void wxNSTextViewControl::GetSelection( long* from, long* to) const
570 NSRange range = [m_textView selectedRange];
571 *from = range.location;
572 *to = range.location + range.length;
576 void wxNSTextViewControl::SetSelection( long from , long to )
578 long textLength = [[m_textView string] length];
579 if ((from == -1) && (to == -1))
586 from = wxMin(textLength,wxMax(from,0)) ;
590 to = wxMax(0,wxMin(textLength,to)) ;
593 NSRange selrange = NSMakeRange(from, to-from);
594 [m_textView setSelectedRange:selrange];
595 [m_textView scrollRangeToVisible:selrange];
598 void wxNSTextViewControl::WriteText(const wxString& str)
601 wxMacConvertNewlines10To13( &st );
602 wxMacEditHelper helper(m_textView);
603 NSEvent* formerEvent = m_lastKeyDownEvent;
604 m_lastKeyDownEvent = nil;
605 [m_textView insertText:wxCFStringRef( st , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
606 m_lastKeyDownEvent = formerEvent;
609 void wxNSTextViewControl::SetFont( const wxFont & font , const wxColour& WXUNUSED(foreground) , long WXUNUSED(windowStyle), bool WXUNUSED(ignoreBlack) )
611 if ([m_textView respondsToSelector:@selector(setFont:)])
612 [m_textView setFont: font.OSXGetNSFont()];
615 bool wxNSTextViewControl::GetStyle(long position, wxTextAttr& style)
617 if (m_textView && position >=0)
620 NSColor* bgcolor = NULL;
621 NSColor* fgcolor = NULL;
622 // NOTE: It appears that other platforms accept GetStyle with the position == length
623 // but that NSTextStorage does not accept length as a valid position.
624 // Therefore we return the default control style in that case.
625 if (position < (long) [[m_textView string] length])
627 NSTextStorage* storage = [m_textView textStorage];
628 font = [[storage attribute:NSFontAttributeName atIndex:position effectiveRange:NULL] autorelease];
629 bgcolor = [[storage attribute:NSBackgroundColorAttributeName atIndex:position effectiveRange:NULL] autorelease];
630 fgcolor = [[storage attribute:NSForegroundColorAttributeName atIndex:position effectiveRange:NULL] autorelease];
634 NSDictionary* attrs = [m_textView typingAttributes];
635 font = [[attrs objectForKey:NSFontAttributeName] autorelease];
636 bgcolor = [[attrs objectForKey:NSBackgroundColorAttributeName] autorelease];
637 fgcolor = [[attrs objectForKey:NSForegroundColorAttributeName] autorelease];
641 style.SetFont(wxFont(font));
644 style.SetBackgroundColour(wxColour(bgcolor));
647 style.SetTextColour(wxColour(fgcolor));
654 void wxNSTextViewControl::SetStyle(long start,
656 const wxTextAttr& style)
659 NSRange range = NSMakeRange(start, end-start);
660 if (start == -1 && end == -1)
661 range = [m_textView selectedRange];
663 NSTextStorage* storage = [m_textView textStorage];
665 wxFont font = style.GetFont();
666 if (style.HasFont() && font.IsOk())
667 [storage addAttribute:NSFontAttributeName value:font.OSXGetNSFont() range:range];
669 wxColour bgcolor = style.GetBackgroundColour();
670 if (style.HasBackgroundColour() && bgcolor.IsOk())
671 [storage addAttribute:NSBackgroundColorAttributeName value:bgcolor.OSXGetNSColor() range:range];
673 wxColour fgcolor = style.GetTextColour();
674 if (style.HasTextColour() && fgcolor.IsOk())
675 [storage addAttribute:NSForegroundColorAttributeName value:fgcolor.OSXGetNSColor() range:range];
679 void wxNSTextViewControl::CheckSpelling(bool check)
682 [m_textView setContinuousSpellCheckingEnabled: check];
685 wxSize wxNSTextViewControl::GetBestSize() const
687 if (m_textView && [m_textView layoutManager])
689 NSRect rect = [[m_textView layoutManager] usedRectForTextContainer: [m_textView textContainer]];
690 return wxSize((int)(rect.size.width + [m_textView textContainerInset].width),
691 (int)(rect.size.height + [m_textView textContainerInset].height));
696 // wxNSTextFieldControl
698 wxNSTextFieldControl::wxNSTextFieldControl( wxTextCtrl *text, WXWidget w )
699 : wxWidgetCocoaImpl(text, w),
700 wxTextWidgetImpl(text)
705 wxNSTextFieldControl::wxNSTextFieldControl(wxWindow *wxPeer,
708 : wxWidgetCocoaImpl(wxPeer, w),
709 wxTextWidgetImpl(entry)
714 void wxNSTextFieldControl::Init(WXWidget w)
716 NSTextField wxOSX_10_6_AND_LATER(<NSTextFieldDelegate>) *tf = (NSTextField wxOSX_10_6_AND_LATER(<NSTextFieldDelegate>)*) w;
718 [m_textField setDelegate: tf];
719 m_selStart = m_selEnd = 0;
720 m_hasEditor = [w isKindOfClass:[NSTextField class]];
723 wxNSTextFieldControl::~wxNSTextFieldControl()
726 [m_textField setDelegate: nil];
729 wxString wxNSTextFieldControl::GetStringValue() const
731 return wxCFStringRef::AsString([m_textField stringValue], m_wxPeer->GetFont().GetEncoding());
734 void wxNSTextFieldControl::SetStringValue( const wxString &str)
736 wxMacEditHelper helper(m_textField);
737 [m_textField setStringValue: wxCFStringRef( str , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
740 void wxNSTextFieldControl::SetMaxLength(unsigned long len)
742 wxMaximumLengthFormatter* formatter = [[[wxMaximumLengthFormatter alloc] init] autorelease];
743 [formatter setMaxLength:len];
744 [m_textField setFormatter:formatter];
747 void wxNSTextFieldControl::Copy()
749 NSText* editor = [m_textField currentEditor];
756 void wxNSTextFieldControl::Cut()
758 NSText* editor = [m_textField currentEditor];
765 void wxNSTextFieldControl::Paste()
767 NSText* editor = [m_textField currentEditor];
774 bool wxNSTextFieldControl::CanPaste() const
779 void wxNSTextFieldControl::SetEditable(bool editable)
781 [m_textField setEditable:editable];
784 void wxNSTextFieldControl::GetSelection( long* from, long* to) const
786 NSText* editor = [m_textField currentEditor];
789 NSRange range = [editor selectedRange];
790 *from = range.location;
791 *to = range.location + range.length;
800 void wxNSTextFieldControl::SetSelection( long from , long to )
802 long textLength = [[m_textField stringValue] length];
803 if ((from == -1) && (to == -1))
810 from = wxMin(textLength,wxMax(from,0)) ;
814 to = wxMax(0,wxMin(textLength,to)) ;
817 NSText* editor = [m_textField currentEditor];
820 [editor setSelectedRange:NSMakeRange(from, to-from)];
829 void wxNSTextFieldControl::WriteText(const wxString& str)
831 NSEvent* formerEvent = m_lastKeyDownEvent;
832 m_lastKeyDownEvent = nil;
833 NSText* editor = [m_textField currentEditor];
836 wxMacEditHelper helper(m_textField);
837 [editor insertText:wxCFStringRef( str , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
841 wxString val = GetStringValue() ;
843 GetSelection( &start , &end ) ;
844 val.Remove( start , end - start ) ;
845 val.insert( start , str ) ;
846 SetStringValue( val ) ;
847 SetSelection( start + str.length() , start + str.length() ) ;
849 m_lastKeyDownEvent = formerEvent;
852 void wxNSTextFieldControl::controlAction(WXWidget WXUNUSED(slf),
853 void* WXUNUSED(_cmd), void *WXUNUSED(sender))
855 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
856 if ( wxpeer && (wxpeer->GetWindowStyle() & wxTE_PROCESS_ENTER) )
858 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, wxpeer->GetId());
859 event.SetEventObject( wxpeer );
860 event.SetString( GetTextEntry()->GetValue() );
861 wxpeer->HandleWindowEvent( event );
865 bool wxNSTextFieldControl::SetHint(const wxString& hint)
867 wxCFStringRef hintstring(hint);
868 [[m_textField cell] setPlaceholderString:hintstring.AsNSString()];
876 wxWidgetImplType* wxWidgetImpl::CreateTextControl( wxTextCtrl* wxpeer,
877 wxWindowMac* WXUNUSED(parent),
878 wxWindowID WXUNUSED(id),
879 const wxString& WXUNUSED(str),
883 long WXUNUSED(extraStyle))
885 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
886 wxWidgetCocoaImpl* c = NULL;
888 if ( style & wxTE_MULTILINE || style & wxTE_RICH || style & wxTE_RICH2 )
890 wxNSTextScrollView* v = nil;
891 v = [[wxNSTextScrollView alloc] initWithFrame:r];
892 c = new wxNSTextViewControl( wxpeer, v );
896 NSTextField* v = nil;
897 if ( style & wxTE_PASSWORD )
898 v = [[wxNSSecureTextField alloc] initWithFrame:r];
900 v = [[wxNSTextField alloc] initWithFrame:r];
902 if ( style & wxNO_BORDER )
904 // FIXME: How can we remove the native control's border?
905 // setBordered is separate from the text ctrl's border.
908 NSTextFieldCell* cell = [v cell];
909 [cell setScrollable:YES];
910 // TODO: Remove if we definitely are sure, it's not needed
911 // as setting scrolling to yes, should turn off any wrapping
912 // [cell setLineBreakMode:NSLineBreakByClipping];
917 c = new wxNSTextFieldControl( wxpeer, wxpeer, v );
919 c->SetNeedsFocusRect( true );
925 #endif // wxUSE_TEXTCTRL