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