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;
63 wxMacEditHelper( NSView* textView )
65 m_textView = textView;
66 m_formerEditable = YES;
69 m_formerEditable = [textView isEditable];
70 m_formerSelectable = [textView isSelectable];
71 [textView setEditable:YES];
79 [m_textView setEditable:m_formerEditable];
80 [m_textView setSelectable:m_formerSelectable];
85 BOOL m_formerEditable ;
86 BOOL m_formerSelectable;
90 @implementation wxNSSecureTextField
94 static BOOL initialized = NO;
98 wxOSXCocoaClassAddWXMethods( self );
102 - (void)controlTextDidChange:(NSNotification *)aNotification
104 wxUnusedVar(aNotification);
105 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
107 impl->controlTextDidChange();
110 - (void)controlTextDidEndEditing:(NSNotification *)aNotification
112 wxUnusedVar(aNotification);
113 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
116 impl->DoNotifyFocusEvent( false, NULL );
122 @interface wxNSTextScrollView : NSScrollView
127 @implementation wxNSTextScrollView
131 static BOOL initialized = NO;
135 wxOSXCocoaClassAddWXMethods( self );
141 @implementation wxNSTextFieldEditor
143 - (void) keyDown:(NSEvent*) event
145 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
146 lastKeyDownEvent = event;
147 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
148 [super keyDown:event];
149 lastKeyDownEvent = nil;
152 - (void) keyUp:(NSEvent*) event
154 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
155 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
159 - (void) flagsChanged:(NSEvent*) event
161 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
162 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
163 [super flagsChanged:event];
166 - (BOOL) performKeyEquivalent:(NSEvent*) event
168 BOOL retval = [super performKeyEquivalent:event];
172 - (void) insertText:(id) str
174 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
175 if ( impl == NULL || lastKeyDownEvent==nil || !impl->DoHandleCharEvent(lastKeyDownEvent, str) )
177 [super insertText:str];
183 @implementation wxNSTextView
187 static BOOL initialized = NO;
191 wxOSXCocoaClassAddWXMethods( self );
195 - (void)textDidChange:(NSNotification *)aNotification
197 wxUnusedVar(aNotification);
198 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
200 impl->controlTextDidChange();
203 - (void) setEnabled:(BOOL) flag
205 // from Technical Q&A QA1461
207 [self setTextColor: [NSColor controlTextColor]];
210 [self setTextColor: [NSColor disabledControlTextColor]];
213 [self setSelectable: flag];
214 [self setEditable: flag];
219 return [self isEditable];
222 - (void)textDidEndEditing:(NSNotification *)aNotification
224 wxUnusedVar(aNotification);
225 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
228 impl->DoNotifyFocusEvent( false, NULL );
234 @implementation wxNSTextField
238 static BOOL initialized = NO;
242 wxOSXCocoaClassAddWXMethods( self );
246 - (id) initWithFrame:(NSRect) frame
248 self = [super initWithFrame:frame];
255 [fieldEditor release];
259 - (void) setFieldEditor:(wxNSTextFieldEditor*) editor
261 fieldEditor = editor;
264 - (wxNSTextFieldEditor*) fieldEditor
269 - (void) setEnabled:(BOOL) flag
271 [super setEnabled: flag];
273 if (![self drawsBackground]) {
274 // Static text is drawn incorrectly when disabled.
275 // For an explanation, see
276 // http://www.cocoabuilder.com/archive/message/cocoa/2006/7/21/168028
278 [self setTextColor: [NSColor controlTextColor]];
280 [self setTextColor: [NSColor secondarySelectedControlColor]];
285 - (void)controlTextDidChange:(NSNotification *)aNotification
287 wxUnusedVar(aNotification);
288 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
290 impl->controlTextDidChange();
293 - (NSArray *)control:(NSControl *)control textView:(NSTextView *)textView completions:(NSArray *)words
294 forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(int*)index
296 NSMutableArray* matches = NULL;
298 wxTextWidgetImpl* impl = (wxNSTextFieldControl * ) wxWidgetImpl::FindFromWXWidget( self );
299 wxTextEntry * const entry = impl->GetTextEntry();
300 wxTextCompleter * const completer = entry->OSXGetCompleter();
303 const wxString prefix = entry->GetValue();
304 if ( completer->Start(prefix) )
307 wordStart = wxCFStringRef::AsString(
308 [[textView string] substringWithRange:charRange]
311 matches = [NSMutableArray array];
314 const wxString s = completer->GetNext();
318 // Normally the completer should return only the strings
319 // starting with the prefix, but there could be exceptions
320 // and, for compatibility with MSW which simply ignores all
321 // entries that don't match the current text control contents,
322 // we ignore them as well. Besides, our own wxTextCompleterFixed
323 // doesn't respect this rule and, moreover, we need to extract
324 // just the rest of the string anyhow.
326 if ( s.StartsWith(prefix, &completion) )
328 // We discarded the entire prefix above but actually we
329 // should include the part of it that consists of the
330 // beginning of the current word, otherwise it would be
331 // lost when completion is accepted as OS X supposes that
332 // our matches do start with the "partial word range"
334 const wxCFStringRef fullWord(wordStart + completion);
335 [matches addObject: fullWord.AsNSString()];
344 - (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector
346 wxUnusedVar(textView);
347 wxUnusedVar(control);
351 // send back key events wx' common code knows how to handle
353 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
356 wxWindow* wxpeer = (wxWindow*) impl->GetWXPeer();
359 if (commandSelector == @selector(insertNewline:))
361 [textView insertNewlineIgnoringFieldEditor:self];
364 else if ( commandSelector == @selector(insertTab:))
366 [textView insertTabIgnoringFieldEditor:self];
369 else if ( commandSelector == @selector(insertBacktab:))
371 [textView insertTabIgnoringFieldEditor:self];
380 - (void)controlTextDidEndEditing:(NSNotification *)aNotification
382 wxUnusedVar(aNotification);
383 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
386 impl->DoNotifyFocusEvent( false, NULL );
391 // wxNSTextViewControl
393 wxNSTextViewControl::wxNSTextViewControl( wxTextCtrl *wxPeer, WXWidget w )
394 : wxWidgetCocoaImpl(wxPeer, w),
395 wxTextWidgetImpl(wxPeer)
397 wxNSTextScrollView* sv = (wxNSTextScrollView*) w;
400 [m_scrollView setHasVerticalScroller:YES];
401 [m_scrollView setHasHorizontalScroller:NO];
402 [m_scrollView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
403 NSSize contentSize = [m_scrollView contentSize];
405 wxNSTextView* tv = [[wxNSTextView alloc] initWithFrame: NSMakeRect(0, 0,
406 contentSize.width, contentSize.height)];
408 [tv setVerticallyResizable:YES];
409 [tv setHorizontallyResizable:NO];
410 [tv setAutoresizingMask:NSViewWidthSizable];
412 [m_scrollView setDocumentView: tv];
414 [tv setDelegate: tv];
416 InstallEventHandler(tv);
419 wxNSTextViewControl::~wxNSTextViewControl()
422 [m_textView setDelegate: nil];
425 bool wxNSTextViewControl::CanFocus() const
427 // since this doesn't work (return false), we hardcode
429 // return [m_textView canBecomeKeyView];
433 wxString wxNSTextViewControl::GetStringValue() const
437 wxString result = wxCFStringRef::AsString([m_textView string], m_wxPeer->GetFont().GetEncoding());
438 wxMacConvertNewlines13To10( &result ) ;
441 return wxEmptyString;
443 void wxNSTextViewControl::SetStringValue( const wxString &str)
446 wxMacConvertNewlines10To13( &st );
447 wxMacEditHelper helper(m_textView);
450 [m_textView setString: wxCFStringRef( st , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
453 void wxNSTextViewControl::Copy()
456 [m_textView copy:nil];
460 void wxNSTextViewControl::Cut()
463 [m_textView cut:nil];
466 void wxNSTextViewControl::Paste()
469 [m_textView paste:nil];
472 bool wxNSTextViewControl::CanPaste() const
477 void wxNSTextViewControl::SetEditable(bool editable)
480 [m_textView setEditable: editable];
483 void wxNSTextViewControl::GetSelection( long* from, long* to) const
487 NSRange range = [m_textView selectedRange];
488 *from = range.location;
489 *to = range.location + range.length;
493 void wxNSTextViewControl::SetSelection( long from , long to )
495 long textLength = [[m_textView string] length];
496 if ((from == -1) && (to == -1))
503 from = wxMin(textLength,wxMax(from,0)) ;
507 to = wxMax(0,wxMin(textLength,to)) ;
510 NSRange selrange = NSMakeRange(from, to-from);
511 [m_textView setSelectedRange:selrange];
512 [m_textView scrollRangeToVisible:selrange];
515 void wxNSTextViewControl::WriteText(const wxString& str)
518 wxMacConvertNewlines10To13( &st );
519 wxMacEditHelper helper(m_textView);
520 NSEvent* formerEvent = m_lastKeyDownEvent;
521 m_lastKeyDownEvent = nil;
522 [m_textView insertText:wxCFStringRef( st , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
523 m_lastKeyDownEvent = formerEvent;
526 void wxNSTextViewControl::SetFont( const wxFont & font , const wxColour& WXUNUSED(foreground) , long WXUNUSED(windowStyle), bool WXUNUSED(ignoreBlack) )
528 if ([m_textView respondsToSelector:@selector(setFont:)])
529 [m_textView setFont: font.OSXGetNSFont()];
532 bool wxNSTextViewControl::GetStyle(long position, wxTextAttr& style)
534 if (m_textView && position >=0)
537 NSColor* bgcolor = NULL;
538 NSColor* fgcolor = NULL;
539 // NOTE: It appears that other platforms accept GetStyle with the position == length
540 // but that NSTextStorage does not accept length as a valid position.
541 // Therefore we return the default control style in that case.
542 if (position < (long) [[m_textView string] length])
544 NSTextStorage* storage = [m_textView textStorage];
545 font = [[storage attribute:NSFontAttributeName atIndex:position effectiveRange:NULL] autorelease];
546 bgcolor = [[storage attribute:NSBackgroundColorAttributeName atIndex:position effectiveRange:NULL] autorelease];
547 fgcolor = [[storage attribute:NSForegroundColorAttributeName atIndex:position effectiveRange:NULL] autorelease];
551 NSDictionary* attrs = [m_textView typingAttributes];
552 font = [[attrs objectForKey:NSFontAttributeName] autorelease];
553 bgcolor = [[attrs objectForKey:NSBackgroundColorAttributeName] autorelease];
554 fgcolor = [[attrs objectForKey:NSForegroundColorAttributeName] autorelease];
558 style.SetFont(wxFont(font));
561 style.SetBackgroundColour(wxColour(bgcolor));
564 style.SetTextColour(wxColour(fgcolor));
571 void wxNSTextViewControl::SetStyle(long start,
573 const wxTextAttr& style)
576 NSRange range = NSMakeRange(start, end-start);
577 if (start == -1 && end == -1)
578 range = [m_textView selectedRange];
580 NSTextStorage* storage = [m_textView textStorage];
582 wxFont font = style.GetFont();
583 if (style.HasFont() && font.IsOk())
584 [storage addAttribute:NSFontAttributeName value:font.OSXGetNSFont() range:range];
586 wxColour bgcolor = style.GetBackgroundColour();
587 if (style.HasBackgroundColour() && bgcolor.IsOk())
588 [storage addAttribute:NSBackgroundColorAttributeName value:bgcolor.OSXGetNSColor() range:range];
590 wxColour fgcolor = style.GetTextColour();
591 if (style.HasTextColour() && fgcolor.IsOk())
592 [storage addAttribute:NSForegroundColorAttributeName value:fgcolor.OSXGetNSColor() range:range];
596 void wxNSTextViewControl::CheckSpelling(bool check)
599 [m_textView setContinuousSpellCheckingEnabled: check];
602 wxSize wxNSTextViewControl::GetBestSize() const
604 if (m_textView && [m_textView layoutManager])
606 NSRect rect = [[m_textView layoutManager] usedRectForTextContainer: [m_textView textContainer]];
607 return wxSize((int)(rect.size.width + [m_textView textContainerInset].width),
608 (int)(rect.size.height + [m_textView textContainerInset].height));
613 // wxNSTextFieldControl
615 wxNSTextFieldControl::wxNSTextFieldControl( wxTextCtrl *text, WXWidget w )
616 : wxWidgetCocoaImpl(text, w),
617 wxTextWidgetImpl(text)
622 wxNSTextFieldControl::wxNSTextFieldControl(wxWindow *wxPeer,
625 : wxWidgetCocoaImpl(wxPeer, w),
626 wxTextWidgetImpl(entry)
631 void wxNSTextFieldControl::Init(WXWidget w)
633 NSTextField wxOSX_10_6_AND_LATER(<NSTextFieldDelegate>) *tf = (NSTextField*) w;
635 [m_textField setDelegate: tf];
636 m_selStart = m_selEnd = 0;
637 m_hasEditor = [w isKindOfClass:[NSTextField class]];
640 wxNSTextFieldControl::~wxNSTextFieldControl()
643 [m_textField setDelegate: nil];
646 wxString wxNSTextFieldControl::GetStringValue() const
648 return wxCFStringRef::AsString([m_textField stringValue], m_wxPeer->GetFont().GetEncoding());
651 void wxNSTextFieldControl::SetStringValue( const wxString &str)
653 wxMacEditHelper helper(m_textField);
654 [m_textField setStringValue: wxCFStringRef( str , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
657 void wxNSTextFieldControl::Copy()
659 NSText* editor = [m_textField currentEditor];
666 void wxNSTextFieldControl::Cut()
668 NSText* editor = [m_textField currentEditor];
675 void wxNSTextFieldControl::Paste()
677 NSText* editor = [m_textField currentEditor];
684 bool wxNSTextFieldControl::CanPaste() const
689 void wxNSTextFieldControl::SetEditable(bool editable)
691 [m_textField setEditable:editable];
694 void wxNSTextFieldControl::GetSelection( long* from, long* to) const
696 NSText* editor = [m_textField currentEditor];
699 NSRange range = [editor selectedRange];
700 *from = range.location;
701 *to = range.location + range.length;
710 void wxNSTextFieldControl::SetSelection( long from , long to )
712 long textLength = [[m_textField stringValue] length];
713 if ((from == -1) && (to == -1))
720 from = wxMin(textLength,wxMax(from,0)) ;
724 to = wxMax(0,wxMin(textLength,to)) ;
727 NSText* editor = [m_textField currentEditor];
730 [editor setSelectedRange:NSMakeRange(from, to-from)];
739 void wxNSTextFieldControl::WriteText(const wxString& str)
741 NSEvent* formerEvent = m_lastKeyDownEvent;
742 m_lastKeyDownEvent = nil;
743 NSText* editor = [m_textField currentEditor];
746 wxMacEditHelper helper(m_textField);
747 [editor insertText:wxCFStringRef( str , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
751 wxString val = GetStringValue() ;
753 GetSelection( &start , &end ) ;
754 val.Remove( start , end - start ) ;
755 val.insert( start , str ) ;
756 SetStringValue( val ) ;
757 SetSelection( start + str.length() , start + str.length() ) ;
759 m_lastKeyDownEvent = formerEvent;
762 void wxNSTextFieldControl::controlAction(WXWidget WXUNUSED(slf),
763 void* WXUNUSED(_cmd), void *WXUNUSED(sender))
765 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
766 if ( wxpeer && (wxpeer->GetWindowStyle() & wxTE_PROCESS_ENTER) )
768 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, wxpeer->GetId());
769 event.SetEventObject( wxpeer );
770 event.SetString( GetTextEntry()->GetValue() );
771 wxpeer->HandleWindowEvent( event );
775 bool wxNSTextFieldControl::SetHint(const wxString& hint)
777 wxCFStringRef hintstring(hint);
778 [[m_textField cell] setPlaceholderString:hintstring.AsNSString()];
786 wxWidgetImplType* wxWidgetImpl::CreateTextControl( wxTextCtrl* wxpeer,
787 wxWindowMac* WXUNUSED(parent),
788 wxWindowID WXUNUSED(id),
789 const wxString& WXUNUSED(str),
793 long WXUNUSED(extraStyle))
795 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
796 wxWidgetCocoaImpl* c = NULL;
798 if ( style & wxTE_MULTILINE || style & wxTE_RICH || style & wxTE_RICH2 )
800 wxNSTextScrollView* v = nil;
801 v = [[wxNSTextScrollView alloc] initWithFrame:r];
802 c = new wxNSTextViewControl( wxpeer, v );
806 NSTextField* v = nil;
807 if ( style & wxTE_PASSWORD )
808 v = [[wxNSSecureTextField alloc] initWithFrame:r];
810 v = [[wxNSTextField alloc] initWithFrame:r];
812 if ( style & wxNO_BORDER )
814 // FIXME: How can we remove the native control's border?
815 // setBordered is separate from the text ctrl's border.
818 NSTextFieldCell* cell = [v cell];
819 [cell setScrollable:YES];
820 // TODO: Remove if we definitely are sure, it's not needed
821 // as setting scrolling to yes, should turn off any wrapping
822 // [cell setLineBreakMode:NSLineBreakByClipping];
827 c = new wxNSTextFieldControl( wxpeer, wxpeer, v );
829 c->SetNeedsFocusRect( true );
835 #endif // wxUSE_TEXTCTRL