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 if ( editor != fieldEditor )
264 [fieldEditor release];
265 fieldEditor = editor;
269 - (wxNSTextFieldEditor*) fieldEditor
274 - (void) setEnabled:(BOOL) flag
276 [super setEnabled: flag];
278 if (![self drawsBackground]) {
279 // Static text is drawn incorrectly when disabled.
280 // For an explanation, see
281 // http://www.cocoabuilder.com/archive/message/cocoa/2006/7/21/168028
283 [self setTextColor: [NSColor controlTextColor]];
285 [self setTextColor: [NSColor secondarySelectedControlColor]];
290 - (void)controlTextDidChange:(NSNotification *)aNotification
292 wxUnusedVar(aNotification);
293 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
295 impl->controlTextDidChange();
298 - (NSArray *)control:(NSControl *)control textView:(NSTextView *)textView completions:(NSArray *)words
299 forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(int*)index
301 NSMutableArray* matches = NULL;
303 wxTextWidgetImpl* impl = (wxNSTextFieldControl * ) wxWidgetImpl::FindFromWXWidget( self );
304 wxTextEntry * const entry = impl->GetTextEntry();
305 wxTextCompleter * const completer = entry->OSXGetCompleter();
308 const wxString prefix = entry->GetValue();
309 if ( completer->Start(prefix) )
312 wordStart = wxCFStringRef::AsString(
313 [[textView string] substringWithRange:charRange]
316 matches = [NSMutableArray array];
319 const wxString s = completer->GetNext();
323 // Normally the completer should return only the strings
324 // starting with the prefix, but there could be exceptions
325 // and, for compatibility with MSW which simply ignores all
326 // entries that don't match the current text control contents,
327 // we ignore them as well. Besides, our own wxTextCompleterFixed
328 // doesn't respect this rule and, moreover, we need to extract
329 // just the rest of the string anyhow.
331 if ( s.StartsWith(prefix, &completion) )
333 // We discarded the entire prefix above but actually we
334 // should include the part of it that consists of the
335 // beginning of the current word, otherwise it would be
336 // lost when completion is accepted as OS X supposes that
337 // our matches do start with the "partial word range"
339 const wxCFStringRef fullWord(wordStart + completion);
340 [matches addObject: fullWord.AsNSString()];
349 - (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector
351 wxUnusedVar(textView);
352 wxUnusedVar(control);
356 // send back key events wx' common code knows how to handle
358 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
361 wxWindow* wxpeer = (wxWindow*) impl->GetWXPeer();
364 if (commandSelector == @selector(insertNewline:))
366 [textView insertNewlineIgnoringFieldEditor:self];
369 else if ( commandSelector == @selector(insertTab:))
371 [textView insertTabIgnoringFieldEditor:self];
374 else if ( commandSelector == @selector(insertBacktab:))
376 [textView insertTabIgnoringFieldEditor:self];
385 - (void)controlTextDidEndEditing:(NSNotification *)aNotification
387 wxUnusedVar(aNotification);
388 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
391 impl->DoNotifyFocusEvent( false, NULL );
396 // wxNSTextViewControl
398 wxNSTextViewControl::wxNSTextViewControl( wxTextCtrl *wxPeer, WXWidget w )
399 : wxWidgetCocoaImpl(wxPeer, w),
400 wxTextWidgetImpl(wxPeer)
402 wxNSTextScrollView* sv = (wxNSTextScrollView*) w;
405 [m_scrollView setHasVerticalScroller:YES];
406 [m_scrollView setHasHorizontalScroller:NO];
407 [m_scrollView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
408 NSSize contentSize = [m_scrollView contentSize];
410 wxNSTextView* tv = [[wxNSTextView alloc] initWithFrame: NSMakeRect(0, 0,
411 contentSize.width, contentSize.height)];
413 [tv setVerticallyResizable:YES];
414 [tv setHorizontallyResizable:NO];
415 [tv setAutoresizingMask:NSViewWidthSizable];
417 [m_scrollView setDocumentView: tv];
419 [tv setDelegate: tv];
421 InstallEventHandler(tv);
424 wxNSTextViewControl::~wxNSTextViewControl()
427 [m_textView setDelegate: nil];
430 bool wxNSTextViewControl::CanFocus() const
432 // since this doesn't work (return false), we hardcode
434 // return [m_textView canBecomeKeyView];
438 wxString wxNSTextViewControl::GetStringValue() const
442 wxString result = wxCFStringRef::AsString([m_textView string], m_wxPeer->GetFont().GetEncoding());
443 wxMacConvertNewlines13To10( &result ) ;
446 return wxEmptyString;
448 void wxNSTextViewControl::SetStringValue( const wxString &str)
451 wxMacConvertNewlines10To13( &st );
452 wxMacEditHelper helper(m_textView);
455 [m_textView setString: wxCFStringRef( st , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
458 void wxNSTextViewControl::Copy()
461 [m_textView copy:nil];
465 void wxNSTextViewControl::Cut()
468 [m_textView cut:nil];
471 void wxNSTextViewControl::Paste()
474 [m_textView paste:nil];
477 bool wxNSTextViewControl::CanPaste() const
482 void wxNSTextViewControl::SetEditable(bool editable)
485 [m_textView setEditable: editable];
488 void wxNSTextViewControl::GetSelection( long* from, long* to) const
492 NSRange range = [m_textView selectedRange];
493 *from = range.location;
494 *to = range.location + range.length;
498 void wxNSTextViewControl::SetSelection( long from , long to )
500 long textLength = [[m_textView string] length];
501 if ((from == -1) && (to == -1))
508 from = wxMin(textLength,wxMax(from,0)) ;
512 to = wxMax(0,wxMin(textLength,to)) ;
515 NSRange selrange = NSMakeRange(from, to-from);
516 [m_textView setSelectedRange:selrange];
517 [m_textView scrollRangeToVisible:selrange];
520 void wxNSTextViewControl::WriteText(const wxString& str)
523 wxMacConvertNewlines10To13( &st );
524 wxMacEditHelper helper(m_textView);
525 NSEvent* formerEvent = m_lastKeyDownEvent;
526 m_lastKeyDownEvent = nil;
527 [m_textView insertText:wxCFStringRef( st , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
528 m_lastKeyDownEvent = formerEvent;
531 void wxNSTextViewControl::SetFont( const wxFont & font , const wxColour& WXUNUSED(foreground) , long WXUNUSED(windowStyle), bool WXUNUSED(ignoreBlack) )
533 if ([m_textView respondsToSelector:@selector(setFont:)])
534 [m_textView setFont: font.OSXGetNSFont()];
537 bool wxNSTextViewControl::GetStyle(long position, wxTextAttr& style)
539 if (m_textView && position >=0)
542 NSColor* bgcolor = NULL;
543 NSColor* fgcolor = NULL;
544 // NOTE: It appears that other platforms accept GetStyle with the position == length
545 // but that NSTextStorage does not accept length as a valid position.
546 // Therefore we return the default control style in that case.
547 if (position < (long) [[m_textView string] length])
549 NSTextStorage* storage = [m_textView textStorage];
550 font = [[storage attribute:NSFontAttributeName atIndex:position effectiveRange:NULL] autorelease];
551 bgcolor = [[storage attribute:NSBackgroundColorAttributeName atIndex:position effectiveRange:NULL] autorelease];
552 fgcolor = [[storage attribute:NSForegroundColorAttributeName atIndex:position effectiveRange:NULL] autorelease];
556 NSDictionary* attrs = [m_textView typingAttributes];
557 font = [[attrs objectForKey:NSFontAttributeName] autorelease];
558 bgcolor = [[attrs objectForKey:NSBackgroundColorAttributeName] autorelease];
559 fgcolor = [[attrs objectForKey:NSForegroundColorAttributeName] autorelease];
563 style.SetFont(wxFont(font));
566 style.SetBackgroundColour(wxColour(bgcolor));
569 style.SetTextColour(wxColour(fgcolor));
576 void wxNSTextViewControl::SetStyle(long start,
578 const wxTextAttr& style)
581 NSRange range = NSMakeRange(start, end-start);
582 if (start == -1 && end == -1)
583 range = [m_textView selectedRange];
585 NSTextStorage* storage = [m_textView textStorage];
587 wxFont font = style.GetFont();
588 if (style.HasFont() && font.IsOk())
589 [storage addAttribute:NSFontAttributeName value:font.OSXGetNSFont() range:range];
591 wxColour bgcolor = style.GetBackgroundColour();
592 if (style.HasBackgroundColour() && bgcolor.IsOk())
593 [storage addAttribute:NSBackgroundColorAttributeName value:bgcolor.OSXGetNSColor() range:range];
595 wxColour fgcolor = style.GetTextColour();
596 if (style.HasTextColour() && fgcolor.IsOk())
597 [storage addAttribute:NSForegroundColorAttributeName value:fgcolor.OSXGetNSColor() range:range];
601 void wxNSTextViewControl::CheckSpelling(bool check)
604 [m_textView setContinuousSpellCheckingEnabled: check];
607 wxSize wxNSTextViewControl::GetBestSize() const
609 if (m_textView && [m_textView layoutManager])
611 NSRect rect = [[m_textView layoutManager] usedRectForTextContainer: [m_textView textContainer]];
612 return wxSize((int)(rect.size.width + [m_textView textContainerInset].width),
613 (int)(rect.size.height + [m_textView textContainerInset].height));
618 // wxNSTextFieldControl
620 wxNSTextFieldControl::wxNSTextFieldControl( wxTextCtrl *text, WXWidget w )
621 : wxWidgetCocoaImpl(text, w),
622 wxTextWidgetImpl(text)
627 wxNSTextFieldControl::wxNSTextFieldControl(wxWindow *wxPeer,
630 : wxWidgetCocoaImpl(wxPeer, w),
631 wxTextWidgetImpl(entry)
636 void wxNSTextFieldControl::Init(WXWidget w)
638 NSTextField wxOSX_10_6_AND_LATER(<NSTextFieldDelegate>) *tf = (NSTextField wxOSX_10_6_AND_LATER(<NSTextFieldDelegate>)*) w;
640 [m_textField setDelegate: tf];
641 m_selStart = m_selEnd = 0;
642 m_hasEditor = [w isKindOfClass:[NSTextField class]];
645 wxNSTextFieldControl::~wxNSTextFieldControl()
648 [m_textField setDelegate: nil];
651 wxString wxNSTextFieldControl::GetStringValue() const
653 return wxCFStringRef::AsString([m_textField stringValue], m_wxPeer->GetFont().GetEncoding());
656 void wxNSTextFieldControl::SetStringValue( const wxString &str)
658 wxMacEditHelper helper(m_textField);
659 [m_textField setStringValue: wxCFStringRef( str , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
662 void wxNSTextFieldControl::Copy()
664 NSText* editor = [m_textField currentEditor];
671 void wxNSTextFieldControl::Cut()
673 NSText* editor = [m_textField currentEditor];
680 void wxNSTextFieldControl::Paste()
682 NSText* editor = [m_textField currentEditor];
689 bool wxNSTextFieldControl::CanPaste() const
694 void wxNSTextFieldControl::SetEditable(bool editable)
696 [m_textField setEditable:editable];
699 void wxNSTextFieldControl::GetSelection( long* from, long* to) const
701 NSText* editor = [m_textField currentEditor];
704 NSRange range = [editor selectedRange];
705 *from = range.location;
706 *to = range.location + range.length;
715 void wxNSTextFieldControl::SetSelection( long from , long to )
717 long textLength = [[m_textField stringValue] length];
718 if ((from == -1) && (to == -1))
725 from = wxMin(textLength,wxMax(from,0)) ;
729 to = wxMax(0,wxMin(textLength,to)) ;
732 NSText* editor = [m_textField currentEditor];
735 [editor setSelectedRange:NSMakeRange(from, to-from)];
744 void wxNSTextFieldControl::WriteText(const wxString& str)
746 NSEvent* formerEvent = m_lastKeyDownEvent;
747 m_lastKeyDownEvent = nil;
748 NSText* editor = [m_textField currentEditor];
751 wxMacEditHelper helper(m_textField);
752 [editor insertText:wxCFStringRef( str , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
756 wxString val = GetStringValue() ;
758 GetSelection( &start , &end ) ;
759 val.Remove( start , end - start ) ;
760 val.insert( start , str ) ;
761 SetStringValue( val ) ;
762 SetSelection( start + str.length() , start + str.length() ) ;
764 m_lastKeyDownEvent = formerEvent;
767 void wxNSTextFieldControl::controlAction(WXWidget WXUNUSED(slf),
768 void* WXUNUSED(_cmd), void *WXUNUSED(sender))
770 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
771 if ( wxpeer && (wxpeer->GetWindowStyle() & wxTE_PROCESS_ENTER) )
773 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, wxpeer->GetId());
774 event.SetEventObject( wxpeer );
775 event.SetString( GetTextEntry()->GetValue() );
776 wxpeer->HandleWindowEvent( event );
780 bool wxNSTextFieldControl::SetHint(const wxString& hint)
782 wxCFStringRef hintstring(hint);
783 [[m_textField cell] setPlaceholderString:hintstring.AsNSString()];
791 wxWidgetImplType* wxWidgetImpl::CreateTextControl( wxTextCtrl* wxpeer,
792 wxWindowMac* WXUNUSED(parent),
793 wxWindowID WXUNUSED(id),
794 const wxString& WXUNUSED(str),
798 long WXUNUSED(extraStyle))
800 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
801 wxWidgetCocoaImpl* c = NULL;
803 if ( style & wxTE_MULTILINE || style & wxTE_RICH || style & wxTE_RICH2 )
805 wxNSTextScrollView* v = nil;
806 v = [[wxNSTextScrollView alloc] initWithFrame:r];
807 c = new wxNSTextViewControl( wxpeer, v );
811 NSTextField* v = nil;
812 if ( style & wxTE_PASSWORD )
813 v = [[wxNSSecureTextField alloc] initWithFrame:r];
815 v = [[wxNSTextField alloc] initWithFrame:r];
817 if ( style & wxNO_BORDER )
819 // FIXME: How can we remove the native control's border?
820 // setBordered is separate from the text ctrl's border.
823 NSTextFieldCell* cell = [v cell];
824 [cell setScrollable:YES];
825 // TODO: Remove if we definitely are sure, it's not needed
826 // as setting scrolling to yes, should turn off any wrapping
827 // [cell setLineBreakMode:NSLineBreakByClipping];
832 c = new wxNSTextFieldControl( wxpeer, wxpeer, v );
834 c->SetNeedsFocusRect( true );
840 #endif // wxUSE_TEXTCTRL