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"
49 #include "wx/osx/private.h"
50 #include "wx/osx/cocoa/private/textimpl.h"
52 @interface NSView(EditableView)
54 - (void)setEditable:(BOOL)flag;
56 - (void)setSelectable:(BOOL)flag;
62 wxMacEditHelper( NSView* textView )
64 m_textView = textView;
65 m_formerEditable = YES;
68 m_formerEditable = [textView isEditable];
69 m_formerSelectable = [textView isSelectable];
70 [textView setEditable:YES];
78 [m_textView setEditable:m_formerEditable];
79 [m_textView setSelectable:m_formerSelectable];
84 BOOL m_formerEditable ;
85 BOOL m_formerSelectable;
89 @implementation wxNSSecureTextField
93 static BOOL initialized = NO;
97 wxOSXCocoaClassAddWXMethods( self );
101 - (void)controlTextDidChange:(NSNotification *)aNotification
103 wxUnusedVar(aNotification);
104 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
106 impl->controlTextDidChange();
109 - (void)controlTextDidEndEditing:(NSNotification *)aNotification
111 wxUnusedVar(aNotification);
112 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
115 impl->DoNotifyFocusEvent( false, NULL );
121 @interface wxNSTextScrollView : NSScrollView
126 @implementation wxNSTextScrollView
130 static BOOL initialized = NO;
134 wxOSXCocoaClassAddWXMethods( self );
140 @implementation wxNSTextFieldEditor
142 - (void) keyDown:(NSEvent*) event
144 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
145 lastKeyDownEvent = event;
146 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
147 [super keyDown:event];
148 lastKeyDownEvent = nil;
151 - (void) keyUp:(NSEvent*) event
153 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
154 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
158 - (void) flagsChanged:(NSEvent*) event
160 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
161 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
162 [super flagsChanged:event];
165 - (BOOL) performKeyEquivalent:(NSEvent*) event
167 BOOL retval = [super performKeyEquivalent:event];
171 - (void) insertText:(id) str
173 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
174 if ( impl == NULL || lastKeyDownEvent==nil || !impl->DoHandleCharEvent(lastKeyDownEvent, str) )
176 [super insertText:str];
182 @implementation wxNSTextView
186 static BOOL initialized = NO;
190 wxOSXCocoaClassAddWXMethods( self );
194 - (void)textDidChange:(NSNotification *)aNotification
196 wxUnusedVar(aNotification);
197 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
199 impl->controlTextDidChange();
202 - (void) setEnabled:(BOOL) flag
204 // from Technical Q&A QA1461
206 [self setTextColor: [NSColor controlTextColor]];
209 [self setTextColor: [NSColor disabledControlTextColor]];
212 [self setSelectable: flag];
213 [self setEditable: flag];
218 return [self isEditable];
221 - (void)textDidEndEditing:(NSNotification *)aNotification
223 wxUnusedVar(aNotification);
224 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
227 impl->DoNotifyFocusEvent( false, NULL );
233 @implementation wxNSTextField
237 static BOOL initialized = NO;
241 wxOSXCocoaClassAddWXMethods( self );
245 - (id) initWithFrame:(NSRect) frame
247 self = [super initWithFrame:frame];
254 [fieldEditor release];
258 - (void) setFieldEditor:(wxNSTextFieldEditor*) editor
260 fieldEditor = editor;
263 - (wxNSTextFieldEditor*) fieldEditor
268 - (void) setEnabled:(BOOL) flag
270 [super setEnabled: flag];
272 if (![self drawsBackground]) {
273 // Static text is drawn incorrectly when disabled.
274 // For an explanation, see
275 // http://www.cocoabuilder.com/archive/message/cocoa/2006/7/21/168028
277 [self setTextColor: [NSColor controlTextColor]];
279 [self setTextColor: [NSColor secondarySelectedControlColor]];
284 - (void)controlTextDidChange:(NSNotification *)aNotification
286 wxUnusedVar(aNotification);
287 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
289 impl->controlTextDidChange();
292 - (NSArray *)control:(NSControl *)control textView:(NSTextView *)textView completions:(NSArray *)words
293 forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(int*)index
295 NSMutableArray* matches = NULL;
296 NSString* partialString;
298 partialString = [[textView string] substringWithRange:charRange];
299 matches = [NSMutableArray array];
301 wxTextWidgetImpl* impl = (wxTextWidgetImpl* ) wxWidgetImpl::FindFromWXWidget( self );
302 wxArrayString completions;
304 // adapt to whatever strategy we have for getting the strings
305 // impl->GetTextEntry()->GetCompletions(wxCFStringRef::AsString(partialString), completions);
307 for (size_t i = 0; i < completions.GetCount(); ++i )
308 [matches addObject: wxCFStringRef(completions[i]).AsNSString()];
310 // [matches sortUsingSelector:@selector(compare:)];
315 - (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector
317 wxUnusedVar(textView);
318 wxUnusedVar(control);
322 // send back key events wx' common code knows how to handle
324 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
327 wxWindow* wxpeer = (wxWindow*) impl->GetWXPeer();
330 if (commandSelector == @selector(insertNewline:))
332 [textView insertNewlineIgnoringFieldEditor:self];
335 else if ( commandSelector == @selector(insertTab:))
337 [textView insertTabIgnoringFieldEditor:self];
340 else if ( commandSelector == @selector(insertBacktab:))
342 [textView insertTabIgnoringFieldEditor:self];
351 - (void)controlTextDidEndEditing:(NSNotification *)aNotification
353 wxUnusedVar(aNotification);
354 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
357 impl->DoNotifyFocusEvent( false, NULL );
362 // wxNSTextViewControl
364 wxNSTextViewControl::wxNSTextViewControl( wxTextCtrl *wxPeer, WXWidget w )
365 : wxWidgetCocoaImpl(wxPeer, w),
366 wxTextWidgetImpl(wxPeer)
368 wxNSTextScrollView* sv = (wxNSTextScrollView*) w;
371 [m_scrollView setHasVerticalScroller:YES];
372 [m_scrollView setHasHorizontalScroller:NO];
373 [m_scrollView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
374 NSSize contentSize = [m_scrollView contentSize];
376 wxNSTextView* tv = [[wxNSTextView alloc] initWithFrame: NSMakeRect(0, 0,
377 contentSize.width, contentSize.height)];
379 [tv setVerticallyResizable:YES];
380 [tv setHorizontallyResizable:NO];
381 [tv setAutoresizingMask:NSViewWidthSizable];
383 [m_scrollView setDocumentView: tv];
385 [tv setDelegate: tv];
387 InstallEventHandler(tv);
390 wxNSTextViewControl::~wxNSTextViewControl()
393 [m_textView setDelegate: nil];
396 bool wxNSTextViewControl::CanFocus() const
398 // since this doesn't work (return false), we hardcode
400 // return [m_textView canBecomeKeyView];
404 wxString wxNSTextViewControl::GetStringValue() const
408 wxString result = wxCFStringRef::AsString([m_textView string], m_wxPeer->GetFont().GetEncoding());
409 wxMacConvertNewlines13To10( &result ) ;
412 return wxEmptyString;
414 void wxNSTextViewControl::SetStringValue( const wxString &str)
417 wxMacConvertNewlines10To13( &st );
418 wxMacEditHelper helper(m_textView);
421 [m_textView setString: wxCFStringRef( st , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
424 void wxNSTextViewControl::Copy()
427 [m_textView copy:nil];
431 void wxNSTextViewControl::Cut()
434 [m_textView cut:nil];
437 void wxNSTextViewControl::Paste()
440 [m_textView paste:nil];
443 bool wxNSTextViewControl::CanPaste() const
448 void wxNSTextViewControl::SetEditable(bool editable)
451 [m_textView setEditable: editable];
454 void wxNSTextViewControl::GetSelection( long* from, long* to) const
458 NSRange range = [m_textView selectedRange];
459 *from = range.location;
460 *to = range.location + range.length;
464 void wxNSTextViewControl::SetSelection( long from , long to )
466 long textLength = [[m_textView string] length];
467 if ((from == -1) && (to == -1))
474 from = wxMin(textLength,wxMax(from,0)) ;
478 to = wxMax(0,wxMin(textLength,to)) ;
481 NSRange selrange = NSMakeRange(from, to-from);
482 [m_textView setSelectedRange:selrange];
483 [m_textView scrollRangeToVisible:selrange];
486 void wxNSTextViewControl::WriteText(const wxString& str)
489 wxMacConvertNewlines10To13( &st );
490 wxMacEditHelper helper(m_textView);
491 NSEvent* formerEvent = m_lastKeyDownEvent;
492 m_lastKeyDownEvent = nil;
493 [m_textView insertText:wxCFStringRef( st , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
494 m_lastKeyDownEvent = formerEvent;
497 void wxNSTextViewControl::SetFont( const wxFont & font , const wxColour& WXUNUSED(foreground) , long WXUNUSED(windowStyle), bool WXUNUSED(ignoreBlack) )
499 if ([m_textView respondsToSelector:@selector(setFont:)])
500 [m_textView setFont: font.OSXGetNSFont()];
503 bool wxNSTextViewControl::GetStyle(long position, wxTextAttr& style)
505 if (m_textView && position >=0)
508 NSColor* bgcolor = NULL;
509 NSColor* fgcolor = NULL;
510 // NOTE: It appears that other platforms accept GetStyle with the position == length
511 // but that NSTextStorage does not accept length as a valid position.
512 // Therefore we return the default control style in that case.
513 if (position < (long) [[m_textView string] length])
515 NSTextStorage* storage = [m_textView textStorage];
516 font = [[storage attribute:NSFontAttributeName atIndex:position effectiveRange:NULL] autorelease];
517 bgcolor = [[storage attribute:NSBackgroundColorAttributeName atIndex:position effectiveRange:NULL] autorelease];
518 fgcolor = [[storage attribute:NSForegroundColorAttributeName atIndex:position effectiveRange:NULL] autorelease];
522 NSDictionary* attrs = [m_textView typingAttributes];
523 font = [[attrs objectForKey:NSFontAttributeName] autorelease];
524 bgcolor = [[attrs objectForKey:NSBackgroundColorAttributeName] autorelease];
525 fgcolor = [[attrs objectForKey:NSForegroundColorAttributeName] autorelease];
529 style.SetFont(wxFont(font));
532 style.SetBackgroundColour(wxColour(bgcolor));
535 style.SetTextColour(wxColour(fgcolor));
542 void wxNSTextViewControl::SetStyle(long start,
544 const wxTextAttr& style)
547 NSRange range = NSMakeRange(start, end-start);
548 if (start == -1 && end == -1)
549 range = [m_textView selectedRange];
551 NSTextStorage* storage = [m_textView textStorage];
553 wxFont font = style.GetFont();
554 if (style.HasFont() && font.IsOk())
555 [storage addAttribute:NSFontAttributeName value:font.OSXGetNSFont() range:range];
557 wxColour bgcolor = style.GetBackgroundColour();
558 if (style.HasBackgroundColour() && bgcolor.IsOk())
559 [storage addAttribute:NSBackgroundColorAttributeName value:bgcolor.OSXGetNSColor() range:range];
561 wxColour fgcolor = style.GetTextColour();
562 if (style.HasTextColour() && fgcolor.IsOk())
563 [storage addAttribute:NSForegroundColorAttributeName value:fgcolor.OSXGetNSColor() range:range];
567 void wxNSTextViewControl::CheckSpelling(bool check)
570 [m_textView setContinuousSpellCheckingEnabled: check];
573 wxSize wxNSTextViewControl::GetBestSize() const
575 if (m_textView && [m_textView layoutManager])
577 NSRect rect = [[m_textView layoutManager] usedRectForTextContainer: [m_textView textContainer]];
578 return wxSize((int)(rect.size.width + [m_textView textContainerInset].width),
579 (int)(rect.size.height + [m_textView textContainerInset].height));
584 // wxNSTextFieldControl
586 wxNSTextFieldControl::wxNSTextFieldControl( wxTextCtrl *text, WXWidget w )
587 : wxWidgetCocoaImpl(text, w),
588 wxTextWidgetImpl(text)
593 wxNSTextFieldControl::wxNSTextFieldControl(wxWindow *wxPeer,
596 : wxWidgetCocoaImpl(wxPeer, w),
597 wxTextWidgetImpl(entry)
602 void wxNSTextFieldControl::Init(WXWidget w)
604 NSTextField wxOSX_10_6_AND_LATER(<NSTextFieldDelegate>) *tf = (NSTextField*) w;
606 [m_textField setDelegate: tf];
607 m_selStart = m_selEnd = 0;
608 m_hasEditor = [w isKindOfClass:[NSTextField class]];
611 wxNSTextFieldControl::~wxNSTextFieldControl()
614 [m_textField setDelegate: nil];
617 wxString wxNSTextFieldControl::GetStringValue() const
619 return wxCFStringRef::AsString([m_textField stringValue], m_wxPeer->GetFont().GetEncoding());
622 void wxNSTextFieldControl::SetStringValue( const wxString &str)
624 wxMacEditHelper helper(m_textField);
625 [m_textField setStringValue: wxCFStringRef( str , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
628 void wxNSTextFieldControl::Copy()
630 NSText* editor = [m_textField currentEditor];
637 void wxNSTextFieldControl::Cut()
639 NSText* editor = [m_textField currentEditor];
646 void wxNSTextFieldControl::Paste()
648 NSText* editor = [m_textField currentEditor];
655 bool wxNSTextFieldControl::CanPaste() const
660 void wxNSTextFieldControl::SetEditable(bool editable)
662 [m_textField setEditable:editable];
665 void wxNSTextFieldControl::GetSelection( long* from, long* to) const
667 NSText* editor = [m_textField currentEditor];
670 NSRange range = [editor selectedRange];
671 *from = range.location;
672 *to = range.location + range.length;
681 void wxNSTextFieldControl::SetSelection( long from , long to )
683 long textLength = [[m_textField stringValue] length];
684 if ((from == -1) && (to == -1))
691 from = wxMin(textLength,wxMax(from,0)) ;
695 to = wxMax(0,wxMin(textLength,to)) ;
698 NSText* editor = [m_textField currentEditor];
701 [editor setSelectedRange:NSMakeRange(from, to-from)];
710 void wxNSTextFieldControl::WriteText(const wxString& str)
712 NSEvent* formerEvent = m_lastKeyDownEvent;
713 m_lastKeyDownEvent = nil;
714 NSText* editor = [m_textField currentEditor];
717 wxMacEditHelper helper(m_textField);
718 [editor insertText:wxCFStringRef( str , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
722 wxString val = GetStringValue() ;
724 GetSelection( &start , &end ) ;
725 val.Remove( start , end - start ) ;
726 val.insert( start , str ) ;
727 SetStringValue( val ) ;
728 SetSelection( start + str.length() , start + str.length() ) ;
730 m_lastKeyDownEvent = formerEvent;
733 void wxNSTextFieldControl::controlAction(WXWidget WXUNUSED(slf),
734 void* WXUNUSED(_cmd), void *WXUNUSED(sender))
736 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
737 if ( wxpeer && (wxpeer->GetWindowStyle() & wxTE_PROCESS_ENTER) )
739 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, wxpeer->GetId());
740 event.SetEventObject( wxpeer );
741 event.SetString( GetTextEntry()->GetValue() );
742 wxpeer->HandleWindowEvent( event );
746 bool wxNSTextFieldControl::SetHint(const wxString& hint)
748 wxCFStringRef hintstring(hint);
749 [[m_textField cell] setPlaceholderString:hintstring.AsNSString()];
757 wxWidgetImplType* wxWidgetImpl::CreateTextControl( wxTextCtrl* wxpeer,
758 wxWindowMac* WXUNUSED(parent),
759 wxWindowID WXUNUSED(id),
760 const wxString& WXUNUSED(str),
764 long WXUNUSED(extraStyle))
766 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
767 wxWidgetCocoaImpl* c = NULL;
769 if ( style & wxTE_MULTILINE || style & wxTE_RICH || style & wxTE_RICH2 )
771 wxNSTextScrollView* v = nil;
772 v = [[wxNSTextScrollView alloc] initWithFrame:r];
773 c = new wxNSTextViewControl( wxpeer, v );
777 NSTextField* v = nil;
778 if ( style & wxTE_PASSWORD )
779 v = [[wxNSSecureTextField alloc] initWithFrame:r];
781 v = [[wxNSTextField alloc] initWithFrame:r];
783 if ( style & wxNO_BORDER )
785 // FIXME: How can we remove the native control's border?
786 // setBordered is separate from the text ctrl's border.
789 NSTextFieldCell* cell = [v cell];
790 [cell setScrollable:YES];
791 // TODO: Remove if we definitely are sure, it's not needed
792 // as setting scrolling to yes, should turn off any wrapping
793 // [cell setLineBreakMode:NSLineBreakByClipping];
798 c = new wxNSTextFieldControl( wxpeer, wxpeer, v );
800 c->SetNeedsFocusRect( true );
806 #endif // wxUSE_TEXTCTRL