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 @implementation wxNSSecureTextField
114 static BOOL initialized = NO;
118 wxOSXCocoaClassAddWXMethods( self );
122 - (void)controlTextDidChange:(NSNotification *)aNotification
124 wxUnusedVar(aNotification);
125 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
127 impl->controlTextDidChange();
130 - (void)controlTextDidEndEditing:(NSNotification *)aNotification
132 wxUnusedVar(aNotification);
133 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
136 impl->DoNotifyFocusEvent( false, NULL );
142 @interface wxNSTextScrollView : NSScrollView
147 @implementation wxNSTextScrollView
151 static BOOL initialized = NO;
155 wxOSXCocoaClassAddWXMethods( self );
161 @implementation wxNSTextFieldEditor
163 - (void) keyDown:(NSEvent*) event
165 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
166 lastKeyDownEvent = event;
167 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
168 [super keyDown:event];
169 lastKeyDownEvent = nil;
172 - (void) keyUp:(NSEvent*) event
174 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
175 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
179 - (void) flagsChanged:(NSEvent*) event
181 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
182 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
183 [super flagsChanged:event];
186 - (BOOL) performKeyEquivalent:(NSEvent*) event
188 BOOL retval = [super performKeyEquivalent:event];
192 - (void) insertText:(id) str
194 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
195 if ( impl == NULL || lastKeyDownEvent==nil || !impl->DoHandleCharEvent(lastKeyDownEvent, str) )
197 [super insertText:str];
203 @implementation wxNSTextView
207 static BOOL initialized = NO;
211 wxOSXCocoaClassAddWXMethods( self );
215 - (void)textDidChange:(NSNotification *)aNotification
217 wxUnusedVar(aNotification);
218 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
220 impl->controlTextDidChange();
223 - (void) setEnabled:(BOOL) flag
225 // from Technical Q&A QA1461
227 [self setTextColor: [NSColor controlTextColor]];
230 [self setTextColor: [NSColor disabledControlTextColor]];
233 [self setSelectable: flag];
234 [self setEditable: flag];
239 return [self isEditable];
242 - (void)textDidEndEditing:(NSNotification *)aNotification
244 wxUnusedVar(aNotification);
246 if ( self == wxMacEditHelper::GetCurrentlyEditedView() )
248 // This notification is generated as the result of calling our own
249 // wxTextCtrl method (e.g. WriteText()) and doesn't correspond to any
250 // real focus loss event so skip generating it.
254 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
257 impl->DoNotifyFocusEvent( false, NULL );
263 @implementation wxNSTextField
267 static BOOL initialized = NO;
271 wxOSXCocoaClassAddWXMethods( self );
275 - (id) initWithFrame:(NSRect) frame
277 self = [super initWithFrame:frame];
284 [fieldEditor release];
288 - (void) setFieldEditor:(wxNSTextFieldEditor*) editor
290 if ( editor != fieldEditor )
293 [fieldEditor release];
294 fieldEditor = editor;
298 - (wxNSTextFieldEditor*) fieldEditor
303 - (void) setEnabled:(BOOL) flag
305 [super setEnabled: flag];
307 if (![self drawsBackground]) {
308 // Static text is drawn incorrectly when disabled.
309 // For an explanation, see
310 // http://www.cocoabuilder.com/archive/message/cocoa/2006/7/21/168028
312 [self setTextColor: [NSColor controlTextColor]];
314 [self setTextColor: [NSColor secondarySelectedControlColor]];
319 - (void)controlTextDidChange:(NSNotification *)aNotification
321 wxUnusedVar(aNotification);
322 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
324 impl->controlTextDidChange();
327 - (NSArray *)control:(NSControl *)control textView:(NSTextView *)textView completions:(NSArray *)words
328 forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger*)index
330 NSMutableArray* matches = NULL;
332 wxTextWidgetImpl* impl = (wxNSTextFieldControl * ) wxWidgetImpl::FindFromWXWidget( self );
333 wxTextEntry * const entry = impl->GetTextEntry();
334 wxTextCompleter * const completer = entry->OSXGetCompleter();
337 const wxString prefix = entry->GetValue();
338 if ( completer->Start(prefix) )
341 wordStart = wxCFStringRef::AsString(
342 [[textView string] substringWithRange:charRange]
345 matches = [NSMutableArray array];
348 const wxString s = completer->GetNext();
352 // Normally the completer should return only the strings
353 // starting with the prefix, but there could be exceptions
354 // and, for compatibility with MSW which simply ignores all
355 // entries that don't match the current text control contents,
356 // we ignore them as well. Besides, our own wxTextCompleterFixed
357 // doesn't respect this rule and, moreover, we need to extract
358 // just the rest of the string anyhow.
360 if ( s.StartsWith(prefix, &completion) )
362 // We discarded the entire prefix above but actually we
363 // should include the part of it that consists of the
364 // beginning of the current word, otherwise it would be
365 // lost when completion is accepted as OS X supposes that
366 // our matches do start with the "partial word range"
368 const wxCFStringRef fullWord(wordStart + completion);
369 [matches addObject: fullWord.AsNSString()];
378 - (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector
380 wxUnusedVar(textView);
381 wxUnusedVar(control);
385 // send back key events wx' common code knows how to handle
387 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
390 wxWindow* wxpeer = (wxWindow*) impl->GetWXPeer();
393 if (commandSelector == @selector(insertNewline:))
395 [textView insertNewlineIgnoringFieldEditor:self];
398 else if ( commandSelector == @selector(insertTab:))
400 [textView insertTabIgnoringFieldEditor:self];
403 else if ( commandSelector == @selector(insertBacktab:))
405 [textView insertTabIgnoringFieldEditor:self];
414 - (void)controlTextDidEndEditing:(NSNotification *)aNotification
416 wxUnusedVar(aNotification);
417 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
420 impl->DoNotifyFocusEvent( false, NULL );
425 // wxNSTextViewControl
427 wxNSTextViewControl::wxNSTextViewControl( wxTextCtrl *wxPeer, WXWidget w )
428 : wxWidgetCocoaImpl(wxPeer, w),
429 wxTextWidgetImpl(wxPeer)
431 wxNSTextScrollView* sv = (wxNSTextScrollView*) w;
434 [m_scrollView setHasVerticalScroller:YES];
435 [m_scrollView setHasHorizontalScroller:NO];
436 [m_scrollView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
437 NSSize contentSize = [m_scrollView contentSize];
439 wxNSTextView* tv = [[wxNSTextView alloc] initWithFrame: NSMakeRect(0, 0,
440 contentSize.width, contentSize.height)];
442 [tv setVerticallyResizable:YES];
443 [tv setHorizontallyResizable:NO];
444 [tv setAutoresizingMask:NSViewWidthSizable];
446 [m_scrollView setDocumentView: tv];
448 [tv setDelegate: tv];
450 InstallEventHandler(tv);
453 wxNSTextViewControl::~wxNSTextViewControl()
456 [m_textView setDelegate: nil];
459 bool wxNSTextViewControl::CanFocus() const
461 // since this doesn't work (return false), we hardcode
463 // return [m_textView canBecomeKeyView];
467 wxString wxNSTextViewControl::GetStringValue() const
471 wxString result = wxCFStringRef::AsString([m_textView string], m_wxPeer->GetFont().GetEncoding());
472 wxMacConvertNewlines13To10( &result ) ;
475 return wxEmptyString;
477 void wxNSTextViewControl::SetStringValue( const wxString &str)
480 wxMacConvertNewlines10To13( &st );
481 wxMacEditHelper helper(m_textView);
484 [m_textView setString: wxCFStringRef( st , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
487 void wxNSTextViewControl::Copy()
490 [m_textView copy:nil];
494 void wxNSTextViewControl::Cut()
497 [m_textView cut:nil];
500 void wxNSTextViewControl::Paste()
503 [m_textView paste:nil];
506 bool wxNSTextViewControl::CanPaste() const
511 void wxNSTextViewControl::SetEditable(bool editable)
514 [m_textView setEditable: editable];
517 void wxNSTextViewControl::GetSelection( long* from, long* to) const
521 NSRange range = [m_textView selectedRange];
522 *from = range.location;
523 *to = range.location + range.length;
527 void wxNSTextViewControl::SetSelection( long from , long to )
529 long textLength = [[m_textView string] length];
530 if ((from == -1) && (to == -1))
537 from = wxMin(textLength,wxMax(from,0)) ;
541 to = wxMax(0,wxMin(textLength,to)) ;
544 NSRange selrange = NSMakeRange(from, to-from);
545 [m_textView setSelectedRange:selrange];
546 [m_textView scrollRangeToVisible:selrange];
549 void wxNSTextViewControl::WriteText(const wxString& str)
552 wxMacConvertNewlines10To13( &st );
553 wxMacEditHelper helper(m_textView);
554 NSEvent* formerEvent = m_lastKeyDownEvent;
555 m_lastKeyDownEvent = nil;
556 [m_textView insertText:wxCFStringRef( st , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
557 m_lastKeyDownEvent = formerEvent;
560 void wxNSTextViewControl::SetFont( const wxFont & font , const wxColour& WXUNUSED(foreground) , long WXUNUSED(windowStyle), bool WXUNUSED(ignoreBlack) )
562 if ([m_textView respondsToSelector:@selector(setFont:)])
563 [m_textView setFont: font.OSXGetNSFont()];
566 bool wxNSTextViewControl::GetStyle(long position, wxTextAttr& style)
568 if (m_textView && position >=0)
571 NSColor* bgcolor = NULL;
572 NSColor* fgcolor = NULL;
573 // NOTE: It appears that other platforms accept GetStyle with the position == length
574 // but that NSTextStorage does not accept length as a valid position.
575 // Therefore we return the default control style in that case.
576 if (position < (long) [[m_textView string] length])
578 NSTextStorage* storage = [m_textView textStorage];
579 font = [[storage attribute:NSFontAttributeName atIndex:position effectiveRange:NULL] autorelease];
580 bgcolor = [[storage attribute:NSBackgroundColorAttributeName atIndex:position effectiveRange:NULL] autorelease];
581 fgcolor = [[storage attribute:NSForegroundColorAttributeName atIndex:position effectiveRange:NULL] autorelease];
585 NSDictionary* attrs = [m_textView typingAttributes];
586 font = [[attrs objectForKey:NSFontAttributeName] autorelease];
587 bgcolor = [[attrs objectForKey:NSBackgroundColorAttributeName] autorelease];
588 fgcolor = [[attrs objectForKey:NSForegroundColorAttributeName] autorelease];
592 style.SetFont(wxFont(font));
595 style.SetBackgroundColour(wxColour(bgcolor));
598 style.SetTextColour(wxColour(fgcolor));
605 void wxNSTextViewControl::SetStyle(long start,
607 const wxTextAttr& style)
610 NSRange range = NSMakeRange(start, end-start);
611 if (start == -1 && end == -1)
612 range = [m_textView selectedRange];
614 NSTextStorage* storage = [m_textView textStorage];
616 wxFont font = style.GetFont();
617 if (style.HasFont() && font.IsOk())
618 [storage addAttribute:NSFontAttributeName value:font.OSXGetNSFont() range:range];
620 wxColour bgcolor = style.GetBackgroundColour();
621 if (style.HasBackgroundColour() && bgcolor.IsOk())
622 [storage addAttribute:NSBackgroundColorAttributeName value:bgcolor.OSXGetNSColor() range:range];
624 wxColour fgcolor = style.GetTextColour();
625 if (style.HasTextColour() && fgcolor.IsOk())
626 [storage addAttribute:NSForegroundColorAttributeName value:fgcolor.OSXGetNSColor() range:range];
630 void wxNSTextViewControl::CheckSpelling(bool check)
633 [m_textView setContinuousSpellCheckingEnabled: check];
636 wxSize wxNSTextViewControl::GetBestSize() const
638 if (m_textView && [m_textView layoutManager])
640 NSRect rect = [[m_textView layoutManager] usedRectForTextContainer: [m_textView textContainer]];
641 return wxSize((int)(rect.size.width + [m_textView textContainerInset].width),
642 (int)(rect.size.height + [m_textView textContainerInset].height));
647 // wxNSTextFieldControl
649 wxNSTextFieldControl::wxNSTextFieldControl( wxTextCtrl *text, WXWidget w )
650 : wxWidgetCocoaImpl(text, w),
651 wxTextWidgetImpl(text)
656 wxNSTextFieldControl::wxNSTextFieldControl(wxWindow *wxPeer,
659 : wxWidgetCocoaImpl(wxPeer, w),
660 wxTextWidgetImpl(entry)
665 void wxNSTextFieldControl::Init(WXWidget w)
667 NSTextField wxOSX_10_6_AND_LATER(<NSTextFieldDelegate>) *tf = (NSTextField wxOSX_10_6_AND_LATER(<NSTextFieldDelegate>)*) w;
669 [m_textField setDelegate: tf];
670 m_selStart = m_selEnd = 0;
671 m_hasEditor = [w isKindOfClass:[NSTextField class]];
674 wxNSTextFieldControl::~wxNSTextFieldControl()
677 [m_textField setDelegate: nil];
680 wxString wxNSTextFieldControl::GetStringValue() const
682 return wxCFStringRef::AsString([m_textField stringValue], m_wxPeer->GetFont().GetEncoding());
685 void wxNSTextFieldControl::SetStringValue( const wxString &str)
687 wxMacEditHelper helper(m_textField);
688 [m_textField setStringValue: wxCFStringRef( str , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
691 void wxNSTextFieldControl::Copy()
693 NSText* editor = [m_textField currentEditor];
700 void wxNSTextFieldControl::Cut()
702 NSText* editor = [m_textField currentEditor];
709 void wxNSTextFieldControl::Paste()
711 NSText* editor = [m_textField currentEditor];
718 bool wxNSTextFieldControl::CanPaste() const
723 void wxNSTextFieldControl::SetEditable(bool editable)
725 [m_textField setEditable:editable];
728 void wxNSTextFieldControl::GetSelection( long* from, long* to) const
730 NSText* editor = [m_textField currentEditor];
733 NSRange range = [editor selectedRange];
734 *from = range.location;
735 *to = range.location + range.length;
744 void wxNSTextFieldControl::SetSelection( long from , long to )
746 long textLength = [[m_textField stringValue] length];
747 if ((from == -1) && (to == -1))
754 from = wxMin(textLength,wxMax(from,0)) ;
758 to = wxMax(0,wxMin(textLength,to)) ;
761 NSText* editor = [m_textField currentEditor];
764 [editor setSelectedRange:NSMakeRange(from, to-from)];
773 void wxNSTextFieldControl::WriteText(const wxString& str)
775 NSEvent* formerEvent = m_lastKeyDownEvent;
776 m_lastKeyDownEvent = nil;
777 NSText* editor = [m_textField currentEditor];
780 wxMacEditHelper helper(m_textField);
781 [editor insertText:wxCFStringRef( str , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
785 wxString val = GetStringValue() ;
787 GetSelection( &start , &end ) ;
788 val.Remove( start , end - start ) ;
789 val.insert( start , str ) ;
790 SetStringValue( val ) ;
791 SetSelection( start + str.length() , start + str.length() ) ;
793 m_lastKeyDownEvent = formerEvent;
796 void wxNSTextFieldControl::controlAction(WXWidget WXUNUSED(slf),
797 void* WXUNUSED(_cmd), void *WXUNUSED(sender))
799 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
800 if ( wxpeer && (wxpeer->GetWindowStyle() & wxTE_PROCESS_ENTER) )
802 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, wxpeer->GetId());
803 event.SetEventObject( wxpeer );
804 event.SetString( GetTextEntry()->GetValue() );
805 wxpeer->HandleWindowEvent( event );
809 bool wxNSTextFieldControl::SetHint(const wxString& hint)
811 wxCFStringRef hintstring(hint);
812 [[m_textField cell] setPlaceholderString:hintstring.AsNSString()];
820 wxWidgetImplType* wxWidgetImpl::CreateTextControl( wxTextCtrl* wxpeer,
821 wxWindowMac* WXUNUSED(parent),
822 wxWindowID WXUNUSED(id),
823 const wxString& WXUNUSED(str),
827 long WXUNUSED(extraStyle))
829 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
830 wxWidgetCocoaImpl* c = NULL;
832 if ( style & wxTE_MULTILINE || style & wxTE_RICH || style & wxTE_RICH2 )
834 wxNSTextScrollView* v = nil;
835 v = [[wxNSTextScrollView alloc] initWithFrame:r];
836 c = new wxNSTextViewControl( wxpeer, v );
840 NSTextField* v = nil;
841 if ( style & wxTE_PASSWORD )
842 v = [[wxNSSecureTextField alloc] initWithFrame:r];
844 v = [[wxNSTextField alloc] initWithFrame:r];
846 if ( style & wxNO_BORDER )
848 // FIXME: How can we remove the native control's border?
849 // setBordered is separate from the text ctrl's border.
852 NSTextFieldCell* cell = [v cell];
853 [cell setScrollable:YES];
854 // TODO: Remove if we definitely are sure, it's not needed
855 // as setting scrolling to yes, should turn off any wrapping
856 // [cell setLineBreakMode:NSLineBreakByClipping];
861 c = new wxNSTextFieldControl( wxpeer, wxpeer, v );
863 c->SetNeedsFocusRect( true );
869 #endif // wxUSE_TEXTCTRL