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