]> git.saurik.com Git - wxWidgets.git/blame - src/osx/cocoa/textctrl.mm
notify the event loop that synthesized events are on the queue, wait for them to...
[wxWidgets.git] / src / osx / cocoa / textctrl.mm
CommitLineData
dbeddfb9
SC
1/////////////////////////////////////////////////////////////////////////////
2// Name: src/osx/cocoa/textctrl.mm
3// Purpose: wxTextCtrl
4// Author: Stefan Csomor
5// Modified by: Ryan Norton (MLTE GetLineLength and GetLineText)
6// Created: 1998-01-01
a9a4f229 7// RCS-ID: $Id$
dbeddfb9
SC
8// Copyright: (c) Stefan Csomor
9// Licence: wxWindows licence
10/////////////////////////////////////////////////////////////////////////////
11
12#include "wx/wxprec.h"
13
14#if wxUSE_TEXTCTRL
15
16#include "wx/textctrl.h"
17
18#ifndef WX_PRECOMP
19 #include "wx/intl.h"
20 #include "wx/app.h"
21 #include "wx/utils.h"
22 #include "wx/dc.h"
23 #include "wx/button.h"
24 #include "wx/menu.h"
25 #include "wx/settings.h"
26 #include "wx/msgdlg.h"
27 #include "wx/toplevel.h"
28#endif
29
30#ifdef __DARWIN__
31 #include <sys/types.h>
32 #include <sys/stat.h>
33#else
34 #include <stat.h>
35#endif
36
37#if wxUSE_STD_IOSTREAM
38 #if wxUSE_IOSTREAMH
39 #include <fstream.h>
40 #else
41 #include <fstream>
42 #endif
43#endif
44
45#include "wx/filefn.h"
46#include "wx/sysopt.h"
47#include "wx/thread.h"
c729f16f 48#include "wx/textcompleter.h"
dbeddfb9
SC
49
50#include "wx/osx/private.h"
1e181c7a 51#include "wx/osx/cocoa/private/textimpl.h"
dbeddfb9 52
03647350 53@interface NSView(EditableView)
5f65ba36
SC
54- (BOOL)isEditable;
55- (void)setEditable:(BOOL)flag;
816b2941
SC
56- (BOOL)isSelectable;
57- (void)setSelectable:(BOOL)flag;
5f65ba36
SC
58@end
59
66fc8b0e
VZ
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.
5f65ba36
SC
65class wxMacEditHelper
66{
67public :
68 wxMacEditHelper( NSView* textView )
69 {
66fc8b0e
VZ
70 m_viewPreviouslyEdited = ms_viewCurrentlyEdited;
71 ms_viewCurrentlyEdited =
63bcc669 72 m_textView = textView;
816b2941 73 m_formerEditable = YES;
5f65ba36
SC
74 if ( textView )
75 {
816b2941
SC
76 m_formerEditable = [textView isEditable];
77 m_formerSelectable = [textView isSelectable];
5f65ba36
SC
78 [textView setEditable:YES];
79 }
80 }
81
82 ~wxMacEditHelper()
83 {
84 if ( m_textView )
816b2941
SC
85 {
86 [m_textView setEditable:m_formerEditable];
87 [m_textView setSelectable:m_formerSelectable];
88 }
66fc8b0e
VZ
89
90 ms_viewCurrentlyEdited = m_viewPreviouslyEdited;
5f65ba36
SC
91 }
92
66fc8b0e
VZ
93 // Returns the last view we were instantiated for or NULL.
94 static NSView *GetCurrentlyEditedView() { return ms_viewCurrentlyEdited; }
95
5f65ba36 96protected :
816b2941
SC
97 BOOL m_formerEditable ;
98 BOOL m_formerSelectable;
5f65ba36 99 NSView* m_textView;
66fc8b0e
VZ
100
101 // The original value of ms_viewCurrentlyEdited when this object was
102 // created.
103 NSView* m_viewPreviouslyEdited;
104
105 static NSView* ms_viewCurrentlyEdited;
5f65ba36
SC
106} ;
107
66fc8b0e
VZ
108NSView* wxMacEditHelper::ms_viewCurrentlyEdited = nil;
109
9c71750d
SC
110// a minimal NSFormatter that just avoids getting too long entries
111@interface wxMaximumLengthFormatter : NSFormatter
112{
113 int maxLength;
114}
115
116@end
117
118@implementation wxMaximumLengthFormatter
119
120- (id)init
121{
6e884381 122 self = [super init];
9c71750d
SC
123 maxLength = 0;
124 return self;
125}
126
127- (void) setMaxLength:(int) maxlen
128{
129 maxLength = maxlen;
130}
131
132- (NSString *)stringForObjectValue:(id)anObject
133{
134 if(![anObject isKindOfClass:[NSString class]])
135 return nil;
136 return [NSString stringWithString:anObject];
137}
138
139- (BOOL)getObjectValue:(id *)obj forString:(NSString *)string errorDescription:(NSString **)error
140{
141 *obj = [NSString stringWithString:string];
142 return YES;
143}
144
145- (BOOL)isPartialStringValid:(NSString **)partialStringPtr proposedSelectedRange:(NSRangePointer)proposedSelRangePtr
146 originalString:(NSString *)origString originalSelectedRange:(NSRange)origSelRange errorDescription:(NSString **)error
147{
148 int len = [*partialStringPtr length];
149 if ( maxLength > 0 && len > maxLength )
150 {
ce7fe42e 151 // TODO wxEVT_TEXT_MAXLEN
9c71750d
SC
152 return NO;
153 }
154 return YES;
155}
156
157@end
158
03647350 159@implementation wxNSSecureTextField
dbeddfb9 160
4dd9fdf8
SC
161+ (void)initialize
162{
163 static BOOL initialized = NO;
03647350 164 if (!initialized)
4dd9fdf8
SC
165 {
166 initialized = YES;
167 wxOSXCocoaClassAddWXMethods( self );
168 }
169}
dbeddfb9 170
4d23a0d3
KO
171- (void)controlTextDidChange:(NSNotification *)aNotification
172{
6331c8c0
SC
173 wxUnusedVar(aNotification);
174 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
4d23a0d3 175 if ( impl )
75a2c6a1 176 impl->controlTextDidChange();
4d23a0d3
KO
177}
178
6d109846
SC
179- (void)controlTextDidEndEditing:(NSNotification *)aNotification
180{
181 wxUnusedVar(aNotification);
182 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
183 if ( impl )
184 {
60d66be3 185 NSResponder * responder = wxNonOwnedWindowCocoaImpl::GetNextFirstResponder();
e17d84e1 186 NSView* otherView = wxOSXGetViewFromResponder(responder);
60d66be3 187
e17d84e1 188 wxWidgetImpl* otherWindow = impl->FindBestFromWXWidget(otherView);
60d66be3 189 impl->DoNotifyFocusEvent( false, otherWindow );
6d109846
SC
190 }
191}
192
a2ce6469
SC
193- (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector
194{
195 wxUnusedVar(textView);
196
197 BOOL handled = NO;
198
199 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( control );
200 if ( impl )
201 {
202 wxWindow* wxpeer = (wxWindow*) impl->GetWXPeer();
203 if ( wxpeer )
204 {
205 if (commandSelector == @selector(insertNewline:))
206 {
207 wxTopLevelWindow *tlw = wxDynamicCast(wxGetTopLevelParent(wxpeer), wxTopLevelWindow);
208 if ( tlw && tlw->GetDefaultItem() )
209 {
210 wxButton *def = wxDynamicCast(tlw->GetDefaultItem(), wxButton);
211 if ( def && def->IsEnabled() )
212 {
ce7fe42e 213 wxCommandEvent event(wxEVT_BUTTON, def->GetId() );
a2ce6469
SC
214 event.SetEventObject(def);
215 def->Command(event);
216 handled = YES;
217 }
218 }
219 }
220 }
221 }
222
223 return handled;
224}
225
e32090ba
SC
226@end
227
1087c6c1 228@interface wxNSTextScrollView : NSScrollView
4d23a0d3 229{
4d23a0d3 230}
1087c6c1
SC
231@end
232
1087c6c1 233@implementation wxNSTextScrollView
c824c165
KO
234
235+ (void)initialize
236{
237 static BOOL initialized = NO;
03647350
VZ
238 if (!initialized)
239 {
c824c165
KO
240 initialized = YES;
241 wxOSXCocoaClassAddWXMethods( self );
242 }
243}
244
7cb2a241
SC
245@end
246
247@implementation wxNSTextFieldEditor
248
249- (void) keyDown:(NSEvent*) event
4d23a0d3 250{
9e55f38d 251 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
7cb2a241
SC
252 lastKeyDownEvent = event;
253 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
254 [super keyDown:event];
255 lastKeyDownEvent = nil;
4d23a0d3 256}
533e2ae1 257
7cb2a241 258- (void) keyUp:(NSEvent*) event
533e2ae1 259{
9e55f38d 260 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
7cb2a241
SC
261 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
262 [super keyUp:event];
533e2ae1 263}
1087c6c1 264
7cb2a241 265- (void) flagsChanged:(NSEvent*) event
1087c6c1 266{
9e55f38d 267 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
7cb2a241
SC
268 if ( impl == NULL || !impl->DoHandleKeyEvent(event) )
269 [super flagsChanged:event];
1087c6c1 270}
1087c6c1 271
7cb2a241
SC
272- (BOOL) performKeyEquivalent:(NSEvent*) event
273{
274 BOOL retval = [super performKeyEquivalent:event];
275 return retval;
276}
1087c6c1 277
7cb2a241 278- (void) insertText:(id) str
1087c6c1 279{
9e55f38d 280 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( (WXWidget) [self delegate] );
7cb2a241 281 if ( impl == NULL || lastKeyDownEvent==nil || !impl->DoHandleCharEvent(lastKeyDownEvent, str) )
1087c6c1 282 {
7cb2a241 283 [super insertText:str];
1087c6c1 284 }
1087c6c1
SC
285}
286
7cb2a241
SC
287@end
288
289@implementation wxNSTextView
1087c6c1 290
7cb2a241 291+ (void)initialize
1087c6c1 292{
7cb2a241 293 static BOOL initialized = NO;
03647350 294 if (!initialized)
7cb2a241
SC
295 {
296 initialized = YES;
297 wxOSXCocoaClassAddWXMethods( self );
298 }
1087c6c1
SC
299}
300
b9cf2753
KO
301- (void)textDidChange:(NSNotification *)aNotification
302{
75a2c6a1
KO
303 wxUnusedVar(aNotification);
304 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
b9cf2753 305 if ( impl )
75a2c6a1 306 impl->controlTextDidChange();
b9cf2753
KO
307}
308
816b2941
SC
309- (void) setEnabled:(BOOL) flag
310{
311 // from Technical Q&A QA1461
312 if (flag) {
313 [self setTextColor: [NSColor controlTextColor]];
314
315 } else {
316 [self setTextColor: [NSColor disabledControlTextColor]];
317 }
318
319 [self setSelectable: flag];
320 [self setEditable: flag];
321}
322
323- (BOOL) isEnabled
324{
325 return [self isEditable];
326}
327
9159a257
SC
328- (void)textDidEndEditing:(NSNotification *)aNotification
329{
330 wxUnusedVar(aNotification);
66fc8b0e
VZ
331
332 if ( self == wxMacEditHelper::GetCurrentlyEditedView() )
333 {
334 // This notification is generated as the result of calling our own
335 // wxTextCtrl method (e.g. WriteText()) and doesn't correspond to any
336 // real focus loss event so skip generating it.
337 return;
338 }
339
9159a257
SC
340 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
341 if ( impl )
342 {
60d66be3 343 NSResponder * responder = wxNonOwnedWindowCocoaImpl::GetNextFirstResponder();
e17d84e1 344 NSView* otherView = wxOSXGetViewFromResponder(responder);
60d66be3 345
e17d84e1 346 wxWidgetImpl* otherWindow = impl->FindBestFromWXWidget(otherView);
60d66be3 347 impl->DoNotifyFocusEvent( false, otherWindow );
9159a257
SC
348 }
349}
350
c824c165
KO
351@end
352
e32090ba 353@implementation wxNSTextField
ffad7b0d 354
e32090ba 355+ (void)initialize
dbeddfb9 356{
e32090ba 357 static BOOL initialized = NO;
03647350 358 if (!initialized)
e32090ba
SC
359 {
360 initialized = YES;
361 wxOSXCocoaClassAddWXMethods( self );
362 }
dbeddfb9 363}
e32090ba 364
7cb2a241
SC
365- (id) initWithFrame:(NSRect) frame
366{
367 self = [super initWithFrame:frame];
368 fieldEditor = nil;
369 return self;
370}
371
af665c2d
SC
372- (void) dealloc
373{
374 [fieldEditor release];
375 [super dealloc];
376}
377
7cb2a241
SC
378- (void) setFieldEditor:(wxNSTextFieldEditor*) editor
379{
c2a22141
SC
380 if ( editor != fieldEditor )
381 {
382 [editor retain];
383 [fieldEditor release];
384 fieldEditor = editor;
385 }
7cb2a241
SC
386}
387
388- (wxNSTextFieldEditor*) fieldEditor
389{
390 return fieldEditor;
391}
392
c3e433b1
SC
393- (void) setEnabled:(BOOL) flag
394{
395 [super setEnabled: flag];
396
397 if (![self drawsBackground]) {
398 // Static text is drawn incorrectly when disabled.
399 // For an explanation, see
400 // http://www.cocoabuilder.com/archive/message/cocoa/2006/7/21/168028
401 if (flag) {
402 [self setTextColor: [NSColor controlTextColor]];
403 } else {
404 [self setTextColor: [NSColor secondarySelectedControlColor]];
405 }
406 }
407}
4d23a0d3 408
ffad7b0d
SC
409- (void)controlTextDidChange:(NSNotification *)aNotification
410{
6331c8c0
SC
411 wxUnusedVar(aNotification);
412 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
ffad7b0d 413 if ( impl )
75a2c6a1 414 impl->controlTextDidChange();
ffad7b0d 415}
dbeddfb9 416
00ba1af9 417- (NSArray *)control:(NSControl *)control textView:(NSTextView *)textView completions:(NSArray *)words
b4bdde87 418 forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger*)index
00ba1af9
SC
419{
420 NSMutableArray* matches = NULL;
00ba1af9 421
c729f16f
VZ
422 wxTextWidgetImpl* impl = (wxNSTextFieldControl * ) wxWidgetImpl::FindFromWXWidget( self );
423 wxTextEntry * const entry = impl->GetTextEntry();
424 wxTextCompleter * const completer = entry->OSXGetCompleter();
425 if ( completer )
426 {
427 const wxString prefix = entry->GetValue();
428 if ( completer->Start(prefix) )
429 {
430 const wxString
431 wordStart = wxCFStringRef::AsString(
432 [[textView string] substringWithRange:charRange]
433 );
434
435 matches = [NSMutableArray array];
436 for ( ;; )
437 {
438 const wxString s = completer->GetNext();
439 if ( s.empty() )
440 break;
441
442 // Normally the completer should return only the strings
443 // starting with the prefix, but there could be exceptions
444 // and, for compatibility with MSW which simply ignores all
445 // entries that don't match the current text control contents,
446 // we ignore them as well. Besides, our own wxTextCompleterFixed
447 // doesn't respect this rule and, moreover, we need to extract
448 // just the rest of the string anyhow.
449 wxString completion;
450 if ( s.StartsWith(prefix, &completion) )
451 {
452 // We discarded the entire prefix above but actually we
453 // should include the part of it that consists of the
454 // beginning of the current word, otherwise it would be
455 // lost when completion is accepted as OS X supposes that
456 // our matches do start with the "partial word range"
457 // passed to us.
458 const wxCFStringRef fullWord(wordStart + completion);
459 [matches addObject: fullWord.AsNSString()];
460 }
461 }
462 }
463 }
464
00ba1af9
SC
465 return matches;
466}
467
76b1a2c2
SC
468- (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector
469{
470 wxUnusedVar(textView);
471 wxUnusedVar(control);
472
473 BOOL handled = NO;
474
475 // send back key events wx' common code knows how to handle
476
477 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
478 if ( impl )
479 {
480 wxWindow* wxpeer = (wxWindow*) impl->GetWXPeer();
481 if ( wxpeer )
482 {
483 if (commandSelector == @selector(insertNewline:))
484 {
485 [textView insertNewlineIgnoringFieldEditor:self];
486 handled = YES;
487 }
488 else if ( commandSelector == @selector(insertTab:))
489 {
490 [textView insertTabIgnoringFieldEditor:self];
491 handled = YES;
492 }
493 else if ( commandSelector == @selector(insertBacktab:))
494 {
495 [textView insertTabIgnoringFieldEditor:self];
496 handled = YES;
497 }
498 }
499 }
500
501 return handled;
502}
503
ffad7b0d
SC
504- (void)controlTextDidEndEditing:(NSNotification *)aNotification
505{
6d109846
SC
506 wxUnusedVar(aNotification);
507 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
ffad7b0d
SC
508 if ( impl )
509 {
8e64b8fe
SC
510 wxNSTextFieldControl* timpl = dynamic_cast<wxNSTextFieldControl*>(impl);
511 if ( fieldEditor )
512 {
513 NSRange range = [fieldEditor selectedRange];
514 timpl->SetInternalSelection(range.location, range.location + range.length);
515 }
516
60d66be3 517 NSResponder * responder = wxNonOwnedWindowCocoaImpl::GetNextFirstResponder();
e17d84e1 518 NSView* otherView = wxOSXGetViewFromResponder(responder);
60d66be3 519
e17d84e1 520 wxWidgetImpl* otherWindow = impl->FindBestFromWXWidget(otherView);
60d66be3 521 impl->DoNotifyFocusEvent( false, otherWindow );
ffad7b0d
SC
522 }
523}
dbeddfb9
SC
524@end
525
c824c165
KO
526// wxNSTextViewControl
527
c072b9ec
VZ
528wxNSTextViewControl::wxNSTextViewControl( wxTextCtrl *wxPeer, WXWidget w )
529 : wxWidgetCocoaImpl(wxPeer, w),
530 wxTextWidgetImpl(wxPeer)
c824c165 531{
1087c6c1
SC
532 wxNSTextScrollView* sv = (wxNSTextScrollView*) w;
533 m_scrollView = sv;
03647350 534
c824c165
KO
535 [m_scrollView setHasVerticalScroller:YES];
536 [m_scrollView setHasHorizontalScroller:NO];
1e70e497
SC
537 // TODO Remove if no regression, this was causing automatic resizes of multi-line textfields when the tlw changed
538 // [m_scrollView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
c824c165 539 NSSize contentSize = [m_scrollView contentSize];
03647350 540
1087c6c1 541 wxNSTextView* tv = [[wxNSTextView alloc] initWithFrame: NSMakeRect(0, 0,
c824c165 542 contentSize.width, contentSize.height)];
1087c6c1
SC
543 m_textView = tv;
544 [tv setVerticallyResizable:YES];
545 [tv setHorizontallyResizable:NO];
546 [tv setAutoresizingMask:NSViewWidthSizable];
03647350 547
1087c6c1 548 [m_scrollView setDocumentView: tv];
c824c165 549
b9cf2753 550 [tv setDelegate: tv];
03647350
VZ
551
552 InstallEventHandler(tv);
c824c165
KO
553}
554
555wxNSTextViewControl::~wxNSTextViewControl()
556{
557 if (m_textView)
558 [m_textView setDelegate: nil];
559}
560
78a17075
KO
561bool wxNSTextViewControl::CanFocus() const
562{
81533a3a
SC
563 // since this doesn't work (return false), we hardcode
564 // if (m_textView)
565 // return [m_textView canBecomeKeyView];
566 return true;
78a17075
KO
567}
568
03647350 569wxString wxNSTextViewControl::GetStringValue() const
c824c165 570{
03647350 571 if (m_textView)
c824c165 572 {
f66ecdc4 573 wxString result = wxCFStringRef::AsString([m_textView string], m_wxPeer->GetFont().GetEncoding());
50b5e38d
SC
574 wxMacConvertNewlines13To10( &result ) ;
575 return result;
c824c165
KO
576 }
577 return wxEmptyString;
578}
03647350 579void wxNSTextViewControl::SetStringValue( const wxString &str)
c824c165 580{
50b5e38d
SC
581 wxString st = str;
582 wxMacConvertNewlines10To13( &st );
5f65ba36 583 wxMacEditHelper helper(m_textView);
50b5e38d 584
c824c165 585 if (m_textView)
50b5e38d 586 [m_textView setString: wxCFStringRef( st , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
c824c165 587}
7cb2a241 588
03647350 589void wxNSTextViewControl::Copy()
c824c165
KO
590{
591 if (m_textView)
592 [m_textView copy:nil];
593
594}
595
03647350 596void wxNSTextViewControl::Cut()
c824c165
KO
597{
598 if (m_textView)
599 [m_textView cut:nil];
600}
601
03647350 602void wxNSTextViewControl::Paste()
c824c165
KO
603{
604 if (m_textView)
605 [m_textView paste:nil];
606}
607
03647350
VZ
608bool wxNSTextViewControl::CanPaste() const
609{
c824c165
KO
610 return true;
611}
612
03647350 613void wxNSTextViewControl::SetEditable(bool editable)
c824c165
KO
614{
615 if (m_textView)
616 [m_textView setEditable: editable];
617}
618
03647350 619void wxNSTextViewControl::GetSelection( long* from, long* to) const
c824c165
KO
620{
621 if (m_textView)
622 {
623 NSRange range = [m_textView selectedRange];
624 *from = range.location;
625 *to = range.location + range.length;
626 }
627}
628
629void wxNSTextViewControl::SetSelection( long from , long to )
630{
50b5e38d
SC
631 long textLength = [[m_textView string] length];
632 if ((from == -1) && (to == -1))
633 {
634 from = 0 ;
635 to = textLength ;
636 }
637 else
638 {
639 from = wxMin(textLength,wxMax(from,0)) ;
640 if ( to == -1 )
641 to = textLength;
642 else
643 to = wxMax(0,wxMin(textLength,to)) ;
644 }
645
2d6aa919
KO
646 NSRange selrange = NSMakeRange(from, to-from);
647 [m_textView setSelectedRange:selrange];
648 [m_textView scrollRangeToVisible:selrange];
c824c165
KO
649}
650
03647350 651void wxNSTextViewControl::WriteText(const wxString& str)
c824c165 652{
50b5e38d
SC
653 wxString st = str;
654 wxMacConvertNewlines10To13( &st );
5f65ba36 655 wxMacEditHelper helper(m_textView);
715824d5
SC
656 NSEvent* formerEvent = m_lastKeyDownEvent;
657 m_lastKeyDownEvent = nil;
50b5e38d 658 [m_textView insertText:wxCFStringRef( st , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
715824d5 659 m_lastKeyDownEvent = formerEvent;
c824c165
KO
660}
661
63bcc669 662void wxNSTextViewControl::SetFont( const wxFont & font , const wxColour& WXUNUSED(foreground) , long WXUNUSED(windowStyle), bool WXUNUSED(ignoreBlack) )
f95dd972
SC
663{
664 if ([m_textView respondsToSelector:@selector(setFont:)])
665 [m_textView setFont: font.OSXGetNSFont()];
666}
667
16671f22
KO
668bool wxNSTextViewControl::GetStyle(long position, wxTextAttr& style)
669{
b9cf2753
KO
670 if (m_textView && position >=0)
671 {
672 NSFont* font = NULL;
673 NSColor* bgcolor = NULL;
674 NSColor* fgcolor = NULL;
675 // NOTE: It appears that other platforms accept GetStyle with the position == length
676 // but that NSTextStorage does not accept length as a valid position.
677 // Therefore we return the default control style in that case.
0f54a3be 678 if (position < (long) [[m_textView string] length])
b9cf2753
KO
679 {
680 NSTextStorage* storage = [m_textView textStorage];
681 font = [[storage attribute:NSFontAttributeName atIndex:position effectiveRange:NULL] autorelease];
682 bgcolor = [[storage attribute:NSBackgroundColorAttributeName atIndex:position effectiveRange:NULL] autorelease];
683 fgcolor = [[storage attribute:NSForegroundColorAttributeName atIndex:position effectiveRange:NULL] autorelease];
684 }
685 else
686 {
687 NSDictionary* attrs = [m_textView typingAttributes];
688 font = [[attrs objectForKey:NSFontAttributeName] autorelease];
689 bgcolor = [[attrs objectForKey:NSBackgroundColorAttributeName] autorelease];
690 fgcolor = [[attrs objectForKey:NSForegroundColorAttributeName] autorelease];
691 }
692
16671f22
KO
693 if (font)
694 style.SetFont(wxFont(font));
b9cf2753 695
16671f22
KO
696 if (bgcolor)
697 style.SetBackgroundColour(wxColour(bgcolor));
b9cf2753
KO
698
699 if (fgcolor)
700 style.SetTextColour(wxColour(fgcolor));
16671f22
KO
701 return true;
702 }
703
704 return false;
705}
706
707void wxNSTextViewControl::SetStyle(long start,
708 long end,
709 const wxTextAttr& style)
710{
1659164a
VZ
711 if ( !m_textView )
712 return;
713
714 if ( start == -1 && end == -1 )
715 {
716 NSMutableDictionary* const
717 attrs = [NSMutableDictionary dictionaryWithCapacity:3];
718 if ( style.HasFont() )
719 [attrs setValue:style.GetFont().OSXGetNSFont() forKey:NSFontAttributeName];
720 if ( style.HasBackgroundColour() )
721 [attrs setValue:style.GetBackgroundColour().OSXGetNSColor() forKey:NSBackgroundColorAttributeName];
722 if ( style.HasTextColour() )
723 [attrs setValue:style.GetTextColour().OSXGetNSColor() forKey:NSForegroundColorAttributeName];
724
725 [m_textView setTypingAttributes:attrs];
726 }
727 else // Set the attributes just for this range.
728 {
16671f22 729 NSRange range = NSMakeRange(start, end-start);
b9cf2753 730
16671f22 731 NSTextStorage* storage = [m_textView textStorage];
dfc9124f
VZ
732 if ( style.HasFont() )
733 [storage addAttribute:NSFontAttributeName value:style.GetFont().OSXGetNSFont() range:range];
734
735 if ( style.HasBackgroundColour() )
736 [storage addAttribute:NSBackgroundColorAttributeName value:style.GetBackgroundColour().OSXGetNSColor() range:range];
1659164a 737
dfc9124f
VZ
738 if ( style.HasTextColour() )
739 [storage addAttribute:NSForegroundColorAttributeName value:style.GetTextColour().OSXGetNSColor() range:range];
16671f22
KO
740 }
741}
f95dd972 742
b9cf2753
KO
743void wxNSTextViewControl::CheckSpelling(bool check)
744{
745 if (m_textView)
746 [m_textView setContinuousSpellCheckingEnabled: check];
747}
748
9ab7ff53
KO
749wxSize wxNSTextViewControl::GetBestSize() const
750{
751 if (m_textView && [m_textView layoutManager])
752 {
753 NSRect rect = [[m_textView layoutManager] usedRectForTextContainer: [m_textView textContainer]];
4a49fa24
VZ
754 return wxSize((int)(rect.size.width + [m_textView textContainerInset].width),
755 (int)(rect.size.height + [m_textView textContainerInset].height));
9ab7ff53 756 }
c8fdb345 757 return wxSize(0,0);
9ab7ff53
KO
758}
759
c824c165
KO
760// wxNSTextFieldControl
761
c072b9ec
VZ
762wxNSTextFieldControl::wxNSTextFieldControl( wxTextCtrl *text, WXWidget w )
763 : wxWidgetCocoaImpl(text, w),
764 wxTextWidgetImpl(text)
765{
c8eab84f 766 Init(w);
c072b9ec
VZ
767}
768
769wxNSTextFieldControl::wxNSTextFieldControl(wxWindow *wxPeer,
770 wxTextEntry *entry,
771 WXWidget w)
772 : wxWidgetCocoaImpl(wxPeer, w),
773 wxTextWidgetImpl(entry)
774{
c8eab84f 775 Init(w);
c072b9ec
VZ
776}
777
778void wxNSTextFieldControl::Init(WXWidget w)
1e181c7a 779{
c2a22141 780 NSTextField wxOSX_10_6_AND_LATER(<NSTextFieldDelegate>) *tf = (NSTextField wxOSX_10_6_AND_LATER(<NSTextFieldDelegate>)*) w;
c8fdb345
SC
781 m_textField = tf;
782 [m_textField setDelegate: tf];
50b5e38d 783 m_selStart = m_selEnd = 0;
7cb2a241 784 m_hasEditor = [w isKindOfClass:[NSTextField class]];
1e181c7a
SC
785}
786
787wxNSTextFieldControl::~wxNSTextFieldControl()
788{
c824c165
KO
789 if (m_textField)
790 [m_textField setDelegate: nil];
1e181c7a
SC
791}
792
03647350 793wxString wxNSTextFieldControl::GetStringValue() const
1e181c7a 794{
f66ecdc4 795 return wxCFStringRef::AsString([m_textField stringValue], m_wxPeer->GetFont().GetEncoding());
1e181c7a 796}
50b5e38d 797
03647350 798void wxNSTextFieldControl::SetStringValue( const wxString &str)
1e181c7a 799{
5f65ba36 800 wxMacEditHelper helper(m_textField);
e32090ba 801 [m_textField setStringValue: wxCFStringRef( str , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
1e181c7a 802}
50b5e38d 803
9c71750d
SC
804void wxNSTextFieldControl::SetMaxLength(unsigned long len)
805{
806 wxMaximumLengthFormatter* formatter = [[[wxMaximumLengthFormatter alloc] init] autorelease];
807 [formatter setMaxLength:len];
808 [m_textField setFormatter:formatter];
809}
810
03647350 811void wxNSTextFieldControl::Copy()
1e181c7a 812{
e32090ba
SC
813 NSText* editor = [m_textField currentEditor];
814 if ( editor )
815 {
816 [editor copy:nil];
817 }
1e181c7a
SC
818}
819
03647350 820void wxNSTextFieldControl::Cut()
1e181c7a 821{
e32090ba
SC
822 NSText* editor = [m_textField currentEditor];
823 if ( editor )
824 {
825 [editor cut:nil];
826 }
1e181c7a
SC
827}
828
03647350 829void wxNSTextFieldControl::Paste()
1e181c7a 830{
e32090ba
SC
831 NSText* editor = [m_textField currentEditor];
832 if ( editor )
833 {
834 [editor paste:nil];
835 }
1e181c7a
SC
836}
837
03647350
VZ
838bool wxNSTextFieldControl::CanPaste() const
839{
e32090ba 840 return true;
1e181c7a
SC
841}
842
03647350 843void wxNSTextFieldControl::SetEditable(bool editable)
1e181c7a 844{
e32090ba 845 [m_textField setEditable:editable];
1e181c7a
SC
846}
847
03647350 848void wxNSTextFieldControl::GetSelection( long* from, long* to) const
1e181c7a 849{
e32090ba
SC
850 NSText* editor = [m_textField currentEditor];
851 if ( editor )
852 {
853 NSRange range = [editor selectedRange];
854 *from = range.location;
855 *to = range.location + range.length;
856 }
50b5e38d
SC
857 else
858 {
859 *from = m_selStart;
860 *to = m_selEnd;
861 }
1e181c7a
SC
862}
863
864void wxNSTextFieldControl::SetSelection( long from , long to )
865{
50b5e38d
SC
866 long textLength = [[m_textField stringValue] length];
867 if ((from == -1) && (to == -1))
868 {
869 from = 0 ;
870 to = textLength ;
871 }
872 else
873 {
874 from = wxMin(textLength,wxMax(from,0)) ;
875 if ( to == -1 )
876 to = textLength;
877 else
878 to = wxMax(0,wxMin(textLength,to)) ;
879 }
880
e32090ba
SC
881 NSText* editor = [m_textField currentEditor];
882 if ( editor )
883 {
884 [editor setSelectedRange:NSMakeRange(from, to-from)];
885 }
8e64b8fe
SC
886
887 // the editor might still be in existence, but we might be already passed our 'focus lost' storage
888 // of the selection, so make sure we copy this
889 m_selStart = from;
890 m_selEnd = to;
1e181c7a
SC
891}
892
03647350 893void wxNSTextFieldControl::WriteText(const wxString& str)
1e181c7a 894{
715824d5
SC
895 NSEvent* formerEvent = m_lastKeyDownEvent;
896 m_lastKeyDownEvent = nil;
50b5e38d
SC
897 NSText* editor = [m_textField currentEditor];
898 if ( editor )
899 {
5f65ba36 900 wxMacEditHelper helper(m_textField);
b5b98611
SC
901 BOOL hasUndo = [editor respondsToSelector:@selector(setAllowsUndo:)];
902 if ( hasUndo )
529f35ff 903 [(NSTextView*)editor setAllowsUndo:NO];
50b5e38d 904 [editor insertText:wxCFStringRef( str , m_wxPeer->GetFont().GetEncoding() ).AsNSString()];
b5b98611 905 if ( hasUndo )
529f35ff 906 [(NSTextView*)editor setAllowsUndo:YES];
50b5e38d
SC
907 }
908 else
909 {
910 wxString val = GetStringValue() ;
911 long start , end ;
912 GetSelection( &start , &end ) ;
913 val.Remove( start , end - start ) ;
914 val.insert( start , str ) ;
915 SetStringValue( val ) ;
916 SetSelection( start + str.length() , start + str.length() ) ;
917 }
715824d5 918 m_lastKeyDownEvent = formerEvent;
1e181c7a 919}
dbeddfb9 920
03647350 921void wxNSTextFieldControl::controlAction(WXWidget WXUNUSED(slf),
6331c8c0 922 void* WXUNUSED(_cmd), void *WXUNUSED(sender))
e32090ba
SC
923{
924 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
03647350 925 if ( wxpeer && (wxpeer->GetWindowStyle() & wxTE_PROCESS_ENTER) )
e32090ba 926 {
ce7fe42e 927 wxCommandEvent event(wxEVT_TEXT_ENTER, wxpeer->GetId());
e32090ba 928 event.SetEventObject( wxpeer );
c072b9ec 929 event.SetString( GetTextEntry()->GetValue() );
e32090ba
SC
930 wxpeer->HandleWindowEvent( event );
931 }
932}
933
8e64b8fe
SC
934void wxNSTextFieldControl::SetInternalSelection( long from , long to )
935{
936 m_selStart = from;
937 m_selEnd = to;
938}
939
1e70e497
SC
940// as becoming first responder on a window - triggers a resign on the same control, we have to avoid
941// the resign notification writing back native selection values before we can set our own
942
943static WXWidget s_widgetBecomingFirstResponder = nil;
944
945bool wxNSTextFieldControl::becomeFirstResponder(WXWidget slf, void *_cmd)
946{
947 s_widgetBecomingFirstResponder = slf;
948 bool retval = wxWidgetCocoaImpl::becomeFirstResponder(slf, _cmd);
949 s_widgetBecomingFirstResponder = nil;
950 if ( retval )
951 {
952 NSText* editor = [m_textField currentEditor];
953 if ( editor )
8e64b8fe
SC
954 {
955 long textLength = [[m_textField stringValue] length];
956 m_selStart = wxMin(textLength,wxMax(m_selStart,0)) ;
957 m_selEnd = wxMax(0,wxMin(textLength,m_selEnd)) ;
958
1e70e497 959 [editor setSelectedRange:NSMakeRange(m_selStart, m_selEnd-m_selStart)];
8e64b8fe 960 }
1e70e497
SC
961 }
962 return retval;
963}
964
965bool wxNSTextFieldControl::resignFirstResponder(WXWidget slf, void *_cmd)
966{
967 if ( slf != s_widgetBecomingFirstResponder )
968 {
969 NSText* editor = [m_textField currentEditor];
970 if ( editor )
971 {
972 NSRange range = [editor selectedRange];
973 m_selStart = range.location;
974 m_selEnd = range.location + range.length;
975 }
976 }
977 return wxWidgetCocoaImpl::resignFirstResponder(slf, _cmd);
978}
979
99eb484a
SC
980bool wxNSTextFieldControl::SetHint(const wxString& hint)
981{
982 wxCFStringRef hintstring(hint);
983 [[m_textField cell] setPlaceholderString:hintstring.AsNSString()];
984 return true;
985}
986
e32090ba
SC
987//
988//
989//
990
03647350
VZ
991wxWidgetImplType* wxWidgetImpl::CreateTextControl( wxTextCtrl* wxpeer,
992 wxWindowMac* WXUNUSED(parent),
993 wxWindowID WXUNUSED(id),
63bcc669 994 const wxString& WXUNUSED(str),
03647350 995 const wxPoint& pos,
dbeddfb9 996 const wxSize& size,
03647350 997 long style,
6331c8c0 998 long WXUNUSED(extraStyle))
dbeddfb9 999{
dbeddfb9 1000 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
c824c165 1001 wxWidgetCocoaImpl* c = NULL;
03647350 1002
98c90969 1003 if ( style & wxTE_MULTILINE )
b15f9375 1004 {
1087c6c1
SC
1005 wxNSTextScrollView* v = nil;
1006 v = [[wxNSTextScrollView alloc] initWithFrame:r];
c824c165 1007 c = new wxNSTextViewControl( wxpeer, v );
58cab5e2 1008 c->SetNeedsFocusRect( true );
c824c165 1009 }
03647350 1010 else
c824c165 1011 {
6331c8c0 1012 NSTextField* v = nil;
c824c165
KO
1013 if ( style & wxTE_PASSWORD )
1014 v = [[wxNSSecureTextField alloc] initWithFrame:r];
1015 else
1016 v = [[wxNSTextField alloc] initWithFrame:r];
03647350 1017
d68a2a24
SC
1018 if ( style & wxTE_RIGHT)
1019 {
1020 [v setAlignment:NSRightTextAlignment];
1021 }
1022 else if ( style & wxTE_CENTRE)
1023 {
1024 [v setAlignment:NSCenterTextAlignment];
1025 }
58cab5e2 1026
3f16e51b
SC
1027 NSTextFieldCell* cell = [v cell];
1028 [cell setScrollable:YES];
1029 // TODO: Remove if we definitely are sure, it's not needed
1030 // as setting scrolling to yes, should turn off any wrapping
1031 // [cell setLineBreakMode:NSLineBreakByClipping];
03647350 1032
c072b9ec 1033 c = new wxNSTextFieldControl( wxpeer, wxpeer, v );
58cab5e2
SC
1034
1035 if ( (style & wxNO_BORDER) || (style & wxSIMPLE_BORDER) )
1036 {
1037 // under 10.7 the textcontrol can draw its own focus
1038 // even if no border is shown, on previous systems
1039 // we have to emulate this
1040 [v setBezeled:NO];
1041 [v setBordered:NO];
1042 if ( UMAGetSystemVersion() < 0x1070 )
1043 c->SetNeedsFocusRect( true );
1044 }
1045 else
1046 {
1047 // use native border
1048 c->SetNeedsFrame(false);
1049 }
b15f9375 1050 }
03647350 1051
dbeddfb9
SC
1052 return c;
1053}
1054
1055
1056#endif // wxUSE_TEXTCTRL