]> git.saurik.com Git - wxWidgets.git/blob - src/osx/cocoa/window.mm
Remove all lines containing cvs/svn "$Id$" keyword.
[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 // Copyright: (c) Stefan Csomor
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
10
11 #include "wx/wxprec.h"
12
13 #ifndef WX_PRECOMP
14 #include "wx/dcclient.h"
15 #include "wx/frame.h"
16 #include "wx/log.h"
17 #include "wx/textctrl.h"
18 #include "wx/combobox.h"
19 #include "wx/radiobut.h"
20 #endif
21
22 #ifdef __WXMAC__
23 #include "wx/osx/private.h"
24 #endif
25
26 #include "wx/evtloop.h"
27
28 #if wxUSE_CARET
29 #include "wx/caret.h"
30 #endif
31
32 #if wxUSE_DRAG_AND_DROP
33 #include "wx/dnd.h"
34 #endif
35
36 #if wxUSE_TOOLTIPS
37 #include "wx/tooltip.h"
38 #endif
39
40 #include <objc/objc-runtime.h>
41
42 // Get the window with the focus
43
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 // wx conventions for horizontal are inverted from vertical (originating from native msw behavior)
690 // right and up are positive values, left and down are negative values, while on OSX right and down
691 // are negative and left and up are positive.
692 wxevent.m_wheelAxis = wxMOUSE_WHEEL_HORIZONTAL;
693 wxevent.m_wheelRotation = -(int)deltaX;
694 }
695 else
696 {
697 wxevent.m_wheelRotation = (int)deltaY;
698 }
699
700 }
701 break ;
702
703 case NSMouseEntered :
704 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
705 break;
706 case NSMouseExited :
707 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
708 break;
709 case NSLeftMouseDragged :
710 case NSRightMouseDragged :
711 case NSOtherMouseDragged :
712 case NSMouseMoved :
713 wxevent.SetEventType( wxEVT_MOTION ) ;
714 break;
715 default :
716 break ;
717 }
718
719 wxevent.m_clickCount = clickCount;
720 wxWindowMac* peer = GetWXPeer();
721 if ( peer )
722 {
723 wxevent.SetEventObject(peer);
724 wxevent.SetId(peer->GetId()) ;
725 }
726 }
727
728 @implementation wxNSView
729
730 + (void)initialize
731 {
732 static BOOL initialized = NO;
733 if (!initialized)
734 {
735 initialized = YES;
736 wxOSXCocoaClassAddWXMethods( self );
737 }
738 }
739
740 /* idea taken from webkit sources: overwrite the methods that (private) NSToolTipManager will use to attach its tracking rectangle
741 * then when changing the tooltip send fake view-exit and view-enter methods which will lead to a tooltip refresh
742 */
743
744
745 - (void)_sendToolTipMouseExited
746 {
747 // Nothing matters except window, trackingNumber, and userData.
748 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
749 location:NSMakePoint(0, 0)
750 modifierFlags:0
751 timestamp:0
752 windowNumber:[[self window] windowNumber]
753 context:NULL
754 eventNumber:0
755 trackingNumber:_lastToolTipTrackTag
756 userData:_lastUserData];
757 [_lastToolTipOwner mouseExited:fakeEvent];
758 }
759
760 - (void)_sendToolTipMouseEntered
761 {
762 // Nothing matters except window, trackingNumber, and userData.
763 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
764 location:NSMakePoint(0, 0)
765 modifierFlags:0
766 timestamp:0
767 windowNumber:[[self window] windowNumber]
768 context:NULL
769 eventNumber:0
770 trackingNumber:_lastToolTipTrackTag
771 userData:_lastUserData];
772 [_lastToolTipOwner mouseEntered:fakeEvent];
773 }
774
775 - (void)setToolTip:(NSString *)string;
776 {
777 if (string)
778 {
779 if ( _hasToolTip )
780 {
781 [self _sendToolTipMouseExited];
782 }
783
784 [super setToolTip:string];
785 _hasToolTip = YES;
786 [self _sendToolTipMouseEntered];
787 }
788 else
789 {
790 if ( _hasToolTip )
791 {
792 [self _sendToolTipMouseExited];
793 [super setToolTip:nil];
794 _hasToolTip = NO;
795 }
796 }
797 }
798
799 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
800 {
801 NSTrackingRectTag tag = [super addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
802 if ( owner != self )
803 {
804 _lastUserData = data;
805 _lastToolTipOwner = owner;
806 _lastToolTipTrackTag = tag;
807 }
808 return tag;
809 }
810
811 - (void)removeTrackingRect:(NSTrackingRectTag)tag
812 {
813 if (tag == _lastToolTipTrackTag)
814 {
815 _lastUserData = NULL;
816 _lastToolTipOwner = nil;
817 _lastToolTipTrackTag = 0;
818 }
819 [super removeTrackingRect:tag];
820 }
821
822 #if wxOSX_USE_NATIVE_FLIPPED
823 - (BOOL)isFlipped
824 {
825 return YES;
826 }
827 #endif
828
829 - (BOOL) canBecomeKeyView
830 {
831 wxWidgetCocoaImpl* viewimpl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
832 if ( viewimpl && viewimpl->IsUserPane() && viewimpl->GetWXPeer() )
833 return viewimpl->GetWXPeer()->AcceptsFocus();
834 return NO;
835 }
836
837 @end // wxNSView
838
839 //
840 // event handlers
841 //
842
843 #if wxUSE_DRAG_AND_DROP
844
845 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
846 // for details on the NSPasteboard -> PasteboardRef conversion
847
848 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
849 {
850 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
851 if (impl == NULL)
852 return NSDragOperationNone;
853
854 return impl->draggingEntered(sender, self, _cmd);
855 }
856
857 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
858 {
859 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
860 if (impl == NULL)
861 return ;
862
863 return impl->draggingExited(sender, self, _cmd);
864 }
865
866 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
867 {
868 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
869 if (impl == NULL)
870 return NSDragOperationNone;
871
872 return impl->draggingUpdated(sender, self, _cmd);
873 }
874
875 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
876 {
877 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
878 if (impl == NULL)
879 return NSDragOperationNone;
880
881 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
882 }
883
884 #endif
885
886 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
887 {
888 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
889 if (impl == NULL)
890 return;
891
892 impl->mouseEvent(event, self, _cmd);
893 }
894
895 void wxOSX_cursorUpdate(NSView* self, SEL _cmd, NSEvent *event)
896 {
897 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
898 if (impl == NULL)
899 return;
900
901 impl->cursorUpdate(event, self, _cmd);
902 }
903
904 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
905 {
906 // This is needed to support click through, otherwise the first click on a window
907 // will not do anything unless it is the active window already.
908 return YES;
909 }
910
911 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
912 {
913 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
914 if (impl == NULL)
915 return;
916
917 impl->keyEvent(event, self, _cmd);
918 }
919
920 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
921 {
922 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
923 if (impl == NULL)
924 return;
925
926 impl->insertText(text, self, _cmd);
927 }
928
929 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
930 {
931 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
932 if (impl == NULL)
933 return NO;
934
935 return impl->performKeyEquivalent(event, self, _cmd);
936 }
937
938 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
939 {
940 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
941 if (impl == NULL)
942 return NO;
943
944 return impl->acceptsFirstResponder(self, _cmd);
945 }
946
947 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
948 {
949 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
950 if (impl == NULL)
951 return NO;
952
953 return impl->becomeFirstResponder(self, _cmd);
954 }
955
956 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
957 {
958 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
959 if (impl == NULL)
960 return NO;
961
962 return impl->resignFirstResponder(self, _cmd);
963 }
964
965 #if !wxOSX_USE_NATIVE_FLIPPED
966
967 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
968 {
969 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
970 if (impl == NULL)
971 return NO;
972
973 return impl->isFlipped(self, _cmd) ? YES:NO;
974 }
975
976 #endif
977
978 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
979
980 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
981 {
982 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
983 if (impl == NULL)
984 return;
985
986 #if wxUSE_THREADS
987 // OS X starts a NSUIHeartBeatThread for animating the default button in a
988 // dialog. This causes a drawRect of the active dialog from outside the
989 // main UI thread. This causes an occasional crash since the wx drawing
990 // objects (like wxPen) are not thread safe.
991 //
992 // Notice that NSUIHeartBeatThread seems to be undocumented and doing
993 // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
994 if ( !wxThread::IsMain() )
995 {
996 if ( impl->IsUserPane() )
997 {
998 wxWindow* win = impl->GetWXPeer();
999 if ( win->UseBgCol() )
1000 {
1001
1002 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1003 CGContextSaveGState( context );
1004
1005 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
1006 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
1007 CGContextFillRect( context, r );
1008
1009 CGContextRestoreGState( context );
1010 }
1011 }
1012 else
1013 {
1014 // just call the superclass handler, we don't need any custom wx drawing
1015 // here and it seems to work fine:
1016 wxOSX_DrawRectHandlerPtr
1017 superimpl = (wxOSX_DrawRectHandlerPtr)
1018 [[self superclass] instanceMethodForSelector:_cmd];
1019 superimpl(self, _cmd, rect);
1020 }
1021
1022 return;
1023 }
1024 #endif // wxUSE_THREADS
1025
1026 return impl->drawRect(&rect, self, _cmd);
1027 }
1028
1029 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
1030 {
1031 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1032 if (impl == NULL)
1033 return;
1034
1035 impl->controlAction(self, _cmd, sender);
1036 }
1037
1038 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
1039 {
1040 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1041 if (impl == NULL)
1042 return;
1043
1044 impl->controlDoubleAction(self, _cmd, sender);
1045 }
1046
1047 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1048 {
1049 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1050 NSPasteboard *pboard = [sender draggingPasteboard];
1051 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1052
1053 wxWindow* wxpeer = GetWXPeer();
1054 if ( wxpeer == NULL )
1055 return NSDragOperationNone;
1056
1057 wxDropTarget* target = wxpeer->GetDropTarget();
1058 if ( target == NULL )
1059 return NSDragOperationNone;
1060
1061 wxDragResult result = wxDragNone;
1062 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1063 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1064
1065 if ( sourceDragMask & NSDragOperationLink )
1066 result = wxDragLink;
1067 else if ( sourceDragMask & NSDragOperationCopy )
1068 result = wxDragCopy;
1069 else if ( sourceDragMask & NSDragOperationMove )
1070 result = wxDragMove;
1071
1072 PasteboardRef pboardRef;
1073 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1074 target->SetCurrentDragPasteboard(pboardRef);
1075 result = target->OnEnter(pt.x, pt.y, result);
1076 CFRelease(pboardRef);
1077
1078 NSDragOperation nsresult = NSDragOperationNone;
1079 switch (result )
1080 {
1081 case wxDragLink:
1082 nsresult = NSDragOperationLink;
1083 case wxDragMove:
1084 nsresult = NSDragOperationMove;
1085 case wxDragCopy:
1086 nsresult = NSDragOperationCopy;
1087 default :
1088 break;
1089 }
1090 return nsresult;
1091 }
1092
1093 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1094 {
1095 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1096 NSPasteboard *pboard = [sender draggingPasteboard];
1097
1098 wxWindow* wxpeer = GetWXPeer();
1099 if ( wxpeer == NULL )
1100 return;
1101
1102 wxDropTarget* target = wxpeer->GetDropTarget();
1103 if ( target == NULL )
1104 return;
1105
1106 PasteboardRef pboardRef;
1107 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1108 target->SetCurrentDragPasteboard(pboardRef);
1109 target->OnLeave();
1110 CFRelease(pboardRef);
1111 }
1112
1113 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1114 {
1115 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1116 NSPasteboard *pboard = [sender draggingPasteboard];
1117 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1118
1119 wxWindow* wxpeer = GetWXPeer();
1120 if ( wxpeer == NULL )
1121 return NSDragOperationNone;
1122
1123 wxDropTarget* target = wxpeer->GetDropTarget();
1124 if ( target == NULL )
1125 return NSDragOperationNone;
1126
1127 wxDragResult result = wxDragNone;
1128 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1129 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1130
1131 if ( sourceDragMask & NSDragOperationLink )
1132 result = wxDragLink;
1133 else if ( sourceDragMask & NSDragOperationCopy )
1134 result = wxDragCopy;
1135 else if ( sourceDragMask & NSDragOperationMove )
1136 result = wxDragMove;
1137
1138 PasteboardRef pboardRef;
1139 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1140 target->SetCurrentDragPasteboard(pboardRef);
1141 result = target->OnDragOver(pt.x, pt.y, result);
1142 CFRelease(pboardRef);
1143
1144 NSDragOperation nsresult = NSDragOperationNone;
1145 switch (result )
1146 {
1147 case wxDragLink:
1148 nsresult = NSDragOperationLink;
1149 case wxDragMove:
1150 nsresult = NSDragOperationMove;
1151 case wxDragCopy:
1152 nsresult = NSDragOperationCopy;
1153 default :
1154 break;
1155 }
1156 return nsresult;
1157 }
1158
1159 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1160 {
1161 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1162
1163 NSPasteboard *pboard = [sender draggingPasteboard];
1164 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1165
1166 wxWindow* wxpeer = GetWXPeer();
1167 wxDropTarget* target = wxpeer->GetDropTarget();
1168 wxDragResult result = wxDragNone;
1169 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1170 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1171
1172 if ( sourceDragMask & NSDragOperationLink )
1173 result = wxDragLink;
1174 else if ( sourceDragMask & NSDragOperationCopy )
1175 result = wxDragCopy;
1176 else if ( sourceDragMask & NSDragOperationMove )
1177 result = wxDragMove;
1178
1179 PasteboardRef pboardRef;
1180 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1181 target->SetCurrentDragPasteboard(pboardRef);
1182
1183 if (target->OnDrop(pt.x, pt.y))
1184 result = target->OnData(pt.x, pt.y, result);
1185
1186 CFRelease(pboardRef);
1187
1188 return result != wxDragNone;
1189 }
1190
1191 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1192 {
1193 // we are getting moved events for all windows in the hierarchy, not something wx expects
1194 // therefore we only handle it for the deepest child in the hierarchy
1195 if ( [event type] == NSMouseMoved )
1196 {
1197 NSView* hitview = [[[slf window] contentView] hitTest:[event locationInWindow]];
1198 if ( hitview == NULL || hitview != slf)
1199 return;
1200 }
1201
1202 if ( !DoHandleMouseEvent(event) )
1203 {
1204 // for plain NSView mouse events would propagate to parents otherwise
1205 // scrollwheel events have to be propagated if not handled in all cases
1206 if (!IsUserPane() || [event type] == NSScrollWheel )
1207 {
1208 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1209 superimpl(slf, (SEL)_cmd, event);
1210
1211 // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
1212 // only trigger if at this moment the mouse is already up
1213 if ( [ event type] == NSLeftMouseDown && !wxGetMouseState().LeftIsDown() )
1214 {
1215 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1216 SetupMouseEvent(wxevent , event) ;
1217 wxevent.SetEventType(wxEVT_LEFT_UP);
1218
1219 GetWXPeer()->HandleWindowEvent(wxevent);
1220 }
1221 }
1222 }
1223 }
1224
1225 void wxWidgetCocoaImpl::cursorUpdate(WX_NSEvent event, WXWidget slf, void *_cmd)
1226 {
1227 if ( !SetupCursor(event) )
1228 {
1229 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1230 superimpl(slf, (SEL)_cmd, event);
1231 }
1232 }
1233
1234 bool wxWidgetCocoaImpl::SetupCursor(WX_NSEvent event)
1235 {
1236 extern wxCursor gGlobalCursor;
1237
1238 if ( gGlobalCursor.IsOk() )
1239 {
1240 gGlobalCursor.MacInstall();
1241 return true;
1242 }
1243 else
1244 {
1245 wxWindow* cursorTarget = GetWXPeer();
1246 wxCoord x,y;
1247 SetupCoordinates(x, y, event);
1248 wxPoint cursorPoint( x , y ) ;
1249
1250 while ( cursorTarget && !cursorTarget->MacSetupCursor( cursorPoint ) )
1251 {
1252 // at least in GTK cursor events are not propagated either ...
1253 #if 1
1254 cursorTarget = NULL;
1255 #else
1256 cursorTarget = cursorTarget->GetParent() ;
1257 if ( cursorTarget )
1258 cursorPoint += cursorTarget->GetPosition();
1259 #endif
1260 }
1261
1262 return cursorTarget != NULL;
1263 }
1264 }
1265
1266 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1267 {
1268 if ( [event type] == NSKeyDown )
1269 {
1270 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1271 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1272 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1273 return;
1274
1275 m_lastKeyDownEvent = event;
1276 }
1277
1278 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1279 {
1280 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1281 superimpl(slf, (SEL)_cmd, event);
1282 }
1283 m_lastKeyDownEvent = NULL;
1284 }
1285
1286 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1287 {
1288 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1289 {
1290 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1291 superimpl(slf, (SEL)_cmd, text);
1292 }
1293 }
1294
1295
1296 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1297 {
1298 bool handled = false;
1299
1300 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1301 SetupKeyEvent( wxevent, event );
1302
1303 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1304 // walk up the ancestors ourselves but let cocoa do it
1305
1306 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1307 if (command != -1)
1308 {
1309 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1310
1311 wxCommandEvent command_event( wxEVT_MENU, command );
1312 command_event.SetEventObject( wxevent.GetEventObject() );
1313 handled = handler->ProcessEvent( command_event );
1314
1315 if ( !handled )
1316 {
1317 // accelerators can also be used with buttons, try them too
1318 command_event.SetEventType(wxEVT_BUTTON);
1319 handled = handler->ProcessEvent( command_event );
1320 }
1321 }
1322
1323 if ( !handled )
1324 {
1325 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1326 return superimpl(slf, (SEL)_cmd, event);
1327 }
1328 return YES;
1329 }
1330
1331 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1332 {
1333 if ( IsUserPane() )
1334 return m_wxPeer->AcceptsFocus();
1335 else
1336 {
1337 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1338 return superimpl(slf, (SEL)_cmd);
1339 }
1340 }
1341
1342 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1343 {
1344 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1345 // get the current focus before running becomeFirstResponder
1346 NSView* otherView = FindFocus();
1347
1348 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1349 BOOL r = superimpl(slf, (SEL)_cmd);
1350 if ( r )
1351 {
1352 DoNotifyFocusEvent( true, otherWindow );
1353 }
1354
1355 return r;
1356 }
1357
1358 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1359 {
1360 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1361 BOOL r = superimpl(slf, (SEL)_cmd);
1362
1363 NSResponder * responder = wxNonOwnedWindowCocoaImpl::GetNextFirstResponder();
1364 NSView* otherView = wxOSXGetViewFromResponder(responder);
1365
1366 wxWidgetImpl* otherWindow = FindBestFromWXWidget(otherView);
1367
1368 // It doesn't make sense to notify about the loss of focus if it's the same
1369 // control in the end, and just a different subview
1370 if ( otherWindow == this )
1371 return r;
1372
1373 // NSTextViews have an editor as true responder, therefore the might get the
1374 // resign notification if their editor takes over, don't trigger any event then
1375 if ( r && !m_hasEditor)
1376 {
1377 DoNotifyFocusEvent( false, otherWindow );
1378 }
1379 return r;
1380 }
1381
1382 #if !wxOSX_USE_NATIVE_FLIPPED
1383
1384 bool wxWidgetCocoaImpl::isFlipped(WXWidget slf, void *WXUNUSED(_cmd))
1385 {
1386 return m_isFlipped;
1387 }
1388
1389 #endif
1390
1391 #define OSX_DEBUG_DRAWING 0
1392
1393 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1394 {
1395 // preparing the update region
1396
1397 wxRegion updateRgn;
1398
1399 // since adding many rects to a region is a costly process, by default use the bounding rect
1400 #if 0
1401 const NSRect *rects;
1402 NSInteger count;
1403 [slf getRectsBeingDrawn:&rects count:&count];
1404 for ( int i = 0 ; i < count ; ++i )
1405 {
1406 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1407 }
1408 #else
1409 updateRgn.Union(wxFromNSRect(slf,*(NSRect*)rect));
1410 #endif
1411
1412 wxWindow* wxpeer = GetWXPeer();
1413
1414 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1415 {
1416 // as this update region is in native window locals we must adapt it to wx window local
1417 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1418 }
1419
1420 // Restrict the update region to the shape of the window, if any, and also
1421 // remember the region that we need to clear later.
1422 wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1423 const bool isTopLevel = tlwParent == wxpeer;
1424 wxRegion clearRgn;
1425 if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1426 {
1427 if ( isTopLevel )
1428 clearRgn = updateRgn;
1429
1430 int xoffset = 0, yoffset = 0;
1431 wxRegion rgn = tlwParent->GetShape();
1432 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1433 rgn.Offset( xoffset, yoffset );
1434 updateRgn.Intersect(rgn);
1435
1436 if ( isTopLevel )
1437 {
1438 // Exclude the window shape from the region to be cleared below.
1439 rgn.Xor(wxpeer->GetSize());
1440 clearRgn.Intersect(rgn);
1441 }
1442 }
1443
1444 wxpeer->GetUpdateRegion() = updateRgn;
1445
1446 // setting up the drawing context
1447
1448 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1449 CGContextSaveGState( context );
1450
1451 #if OSX_DEBUG_DRAWING
1452 CGContextBeginPath( context );
1453 CGContextMoveToPoint(context, 0, 0);
1454 NSRect bounds = [slf bounds];
1455 CGContextAddLineToPoint(context, 10, 0);
1456 CGContextMoveToPoint(context, 0, 0);
1457 CGContextAddLineToPoint(context, 0, 10);
1458 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1459 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1460 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1461 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1462 CGContextClosePath( context );
1463 CGContextStrokePath(context);
1464 #endif
1465
1466 if ( ![slf isFlipped] )
1467 {
1468 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1469 CGContextScaleCTM( context, 1, -1 );
1470 }
1471
1472 wxpeer->MacSetCGContextRef( context );
1473
1474 bool handled = wxpeer->MacDoRedraw( 0 );
1475 CGContextRestoreGState( context );
1476
1477 CGContextSaveGState( context );
1478 if ( !handled )
1479 {
1480 // call super
1481 SEL _cmd = @selector(drawRect:);
1482 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1483 superimpl(slf, _cmd, *(NSRect*)rect);
1484 CGContextRestoreGState( context );
1485 CGContextSaveGState( context );
1486 }
1487 // as we called restore above, we have to flip again if necessary
1488 if ( ![slf isFlipped] )
1489 {
1490 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1491 CGContextScaleCTM( context, 1, -1 );
1492 }
1493
1494 if ( isTopLevel )
1495 {
1496 // We also need to explicitly draw the part of the top level window
1497 // outside of its region with transparent colour to ensure that it is
1498 // really transparent.
1499 if ( clearRgn.IsOk() )
1500 {
1501 wxMacCGContextStateSaver saveState(context);
1502 wxWindowDC dc(wxpeer);
1503 dc.SetBackground(wxBrush(wxTransparentColour));
1504 dc.SetDeviceClippingRegion(clearRgn);
1505 dc.Clear();
1506 }
1507
1508 #if wxUSE_GRAPHICS_CONTEXT
1509 // If the window shape is defined by a path, stroke the path to show
1510 // the window border.
1511 const wxGraphicsPath& path = tlwParent->GetShapePath();
1512 if ( !path.IsNull() )
1513 {
1514 CGContextSetLineWidth(context, 1);
1515 CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1516 CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1517 CGContextStrokePath(context);
1518 }
1519 #endif // wxUSE_GRAPHICS_CONTEXT
1520 }
1521
1522 wxpeer->MacPaintChildrenBorders();
1523 wxpeer->MacSetCGContextRef( NULL );
1524 CGContextRestoreGState( context );
1525 }
1526
1527 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1528 {
1529 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1530 if ( wxpeer )
1531 {
1532 wxpeer->OSXSimulateFocusEvents();
1533 wxpeer->OSXHandleClicked(0);
1534 }
1535 }
1536
1537 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1538 {
1539 }
1540
1541 void wxWidgetCocoaImpl::controlTextDidChange()
1542 {
1543 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1544 if ( wxpeer )
1545 {
1546 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1547 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1548 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1549 if ( tc )
1550 tc->SendTextUpdatedEventIfAllowed();
1551 else if ( cb )
1552 cb->SendTextUpdatedEventIfAllowed();
1553 else
1554 {
1555 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1556 }
1557 }
1558 }
1559
1560 //
1561
1562 #if OBJC_API_VERSION >= 2
1563
1564 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1565 class_addMethod(c, s, i, t );
1566
1567 #else
1568
1569 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1570 { s, (char*) t, i },
1571
1572 #endif
1573
1574 void wxOSXCocoaClassAddWXMethods(Class c)
1575 {
1576
1577 #if OBJC_API_VERSION < 2
1578 static objc_method wxmethods[] =
1579 {
1580 #endif
1581
1582 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1583 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1584 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1585
1586 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1587 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1588 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1589
1590 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1591
1592 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1593 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1594 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1595
1596 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1597
1598 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1599 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1600 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1601
1602 wxOSX_CLASS_ADD_METHOD(c, @selector(cursorUpdate:), (IMP) wxOSX_cursorUpdate, "v@:@" )
1603
1604 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1605 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1606 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1607
1608 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1609
1610 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1611
1612 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1613 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1614 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1615
1616 #if !wxOSX_USE_NATIVE_FLIPPED
1617 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1618 #endif
1619 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1620
1621 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1622 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1623
1624 #if wxUSE_DRAG_AND_DROP
1625 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1626 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1627 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1628 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1629 #endif
1630
1631 #if OBJC_API_VERSION < 2
1632 } ;
1633 static int method_count = WXSIZEOF( wxmethods );
1634 static objc_method_list *wxmethodlist = NULL;
1635 if ( wxmethodlist == NULL )
1636 {
1637 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1638 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1639 wxmethodlist->method_count = method_count;
1640 wxmethodlist->obsolete = 0;
1641 }
1642 class_addMethods( c, wxmethodlist );
1643 #endif
1644 }
1645
1646 //
1647 // C++ implementation class
1648 //
1649
1650 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1651
1652 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1653 wxWidgetImpl( peer, isRootControl, isUserPane )
1654 {
1655 Init();
1656 m_osxView = w;
1657
1658 // check if the user wants to create the control initially hidden
1659 if ( !peer->IsShown() )
1660 SetVisibility(false);
1661
1662 // gc aware handling
1663 if ( m_osxView )
1664 CFRetain(m_osxView);
1665 [m_osxView release];
1666 }
1667
1668 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1669 {
1670 Init();
1671 }
1672
1673 void wxWidgetCocoaImpl::Init()
1674 {
1675 m_osxView = NULL;
1676 #if !wxOSX_USE_NATIVE_FLIPPED
1677 m_isFlipped = true;
1678 #endif
1679 m_lastKeyDownEvent = NULL;
1680 m_hasEditor = false;
1681 }
1682
1683 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1684 {
1685 RemoveAssociations( this );
1686
1687 if ( !IsRootControl() )
1688 {
1689 NSView *sv = [m_osxView superview];
1690 if ( sv != nil )
1691 [m_osxView removeFromSuperview];
1692 }
1693 // gc aware handling
1694 if ( m_osxView )
1695 CFRelease(m_osxView);
1696 }
1697
1698 bool wxWidgetCocoaImpl::IsVisible() const
1699 {
1700 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1701 }
1702
1703 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1704 {
1705 [m_osxView setHidden:(visible ? NO:YES)];
1706 }
1707
1708 double wxWidgetCocoaImpl::GetContentScaleFactor() const
1709 {
1710 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
1711 NSWindow* tlw = [m_osxView window];
1712 if ( [ tlw respondsToSelector:@selector(backingScaleFactor) ] )
1713 return [tlw backingScaleFactor];
1714 else
1715 #endif
1716 return 1.0;
1717 }
1718
1719 // ----------------------------------------------------------------------------
1720 // window animation stuff
1721 // ----------------------------------------------------------------------------
1722
1723 // define a delegate used to refresh the window during animation
1724 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1725 {
1726 wxWindow *m_win;
1727 bool m_isDone;
1728 }
1729
1730 - (id)init:(wxWindow *)win;
1731
1732 - (bool)isDone;
1733
1734 // NSAnimationDelegate methods
1735 - (void)animationDidEnd:(NSAnimation*)animation;
1736 - (void)animation:(NSAnimation*)animation
1737 didReachProgressMark:(NSAnimationProgress)progress;
1738 @end
1739
1740 @implementation wxNSAnimationDelegate
1741
1742 - (id)init:(wxWindow *)win
1743 {
1744 self = [super init];
1745
1746 m_win = win;
1747 m_isDone = false;
1748
1749 return self;
1750 }
1751
1752 - (bool)isDone
1753 {
1754 return m_isDone;
1755 }
1756
1757 - (void)animation:(NSAnimation*)animation
1758 didReachProgressMark:(NSAnimationProgress)progress
1759 {
1760 wxUnusedVar(animation);
1761 wxUnusedVar(progress);
1762
1763 m_win->SendSizeEvent();
1764 }
1765
1766 - (void)animationDidEnd:(NSAnimation*)animation
1767 {
1768 wxUnusedVar(animation);
1769 m_isDone = true;
1770 }
1771
1772 @end
1773
1774 /* static */
1775 bool
1776 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1777 bool show,
1778 wxShowEffect effect,
1779 unsigned timeout)
1780 {
1781 // create the dictionary describing the animation to perform on this view
1782 NSObject * const
1783 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1784 NSMutableDictionary * const
1785 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1786 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1787
1788 // determine the start and end rectangles assuming we're hiding the window
1789 const wxRect rectOrig = win->GetRect();
1790 wxRect rectStart,
1791 rectEnd;
1792 rectStart =
1793 rectEnd = rectOrig;
1794
1795 if ( show )
1796 {
1797 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1798 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1799 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1800 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1801 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1802 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1803 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1804 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1805 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1806 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1807 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1808 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1809 }
1810
1811 switch ( effect )
1812 {
1813 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1814 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1815 rectEnd.width = 0;
1816 break;
1817
1818 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1819 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1820 rectEnd.x = rectStart.GetRight();
1821 rectEnd.width = 0;
1822 break;
1823
1824 case wxSHOW_EFFECT_ROLL_TO_TOP:
1825 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1826 rectEnd.height = 0;
1827 break;
1828
1829 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1830 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1831 rectEnd.y = rectStart.GetBottom();
1832 rectEnd.height = 0;
1833 break;
1834
1835 case wxSHOW_EFFECT_EXPAND:
1836 rectEnd.x = rectStart.x + rectStart.width / 2;
1837 rectEnd.y = rectStart.y + rectStart.height / 2;
1838 rectEnd.width =
1839 rectEnd.height = 0;
1840 break;
1841
1842 case wxSHOW_EFFECT_BLEND:
1843 [dict setObject:(show ? NSViewAnimationFadeInEffect
1844 : NSViewAnimationFadeOutEffect)
1845 forKey:NSViewAnimationEffectKey];
1846 break;
1847
1848 case wxSHOW_EFFECT_NONE:
1849 case wxSHOW_EFFECT_MAX:
1850 wxFAIL_MSG( "unexpected animation effect" );
1851 return false;
1852
1853 default:
1854 wxFAIL_MSG( "unknown animation effect" );
1855 return false;
1856 };
1857
1858 if ( show )
1859 {
1860 // we need to restore it to the original rectangle instead of making it
1861 // disappear
1862 wxSwap(rectStart, rectEnd);
1863
1864 // and as the window is currently hidden, we need to show it for the
1865 // animation to be visible at all (but don't restore it at its full
1866 // rectangle as it shouldn't appear immediately)
1867 win->SetSize(rectStart);
1868 win->Show();
1869 }
1870
1871 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1872 ? [(NSView *)viewOrWin superview]
1873 : nil;
1874 const NSRect rStart = wxToNSRect(parentView, rectStart);
1875 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1876
1877 [dict setObject:[NSValue valueWithRect:rStart]
1878 forKey:NSViewAnimationStartFrameKey];
1879 [dict setObject:[NSValue valueWithRect:rEnd]
1880 forKey:NSViewAnimationEndFrameKey];
1881
1882 // create an animation using the values in the above dictionary
1883 NSViewAnimation * const
1884 anim = [[NSViewAnimation alloc]
1885 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1886
1887 if ( !timeout )
1888 {
1889 // what is a good default duration? Windows uses 200ms, Web frameworks
1890 // use anything from 250ms to 1s... choose something in the middle
1891 timeout = 500;
1892 }
1893
1894 [anim setDuration:timeout/1000.]; // duration is in seconds here
1895
1896 // if the window being animated changes its layout depending on its size
1897 // (which is almost always the case) we need to redo it during animation
1898 //
1899 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1900 // controls in wxInfoBar visibly jump around)
1901 const int NUM_LAYOUTS = 20;
1902 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1903 [anim addProgressMark:f];
1904
1905 wxNSAnimationDelegate * const
1906 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1907 [anim setDelegate:animDelegate];
1908 [anim startAnimation];
1909
1910 // Cocoa is capable of doing animation asynchronously or even from separate
1911 // thread but wx API doesn't provide any way to be notified about the
1912 // animation end and without this we really must ensure that the window has
1913 // the expected (i.e. the same as if a simple Show() had been used) size
1914 // when we return, so block here until the animation finishes
1915 //
1916 // notice that because the default animation mode is NSAnimationBlocking,
1917 // no user input events ought to be processed from here
1918 {
1919 wxEventLoopGuarantor ensureEventLoopExistence;
1920 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1921 while ( ![animDelegate isDone] )
1922 loop->Dispatch();
1923 }
1924
1925 if ( !show )
1926 {
1927 // NSViewAnimation is smart enough to hide the NSView being animated at
1928 // the end but we also must ensure that it's hidden for wx too
1929 win->Hide();
1930
1931 // and we must also restore its size because it isn't expected to
1932 // change just because the window was hidden
1933 win->SetSize(rectOrig);
1934 }
1935 else
1936 {
1937 // refresh it once again after the end to ensure that everything is in
1938 // place
1939 win->SendSizeEvent();
1940 }
1941
1942 [anim setDelegate:nil];
1943 [animDelegate release];
1944 [anim release];
1945
1946 return true;
1947 }
1948
1949 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1950 wxShowEffect effect,
1951 unsigned timeout)
1952 {
1953 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1954 }
1955
1956 /* note that the drawing order between siblings is not defined under 10.4 */
1957 /* only starting from 10.5 the subview order is respected */
1958
1959 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1960 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
1961 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
1962 * expects a function returning the new non-enum NSComparsionResult.
1963 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1964 */
1965 #if defined(NSINTEGER_DEFINED)
1966 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1967 #else
1968 typedef int CocoaWindowCompareFunctionResult;
1969 #endif
1970
1971 class CocoaWindowCompareContext
1972 {
1973 wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1974 public:
1975 CocoaWindowCompareContext(); // Not implemented
1976 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1977 {
1978 m_target = target;
1979 // Cocoa sorts subviews in-place.. make a copy
1980 m_subviews = [subviews copy];
1981 }
1982
1983 ~CocoaWindowCompareContext()
1984 { // release the copy
1985 [m_subviews release];
1986 }
1987 NSView* target()
1988 { return m_target; }
1989
1990 NSArray* subviews()
1991 { return m_subviews; }
1992
1993 /* Helper function that returns the comparison based off of the original ordering */
1994 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1995 {
1996 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1997 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1998 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1999 // likely compare higher than the other view which is reasonable considering the only way that
2000 // can happen is if the subview was added after our call to subviews but before the call to
2001 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
2002 // that case should never occur anyway because that would imply a multi-threaded GUI call
2003 // which is a big no-no with Cocoa.
2004
2005 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
2006 NSComparisonResult result = (firstI < secondI)
2007 ? NSOrderedAscending /* -1 */
2008 : (firstI > secondI)
2009 ? NSOrderedDescending /* 1 */
2010 : NSOrderedSame /* 0 */;
2011
2012 return result;
2013 }
2014 private:
2015 /* The subview we are trying to Raise or Lower */
2016 NSView *m_target;
2017 /* A copy of the original array of subviews */
2018 NSArray *m_subviews;
2019 };
2020
2021 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
2022 * the target view is always higher than every other view. When comparing two views neither of
2023 * which is the target, it returns the correct response based on the original ordering
2024 */
2025 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
2026 {
2027 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2028 // first should be ordered higher
2029 if(first==compareContext->target())
2030 return NSOrderedDescending;
2031 // second should be ordered higher
2032 if(second==compareContext->target())
2033 return NSOrderedAscending;
2034 return compareContext->CompareUsingOriginalOrdering(first,second);
2035 }
2036
2037 void wxWidgetCocoaImpl::Raise()
2038 {
2039 NSView* nsview = m_osxView;
2040
2041 NSView *superview = [nsview superview];
2042 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2043
2044 [superview sortSubviewsUsingFunction:
2045 CocoaRaiseWindowCompareFunction
2046 context: &compareContext];
2047
2048 }
2049
2050 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
2051 * the target view is always lower than every other view. When comparing two views neither of
2052 * which is the target, it returns the correct response based on the original ordering
2053 */
2054 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
2055 {
2056 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2057 // first should be ordered lower
2058 if(first==compareContext->target())
2059 return NSOrderedAscending;
2060 // second should be ordered lower
2061 if(second==compareContext->target())
2062 return NSOrderedDescending;
2063 return compareContext->CompareUsingOriginalOrdering(first,second);
2064 }
2065
2066 void wxWidgetCocoaImpl::Lower()
2067 {
2068 NSView* nsview = m_osxView;
2069
2070 NSView *superview = [nsview superview];
2071 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2072
2073 [superview sortSubviewsUsingFunction:
2074 CocoaLowerWindowCompareFunction
2075 context: &compareContext];
2076 }
2077
2078 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
2079 {
2080 #if 1
2081 SetNeedsDisplay() ;
2082 #else
2083 // We should do something like this, but it wasn't working in 10.4.
2084 if (GetNeedsDisplay() )
2085 {
2086 SetNeedsDisplay() ;
2087 }
2088 NSRect r = wxToNSRect( [m_osxView superview], *rect );
2089 NSSize offset = NSMakeSize((float)dx, (float)dy);
2090 [m_osxView scrollRect:r by:offset];
2091 #endif
2092 }
2093
2094 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
2095 {
2096 wxWindowMac* parent = GetWXPeer()->GetParent();
2097 // under Cocoa we might have a contentView in the wxParent to which we have to
2098 // adjust the coordinates
2099 if (parent && [m_osxView superview] != parent->GetHandle() )
2100 {
2101 int cx = 0,cy = 0,cw = 0,ch = 0;
2102 if ( parent->GetPeer() )
2103 {
2104 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2105 x -= cx;
2106 y -= cy;
2107 }
2108 }
2109 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
2110 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
2111 [m_osxView setFrame:r];
2112 [[m_osxView superview] setNeedsDisplayInRect:r];
2113 }
2114
2115 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
2116 {
2117 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
2118 x = r.GetLeft();
2119 y = r.GetTop();
2120
2121 // under Cocoa we might have a contentView in the wxParent to which we have to
2122 // adjust the coordinates
2123 wxWindowMac* parent = GetWXPeer()->GetParent();
2124 if (parent && [m_osxView superview] != parent->GetHandle() )
2125 {
2126 int cx = 0,cy = 0,cw = 0,ch = 0;
2127 if ( parent->GetPeer() )
2128 {
2129 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2130 x += cx;
2131 y += cy;
2132 }
2133 }
2134 }
2135
2136 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2137 {
2138 NSRect rect = [m_osxView frame];
2139 width = (int)rect.size.width;
2140 height = (int)rect.size.height;
2141 }
2142
2143 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
2144 {
2145 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2146 {
2147 NSView* cv = [m_osxView contentView];
2148
2149 NSRect bounds = [m_osxView bounds];
2150 NSRect rect = [cv frame];
2151
2152 int y = (int)rect.origin.y;
2153 int x = (int)rect.origin.x;
2154 if ( ![ m_osxView isFlipped ] )
2155 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
2156 left = x;
2157 top = y;
2158 width = (int)rect.size.width;
2159 height = (int)rect.size.height;
2160 }
2161 else
2162 {
2163 left = top = 0;
2164 GetSize( width, height );
2165 }
2166 }
2167
2168 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2169 {
2170 if ( where )
2171 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2172 else
2173 [m_osxView setNeedsDisplay:YES];
2174 }
2175
2176 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2177 {
2178 return [m_osxView needsDisplay];
2179 }
2180
2181 bool wxWidgetCocoaImpl::CanFocus() const
2182 {
2183 return [m_osxView canBecomeKeyView] == YES;
2184 }
2185
2186 bool wxWidgetCocoaImpl::HasFocus() const
2187 {
2188 return ( FindFocus() == m_osxView );
2189 }
2190
2191 bool wxWidgetCocoaImpl::SetFocus()
2192 {
2193 if ( !CanFocus() )
2194 return false;
2195
2196 // TODO remove if no issues arise: should not raise the window, only assign focus
2197 //[[m_osxView window] makeKeyAndOrderFront:nil] ;
2198 [[m_osxView window] makeFirstResponder: m_osxView] ;
2199 return true;
2200 }
2201
2202 void wxWidgetCocoaImpl::SetDropTarget(wxDropTarget* target)
2203 {
2204 [m_osxView unregisterDraggedTypes];
2205
2206 if ( target == NULL )
2207 return;
2208
2209 wxDataObject* dobj = target->GetDataObject();
2210
2211 if( dobj )
2212 {
2213 CFMutableArrayRef typesarray = CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
2214 dobj->AddSupportedTypes(typesarray);
2215 NSView* targetView = m_osxView;
2216 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2217 targetView = [(NSScrollView*) m_osxView documentView];
2218
2219 [targetView registerForDraggedTypes:(NSArray*)typesarray];
2220 CFRelease(typesarray);
2221 }
2222 }
2223
2224 void wxWidgetCocoaImpl::RemoveFromParent()
2225 {
2226 [m_osxView removeFromSuperview];
2227 }
2228
2229 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2230 {
2231 NSView* container = parent->GetWXWidget() ;
2232 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2233 [container addSubview:m_osxView];
2234
2235 if( m_wxPeer->IsFrozen() )
2236 [[m_osxView window] disableFlushWindow];
2237 }
2238
2239 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2240 {
2241 NSView* targetView = m_osxView;
2242 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2243 targetView = [(NSScrollView*) m_osxView documentView];
2244
2245 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2246 {
2247 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2248 green:(CGFloat) (col.Green() / 255.0)
2249 blue:(CGFloat) (col.Blue() / 255.0)
2250 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2251 }
2252 }
2253
2254 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2255 {
2256 BOOL opaque = ( style == wxBG_STYLE_PAINT );
2257
2258 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2259 {
2260 [m_osxView setOpaque: opaque];
2261 }
2262
2263 return true ;
2264 }
2265
2266 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2267 {
2268 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2269 {
2270 wxCFStringRef cf( title , encoding );
2271 [m_osxView setTitle:cf.AsNSString()];
2272 }
2273 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2274 {
2275 wxCFStringRef cf( title , encoding );
2276 [m_osxView setStringValue:cf.AsNSString()];
2277 }
2278 }
2279
2280
2281 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2282 {
2283 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2284 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2285 *pt = wxFromNSPoint( to->GetWXWidget(), p );
2286 }
2287
2288 wxInt32 wxWidgetCocoaImpl::GetValue() const
2289 {
2290 return [(NSControl*)m_osxView intValue];
2291 }
2292
2293 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2294 {
2295 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
2296 {
2297 [m_osxView setIntValue:v];
2298 }
2299 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2300 {
2301 [m_osxView setFloatValue:(double)v];
2302 }
2303 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2304 {
2305 [m_osxView setDoubleValue:(double)v];
2306 }
2307 }
2308
2309 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2310 {
2311 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
2312 {
2313 [m_osxView setMinValue:(double)v];
2314 }
2315 }
2316
2317 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2318 {
2319 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2320 {
2321 [m_osxView setMaxValue:(double)v];
2322 }
2323 }
2324
2325 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2326 {
2327 if ( [m_osxView respondsToSelector:@selector(minValue)] )
2328 {
2329 return (int)[m_osxView minValue];
2330 }
2331 return 0;
2332 }
2333
2334 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2335 {
2336 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
2337 {
2338 return (int)[m_osxView maxValue];
2339 }
2340 return 0;
2341 }
2342
2343 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2344 {
2345 wxBitmap bmp;
2346
2347 // TODO: how to create a wxBitmap from NSImage?
2348 #if 0
2349 if ( [m_osxView respondsToSelector:@selector(image:)] )
2350 bmp = [m_osxView image];
2351 #endif
2352
2353 return bmp;
2354 }
2355
2356 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2357 {
2358 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
2359 {
2360 if (bitmap.IsOk())
2361 [m_osxView setImage:bitmap.GetNSImage()];
2362 else
2363 [m_osxView setImage:nil];
2364
2365 [m_osxView setNeedsDisplay:YES];
2366 }
2367 }
2368
2369 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2370 {
2371 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2372 {
2373 NSCellImagePosition pos;
2374 switch ( dir )
2375 {
2376 case wxLEFT:
2377 pos = NSImageLeft;
2378 break;
2379
2380 case wxRIGHT:
2381 pos = NSImageRight;
2382 break;
2383
2384 case wxTOP:
2385 pos = NSImageAbove;
2386 break;
2387
2388 case wxBOTTOM:
2389 pos = NSImageBelow;
2390 break;
2391
2392 default:
2393 wxFAIL_MSG( "invalid image position" );
2394 pos = NSNoImage;
2395 }
2396
2397 [m_osxView setImagePosition:pos];
2398 }
2399 }
2400
2401 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2402 {
2403 // implementation in subclass
2404 }
2405
2406 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2407 {
2408 r->x = r->y = r->width = r->height = 0;
2409
2410 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2411 {
2412 NSRect former = [m_osxView frame];
2413 [m_osxView sizeToFit];
2414 NSRect best = [m_osxView frame];
2415 [m_osxView setFrame:former];
2416 r->width = (int)best.size.width;
2417 r->height = (int)best.size.height;
2418 }
2419 }
2420
2421 bool wxWidgetCocoaImpl::IsEnabled() const
2422 {
2423 NSView* targetView = m_osxView;
2424 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2425 targetView = [(NSScrollView*) m_osxView documentView];
2426
2427 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2428 return [targetView isEnabled];
2429 return true;
2430 }
2431
2432 void wxWidgetCocoaImpl::Enable( bool enable )
2433 {
2434 NSView* targetView = m_osxView;
2435 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2436 targetView = [(NSScrollView*) m_osxView documentView];
2437
2438 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2439 [targetView setEnabled:enable];
2440 }
2441
2442 void wxWidgetCocoaImpl::PulseGauge()
2443 {
2444 }
2445
2446 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2447 {
2448 }
2449
2450 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2451 {
2452 NSControlSize size = NSRegularControlSize;
2453
2454 switch ( variant )
2455 {
2456 case wxWINDOW_VARIANT_NORMAL :
2457 size = NSRegularControlSize;
2458 break ;
2459
2460 case wxWINDOW_VARIANT_SMALL :
2461 size = NSSmallControlSize;
2462 break ;
2463
2464 case wxWINDOW_VARIANT_MINI :
2465 size = NSMiniControlSize;
2466 break ;
2467
2468 case wxWINDOW_VARIANT_LARGE :
2469 size = NSRegularControlSize;
2470 break ;
2471
2472 default:
2473 wxFAIL_MSG(wxT("unexpected window variant"));
2474 break ;
2475 }
2476 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2477 [m_osxView setControlSize:size];
2478 else if ([m_osxView respondsToSelector:@selector(cell)])
2479 {
2480 id cell = [(id)m_osxView cell];
2481 if ([cell respondsToSelector:@selector(setControlSize:)])
2482 [cell setControlSize:size];
2483 }
2484
2485 // we need to propagate this to inner views as well
2486 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2487 {
2488 NSView* targetView = [(NSScrollView*) m_osxView documentView];
2489
2490 if ( [targetView respondsToSelector:@selector(setControlSize:)] )
2491 [targetView setControlSize:size];
2492 else if ([targetView respondsToSelector:@selector(cell)])
2493 {
2494 id cell = [(id)targetView cell];
2495 if ([cell respondsToSelector:@selector(setControlSize:)])
2496 [cell setControlSize:size];
2497 }
2498 }
2499 }
2500
2501 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2502 {
2503 NSView* targetView = m_osxView;
2504 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2505 targetView = [(NSScrollView*) m_osxView documentView];
2506
2507 if ([targetView respondsToSelector:@selector(setFont:)])
2508 [targetView setFont: font.OSXGetNSFont()];
2509 if ([targetView respondsToSelector:@selector(setTextColor:)])
2510 [targetView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2511 green:(CGFloat) (col.Green() / 255.0)
2512 blue:(CGFloat) (col.Blue() / 255.0)
2513 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2514 }
2515
2516 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2517 {
2518 if ( tooltip )
2519 {
2520 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2521 [m_osxView setToolTip: cf.AsNSString()];
2522 }
2523 else
2524 {
2525 [m_osxView setToolTip:nil];
2526 }
2527 }
2528
2529 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2530 {
2531 WXWidget c = control ? control : (WXWidget) m_osxView;
2532 wxWidgetImpl::Associate( c, this ) ;
2533 if ([c respondsToSelector:@selector(setAction:)])
2534 {
2535 [c setTarget: c];
2536 if ( dynamic_cast<wxRadioButton*>(GetWXPeer()) )
2537 {
2538 // everything already set up
2539 }
2540 else
2541 [c setAction: @selector(controlAction:)];
2542
2543 if ([c respondsToSelector:@selector(setDoubleAction:)])
2544 {
2545 [c setDoubleAction: @selector(controlDoubleAction:)];
2546 }
2547
2548 }
2549 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingCursorUpdate|NSTrackingMouseMoved|NSTrackingActiveAlways|NSTrackingInVisibleRect;
2550 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: NSZeroRect options: options owner: m_osxView userInfo: nil];
2551 [m_osxView addTrackingArea: area];
2552 [area release];
2553 }
2554
2555 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2556 {
2557 wxKeyEvent wxevent(wxEVT_CHAR);
2558 SetupKeyEvent( wxevent, event, text );
2559
2560 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2561 }
2562
2563 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2564 {
2565 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2566 SetupKeyEvent( wxevent, event );
2567
2568 // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2569 // the key is pressed, not when it's released (the type of wxevent is
2570 // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2571 if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2572 {
2573 wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2574 if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2575 && !eventHook.IsNextEventAllowed() )
2576 return true;
2577 }
2578
2579 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2580
2581 // this will fire higher level events, like insertText, to help
2582 // us handle EVT_CHAR, etc.
2583
2584 if ( !result )
2585 {
2586 if ( [event type] == NSKeyDown)
2587 {
2588 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2589
2590 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2591 {
2592 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2593 wxKeyEvent wxevent2(wxevent) ;
2594 wxevent2.SetEventType(wxEVT_CHAR);
2595 SetupKeyEvent( wxevent2, event );
2596 wxevent2.m_keyCode = keycode;
2597 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2598 }
2599 else if (wxevent.CmdDown())
2600 {
2601 wxKeyEvent wxevent2(wxevent) ;
2602 wxevent2.SetEventType(wxEVT_CHAR);
2603 SetupKeyEvent( wxevent2, event );
2604 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2605 }
2606 else
2607 {
2608 if ( IsUserPane() && !wxevent.CmdDown() )
2609 {
2610 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2611 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2612 else
2613 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2614 result = true;
2615 }
2616 }
2617 }
2618 }
2619
2620 return result;
2621 }
2622
2623 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2624 {
2625 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2626 SetupMouseEvent(wxevent , event) ;
2627 bool result = GetWXPeer()->HandleWindowEvent(wxevent);
2628
2629 (void)SetupCursor(event);
2630
2631 return result;
2632 }
2633
2634 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2635 {
2636 wxWindow* thisWindow = GetWXPeer();
2637 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2638 {
2639 thisWindow->MacInvalidateBorders();
2640 }
2641
2642 if ( receivedFocus )
2643 {
2644 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2645 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2646 thisWindow->HandleWindowEvent(eventFocus);
2647
2648 #if wxUSE_CARET
2649 if ( thisWindow->GetCaret() )
2650 thisWindow->GetCaret()->OnSetFocus();
2651 #endif
2652
2653 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2654 event.SetEventObject(thisWindow);
2655 if (otherWindow)
2656 event.SetWindow(otherWindow->GetWXPeer());
2657 thisWindow->HandleWindowEvent(event) ;
2658 }
2659 else // !receivedFocus
2660 {
2661 #if wxUSE_CARET
2662 if ( thisWindow->GetCaret() )
2663 thisWindow->GetCaret()->OnKillFocus();
2664 #endif
2665
2666 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2667
2668 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2669 event.SetEventObject(thisWindow);
2670 if (otherWindow)
2671 event.SetWindow(otherWindow->GetWXPeer());
2672 thisWindow->HandleWindowEvent(event) ;
2673 }
2674 }
2675
2676 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2677 {
2678 if ( !wxIsBusy() )
2679 {
2680 NSPoint location = [NSEvent mouseLocation];
2681 location = [[m_osxView window] convertScreenToBase:location];
2682 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2683
2684 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2685 {
2686 [(NSCursor*)cursor.GetHCURSOR() set];
2687 }
2688 }
2689 }
2690
2691 void wxWidgetCocoaImpl::CaptureMouse()
2692 {
2693 // TODO remove if we don't get into problems with cursor settings
2694 // [[m_osxView window] disableCursorRects];
2695 }
2696
2697 void wxWidgetCocoaImpl::ReleaseMouse()
2698 {
2699 // TODO remove if we don't get into problems with cursor settings
2700 // [[m_osxView window] enableCursorRects];
2701 }
2702
2703 #if !wxOSX_USE_NATIVE_FLIPPED
2704
2705 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2706 {
2707 m_isFlipped = flipped;
2708 }
2709
2710 #endif
2711
2712 void wxWidgetCocoaImpl::SetDrawingEnabled(bool enabled)
2713 {
2714 if ( enabled )
2715 {
2716 [[m_osxView window] enableFlushWindow];
2717 [m_osxView setNeedsDisplay:YES];
2718 }
2719 else
2720 {
2721 [[m_osxView window] disableFlushWindow];
2722 }
2723 }
2724 //
2725 // Factory methods
2726 //
2727
2728 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2729 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2730 long WXUNUSED(style), long WXUNUSED(extraStyle))
2731 {
2732 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2733 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2734
2735 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2736 return c;
2737 }
2738
2739 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2740 {
2741 NSWindow* tlw = now->GetWXWindow();
2742
2743 wxWidgetCocoaImpl* c = NULL;
2744 if ( now->IsNativeWindowWrapper() )
2745 {
2746 NSView* cv = [tlw contentView];
2747 c = new wxWidgetCocoaImpl( now, cv, true );
2748 if ( cv != nil )
2749 {
2750 // increase ref count, because the impl destructor will decrement it again
2751 CFRetain(cv);
2752 if ( !now->IsShown() )
2753 [cv setHidden:NO];
2754 }
2755 }
2756 else
2757 {
2758 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2759 c = new wxWidgetCocoaImpl( now, v, true );
2760 c->InstallEventHandler();
2761 [tlw setContentView:v];
2762 }
2763 return c;
2764 }