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