]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/osx/cocoa/window.mm
Fix install_name_tool calls in OS X "make install".
[wxWidgets.git] / src / osx / cocoa / window.mm
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: src/osx/cocoa/window.mm
3// Purpose: widgets (non tlw) for cocoa
4// Author: Stefan Csomor
5// Modified by:
6// Created: 2008-06-20
7// Copyright: (c) Stefan Csomor
8// Licence: wxWindows licence
9/////////////////////////////////////////////////////////////////////////////
10
11#include "wx/wxprec.h"
12
13#ifndef WX_PRECOMP
14 #include "wx/dcclient.h"
15 #include "wx/frame.h"
16 #include "wx/log.h"
17 #include "wx/textctrl.h"
18 #include "wx/combobox.h"
19 #include "wx/radiobut.h"
20#endif
21
22#ifdef __WXMAC__
23 #include "wx/osx/private.h"
24#endif
25
26#include "wx/evtloop.h"
27
28#if wxUSE_CARET
29 #include "wx/caret.h"
30#endif
31
32#if wxUSE_DRAG_AND_DROP
33 #include "wx/dnd.h"
34#endif
35
36#if wxUSE_TOOLTIPS
37 #include "wx/tooltip.h"
38#endif
39
40#include <objc/objc-runtime.h>
41
42// Get the window with the focus
43
44NSView* wxOSXGetViewFromResponder( NSResponder* responder )
45{
46 NSView* view = nil;
47 if ( [responder isKindOfClass:[NSTextView class]] )
48 {
49 NSView* delegate = (NSView*) [(NSTextView*)responder delegate];
50 if ( [delegate isKindOfClass:[NSTextField class] ] )
51 view = delegate;
52 else
53 view = (NSView*) responder;
54 }
55 else
56 {
57 if ( [responder isKindOfClass:[NSView class]] )
58 view = (NSView*) responder;
59 }
60 return view;
61}
62
63NSView* GetFocusedViewInWindow( NSWindow* keyWindow )
64{
65 NSView* focusedView = nil;
66 if ( keyWindow != nil )
67 focusedView = wxOSXGetViewFromResponder([keyWindow firstResponder]);
68
69 return focusedView;
70}
71
72WXWidget wxWidgetImpl::FindFocus()
73{
74 return GetFocusedViewInWindow( [NSApp keyWindow] );;
75}
76
77wxWidgetImpl* wxWidgetImpl::FindBestFromWXWidget(WXWidget control)
78{
79 wxWidgetImpl* impl = FindFromWXWidget(control);
80
81 // NSScrollViews can have their subviews like NSClipView
82 // therefore check and use the NSScrollView peer in that case
83 if ( impl == NULL && [[control superview] isKindOfClass:[NSScrollView class]])
84 impl = FindFromWXWidget([control superview]);
85
86 return impl;
87}
88
89
90NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
91{
92 int x, y, w, h ;
93
94 window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
95 wxRect bounds(x,y,w,h);
96 NSView* sv = (window->GetParent()->GetHandle() );
97
98 return wxToNSRect( sv, bounds );
99}
100
101@interface wxNSView : NSView
102{
103 BOOL _hasToolTip;
104 NSTrackingRectTag _lastToolTipTrackTag;
105 id _lastToolTipOwner;
106 void* _lastUserData;
107
108}
109
110@end // wxNSView
111
112@interface wxNSView(TextInput) <NSTextInputClient>
113
114- (void)insertText:(id)aString replacementRange:(NSRange)replacementRange;
115- (void)doCommandBySelector:(SEL)aSelector;
116- (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange;
117- (void)unmarkText;
118- (NSRange)selectedRange;
119- (NSRange)markedRange;
120- (BOOL)hasMarkedText;
121- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange;
122- (NSArray*)validAttributesForMarkedText;
123- (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange;
124- (NSUInteger)characterIndexForPoint:(NSPoint)aPoint;
125
126@end
127
128@interface NSView(PossibleMethods)
129- (void)setTitle:(NSString *)aString;
130- (void)setStringValue:(NSString *)aString;
131- (void)setIntValue:(int)anInt;
132- (void)setFloatValue:(float)aFloat;
133- (void)setDoubleValue:(double)aDouble;
134
135- (double)minValue;
136- (double)maxValue;
137- (void)setMinValue:(double)aDouble;
138- (void)setMaxValue:(double)aDouble;
139
140- (void)sizeToFit;
141
142- (BOOL)isEnabled;
143- (void)setEnabled:(BOOL)flag;
144
145- (void)setImage:(NSImage *)image;
146- (void)setControlSize:(NSControlSize)size;
147
148- (void)setFont:(NSFont *)fontObject;
149
150- (id)contentView;
151
152- (void)setTarget:(id)anObject;
153- (void)setAction:(SEL)aSelector;
154- (void)setDoubleAction:(SEL)aSelector;
155- (void)setBackgroundColor:(NSColor*)aColor;
156- (void)setOpaque:(BOOL)opaque;
157- (void)setTextColor:(NSColor *)color;
158- (void)setImagePosition:(NSCellImagePosition)aPosition;
159@end
160
161// The following code is a combination of the code listed here:
162// http://lists.apple.com/archives/cocoa-dev/2008/Apr/msg01582.html
163// (which can't be used because KLGetCurrentKeyboardLayout etc aren't 64-bit)
164// and the code here:
165// http://inquisitivecocoa.com/category/objective-c/
166@interface NSEvent (OsGuiUtilsAdditions)
167- (NSString*) charactersIgnoringModifiersIncludingShift;
168@end
169
170@implementation NSEvent (OsGuiUtilsAdditions)
171- (NSString*) charactersIgnoringModifiersIncludingShift {
172 // First try -charactersIgnoringModifiers and look for keys which UCKeyTranslate translates
173 // differently than AppKit.
174 NSString* c = [self charactersIgnoringModifiers];
175 if ([c length] == 1) {
176 unichar codepoint = [c characterAtIndex:0];
177 if ((codepoint >= 0xF700 && codepoint <= 0xF8FF) || codepoint == 0x7F) {
178 return c;
179 }
180 }
181 // This is not a "special" key, so ask UCKeyTranslate to give us the character with no
182 // modifiers attached. Actually, that's not quite accurate; we attach the Command modifier
183 // which hints the OS to use Latin characters where possible, which is generally what we want.
184 NSString* result = @"";
185 TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
186 CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
187 CFRelease(currentKeyboard);
188 if (uchr == NULL) {
189 // this can happen for some non-U.S. input methods (eg. Romaji or Hiragana)
190 return c;
191 }
192 const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
193 if (keyboardLayout) {
194 UInt32 deadKeyState = 0;
195 UniCharCount maxStringLength = 255;
196 UniCharCount actualStringLength = 0;
197 UniChar unicodeString[maxStringLength];
198
199 OSStatus status = UCKeyTranslate(keyboardLayout,
200 [self keyCode],
201 kUCKeyActionDown,
202 cmdKey >> 8, // force the Command key to "on"
203 LMGetKbdType(),
204 kUCKeyTranslateNoDeadKeysMask,
205 &deadKeyState,
206 maxStringLength,
207 &actualStringLength,
208 unicodeString);
209
210 if(status == noErr)
211 result = [NSString stringWithCharacters:unicodeString length:(NSInteger)actualStringLength];
212 }
213 return result;
214}
215@end
216
217long wxOSXTranslateCocoaKey( NSEvent* event, int eventType )
218{
219 long retval = 0;
220
221 if ([event type] != NSFlagsChanged)
222 {
223 NSString* s = [event charactersIgnoringModifiersIncludingShift];
224 // backspace char reports as delete w/modifiers for some reason
225 if ([s length] == 1)
226 {
227 if ( eventType == wxEVT_CHAR && ([event modifierFlags] & NSControlKeyMask) && ( [s characterAtIndex:0] >= 'a' && [s characterAtIndex:0] <= 'z' ) )
228 {
229 retval = WXK_CONTROL_A + ([s characterAtIndex:0] - 'a');
230 }
231 else
232 {
233 switch ( [s characterAtIndex:0] )
234 {
235 // backspace key
236 case 0x7F :
237 case 8 :
238 retval = WXK_BACK;
239 break;
240 case NSUpArrowFunctionKey :
241 retval = WXK_UP;
242 break;
243 case NSDownArrowFunctionKey :
244 retval = WXK_DOWN;
245 break;
246 case NSLeftArrowFunctionKey :
247 retval = WXK_LEFT;
248 break;
249 case NSRightArrowFunctionKey :
250 retval = WXK_RIGHT;
251 break;
252 case NSInsertFunctionKey :
253 retval = WXK_INSERT;
254 break;
255 case NSDeleteFunctionKey :
256 retval = WXK_DELETE;
257 break;
258 case NSHomeFunctionKey :
259 retval = WXK_HOME;
260 break;
261 // case NSBeginFunctionKey :
262 // retval = WXK_BEGIN;
263 // break;
264 case NSEndFunctionKey :
265 retval = WXK_END;
266 break;
267 case NSPageUpFunctionKey :
268 retval = WXK_PAGEUP;
269 break;
270 case NSPageDownFunctionKey :
271 retval = WXK_PAGEDOWN;
272 break;
273 case NSHelpFunctionKey :
274 retval = WXK_HELP;
275 break;
276 default:
277 int intchar = [s characterAtIndex: 0];
278 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
279 retval = WXK_F1 + (intchar - NSF1FunctionKey );
280 else if ( intchar > 0 && intchar < 32 )
281 retval = intchar;
282 break;
283 }
284 }
285 }
286 }
287
288 // Some keys don't seem to have constants. The code mimics the approach
289 // taken by WebKit. See:
290 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
291 switch( [event keyCode] )
292 {
293 // command key
294 case 54:
295 case 55:
296 retval = WXK_CONTROL;
297 break;
298 // caps locks key
299 case 57: // Capslock
300 retval = WXK_CAPITAL;
301 break;
302 // shift key
303 case 56: // Left Shift
304 case 60: // Right Shift
305 retval = WXK_SHIFT;
306 break;
307 // alt key
308 case 58: // Left Alt
309 case 61: // Right Alt
310 retval = WXK_ALT;
311 break;
312 // ctrl key
313 case 59: // Left Ctrl
314 case 62: // Right Ctrl
315 retval = WXK_RAW_CONTROL;
316 break;
317 // clear key
318 case 71:
319 retval = WXK_CLEAR;
320 break;
321 // tab key
322 case 48:
323 retval = WXK_TAB;
324 break;
325 default:
326 break;
327 }
328
329 // Check for NUMPAD keys. For KEY_UP/DOWN events we need to use the
330 // WXK_NUMPAD constants, but for the CHAR event we want to use the
331 // standard ascii values
332 if ( eventType != wxEVT_CHAR )
333 {
334 switch( [event keyCode] )
335 {
336 case 75: // /
337 retval = WXK_NUMPAD_DIVIDE;
338 break;
339 case 67: // *
340 retval = WXK_NUMPAD_MULTIPLY;
341 break;
342 case 78: // -
343 retval = WXK_NUMPAD_SUBTRACT;
344 break;
345 case 69: // +
346 retval = WXK_NUMPAD_ADD;
347 break;
348 case 76: // Enter
349 retval = WXK_NUMPAD_ENTER;
350 break;
351 case 65: // .
352 retval = WXK_NUMPAD_DECIMAL;
353 break;
354 case 82: // 0
355 retval = WXK_NUMPAD0;
356 break;
357 case 83: // 1
358 retval = WXK_NUMPAD1;
359 break;
360 case 84: // 2
361 retval = WXK_NUMPAD2;
362 break;
363 case 85: // 3
364 retval = WXK_NUMPAD3;
365 break;
366 case 86: // 4
367 retval = WXK_NUMPAD4;
368 break;
369 case 87: // 5
370 retval = WXK_NUMPAD5;
371 break;
372 case 88: // 6
373 retval = WXK_NUMPAD6;
374 break;
375 case 89: // 7
376 retval = WXK_NUMPAD7;
377 break;
378 case 91: // 8
379 retval = WXK_NUMPAD8;
380 break;
381 case 92: // 9
382 retval = WXK_NUMPAD9;
383 break;
384 default:
385 //retval = [event keyCode];
386 break;
387 }
388 }
389 return retval;
390}
391
392void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
393{
394 UInt32 modifiers = [nsEvent modifierFlags] ;
395 int eventType = [nsEvent type];
396
397 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
398 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
399 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
400 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
401
402 wxevent.m_rawCode = [nsEvent keyCode];
403 wxevent.m_rawFlags = modifiers;
404
405 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
406
407 wxString chars;
408 if ( eventType != NSFlagsChanged )
409 {
410 NSString* nschars = [[nsEvent charactersIgnoringModifiersIncludingShift] uppercaseString];
411 if ( charString )
412 {
413 // if charString is set, it did not come from key up / key down
414 wxevent.SetEventType( wxEVT_CHAR );
415 chars = wxCFStringRef::AsString(charString);
416 }
417 else if ( nschars )
418 {
419 chars = wxCFStringRef::AsString(nschars);
420 }
421 }
422
423 int aunichar = chars.Length() > 0 ? chars[0] : 0;
424 long keyval = 0;
425
426 if (wxevent.GetEventType() != wxEVT_CHAR)
427 {
428 keyval = wxOSXTranslateCocoaKey(nsEvent, wxevent.GetEventType()) ;
429 switch (eventType)
430 {
431 case NSKeyDown :
432 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
433 break;
434 case NSKeyUp :
435 wxevent.SetEventType( wxEVT_KEY_UP ) ;
436 break;
437 case NSFlagsChanged :
438 switch (keyval)
439 {
440 case WXK_CONTROL:
441 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
442 break;
443 case WXK_SHIFT:
444 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
445 break;
446 case WXK_ALT:
447 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
448 break;
449 case WXK_RAW_CONTROL:
450 wxevent.SetEventType( wxevent.m_rawControlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
451 break;
452 }
453 break;
454 default :
455 break ;
456 }
457 }
458
459 if ( !keyval )
460 {
461 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
462 keyval = wxToupper( aunichar ) ;
463 else
464 keyval = aunichar;
465 }
466
467#if wxUSE_UNICODE
468 // OS X generates events with key codes in Unicode private use area for
469 // unprintable symbols such as cursor arrows (WXK_UP is mapped to U+F700)
470 // and function keys (WXK_F2 is U+F705). We don't want to use them as the
471 // result of wxKeyEvent::GetUnicodeKey() however as it's supposed to return
472 // WXK_NONE for "non characters" so explicitly exclude them.
473 //
474 // We only exclude the private use area inside the Basic Multilingual Plane
475 // as key codes beyond it don't seem to be currently used.
476 if ( !(aunichar >= 0xe000 && aunichar < 0xf900) )
477 wxevent.m_uniChar = aunichar;
478#endif
479 wxevent.m_keyCode = keyval;
480
481 wxWindowMac* peer = GetWXPeer();
482 if ( peer )
483 {
484 wxevent.SetEventObject(peer);
485 wxevent.SetId(peer->GetId()) ;
486 }
487}
488
489UInt32 g_lastButton = 0 ;
490bool g_lastButtonWasFakeRight = false ;
491
492// better scroll wheel support
493// see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
494
495@interface NSEvent (DeviceDelta)
496- (CGFloat)deviceDeltaX;
497- (CGFloat)deviceDeltaY;
498
499// 10.7+
500- (BOOL)hasPreciseScrollingDeltas;
501- (CGFloat)scrollingDeltaX;
502- (CGFloat)scrollingDeltaY;
503@end
504
505void wxWidgetCocoaImpl::SetupCoordinates(wxCoord &x, wxCoord &y, NSEvent* nsEvent)
506{
507 NSPoint locationInWindow = [nsEvent locationInWindow];
508
509 // adjust coordinates for the window of the target view
510 if ( [nsEvent window] != [m_osxView window] )
511 {
512 if ( [nsEvent window] != nil )
513 locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
514
515 if ( [m_osxView window] != nil )
516 locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
517 }
518
519 NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
520 wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
521
522 x = locationInViewWX.x;
523 y = locationInViewWX.y;
524
525}
526
527void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
528{
529 int eventType = [nsEvent type];
530 UInt32 modifiers = [nsEvent modifierFlags] ;
531
532 SetupCoordinates(wxevent.m_x, wxevent.m_y, nsEvent);
533
534 // these parameters are not given for all events
535 UInt32 button = [nsEvent buttonNumber];
536 UInt32 clickCount = 0;
537
538 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
539 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
540 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
541 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
542 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
543
544 UInt32 mouseChord = 0;
545
546 switch (eventType)
547 {
548 case NSLeftMouseDown :
549 case NSLeftMouseDragged :
550 mouseChord = 1U;
551 break;
552 case NSRightMouseDown :
553 case NSRightMouseDragged :
554 mouseChord = 2U;
555 break;
556 case NSOtherMouseDown :
557 case NSOtherMouseDragged :
558 mouseChord = 4U;
559 break;
560 }
561
562 // a control click is interpreted as a right click
563 bool thisButtonIsFakeRight = false ;
564 if ( button == 0 && (modifiers & NSControlKeyMask) )
565 {
566 button = 1 ;
567 thisButtonIsFakeRight = true ;
568 }
569
570 // otherwise we report double clicks by connecting a left click with a ctrl-left click
571 if ( clickCount > 1 && button != g_lastButton )
572 clickCount = 1 ;
573
574 // we must make sure that our synthetic 'right' button corresponds in
575 // mouse down, moved and mouse up, and does not deliver a right down and left up
576 switch (eventType)
577 {
578 case NSLeftMouseDown :
579 case NSRightMouseDown :
580 case NSOtherMouseDown :
581 g_lastButton = button ;
582 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
583 break;
584 }
585
586 if ( button == 0 )
587 {
588 g_lastButton = 0 ;
589 g_lastButtonWasFakeRight = false ;
590 }
591 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
592 button = g_lastButton ;
593
594 // Adjust the chord mask to remove the primary button and add the
595 // secondary button. It is possible that the secondary button is
596 // already pressed, e.g. on a mouse connected to a laptop, but this
597 // possibility is ignored here:
598 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
599 mouseChord = ((mouseChord & ~1U) | 2U);
600
601 if(mouseChord & 1U)
602 wxevent.m_leftDown = true ;
603 if(mouseChord & 2U)
604 wxevent.m_rightDown = true ;
605 if(mouseChord & 4U)
606 wxevent.m_middleDown = true ;
607
608 // translate into wx types
609 switch (eventType)
610 {
611 case NSLeftMouseDown :
612 case NSRightMouseDown :
613 case NSOtherMouseDown :
614 clickCount = [nsEvent clickCount];
615 switch ( button )
616 {
617 case 0 :
618 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
619 break ;
620
621 case 1 :
622 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
623 break ;
624
625 case 2 :
626 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
627 break ;
628
629 default:
630 break ;
631 }
632 break ;
633
634 case NSLeftMouseUp :
635 case NSRightMouseUp :
636 case NSOtherMouseUp :
637 clickCount = [nsEvent clickCount];
638 switch ( button )
639 {
640 case 0 :
641 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
642 break ;
643
644 case 1 :
645 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
646 break ;
647
648 case 2 :
649 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
650 break ;
651
652 default:
653 break ;
654 }
655 break ;
656
657 case NSScrollWheel :
658 {
659 float deltaX = 0.0;
660 float deltaY = 0.0;
661
662 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
663
664 if ( UMAGetSystemVersion() >= 0x1070 )
665 {
666 if ( [nsEvent hasPreciseScrollingDeltas] )
667 {
668 deltaX = [nsEvent scrollingDeltaX];
669 deltaY = [nsEvent scrollingDeltaY];
670 }
671 else
672 {
673 deltaX = [nsEvent scrollingDeltaX] * 10;
674 deltaY = [nsEvent scrollingDeltaY] * 10;
675 }
676 }
677 else
678 {
679 const EventRef cEvent = (EventRef) [nsEvent eventRef];
680 // see http://developer.apple.com/qa/qa2005/qa1453.html
681 // for more details on why we have to look for the exact type
682
683 bool isMouseScrollEvent = false;
684 if ( cEvent )
685 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
686
687 if ( isMouseScrollEvent )
688 {
689 deltaX = [nsEvent deviceDeltaX];
690 deltaY = [nsEvent deviceDeltaY];
691 }
692 else
693 {
694 deltaX = ([nsEvent deltaX] * 10);
695 deltaY = ([nsEvent deltaY] * 10);
696 }
697 }
698
699 wxevent.m_wheelDelta = 10;
700 wxevent.m_linesPerAction = 1;
701 wxevent.m_columnsPerAction = 1;
702
703 if ( fabs(deltaX) > fabs(deltaY) )
704 {
705 // wx conventions for horizontal are inverted from vertical (originating from native msw behavior)
706 // right and up are positive values, left and down are negative values, while on OSX right and down
707 // are negative and left and up are positive.
708 wxevent.m_wheelAxis = wxMOUSE_WHEEL_HORIZONTAL;
709 wxevent.m_wheelRotation = -(int)deltaX;
710 }
711 else
712 {
713 wxevent.m_wheelRotation = (int)deltaY;
714 }
715
716 }
717 break ;
718
719 case NSMouseEntered :
720 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
721 break;
722 case NSMouseExited :
723 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
724 break;
725 case NSLeftMouseDragged :
726 case NSRightMouseDragged :
727 case NSOtherMouseDragged :
728 case NSMouseMoved :
729 wxevent.SetEventType( wxEVT_MOTION ) ;
730 break;
731 default :
732 break ;
733 }
734
735 wxevent.m_clickCount = clickCount;
736 wxWindowMac* peer = GetWXPeer();
737 if ( peer )
738 {
739 wxevent.SetEventObject(peer);
740 wxevent.SetId(peer->GetId()) ;
741 }
742}
743
744@implementation wxNSView
745
746+ (void)initialize
747{
748 static BOOL initialized = NO;
749 if (!initialized)
750 {
751 initialized = YES;
752 wxOSXCocoaClassAddWXMethods( self );
753 }
754}
755
756/* idea taken from webkit sources: overwrite the methods that (private) NSToolTipManager will use to attach its tracking rectangle
757 * then when changing the tooltip send fake view-exit and view-enter methods which will lead to a tooltip refresh
758 */
759
760
761- (void)_sendToolTipMouseExited
762{
763 // Nothing matters except window, trackingNumber, and userData.
764 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
765 location:NSMakePoint(0, 0)
766 modifierFlags:0
767 timestamp:0
768 windowNumber:[[self window] windowNumber]
769 context:NULL
770 eventNumber:0
771 trackingNumber:_lastToolTipTrackTag
772 userData:_lastUserData];
773 [_lastToolTipOwner mouseExited:fakeEvent];
774}
775
776- (void)_sendToolTipMouseEntered
777{
778 // Nothing matters except window, trackingNumber, and userData.
779 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
780 location:NSMakePoint(0, 0)
781 modifierFlags:0
782 timestamp:0
783 windowNumber:[[self window] windowNumber]
784 context:NULL
785 eventNumber:0
786 trackingNumber:_lastToolTipTrackTag
787 userData:_lastUserData];
788 [_lastToolTipOwner mouseEntered:fakeEvent];
789}
790
791- (void)setToolTip:(NSString *)string;
792{
793 if (string)
794 {
795 if ( _hasToolTip )
796 {
797 [self _sendToolTipMouseExited];
798 }
799
800 [super setToolTip:string];
801 _hasToolTip = YES;
802 [self _sendToolTipMouseEntered];
803 }
804 else
805 {
806 if ( _hasToolTip )
807 {
808 [self _sendToolTipMouseExited];
809 [super setToolTip:nil];
810 _hasToolTip = NO;
811 }
812 }
813}
814
815- (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
816{
817 NSTrackingRectTag tag = [super addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
818 if ( owner != self )
819 {
820 _lastUserData = data;
821 _lastToolTipOwner = owner;
822 _lastToolTipTrackTag = tag;
823 }
824 return tag;
825}
826
827- (void)removeTrackingRect:(NSTrackingRectTag)tag
828{
829 if (tag == _lastToolTipTrackTag)
830 {
831 _lastUserData = NULL;
832 _lastToolTipOwner = nil;
833 _lastToolTipTrackTag = 0;
834 }
835 [super removeTrackingRect:tag];
836}
837
838#if wxOSX_USE_NATIVE_FLIPPED
839- (BOOL)isFlipped
840{
841 return YES;
842}
843#endif
844
845- (BOOL) canBecomeKeyView
846{
847 wxWidgetCocoaImpl* viewimpl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
848 if ( viewimpl && viewimpl->IsUserPane() && viewimpl->GetWXPeer() )
849 return viewimpl->GetWXPeer()->AcceptsFocus();
850 return NO;
851}
852
853@end // wxNSView
854
855// We need to adopt NSTextInputClient protocol in order to interpretKeyEvents: to work.
856// Currently, only insertText:(replacementRange:) is
857// implemented here, and the rest of the methods are stubs.
858// It is hoped that someday IME-related functionality is implemented in
859// wxWidgets and the methods of this protocol are fully working.
860
861@implementation wxNSView(TextInput)
862
863void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text);
864
865- (void)insertText:(id)aString replacementRange:(NSRange)replacementRange
866{
867 wxOSX_insertText(self, @selector(insertText:), aString);
868}
869
870- (void)doCommandBySelector:(SEL)aSelector
871{
872 // these are already caught in the keyEvent handler
873}
874
875- (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
876{
877}
878
879- (void)unmarkText
880{
881}
882
883- (NSRange)selectedRange
884{
885 return NSMakeRange(NSNotFound, 0);
886}
887
888- (NSRange)markedRange
889{
890 return NSMakeRange(NSNotFound, 0);
891}
892
893- (BOOL)hasMarkedText
894{
895 return NO;
896}
897
898- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange
899{
900 return nil;
901}
902
903- (NSArray*)validAttributesForMarkedText
904{
905 return nil;
906}
907
908- (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange
909{
910 return NSMakeRect(0, 0, 0, 0);
911}
912- (NSUInteger)characterIndexForPoint:(NSPoint)aPoint
913{
914 return NSNotFound;
915}
916
917@end // wxNSView(TextInput)
918
919
920//
921// event handlers
922//
923
924#if wxUSE_DRAG_AND_DROP
925
926// see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
927// for details on the NSPasteboard -> PasteboardRef conversion
928
929NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
930{
931 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
932 if (impl == NULL)
933 return NSDragOperationNone;
934
935 return impl->draggingEntered(sender, self, _cmd);
936}
937
938void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
939{
940 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
941 if (impl == NULL)
942 return ;
943
944 return impl->draggingExited(sender, self, _cmd);
945}
946
947NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
948{
949 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
950 if (impl == NULL)
951 return NSDragOperationNone;
952
953 return impl->draggingUpdated(sender, self, _cmd);
954}
955
956BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
957{
958 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
959 if (impl == NULL)
960 return NSDragOperationNone;
961
962 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
963}
964
965#endif
966
967void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
968{
969 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
970 if (impl == NULL)
971 return;
972
973 impl->mouseEvent(event, self, _cmd);
974}
975
976void wxOSX_cursorUpdate(NSView* self, SEL _cmd, NSEvent *event)
977{
978 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
979 if (impl == NULL)
980 return;
981
982 impl->cursorUpdate(event, self, _cmd);
983}
984
985BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
986{
987 // This is needed to support click through, otherwise the first click on a window
988 // will not do anything unless it is the active window already.
989 return YES;
990}
991
992void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
993{
994 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
995 if (impl == NULL)
996 return;
997
998 impl->keyEvent(event, self, _cmd);
999}
1000
1001void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
1002{
1003 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1004 if (impl == NULL)
1005 return;
1006
1007 impl->insertText(text, self, _cmd);
1008}
1009
1010BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
1011{
1012 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1013 if (impl == NULL)
1014 return NO;
1015
1016 return impl->performKeyEquivalent(event, self, _cmd);
1017}
1018
1019BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
1020{
1021 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1022 if (impl == NULL)
1023 return NO;
1024
1025 return impl->acceptsFirstResponder(self, _cmd);
1026}
1027
1028BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
1029{
1030 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1031 if (impl == NULL)
1032 return NO;
1033
1034 return impl->becomeFirstResponder(self, _cmd);
1035}
1036
1037BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
1038{
1039 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1040 if (impl == NULL)
1041 return NO;
1042
1043 return impl->resignFirstResponder(self, _cmd);
1044}
1045
1046#if !wxOSX_USE_NATIVE_FLIPPED
1047
1048BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
1049{
1050 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1051 if (impl == NULL)
1052 return NO;
1053
1054 return impl->isFlipped(self, _cmd) ? YES:NO;
1055}
1056
1057#endif
1058
1059typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
1060
1061void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
1062{
1063 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1064 if (impl == NULL)
1065 return;
1066
1067#if wxUSE_THREADS
1068 // OS X starts a NSUIHeartBeatThread for animating the default button in a
1069 // dialog. This causes a drawRect of the active dialog from outside the
1070 // main UI thread. This causes an occasional crash since the wx drawing
1071 // objects (like wxPen) are not thread safe.
1072 //
1073 // Notice that NSUIHeartBeatThread seems to be undocumented and doing
1074 // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
1075 if ( !wxThread::IsMain() )
1076 {
1077 if ( impl->IsUserPane() )
1078 {
1079 wxWindow* win = impl->GetWXPeer();
1080 if ( win->UseBgCol() )
1081 {
1082
1083 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1084 CGContextSaveGState( context );
1085
1086 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
1087 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
1088 CGContextFillRect( context, r );
1089
1090 CGContextRestoreGState( context );
1091 }
1092 }
1093 else
1094 {
1095 // just call the superclass handler, we don't need any custom wx drawing
1096 // here and it seems to work fine:
1097 wxOSX_DrawRectHandlerPtr
1098 superimpl = (wxOSX_DrawRectHandlerPtr)
1099 [[self superclass] instanceMethodForSelector:_cmd];
1100 superimpl(self, _cmd, rect);
1101 }
1102
1103 return;
1104 }
1105#endif // wxUSE_THREADS
1106
1107 return impl->drawRect(&rect, self, _cmd);
1108}
1109
1110void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
1111{
1112 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1113 if (impl == NULL)
1114 return;
1115
1116 impl->controlAction(self, _cmd, sender);
1117}
1118
1119void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
1120{
1121 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1122 if (impl == NULL)
1123 return;
1124
1125 impl->controlDoubleAction(self, _cmd, sender);
1126}
1127
1128unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1129{
1130 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1131 NSPasteboard *pboard = [sender draggingPasteboard];
1132 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1133
1134 wxWindow* wxpeer = GetWXPeer();
1135 if ( wxpeer == NULL )
1136 return NSDragOperationNone;
1137
1138 wxDropTarget* target = wxpeer->GetDropTarget();
1139 if ( target == NULL )
1140 return NSDragOperationNone;
1141
1142 wxDragResult result = wxDragNone;
1143 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1144 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1145
1146 if ( sourceDragMask & NSDragOperationLink )
1147 result = wxDragLink;
1148 else if ( sourceDragMask & NSDragOperationCopy )
1149 result = wxDragCopy;
1150 else if ( sourceDragMask & NSDragOperationMove )
1151 result = wxDragMove;
1152
1153 PasteboardRef pboardRef;
1154 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1155 target->SetCurrentDragPasteboard(pboardRef);
1156 result = target->OnEnter(pt.x, pt.y, result);
1157 CFRelease(pboardRef);
1158
1159 NSDragOperation nsresult = NSDragOperationNone;
1160 switch (result )
1161 {
1162 case wxDragLink:
1163 nsresult = NSDragOperationLink;
1164 case wxDragMove:
1165 nsresult = NSDragOperationMove;
1166 case wxDragCopy:
1167 nsresult = NSDragOperationCopy;
1168 default :
1169 break;
1170 }
1171 return nsresult;
1172}
1173
1174void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1175{
1176 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1177 NSPasteboard *pboard = [sender draggingPasteboard];
1178
1179 wxWindow* wxpeer = GetWXPeer();
1180 if ( wxpeer == NULL )
1181 return;
1182
1183 wxDropTarget* target = wxpeer->GetDropTarget();
1184 if ( target == NULL )
1185 return;
1186
1187 PasteboardRef pboardRef;
1188 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1189 target->SetCurrentDragPasteboard(pboardRef);
1190 target->OnLeave();
1191 CFRelease(pboardRef);
1192 }
1193
1194unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1195{
1196 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1197 NSPasteboard *pboard = [sender draggingPasteboard];
1198 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1199
1200 wxWindow* wxpeer = GetWXPeer();
1201 if ( wxpeer == NULL )
1202 return NSDragOperationNone;
1203
1204 wxDropTarget* target = wxpeer->GetDropTarget();
1205 if ( target == NULL )
1206 return NSDragOperationNone;
1207
1208 wxDragResult result = wxDragNone;
1209 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1210 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1211
1212 if ( sourceDragMask & NSDragOperationLink )
1213 result = wxDragLink;
1214 else if ( sourceDragMask & NSDragOperationCopy )
1215 result = wxDragCopy;
1216 else if ( sourceDragMask & NSDragOperationMove )
1217 result = wxDragMove;
1218
1219 PasteboardRef pboardRef;
1220 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1221 target->SetCurrentDragPasteboard(pboardRef);
1222 result = target->OnDragOver(pt.x, pt.y, result);
1223 CFRelease(pboardRef);
1224
1225 NSDragOperation nsresult = NSDragOperationNone;
1226 switch (result )
1227 {
1228 case wxDragLink:
1229 nsresult = NSDragOperationLink;
1230 case wxDragMove:
1231 nsresult = NSDragOperationMove;
1232 case wxDragCopy:
1233 nsresult = NSDragOperationCopy;
1234 default :
1235 break;
1236 }
1237 return nsresult;
1238}
1239
1240bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1241{
1242 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1243
1244 NSPasteboard *pboard = [sender draggingPasteboard];
1245 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1246
1247 wxWindow* wxpeer = GetWXPeer();
1248 wxDropTarget* target = wxpeer->GetDropTarget();
1249 wxDragResult result = wxDragNone;
1250 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1251 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1252
1253 if ( sourceDragMask & NSDragOperationLink )
1254 result = wxDragLink;
1255 else if ( sourceDragMask & NSDragOperationCopy )
1256 result = wxDragCopy;
1257 else if ( sourceDragMask & NSDragOperationMove )
1258 result = wxDragMove;
1259
1260 PasteboardRef pboardRef;
1261 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1262 target->SetCurrentDragPasteboard(pboardRef);
1263
1264 if (target->OnDrop(pt.x, pt.y))
1265 result = target->OnData(pt.x, pt.y, result);
1266
1267 CFRelease(pboardRef);
1268
1269 return result != wxDragNone;
1270}
1271
1272void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1273{
1274 // we are getting moved events for all windows in the hierarchy, not something wx expects
1275 // therefore we only handle it for the deepest child in the hierarchy
1276 if ( [event type] == NSMouseMoved )
1277 {
1278 NSView* hitview = [[[slf window] contentView] hitTest:[event locationInWindow]];
1279 if ( hitview == NULL || hitview != slf)
1280 return;
1281 }
1282
1283 if ( !DoHandleMouseEvent(event) )
1284 {
1285 // for plain NSView mouse events would propagate to parents otherwise
1286 // scrollwheel events have to be propagated if not handled in all cases
1287 if (!IsUserPane() || [event type] == NSScrollWheel )
1288 {
1289 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1290 superimpl(slf, (SEL)_cmd, event);
1291
1292 // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
1293 // only trigger if at this moment the mouse is already up
1294 if ( [ event type] == NSLeftMouseDown && !wxGetMouseState().LeftIsDown() )
1295 {
1296 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1297 SetupMouseEvent(wxevent , event) ;
1298 wxevent.SetEventType(wxEVT_LEFT_UP);
1299
1300 GetWXPeer()->HandleWindowEvent(wxevent);
1301 }
1302 }
1303 }
1304}
1305
1306void wxWidgetCocoaImpl::cursorUpdate(WX_NSEvent event, WXWidget slf, void *_cmd)
1307{
1308 if ( !SetupCursor(event) )
1309 {
1310 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1311 superimpl(slf, (SEL)_cmd, event);
1312 }
1313 }
1314
1315bool wxWidgetCocoaImpl::SetupCursor(WX_NSEvent event)
1316{
1317 extern wxCursor gGlobalCursor;
1318
1319 if ( gGlobalCursor.IsOk() )
1320 {
1321 gGlobalCursor.MacInstall();
1322 return true;
1323 }
1324 else
1325 {
1326 wxWindow* cursorTarget = GetWXPeer();
1327 wxCoord x,y;
1328 SetupCoordinates(x, y, event);
1329 wxPoint cursorPoint( x , y ) ;
1330
1331 while ( cursorTarget && !cursorTarget->MacSetupCursor( cursorPoint ) )
1332 {
1333 // at least in GTK cursor events are not propagated either ...
1334#if 1
1335 cursorTarget = NULL;
1336#else
1337 cursorTarget = cursorTarget->GetParent() ;
1338 if ( cursorTarget )
1339 cursorPoint += cursorTarget->GetPosition();
1340#endif
1341 }
1342
1343 return cursorTarget != NULL;
1344 }
1345}
1346
1347void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1348{
1349 if ( [event type] == NSKeyDown )
1350 {
1351 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1352 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1353 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1354 return;
1355
1356 m_lastKeyDownEvent = event;
1357 }
1358
1359 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1360 {
1361 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1362 superimpl(slf, (SEL)_cmd, event);
1363 }
1364 m_lastKeyDownEvent = NULL;
1365}
1366
1367void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1368{
1369 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1370 {
1371 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1372 superimpl(slf, (SEL)_cmd, text);
1373 }
1374}
1375
1376
1377bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1378{
1379 bool handled = false;
1380
1381 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1382 SetupKeyEvent( wxevent, event );
1383
1384 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1385 // walk up the ancestors ourselves but let cocoa do it
1386
1387 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1388 if (command != -1)
1389 {
1390 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1391
1392 wxCommandEvent command_event( wxEVT_MENU, command );
1393 command_event.SetEventObject( wxevent.GetEventObject() );
1394 handled = handler->ProcessEvent( command_event );
1395
1396 if ( !handled )
1397 {
1398 // accelerators can also be used with buttons, try them too
1399 command_event.SetEventType(wxEVT_BUTTON);
1400 handled = handler->ProcessEvent( command_event );
1401 }
1402 }
1403
1404 if ( !handled )
1405 {
1406 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1407 return superimpl(slf, (SEL)_cmd, event);
1408 }
1409 return YES;
1410}
1411
1412bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1413{
1414 if ( IsUserPane() )
1415 return m_wxPeer->AcceptsFocus();
1416 else
1417 {
1418 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1419 return superimpl(slf, (SEL)_cmd);
1420 }
1421}
1422
1423bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1424{
1425 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1426 // get the current focus before running becomeFirstResponder
1427 NSView* otherView = FindFocus();
1428
1429 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1430 BOOL r = superimpl(slf, (SEL)_cmd);
1431 if ( r )
1432 {
1433 DoNotifyFocusEvent( true, otherWindow );
1434 }
1435
1436 return r;
1437}
1438
1439bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1440{
1441 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1442 BOOL r = superimpl(slf, (SEL)_cmd);
1443
1444 NSResponder * responder = wxNonOwnedWindowCocoaImpl::GetNextFirstResponder();
1445 NSView* otherView = wxOSXGetViewFromResponder(responder);
1446
1447 wxWidgetImpl* otherWindow = FindBestFromWXWidget(otherView);
1448
1449 // It doesn't make sense to notify about the loss of focus if it's the same
1450 // control in the end, and just a different subview
1451 if ( otherWindow == this )
1452 return r;
1453
1454 // NSTextViews have an editor as true responder, therefore the might get the
1455 // resign notification if their editor takes over, don't trigger any event then
1456 if ( r && !m_hasEditor)
1457 {
1458 DoNotifyFocusEvent( false, otherWindow );
1459 }
1460 return r;
1461}
1462
1463#if !wxOSX_USE_NATIVE_FLIPPED
1464
1465bool wxWidgetCocoaImpl::isFlipped(WXWidget slf, void *WXUNUSED(_cmd))
1466{
1467 return m_isFlipped;
1468}
1469
1470#endif
1471
1472#define OSX_DEBUG_DRAWING 0
1473
1474void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1475{
1476 // preparing the update region
1477
1478 wxRegion updateRgn;
1479
1480 // since adding many rects to a region is a costly process, by default use the bounding rect
1481#if 0
1482 const NSRect *rects;
1483 NSInteger count;
1484 [slf getRectsBeingDrawn:&rects count:&count];
1485 for ( int i = 0 ; i < count ; ++i )
1486 {
1487 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1488 }
1489#else
1490 updateRgn.Union(wxFromNSRect(slf,*(NSRect*)rect));
1491#endif
1492
1493 wxWindow* wxpeer = GetWXPeer();
1494
1495 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1496 {
1497 // as this update region is in native window locals we must adapt it to wx window local
1498 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1499 }
1500
1501 // Restrict the update region to the shape of the window, if any, and also
1502 // remember the region that we need to clear later.
1503 wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1504 const bool isTopLevel = tlwParent == wxpeer;
1505 wxRegion clearRgn;
1506 if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1507 {
1508 if ( isTopLevel )
1509 clearRgn = updateRgn;
1510
1511 int xoffset = 0, yoffset = 0;
1512 wxRegion rgn = tlwParent->GetShape();
1513 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1514 rgn.Offset( xoffset, yoffset );
1515 updateRgn.Intersect(rgn);
1516
1517 if ( isTopLevel )
1518 {
1519 // Exclude the window shape from the region to be cleared below.
1520 rgn.Xor(wxpeer->GetSize());
1521 clearRgn.Intersect(rgn);
1522 }
1523 }
1524
1525 wxpeer->GetUpdateRegion() = updateRgn;
1526
1527 // setting up the drawing context
1528
1529 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1530 CGContextSaveGState( context );
1531
1532#if OSX_DEBUG_DRAWING
1533 CGContextBeginPath( context );
1534 CGContextMoveToPoint(context, 0, 0);
1535 NSRect bounds = [slf bounds];
1536 CGContextAddLineToPoint(context, 10, 0);
1537 CGContextMoveToPoint(context, 0, 0);
1538 CGContextAddLineToPoint(context, 0, 10);
1539 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1540 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1541 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1542 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1543 CGContextClosePath( context );
1544 CGContextStrokePath(context);
1545#endif
1546
1547 if ( ![slf isFlipped] )
1548 {
1549 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1550 CGContextScaleCTM( context, 1, -1 );
1551 }
1552
1553 wxpeer->MacSetCGContextRef( context );
1554
1555 bool handled = wxpeer->MacDoRedraw( 0 );
1556 CGContextRestoreGState( context );
1557
1558 CGContextSaveGState( context );
1559 if ( !handled )
1560 {
1561 // call super
1562 SEL _cmd = @selector(drawRect:);
1563 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1564 superimpl(slf, _cmd, *(NSRect*)rect);
1565 CGContextRestoreGState( context );
1566 CGContextSaveGState( context );
1567 }
1568 // as we called restore above, we have to flip again if necessary
1569 if ( ![slf isFlipped] )
1570 {
1571 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1572 CGContextScaleCTM( context, 1, -1 );
1573 }
1574
1575 if ( isTopLevel )
1576 {
1577 // We also need to explicitly draw the part of the top level window
1578 // outside of its region with transparent colour to ensure that it is
1579 // really transparent.
1580 if ( clearRgn.IsOk() )
1581 {
1582 wxMacCGContextStateSaver saveState(context);
1583 wxWindowDC dc(wxpeer);
1584 dc.SetBackground(wxBrush(wxTransparentColour));
1585 dc.SetDeviceClippingRegion(clearRgn);
1586 dc.Clear();
1587 }
1588
1589#if wxUSE_GRAPHICS_CONTEXT
1590 // If the window shape is defined by a path, stroke the path to show
1591 // the window border.
1592 const wxGraphicsPath& path = tlwParent->GetShapePath();
1593 if ( !path.IsNull() )
1594 {
1595 CGContextSetLineWidth(context, 1);
1596 CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1597 CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1598 CGContextStrokePath(context);
1599 }
1600#endif // wxUSE_GRAPHICS_CONTEXT
1601 }
1602
1603 wxpeer->MacPaintChildrenBorders();
1604 wxpeer->MacSetCGContextRef( NULL );
1605 CGContextRestoreGState( context );
1606}
1607
1608void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1609{
1610 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1611 if ( wxpeer )
1612 {
1613 wxpeer->OSXSimulateFocusEvents();
1614 wxpeer->OSXHandleClicked(0);
1615 }
1616}
1617
1618void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1619{
1620}
1621
1622void wxWidgetCocoaImpl::controlTextDidChange()
1623{
1624 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1625 if ( wxpeer )
1626 {
1627 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1628 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1629 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1630 if ( tc )
1631 tc->SendTextUpdatedEventIfAllowed();
1632 else if ( cb )
1633 cb->SendTextUpdatedEventIfAllowed();
1634 else
1635 {
1636 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1637 }
1638 }
1639}
1640
1641//
1642
1643#if OBJC_API_VERSION >= 2
1644
1645#define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1646 class_addMethod(c, s, i, t );
1647
1648#else
1649
1650#define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1651 { s, (char*) t, i },
1652
1653#endif
1654
1655void wxOSXCocoaClassAddWXMethods(Class c)
1656{
1657
1658#if OBJC_API_VERSION < 2
1659 static objc_method wxmethods[] =
1660 {
1661#endif
1662
1663 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1664 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1665 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1666
1667 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1668 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1669 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1670
1671 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1672
1673 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1674 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1675 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1676
1677 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1678
1679 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1680 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1681 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1682
1683 wxOSX_CLASS_ADD_METHOD(c, @selector(cursorUpdate:), (IMP) wxOSX_cursorUpdate, "v@:@" )
1684
1685 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1686 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1687 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1688
1689 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1690
1691 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1692
1693 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1694 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1695 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1696
1697#if !wxOSX_USE_NATIVE_FLIPPED
1698 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1699#endif
1700 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1701
1702 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1703 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1704
1705#if wxUSE_DRAG_AND_DROP
1706 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1707 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1708 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1709 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1710#endif
1711
1712#if OBJC_API_VERSION < 2
1713 } ;
1714 static int method_count = WXSIZEOF( wxmethods );
1715 static objc_method_list *wxmethodlist = NULL;
1716 if ( wxmethodlist == NULL )
1717 {
1718 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1719 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1720 wxmethodlist->method_count = method_count;
1721 wxmethodlist->obsolete = 0;
1722 }
1723 class_addMethods( c, wxmethodlist );
1724#endif
1725}
1726
1727//
1728// C++ implementation class
1729//
1730
1731IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1732
1733wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1734 wxWidgetImpl( peer, isRootControl, isUserPane )
1735{
1736 Init();
1737 m_osxView = w;
1738
1739 // check if the user wants to create the control initially hidden
1740 if ( !peer->IsShown() )
1741 SetVisibility(false);
1742
1743 // gc aware handling
1744 if ( m_osxView )
1745 CFRetain(m_osxView);
1746 [m_osxView release];
1747}
1748
1749wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1750{
1751 Init();
1752}
1753
1754void wxWidgetCocoaImpl::Init()
1755{
1756 m_osxView = NULL;
1757#if !wxOSX_USE_NATIVE_FLIPPED
1758 m_isFlipped = true;
1759#endif
1760 m_lastKeyDownEvent = NULL;
1761 m_hasEditor = false;
1762}
1763
1764wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1765{
1766 RemoveAssociations( this );
1767
1768 if ( !IsRootControl() )
1769 {
1770 NSView *sv = [m_osxView superview];
1771 if ( sv != nil )
1772 [m_osxView removeFromSuperview];
1773 }
1774 // gc aware handling
1775 if ( m_osxView )
1776 CFRelease(m_osxView);
1777}
1778
1779bool wxWidgetCocoaImpl::IsVisible() const
1780{
1781 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1782}
1783
1784void wxWidgetCocoaImpl::SetVisibility( bool visible )
1785{
1786 [m_osxView setHidden:(visible ? NO:YES)];
1787}
1788
1789double wxWidgetCocoaImpl::GetContentScaleFactor() const
1790{
1791#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
1792 NSWindow* tlw = [m_osxView window];
1793 if ( [ tlw respondsToSelector:@selector(backingScaleFactor) ] )
1794 return [tlw backingScaleFactor];
1795 else
1796#endif
1797 return 1.0;
1798}
1799
1800// ----------------------------------------------------------------------------
1801// window animation stuff
1802// ----------------------------------------------------------------------------
1803
1804// define a delegate used to refresh the window during animation
1805@interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1806{
1807 wxWindow *m_win;
1808 bool m_isDone;
1809}
1810
1811- (id)init:(wxWindow *)win;
1812
1813- (bool)isDone;
1814
1815// NSAnimationDelegate methods
1816- (void)animationDidEnd:(NSAnimation*)animation;
1817- (void)animation:(NSAnimation*)animation
1818 didReachProgressMark:(NSAnimationProgress)progress;
1819@end
1820
1821@implementation wxNSAnimationDelegate
1822
1823- (id)init:(wxWindow *)win
1824{
1825 self = [super init];
1826
1827 m_win = win;
1828 m_isDone = false;
1829
1830 return self;
1831}
1832
1833- (bool)isDone
1834{
1835 return m_isDone;
1836}
1837
1838- (void)animation:(NSAnimation*)animation
1839 didReachProgressMark:(NSAnimationProgress)progress
1840{
1841 wxUnusedVar(animation);
1842 wxUnusedVar(progress);
1843
1844 m_win->SendSizeEvent();
1845}
1846
1847- (void)animationDidEnd:(NSAnimation*)animation
1848{
1849 wxUnusedVar(animation);
1850 m_isDone = true;
1851}
1852
1853@end
1854
1855/* static */
1856bool
1857wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1858 bool show,
1859 wxShowEffect effect,
1860 unsigned timeout)
1861{
1862 // create the dictionary describing the animation to perform on this view
1863 NSObject * const
1864 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1865 NSMutableDictionary * const
1866 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1867 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1868
1869 // determine the start and end rectangles assuming we're hiding the window
1870 const wxRect rectOrig = win->GetRect();
1871 wxRect rectStart,
1872 rectEnd;
1873 rectStart =
1874 rectEnd = rectOrig;
1875
1876 if ( show )
1877 {
1878 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1879 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1880 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1881 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1882 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1883 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1884 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1885 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1886 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1887 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1888 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1889 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1890 }
1891
1892 switch ( effect )
1893 {
1894 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1895 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1896 rectEnd.width = 0;
1897 break;
1898
1899 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1900 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1901 rectEnd.x = rectStart.GetRight();
1902 rectEnd.width = 0;
1903 break;
1904
1905 case wxSHOW_EFFECT_ROLL_TO_TOP:
1906 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1907 rectEnd.height = 0;
1908 break;
1909
1910 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1911 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1912 rectEnd.y = rectStart.GetBottom();
1913 rectEnd.height = 0;
1914 break;
1915
1916 case wxSHOW_EFFECT_EXPAND:
1917 rectEnd.x = rectStart.x + rectStart.width / 2;
1918 rectEnd.y = rectStart.y + rectStart.height / 2;
1919 rectEnd.width =
1920 rectEnd.height = 0;
1921 break;
1922
1923 case wxSHOW_EFFECT_BLEND:
1924 [dict setObject:(show ? NSViewAnimationFadeInEffect
1925 : NSViewAnimationFadeOutEffect)
1926 forKey:NSViewAnimationEffectKey];
1927 break;
1928
1929 case wxSHOW_EFFECT_NONE:
1930 case wxSHOW_EFFECT_MAX:
1931 wxFAIL_MSG( "unexpected animation effect" );
1932 return false;
1933
1934 default:
1935 wxFAIL_MSG( "unknown animation effect" );
1936 return false;
1937 };
1938
1939 if ( show )
1940 {
1941 // we need to restore it to the original rectangle instead of making it
1942 // disappear
1943 wxSwap(rectStart, rectEnd);
1944
1945 // and as the window is currently hidden, we need to show it for the
1946 // animation to be visible at all (but don't restore it at its full
1947 // rectangle as it shouldn't appear immediately)
1948 win->SetSize(rectStart);
1949 win->Show();
1950 }
1951
1952 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1953 ? [(NSView *)viewOrWin superview]
1954 : nil;
1955 const NSRect rStart = wxToNSRect(parentView, rectStart);
1956 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1957
1958 [dict setObject:[NSValue valueWithRect:rStart]
1959 forKey:NSViewAnimationStartFrameKey];
1960 [dict setObject:[NSValue valueWithRect:rEnd]
1961 forKey:NSViewAnimationEndFrameKey];
1962
1963 // create an animation using the values in the above dictionary
1964 NSViewAnimation * const
1965 anim = [[NSViewAnimation alloc]
1966 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1967
1968 if ( !timeout )
1969 {
1970 // what is a good default duration? Windows uses 200ms, Web frameworks
1971 // use anything from 250ms to 1s... choose something in the middle
1972 timeout = 500;
1973 }
1974
1975 [anim setDuration:timeout/1000.]; // duration is in seconds here
1976
1977 // if the window being animated changes its layout depending on its size
1978 // (which is almost always the case) we need to redo it during animation
1979 //
1980 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1981 // controls in wxInfoBar visibly jump around)
1982 const int NUM_LAYOUTS = 20;
1983 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1984 [anim addProgressMark:f];
1985
1986 wxNSAnimationDelegate * const
1987 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1988 [anim setDelegate:animDelegate];
1989 [anim startAnimation];
1990
1991 // Cocoa is capable of doing animation asynchronously or even from separate
1992 // thread but wx API doesn't provide any way to be notified about the
1993 // animation end and without this we really must ensure that the window has
1994 // the expected (i.e. the same as if a simple Show() had been used) size
1995 // when we return, so block here until the animation finishes
1996 //
1997 // notice that because the default animation mode is NSAnimationBlocking,
1998 // no user input events ought to be processed from here
1999 {
2000 wxEventLoopGuarantor ensureEventLoopExistence;
2001 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
2002 while ( ![animDelegate isDone] )
2003 loop->Dispatch();
2004 }
2005
2006 if ( !show )
2007 {
2008 // NSViewAnimation is smart enough to hide the NSView being animated at
2009 // the end but we also must ensure that it's hidden for wx too
2010 win->Hide();
2011
2012 // and we must also restore its size because it isn't expected to
2013 // change just because the window was hidden
2014 win->SetSize(rectOrig);
2015 }
2016 else
2017 {
2018 // refresh it once again after the end to ensure that everything is in
2019 // place
2020 win->SendSizeEvent();
2021 }
2022
2023 [anim setDelegate:nil];
2024 [animDelegate release];
2025 [anim release];
2026
2027 return true;
2028}
2029
2030bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
2031 wxShowEffect effect,
2032 unsigned timeout)
2033{
2034 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
2035}
2036
2037/* note that the drawing order between siblings is not defined under 10.4 */
2038/* only starting from 10.5 the subview order is respected */
2039
2040/* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
2041 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
2042 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
2043 * expects a function returning the new non-enum NSComparsionResult.
2044 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
2045 */
2046#if defined(NSINTEGER_DEFINED)
2047typedef NSComparisonResult CocoaWindowCompareFunctionResult;
2048#else
2049typedef int CocoaWindowCompareFunctionResult;
2050#endif
2051
2052class CocoaWindowCompareContext
2053{
2054 wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
2055public:
2056 CocoaWindowCompareContext(); // Not implemented
2057 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
2058 {
2059 m_target = target;
2060 // Cocoa sorts subviews in-place.. make a copy
2061 m_subviews = [subviews copy];
2062 }
2063
2064 ~CocoaWindowCompareContext()
2065 { // release the copy
2066 [m_subviews release];
2067 }
2068 NSView* target()
2069 { return m_target; }
2070
2071 NSArray* subviews()
2072 { return m_subviews; }
2073
2074 /* Helper function that returns the comparison based off of the original ordering */
2075 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
2076 {
2077 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
2078 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
2079 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
2080 // likely compare higher than the other view which is reasonable considering the only way that
2081 // can happen is if the subview was added after our call to subviews but before the call to
2082 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
2083 // that case should never occur anyway because that would imply a multi-threaded GUI call
2084 // which is a big no-no with Cocoa.
2085
2086 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
2087 NSComparisonResult result = (firstI < secondI)
2088 ? NSOrderedAscending /* -1 */
2089 : (firstI > secondI)
2090 ? NSOrderedDescending /* 1 */
2091 : NSOrderedSame /* 0 */;
2092
2093 return result;
2094 }
2095private:
2096 /* The subview we are trying to Raise or Lower */
2097 NSView *m_target;
2098 /* A copy of the original array of subviews */
2099 NSArray *m_subviews;
2100};
2101
2102/* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
2103 * the target view is always higher than every other view. When comparing two views neither of
2104 * which is the target, it returns the correct response based on the original ordering
2105 */
2106static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
2107{
2108 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2109 // first should be ordered higher
2110 if(first==compareContext->target())
2111 return NSOrderedDescending;
2112 // second should be ordered higher
2113 if(second==compareContext->target())
2114 return NSOrderedAscending;
2115 return compareContext->CompareUsingOriginalOrdering(first,second);
2116}
2117
2118void wxWidgetCocoaImpl::Raise()
2119{
2120 NSView* nsview = m_osxView;
2121
2122 NSView *superview = [nsview superview];
2123 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2124
2125 [superview sortSubviewsUsingFunction:
2126 CocoaRaiseWindowCompareFunction
2127 context: &compareContext];
2128
2129}
2130
2131/* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
2132 * the target view is always lower than every other view. When comparing two views neither of
2133 * which is the target, it returns the correct response based on the original ordering
2134 */
2135static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
2136{
2137 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2138 // first should be ordered lower
2139 if(first==compareContext->target())
2140 return NSOrderedAscending;
2141 // second should be ordered lower
2142 if(second==compareContext->target())
2143 return NSOrderedDescending;
2144 return compareContext->CompareUsingOriginalOrdering(first,second);
2145}
2146
2147void wxWidgetCocoaImpl::Lower()
2148{
2149 NSView* nsview = m_osxView;
2150
2151 NSView *superview = [nsview superview];
2152 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2153
2154 [superview sortSubviewsUsingFunction:
2155 CocoaLowerWindowCompareFunction
2156 context: &compareContext];
2157}
2158
2159void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
2160{
2161#if 1
2162 SetNeedsDisplay() ;
2163#else
2164 // We should do something like this, but it wasn't working in 10.4.
2165 if (GetNeedsDisplay() )
2166 {
2167 SetNeedsDisplay() ;
2168 }
2169 NSRect r = wxToNSRect( [m_osxView superview], *rect );
2170 NSSize offset = NSMakeSize((float)dx, (float)dy);
2171 [m_osxView scrollRect:r by:offset];
2172#endif
2173}
2174
2175void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
2176{
2177 wxWindowMac* parent = GetWXPeer()->GetParent();
2178 // under Cocoa we might have a contentView in the wxParent to which we have to
2179 // adjust the coordinates
2180 if (parent && [m_osxView superview] != parent->GetHandle() )
2181 {
2182 int cx = 0,cy = 0,cw = 0,ch = 0;
2183 if ( parent->GetPeer() )
2184 {
2185 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2186 x -= cx;
2187 y -= cy;
2188 }
2189 }
2190 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
2191 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
2192 [m_osxView setFrame:r];
2193 [[m_osxView superview] setNeedsDisplayInRect:r];
2194}
2195
2196void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
2197{
2198 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
2199 x = r.GetLeft();
2200 y = r.GetTop();
2201
2202 // under Cocoa we might have a contentView in the wxParent to which we have to
2203 // adjust the coordinates
2204 wxWindowMac* parent = GetWXPeer()->GetParent();
2205 if (parent && [m_osxView superview] != parent->GetHandle() )
2206 {
2207 int cx = 0,cy = 0,cw = 0,ch = 0;
2208 if ( parent->GetPeer() )
2209 {
2210 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2211 x += cx;
2212 y += cy;
2213 }
2214 }
2215}
2216
2217void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2218{
2219 NSRect rect = [m_osxView frame];
2220 width = (int)rect.size.width;
2221 height = (int)rect.size.height;
2222}
2223
2224void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
2225{
2226 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2227 {
2228 NSView* cv = [m_osxView contentView];
2229
2230 NSRect bounds = [m_osxView bounds];
2231 NSRect rect = [cv frame];
2232
2233 int y = (int)rect.origin.y;
2234 int x = (int)rect.origin.x;
2235 if ( ![ m_osxView isFlipped ] )
2236 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
2237 left = x;
2238 top = y;
2239 width = (int)rect.size.width;
2240 height = (int)rect.size.height;
2241 }
2242 else
2243 {
2244 left = top = 0;
2245 GetSize( width, height );
2246 }
2247}
2248
2249void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2250{
2251 if ( where )
2252 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2253 else
2254 [m_osxView setNeedsDisplay:YES];
2255}
2256
2257bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2258{
2259 return [m_osxView needsDisplay];
2260}
2261
2262bool wxWidgetCocoaImpl::CanFocus() const
2263{
2264 return [m_osxView canBecomeKeyView] == YES;
2265}
2266
2267bool wxWidgetCocoaImpl::HasFocus() const
2268{
2269 return ( FindFocus() == m_osxView );
2270}
2271
2272bool wxWidgetCocoaImpl::SetFocus()
2273{
2274 if ( !CanFocus() )
2275 return false;
2276
2277 // TODO remove if no issues arise: should not raise the window, only assign focus
2278 //[[m_osxView window] makeKeyAndOrderFront:nil] ;
2279 [[m_osxView window] makeFirstResponder: m_osxView] ;
2280 return true;
2281}
2282
2283void wxWidgetCocoaImpl::SetDropTarget(wxDropTarget* target)
2284{
2285 [m_osxView unregisterDraggedTypes];
2286
2287 if ( target == NULL )
2288 return;
2289
2290 wxDataObject* dobj = target->GetDataObject();
2291
2292 if( dobj )
2293 {
2294 CFMutableArrayRef typesarray = CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
2295 dobj->AddSupportedTypes(typesarray);
2296 NSView* targetView = m_osxView;
2297 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2298 targetView = [(NSScrollView*) m_osxView documentView];
2299
2300 [targetView registerForDraggedTypes:(NSArray*)typesarray];
2301 CFRelease(typesarray);
2302 }
2303}
2304
2305void wxWidgetCocoaImpl::RemoveFromParent()
2306{
2307 [m_osxView removeFromSuperview];
2308}
2309
2310void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2311{
2312 NSView* container = parent->GetWXWidget() ;
2313 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2314 [container addSubview:m_osxView];
2315
2316 if( m_wxPeer->IsFrozen() )
2317 [[m_osxView window] disableFlushWindow];
2318}
2319
2320void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2321{
2322 NSView* targetView = m_osxView;
2323 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2324 targetView = [(NSScrollView*) m_osxView documentView];
2325
2326 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2327 {
2328 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2329 green:(CGFloat) (col.Green() / 255.0)
2330 blue:(CGFloat) (col.Blue() / 255.0)
2331 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2332 }
2333}
2334
2335bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2336{
2337 BOOL opaque = ( style == wxBG_STYLE_PAINT );
2338
2339 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2340 {
2341 [m_osxView setOpaque: opaque];
2342 }
2343
2344 return true ;
2345}
2346
2347void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2348{
2349 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2350 {
2351 wxCFStringRef cf( title , encoding );
2352 [m_osxView setTitle:cf.AsNSString()];
2353 }
2354 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2355 {
2356 wxCFStringRef cf( title , encoding );
2357 [m_osxView setStringValue:cf.AsNSString()];
2358 }
2359}
2360
2361
2362void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2363{
2364 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2365 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2366 *pt = wxFromNSPoint( to->GetWXWidget(), p );
2367}
2368
2369wxInt32 wxWidgetCocoaImpl::GetValue() const
2370{
2371 return [(NSControl*)m_osxView intValue];
2372}
2373
2374void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2375{
2376 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
2377 {
2378 [m_osxView setIntValue:v];
2379 }
2380 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2381 {
2382 [m_osxView setFloatValue:(double)v];
2383 }
2384 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2385 {
2386 [m_osxView setDoubleValue:(double)v];
2387 }
2388}
2389
2390void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2391{
2392 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
2393 {
2394 [m_osxView setMinValue:(double)v];
2395 }
2396}
2397
2398void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2399{
2400 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2401 {
2402 [m_osxView setMaxValue:(double)v];
2403 }
2404}
2405
2406wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2407{
2408 if ( [m_osxView respondsToSelector:@selector(minValue)] )
2409 {
2410 return (int)[m_osxView minValue];
2411 }
2412 return 0;
2413}
2414
2415wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2416{
2417 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
2418 {
2419 return (int)[m_osxView maxValue];
2420 }
2421 return 0;
2422}
2423
2424wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2425{
2426 wxBitmap bmp;
2427
2428 // TODO: how to create a wxBitmap from NSImage?
2429#if 0
2430 if ( [m_osxView respondsToSelector:@selector(image:)] )
2431 bmp = [m_osxView image];
2432#endif
2433
2434 return bmp;
2435}
2436
2437void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2438{
2439 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
2440 {
2441 if (bitmap.IsOk())
2442 [m_osxView setImage:bitmap.GetNSImage()];
2443 else
2444 [m_osxView setImage:nil];
2445
2446 [m_osxView setNeedsDisplay:YES];
2447 }
2448}
2449
2450void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2451{
2452 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2453 {
2454 NSCellImagePosition pos;
2455 switch ( dir )
2456 {
2457 case wxLEFT:
2458 pos = NSImageLeft;
2459 break;
2460
2461 case wxRIGHT:
2462 pos = NSImageRight;
2463 break;
2464
2465 case wxTOP:
2466 pos = NSImageAbove;
2467 break;
2468
2469 case wxBOTTOM:
2470 pos = NSImageBelow;
2471 break;
2472
2473 default:
2474 wxFAIL_MSG( "invalid image position" );
2475 pos = NSNoImage;
2476 }
2477
2478 [m_osxView setImagePosition:pos];
2479 }
2480}
2481
2482void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2483{
2484 // implementation in subclass
2485}
2486
2487void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2488{
2489 r->x = r->y = r->width = r->height = 0;
2490
2491 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2492 {
2493 NSRect former = [m_osxView frame];
2494 [m_osxView sizeToFit];
2495 NSRect best = [m_osxView frame];
2496 [m_osxView setFrame:former];
2497 r->width = (int)best.size.width;
2498 r->height = (int)best.size.height;
2499 }
2500}
2501
2502bool wxWidgetCocoaImpl::IsEnabled() const
2503{
2504 NSView* targetView = m_osxView;
2505 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2506 targetView = [(NSScrollView*) m_osxView documentView];
2507
2508 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2509 return [targetView isEnabled];
2510 return true;
2511}
2512
2513void wxWidgetCocoaImpl::Enable( bool enable )
2514{
2515 NSView* targetView = m_osxView;
2516 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2517 targetView = [(NSScrollView*) m_osxView documentView];
2518
2519 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2520 [targetView setEnabled:enable];
2521}
2522
2523void wxWidgetCocoaImpl::PulseGauge()
2524{
2525}
2526
2527void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2528{
2529}
2530
2531void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2532{
2533 NSControlSize size = NSRegularControlSize;
2534
2535 switch ( variant )
2536 {
2537 case wxWINDOW_VARIANT_NORMAL :
2538 size = NSRegularControlSize;
2539 break ;
2540
2541 case wxWINDOW_VARIANT_SMALL :
2542 size = NSSmallControlSize;
2543 break ;
2544
2545 case wxWINDOW_VARIANT_MINI :
2546 size = NSMiniControlSize;
2547 break ;
2548
2549 case wxWINDOW_VARIANT_LARGE :
2550 size = NSRegularControlSize;
2551 break ;
2552
2553 default:
2554 wxFAIL_MSG(wxT("unexpected window variant"));
2555 break ;
2556 }
2557 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2558 [m_osxView setControlSize:size];
2559 else if ([m_osxView respondsToSelector:@selector(cell)])
2560 {
2561 id cell = [(id)m_osxView cell];
2562 if ([cell respondsToSelector:@selector(setControlSize:)])
2563 [cell setControlSize:size];
2564 }
2565
2566 // we need to propagate this to inner views as well
2567 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2568 {
2569 NSView* targetView = [(NSScrollView*) m_osxView documentView];
2570
2571 if ( [targetView respondsToSelector:@selector(setControlSize:)] )
2572 [targetView setControlSize:size];
2573 else if ([targetView respondsToSelector:@selector(cell)])
2574 {
2575 id cell = [(id)targetView cell];
2576 if ([cell respondsToSelector:@selector(setControlSize:)])
2577 [cell setControlSize:size];
2578 }
2579 }
2580}
2581
2582void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2583{
2584 NSView* targetView = m_osxView;
2585 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2586 targetView = [(NSScrollView*) m_osxView documentView];
2587
2588 if ([targetView respondsToSelector:@selector(setFont:)])
2589 [targetView setFont: font.OSXGetNSFont()];
2590 if ([targetView respondsToSelector:@selector(setTextColor:)])
2591 [targetView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2592 green:(CGFloat) (col.Green() / 255.0)
2593 blue:(CGFloat) (col.Blue() / 255.0)
2594 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2595}
2596
2597void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2598{
2599 if ( tooltip )
2600 {
2601 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2602 [m_osxView setToolTip: cf.AsNSString()];
2603 }
2604 else
2605 {
2606 [m_osxView setToolTip:nil];
2607 }
2608}
2609
2610void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2611{
2612 WXWidget c = control ? control : (WXWidget) m_osxView;
2613 wxWidgetImpl::Associate( c, this ) ;
2614 if ([c respondsToSelector:@selector(setAction:)])
2615 {
2616 [c setTarget: c];
2617 if ( dynamic_cast<wxRadioButton*>(GetWXPeer()) )
2618 {
2619 // everything already set up
2620 }
2621 else
2622 [c setAction: @selector(controlAction:)];
2623
2624 if ([c respondsToSelector:@selector(setDoubleAction:)])
2625 {
2626 [c setDoubleAction: @selector(controlDoubleAction:)];
2627 }
2628
2629 }
2630 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingCursorUpdate|NSTrackingMouseMoved|NSTrackingActiveAlways|NSTrackingInVisibleRect;
2631 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: NSZeroRect options: options owner: m_osxView userInfo: nil];
2632 [m_osxView addTrackingArea: area];
2633 [area release];
2634 }
2635
2636bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2637{
2638 bool result = false;
2639
2640 for (NSUInteger i = 0; i < [text length]; ++i)
2641 {
2642 wxKeyEvent wxevent(wxEVT_CHAR);
2643 unichar c = [text characterAtIndex:i];
2644 SetupKeyEvent( wxevent, event, [NSString stringWithCharacters:&c length:1]);
2645
2646 result = GetWXPeer()->OSXHandleKeyEvent(wxevent) || result;
2647 }
2648
2649 return result;
2650}
2651
2652bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2653{
2654 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2655 SetupKeyEvent( wxevent, event );
2656
2657 // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2658 // the key is pressed, not when it's released (the type of wxevent is
2659 // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2660 if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2661 {
2662 wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2663 if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2664 && !eventHook.IsNextEventAllowed() )
2665 return true;
2666 }
2667
2668 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2669
2670 // this will fire higher level events, like insertText, to help
2671 // us handle EVT_CHAR, etc.
2672
2673 if ( !result )
2674 {
2675 if ( [event type] == NSKeyDown)
2676 {
2677 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2678
2679 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2680 {
2681 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2682 wxKeyEvent wxevent2(wxevent) ;
2683 wxevent2.SetEventType(wxEVT_CHAR);
2684 SetupKeyEvent( wxevent2, event );
2685 wxevent2.m_keyCode = keycode;
2686 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2687 }
2688 else if (wxevent.CmdDown())
2689 {
2690 wxKeyEvent wxevent2(wxevent) ;
2691 wxevent2.SetEventType(wxEVT_CHAR);
2692 SetupKeyEvent( wxevent2, event );
2693 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2694 }
2695 else
2696 {
2697 if ( IsUserPane() && !wxevent.CmdDown() )
2698 {
2699 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2700 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2701 else
2702 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2703 result = true;
2704 }
2705 }
2706 }
2707 }
2708
2709 return result;
2710}
2711
2712bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2713{
2714 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2715 SetupMouseEvent(wxevent , event) ;
2716 bool result = GetWXPeer()->HandleWindowEvent(wxevent);
2717
2718 (void)SetupCursor(event);
2719
2720 return result;
2721}
2722
2723void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2724{
2725 wxWindow* thisWindow = GetWXPeer();
2726 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2727 {
2728 thisWindow->MacInvalidateBorders();
2729 }
2730
2731 if ( receivedFocus )
2732 {
2733 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2734 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2735 thisWindow->HandleWindowEvent(eventFocus);
2736
2737#if wxUSE_CARET
2738 if ( thisWindow->GetCaret() )
2739 thisWindow->GetCaret()->OnSetFocus();
2740#endif
2741
2742 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2743 event.SetEventObject(thisWindow);
2744 if (otherWindow)
2745 event.SetWindow(otherWindow->GetWXPeer());
2746 thisWindow->HandleWindowEvent(event) ;
2747 }
2748 else // !receivedFocus
2749 {
2750#if wxUSE_CARET
2751 if ( thisWindow->GetCaret() )
2752 thisWindow->GetCaret()->OnKillFocus();
2753#endif
2754
2755 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2756
2757 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2758 event.SetEventObject(thisWindow);
2759 if (otherWindow)
2760 event.SetWindow(otherWindow->GetWXPeer());
2761 thisWindow->HandleWindowEvent(event) ;
2762 }
2763}
2764
2765void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2766{
2767 if ( !wxIsBusy() )
2768 {
2769 NSPoint location = [NSEvent mouseLocation];
2770 location = [[m_osxView window] convertScreenToBase:location];
2771 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2772
2773 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2774 {
2775 [(NSCursor*)cursor.GetHCURSOR() set];
2776 }
2777 }
2778}
2779
2780void wxWidgetCocoaImpl::CaptureMouse()
2781{
2782 // TODO remove if we don't get into problems with cursor settings
2783 // [[m_osxView window] disableCursorRects];
2784}
2785
2786void wxWidgetCocoaImpl::ReleaseMouse()
2787{
2788 // TODO remove if we don't get into problems with cursor settings
2789 // [[m_osxView window] enableCursorRects];
2790}
2791
2792#if !wxOSX_USE_NATIVE_FLIPPED
2793
2794void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2795{
2796 m_isFlipped = flipped;
2797}
2798
2799#endif
2800
2801void wxWidgetCocoaImpl::SetDrawingEnabled(bool enabled)
2802{
2803 if ( enabled )
2804 {
2805 [[m_osxView window] enableFlushWindow];
2806 [m_osxView setNeedsDisplay:YES];
2807 }
2808 else
2809 {
2810 [[m_osxView window] disableFlushWindow];
2811 }
2812}
2813//
2814// Factory methods
2815//
2816
2817wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2818 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2819 long WXUNUSED(style), long WXUNUSED(extraStyle))
2820{
2821 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2822 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2823
2824 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2825 return c;
2826}
2827
2828wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2829{
2830 NSWindow* tlw = now->GetWXWindow();
2831
2832 wxWidgetCocoaImpl* c = NULL;
2833 if ( now->IsNativeWindowWrapper() )
2834 {
2835 NSView* cv = [tlw contentView];
2836 c = new wxWidgetCocoaImpl( now, cv, true );
2837 if ( cv != nil )
2838 {
2839 // increase ref count, because the impl destructor will decrement it again
2840 CFRetain(cv);
2841 if ( !now->IsShown() )
2842 [cv setHidden:NO];
2843 }
2844 }
2845 else
2846 {
2847 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2848 c = new wxWidgetCocoaImpl( now, v, true );
2849 c->InstallEventHandler();
2850 [tlw setContentView:v];
2851 }
2852 return c;
2853}