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