]> git.saurik.com Git - wxWidgets.git/blob - src/osx/cocoa/window.mm
8580b52b5baf2c5b34b49a071effb6a06b462b7c
[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 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1189 {
1190 // we are getting moved events for all windows in the hierarchy, not something wx expects
1191 // therefore we only handle it for the deepest child in the hierarchy
1192 if ( [event type] == NSMouseMoved )
1193 {
1194 NSView* hitview = [[[slf window] contentView] hitTest:[event locationInWindow]];
1195 if ( hitview == NULL || hitview != slf)
1196 return;
1197 }
1198
1199 if ( !DoHandleMouseEvent(event) )
1200 {
1201 // for plain NSView mouse events would propagate to parents otherwise
1202 // scrollwheel events have to be propagated if not handled in all cases
1203 if (!IsUserPane() || [event type] == NSScrollWheel )
1204 {
1205 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1206 superimpl(slf, (SEL)_cmd, event);
1207
1208 // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
1209 // only trigger if at this moment the mouse is already up
1210 if ( [ event type] == NSLeftMouseDown && !wxGetMouseState().LeftIsDown() )
1211 {
1212 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1213 SetupMouseEvent(wxevent , event) ;
1214 wxevent.SetEventType(wxEVT_LEFT_UP);
1215
1216 GetWXPeer()->HandleWindowEvent(wxevent);
1217 }
1218 }
1219 }
1220 }
1221
1222 void wxWidgetCocoaImpl::cursorUpdate(WX_NSEvent event, WXWidget slf, void *_cmd)
1223 {
1224 if ( !SetupCursor(event) )
1225 {
1226 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1227 superimpl(slf, (SEL)_cmd, event);
1228 }
1229 }
1230
1231 bool wxWidgetCocoaImpl::SetupCursor(WX_NSEvent event)
1232 {
1233 extern wxCursor gGlobalCursor;
1234
1235 if ( gGlobalCursor.IsOk() )
1236 {
1237 gGlobalCursor.MacInstall();
1238 return true;
1239 }
1240 else
1241 {
1242 wxWindow* cursorTarget = GetWXPeer();
1243 wxCoord x,y;
1244 SetupCoordinates(x, y, event);
1245 wxPoint cursorPoint( x , y ) ;
1246
1247 while ( cursorTarget && !cursorTarget->MacSetupCursor( cursorPoint ) )
1248 {
1249 // at least in GTK cursor events are not propagated either ...
1250 #if 1
1251 cursorTarget = NULL;
1252 #else
1253 cursorTarget = cursorTarget->GetParent() ;
1254 if ( cursorTarget )
1255 cursorPoint += cursorTarget->GetPosition();
1256 #endif
1257 }
1258
1259 return cursorTarget != NULL;
1260 }
1261 }
1262
1263 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1264 {
1265 if ( [event type] == NSKeyDown )
1266 {
1267 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1268 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1269 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1270 return;
1271
1272 m_lastKeyDownEvent = event;
1273 }
1274
1275 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1276 {
1277 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1278 superimpl(slf, (SEL)_cmd, event);
1279 }
1280 m_lastKeyDownEvent = NULL;
1281 }
1282
1283 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1284 {
1285 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1286 {
1287 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1288 superimpl(slf, (SEL)_cmd, text);
1289 }
1290 }
1291
1292
1293 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1294 {
1295 bool handled = false;
1296
1297 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1298 SetupKeyEvent( wxevent, event );
1299
1300 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1301 // walk up the ancestors ourselves but let cocoa do it
1302
1303 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1304 if (command != -1)
1305 {
1306 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1307
1308 wxCommandEvent command_event( wxEVT_MENU, command );
1309 command_event.SetEventObject( wxevent.GetEventObject() );
1310 handled = handler->ProcessEvent( command_event );
1311
1312 if ( !handled )
1313 {
1314 // accelerators can also be used with buttons, try them too
1315 command_event.SetEventType(wxEVT_BUTTON);
1316 handled = handler->ProcessEvent( command_event );
1317 }
1318 }
1319
1320 if ( !handled )
1321 {
1322 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1323 return superimpl(slf, (SEL)_cmd, event);
1324 }
1325 return YES;
1326 }
1327
1328 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1329 {
1330 if ( IsUserPane() )
1331 return m_wxPeer->AcceptsFocus();
1332 else
1333 {
1334 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1335 return superimpl(slf, (SEL)_cmd);
1336 }
1337 }
1338
1339 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1340 {
1341 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1342 // get the current focus before running becomeFirstResponder
1343 NSView* otherView = FindFocus();
1344
1345 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1346 BOOL r = superimpl(slf, (SEL)_cmd);
1347 if ( r )
1348 {
1349 DoNotifyFocusEvent( true, otherWindow );
1350 }
1351
1352 return r;
1353 }
1354
1355 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1356 {
1357 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1358 BOOL r = superimpl(slf, (SEL)_cmd);
1359
1360 NSResponder * responder = wxNonOwnedWindowCocoaImpl::GetNextFirstResponder();
1361 NSView* otherView = wxOSXGetViewFromResponder(responder);
1362
1363 wxWidgetImpl* otherWindow = FindBestFromWXWidget(otherView);
1364
1365 // It doesn't make sense to notify about the loss of focus if it's the same
1366 // control in the end, and just a different subview
1367 if ( otherWindow == this )
1368 return r;
1369
1370 // NSTextViews have an editor as true responder, therefore the might get the
1371 // resign notification if their editor takes over, don't trigger any event then
1372 if ( r && !m_hasEditor)
1373 {
1374 DoNotifyFocusEvent( false, otherWindow );
1375 }
1376 return r;
1377 }
1378
1379 #if !wxOSX_USE_NATIVE_FLIPPED
1380
1381 bool wxWidgetCocoaImpl::isFlipped(WXWidget slf, void *WXUNUSED(_cmd))
1382 {
1383 return m_isFlipped;
1384 }
1385
1386 #endif
1387
1388 #define OSX_DEBUG_DRAWING 0
1389
1390 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1391 {
1392 // preparing the update region
1393
1394 wxRegion updateRgn;
1395
1396 // since adding many rects to a region is a costly process, by default use the bounding rect
1397 #if 0
1398 const NSRect *rects;
1399 NSInteger count;
1400 [slf getRectsBeingDrawn:&rects count:&count];
1401 for ( int i = 0 ; i < count ; ++i )
1402 {
1403 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1404 }
1405 #else
1406 updateRgn.Union(wxFromNSRect(slf,*(NSRect*)rect));
1407 #endif
1408
1409 wxWindow* wxpeer = GetWXPeer();
1410
1411 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1412 {
1413 // as this update region is in native window locals we must adapt it to wx window local
1414 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1415 }
1416
1417 // Restrict the update region to the shape of the window, if any, and also
1418 // remember the region that we need to clear later.
1419 wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1420 const bool isTopLevel = tlwParent == wxpeer;
1421 wxRegion clearRgn;
1422 if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1423 {
1424 if ( isTopLevel )
1425 clearRgn = updateRgn;
1426
1427 int xoffset = 0, yoffset = 0;
1428 wxRegion rgn = tlwParent->GetShape();
1429 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1430 rgn.Offset( xoffset, yoffset );
1431 updateRgn.Intersect(rgn);
1432
1433 if ( isTopLevel )
1434 {
1435 // Exclude the window shape from the region to be cleared below.
1436 rgn.Xor(wxpeer->GetSize());
1437 clearRgn.Intersect(rgn);
1438 }
1439 }
1440
1441 wxpeer->GetUpdateRegion() = updateRgn;
1442
1443 // setting up the drawing context
1444
1445 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1446 CGContextSaveGState( context );
1447
1448 #if OSX_DEBUG_DRAWING
1449 CGContextBeginPath( context );
1450 CGContextMoveToPoint(context, 0, 0);
1451 NSRect bounds = [slf bounds];
1452 CGContextAddLineToPoint(context, 10, 0);
1453 CGContextMoveToPoint(context, 0, 0);
1454 CGContextAddLineToPoint(context, 0, 10);
1455 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1456 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1457 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1458 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1459 CGContextClosePath( context );
1460 CGContextStrokePath(context);
1461 #endif
1462
1463 if ( ![slf isFlipped] )
1464 {
1465 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1466 CGContextScaleCTM( context, 1, -1 );
1467 }
1468
1469 wxpeer->MacSetCGContextRef( context );
1470
1471 bool handled = wxpeer->MacDoRedraw( 0 );
1472 CGContextRestoreGState( context );
1473
1474 CGContextSaveGState( context );
1475 if ( !handled )
1476 {
1477 // call super
1478 SEL _cmd = @selector(drawRect:);
1479 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1480 superimpl(slf, _cmd, *(NSRect*)rect);
1481 CGContextRestoreGState( context );
1482 CGContextSaveGState( context );
1483 }
1484 // as we called restore above, we have to flip again if necessary
1485 if ( ![slf isFlipped] )
1486 {
1487 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1488 CGContextScaleCTM( context, 1, -1 );
1489 }
1490
1491 if ( isTopLevel )
1492 {
1493 // We also need to explicitly draw the part of the top level window
1494 // outside of its region with transparent colour to ensure that it is
1495 // really transparent.
1496 if ( clearRgn.IsOk() )
1497 {
1498 wxMacCGContextStateSaver saveState(context);
1499 wxWindowDC dc(wxpeer);
1500 dc.SetBackground(wxBrush(wxTransparentColour));
1501 dc.SetDeviceClippingRegion(clearRgn);
1502 dc.Clear();
1503 }
1504
1505 #if wxUSE_GRAPHICS_CONTEXT
1506 // If the window shape is defined by a path, stroke the path to show
1507 // the window border.
1508 const wxGraphicsPath& path = tlwParent->GetShapePath();
1509 if ( !path.IsNull() )
1510 {
1511 CGContextSetLineWidth(context, 1);
1512 CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1513 CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1514 CGContextStrokePath(context);
1515 }
1516 #endif // wxUSE_GRAPHICS_CONTEXT
1517 }
1518
1519 wxpeer->MacPaintChildrenBorders();
1520 wxpeer->MacSetCGContextRef( NULL );
1521 CGContextRestoreGState( context );
1522 }
1523
1524 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1525 {
1526 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1527 if ( wxpeer )
1528 {
1529 wxpeer->OSXSimulateFocusEvents();
1530 wxpeer->OSXHandleClicked(0);
1531 }
1532 }
1533
1534 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1535 {
1536 }
1537
1538 void wxWidgetCocoaImpl::controlTextDidChange()
1539 {
1540 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1541 if ( wxpeer )
1542 {
1543 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1544 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1545 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1546 if ( tc )
1547 tc->SendTextUpdatedEventIfAllowed();
1548 else if ( cb )
1549 cb->SendTextUpdatedEventIfAllowed();
1550 else
1551 {
1552 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1553 }
1554 }
1555 }
1556
1557 //
1558
1559 #if OBJC_API_VERSION >= 2
1560
1561 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1562 class_addMethod(c, s, i, t );
1563
1564 #else
1565
1566 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1567 { s, (char*) t, i },
1568
1569 #endif
1570
1571 void wxOSXCocoaClassAddWXMethods(Class c)
1572 {
1573
1574 #if OBJC_API_VERSION < 2
1575 static objc_method wxmethods[] =
1576 {
1577 #endif
1578
1579 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1580 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1581 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1582
1583 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1584 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1585 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1586
1587 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1588
1589 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1590 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1591 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1592
1593 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1594
1595 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1596 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1597 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1598
1599 wxOSX_CLASS_ADD_METHOD(c, @selector(cursorUpdate:), (IMP) wxOSX_cursorUpdate, "v@:@" )
1600
1601 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1602 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1603 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1604
1605 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1606
1607 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1608
1609 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1610 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1611 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1612
1613 #if !wxOSX_USE_NATIVE_FLIPPED
1614 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1615 #endif
1616 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1617
1618 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1619 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1620
1621 #if wxUSE_DRAG_AND_DROP
1622 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1623 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1624 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1625 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1626 #endif
1627
1628 #if OBJC_API_VERSION < 2
1629 } ;
1630 static int method_count = WXSIZEOF( wxmethods );
1631 static objc_method_list *wxmethodlist = NULL;
1632 if ( wxmethodlist == NULL )
1633 {
1634 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1635 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1636 wxmethodlist->method_count = method_count;
1637 wxmethodlist->obsolete = 0;
1638 }
1639 class_addMethods( c, wxmethodlist );
1640 #endif
1641 }
1642
1643 //
1644 // C++ implementation class
1645 //
1646
1647 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1648
1649 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1650 wxWidgetImpl( peer, isRootControl, isUserPane )
1651 {
1652 Init();
1653 m_osxView = w;
1654
1655 // check if the user wants to create the control initially hidden
1656 if ( !peer->IsShown() )
1657 SetVisibility(false);
1658
1659 // gc aware handling
1660 if ( m_osxView )
1661 CFRetain(m_osxView);
1662 [m_osxView release];
1663 }
1664
1665 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1666 {
1667 Init();
1668 }
1669
1670 void wxWidgetCocoaImpl::Init()
1671 {
1672 m_osxView = NULL;
1673 #if !wxOSX_USE_NATIVE_FLIPPED
1674 m_isFlipped = true;
1675 #endif
1676 m_lastKeyDownEvent = NULL;
1677 m_hasEditor = false;
1678 }
1679
1680 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1681 {
1682 RemoveAssociations( this );
1683
1684 if ( !IsRootControl() )
1685 {
1686 NSView *sv = [m_osxView superview];
1687 if ( sv != nil )
1688 [m_osxView removeFromSuperview];
1689 }
1690 // gc aware handling
1691 if ( m_osxView )
1692 CFRelease(m_osxView);
1693 }
1694
1695 bool wxWidgetCocoaImpl::IsVisible() const
1696 {
1697 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1698 }
1699
1700 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1701 {
1702 [m_osxView setHidden:(visible ? NO:YES)];
1703 }
1704
1705 // ----------------------------------------------------------------------------
1706 // window animation stuff
1707 // ----------------------------------------------------------------------------
1708
1709 // define a delegate used to refresh the window during animation
1710 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1711 {
1712 wxWindow *m_win;
1713 bool m_isDone;
1714 }
1715
1716 - (id)init:(wxWindow *)win;
1717
1718 - (bool)isDone;
1719
1720 // NSAnimationDelegate methods
1721 - (void)animationDidEnd:(NSAnimation*)animation;
1722 - (void)animation:(NSAnimation*)animation
1723 didReachProgressMark:(NSAnimationProgress)progress;
1724 @end
1725
1726 @implementation wxNSAnimationDelegate
1727
1728 - (id)init:(wxWindow *)win
1729 {
1730 self = [super init];
1731
1732 m_win = win;
1733 m_isDone = false;
1734
1735 return self;
1736 }
1737
1738 - (bool)isDone
1739 {
1740 return m_isDone;
1741 }
1742
1743 - (void)animation:(NSAnimation*)animation
1744 didReachProgressMark:(NSAnimationProgress)progress
1745 {
1746 wxUnusedVar(animation);
1747 wxUnusedVar(progress);
1748
1749 m_win->SendSizeEvent();
1750 }
1751
1752 - (void)animationDidEnd:(NSAnimation*)animation
1753 {
1754 wxUnusedVar(animation);
1755 m_isDone = true;
1756 }
1757
1758 @end
1759
1760 /* static */
1761 bool
1762 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1763 bool show,
1764 wxShowEffect effect,
1765 unsigned timeout)
1766 {
1767 // create the dictionary describing the animation to perform on this view
1768 NSObject * const
1769 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1770 NSMutableDictionary * const
1771 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1772 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1773
1774 // determine the start and end rectangles assuming we're hiding the window
1775 const wxRect rectOrig = win->GetRect();
1776 wxRect rectStart,
1777 rectEnd;
1778 rectStart =
1779 rectEnd = rectOrig;
1780
1781 if ( show )
1782 {
1783 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1784 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1785 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1786 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1787 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1788 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1789 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1790 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1791 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1792 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1793 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1794 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1795 }
1796
1797 switch ( effect )
1798 {
1799 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1800 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1801 rectEnd.width = 0;
1802 break;
1803
1804 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1805 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1806 rectEnd.x = rectStart.GetRight();
1807 rectEnd.width = 0;
1808 break;
1809
1810 case wxSHOW_EFFECT_ROLL_TO_TOP:
1811 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1812 rectEnd.height = 0;
1813 break;
1814
1815 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1816 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1817 rectEnd.y = rectStart.GetBottom();
1818 rectEnd.height = 0;
1819 break;
1820
1821 case wxSHOW_EFFECT_EXPAND:
1822 rectEnd.x = rectStart.x + rectStart.width / 2;
1823 rectEnd.y = rectStart.y + rectStart.height / 2;
1824 rectEnd.width =
1825 rectEnd.height = 0;
1826 break;
1827
1828 case wxSHOW_EFFECT_BLEND:
1829 [dict setObject:(show ? NSViewAnimationFadeInEffect
1830 : NSViewAnimationFadeOutEffect)
1831 forKey:NSViewAnimationEffectKey];
1832 break;
1833
1834 case wxSHOW_EFFECT_NONE:
1835 case wxSHOW_EFFECT_MAX:
1836 wxFAIL_MSG( "unexpected animation effect" );
1837 return false;
1838
1839 default:
1840 wxFAIL_MSG( "unknown animation effect" );
1841 return false;
1842 };
1843
1844 if ( show )
1845 {
1846 // we need to restore it to the original rectangle instead of making it
1847 // disappear
1848 wxSwap(rectStart, rectEnd);
1849
1850 // and as the window is currently hidden, we need to show it for the
1851 // animation to be visible at all (but don't restore it at its full
1852 // rectangle as it shouldn't appear immediately)
1853 win->SetSize(rectStart);
1854 win->Show();
1855 }
1856
1857 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1858 ? [(NSView *)viewOrWin superview]
1859 : nil;
1860 const NSRect rStart = wxToNSRect(parentView, rectStart);
1861 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1862
1863 [dict setObject:[NSValue valueWithRect:rStart]
1864 forKey:NSViewAnimationStartFrameKey];
1865 [dict setObject:[NSValue valueWithRect:rEnd]
1866 forKey:NSViewAnimationEndFrameKey];
1867
1868 // create an animation using the values in the above dictionary
1869 NSViewAnimation * const
1870 anim = [[NSViewAnimation alloc]
1871 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1872
1873 if ( !timeout )
1874 {
1875 // what is a good default duration? Windows uses 200ms, Web frameworks
1876 // use anything from 250ms to 1s... choose something in the middle
1877 timeout = 500;
1878 }
1879
1880 [anim setDuration:timeout/1000.]; // duration is in seconds here
1881
1882 // if the window being animated changes its layout depending on its size
1883 // (which is almost always the case) we need to redo it during animation
1884 //
1885 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1886 // controls in wxInfoBar visibly jump around)
1887 const int NUM_LAYOUTS = 20;
1888 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1889 [anim addProgressMark:f];
1890
1891 wxNSAnimationDelegate * const
1892 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1893 [anim setDelegate:animDelegate];
1894 [anim startAnimation];
1895
1896 // Cocoa is capable of doing animation asynchronously or even from separate
1897 // thread but wx API doesn't provide any way to be notified about the
1898 // animation end and without this we really must ensure that the window has
1899 // the expected (i.e. the same as if a simple Show() had been used) size
1900 // when we return, so block here until the animation finishes
1901 //
1902 // notice that because the default animation mode is NSAnimationBlocking,
1903 // no user input events ought to be processed from here
1904 {
1905 wxEventLoopGuarantor ensureEventLoopExistence;
1906 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1907 while ( ![animDelegate isDone] )
1908 loop->Dispatch();
1909 }
1910
1911 if ( !show )
1912 {
1913 // NSViewAnimation is smart enough to hide the NSView being animated at
1914 // the end but we also must ensure that it's hidden for wx too
1915 win->Hide();
1916
1917 // and we must also restore its size because it isn't expected to
1918 // change just because the window was hidden
1919 win->SetSize(rectOrig);
1920 }
1921 else
1922 {
1923 // refresh it once again after the end to ensure that everything is in
1924 // place
1925 win->SendSizeEvent();
1926 }
1927
1928 [anim setDelegate:nil];
1929 [animDelegate release];
1930 [anim release];
1931
1932 return true;
1933 }
1934
1935 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1936 wxShowEffect effect,
1937 unsigned timeout)
1938 {
1939 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1940 }
1941
1942 /* note that the drawing order between siblings is not defined under 10.4 */
1943 /* only starting from 10.5 the subview order is respected */
1944
1945 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1946 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
1947 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
1948 * expects a function returning the new non-enum NSComparsionResult.
1949 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1950 */
1951 #if defined(NSINTEGER_DEFINED)
1952 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1953 #else
1954 typedef int CocoaWindowCompareFunctionResult;
1955 #endif
1956
1957 class CocoaWindowCompareContext
1958 {
1959 wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1960 public:
1961 CocoaWindowCompareContext(); // Not implemented
1962 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1963 {
1964 m_target = target;
1965 // Cocoa sorts subviews in-place.. make a copy
1966 m_subviews = [subviews copy];
1967 }
1968
1969 ~CocoaWindowCompareContext()
1970 { // release the copy
1971 [m_subviews release];
1972 }
1973 NSView* target()
1974 { return m_target; }
1975
1976 NSArray* subviews()
1977 { return m_subviews; }
1978
1979 /* Helper function that returns the comparison based off of the original ordering */
1980 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1981 {
1982 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1983 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1984 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1985 // likely compare higher than the other view which is reasonable considering the only way that
1986 // can happen is if the subview was added after our call to subviews but before the call to
1987 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
1988 // that case should never occur anyway because that would imply a multi-threaded GUI call
1989 // which is a big no-no with Cocoa.
1990
1991 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
1992 NSComparisonResult result = (firstI < secondI)
1993 ? NSOrderedAscending /* -1 */
1994 : (firstI > secondI)
1995 ? NSOrderedDescending /* 1 */
1996 : NSOrderedSame /* 0 */;
1997
1998 return result;
1999 }
2000 private:
2001 /* The subview we are trying to Raise or Lower */
2002 NSView *m_target;
2003 /* A copy of the original array of subviews */
2004 NSArray *m_subviews;
2005 };
2006
2007 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
2008 * the target view is always higher than every other view. When comparing two views neither of
2009 * which is the target, it returns the correct response based on the original ordering
2010 */
2011 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
2012 {
2013 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2014 // first should be ordered higher
2015 if(first==compareContext->target())
2016 return NSOrderedDescending;
2017 // second should be ordered higher
2018 if(second==compareContext->target())
2019 return NSOrderedAscending;
2020 return compareContext->CompareUsingOriginalOrdering(first,second);
2021 }
2022
2023 void wxWidgetCocoaImpl::Raise()
2024 {
2025 NSView* nsview = m_osxView;
2026
2027 NSView *superview = [nsview superview];
2028 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2029
2030 [superview sortSubviewsUsingFunction:
2031 CocoaRaiseWindowCompareFunction
2032 context: &compareContext];
2033
2034 }
2035
2036 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
2037 * the target view is always lower than every other view. When comparing two views neither of
2038 * which is the target, it returns the correct response based on the original ordering
2039 */
2040 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
2041 {
2042 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2043 // first should be ordered lower
2044 if(first==compareContext->target())
2045 return NSOrderedAscending;
2046 // second should be ordered lower
2047 if(second==compareContext->target())
2048 return NSOrderedDescending;
2049 return compareContext->CompareUsingOriginalOrdering(first,second);
2050 }
2051
2052 void wxWidgetCocoaImpl::Lower()
2053 {
2054 NSView* nsview = m_osxView;
2055
2056 NSView *superview = [nsview superview];
2057 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2058
2059 [superview sortSubviewsUsingFunction:
2060 CocoaLowerWindowCompareFunction
2061 context: &compareContext];
2062 }
2063
2064 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
2065 {
2066 #if 1
2067 SetNeedsDisplay() ;
2068 #else
2069 // We should do something like this, but it wasn't working in 10.4.
2070 if (GetNeedsDisplay() )
2071 {
2072 SetNeedsDisplay() ;
2073 }
2074 NSRect r = wxToNSRect( [m_osxView superview], *rect );
2075 NSSize offset = NSMakeSize((float)dx, (float)dy);
2076 [m_osxView scrollRect:r by:offset];
2077 #endif
2078 }
2079
2080 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
2081 {
2082 wxWindowMac* parent = GetWXPeer()->GetParent();
2083 // under Cocoa we might have a contentView in the wxParent to which we have to
2084 // adjust the coordinates
2085 if (parent && [m_osxView superview] != parent->GetHandle() )
2086 {
2087 int cx = 0,cy = 0,cw = 0,ch = 0;
2088 if ( parent->GetPeer() )
2089 {
2090 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2091 x -= cx;
2092 y -= cy;
2093 }
2094 }
2095 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
2096 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
2097 [m_osxView setFrame:r];
2098 [[m_osxView superview] setNeedsDisplayInRect:r];
2099 }
2100
2101 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
2102 {
2103 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
2104 x = r.GetLeft();
2105 y = r.GetTop();
2106
2107 // under Cocoa we might have a contentView in the wxParent to which we have to
2108 // adjust the coordinates
2109 wxWindowMac* parent = GetWXPeer()->GetParent();
2110 if (parent && [m_osxView superview] != parent->GetHandle() )
2111 {
2112 int cx = 0,cy = 0,cw = 0,ch = 0;
2113 if ( parent->GetPeer() )
2114 {
2115 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2116 x += cx;
2117 y += cy;
2118 }
2119 }
2120 }
2121
2122 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2123 {
2124 NSRect rect = [m_osxView frame];
2125 width = (int)rect.size.width;
2126 height = (int)rect.size.height;
2127 }
2128
2129 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
2130 {
2131 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2132 {
2133 NSView* cv = [m_osxView contentView];
2134
2135 NSRect bounds = [m_osxView bounds];
2136 NSRect rect = [cv frame];
2137
2138 int y = (int)rect.origin.y;
2139 int x = (int)rect.origin.x;
2140 if ( ![ m_osxView isFlipped ] )
2141 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
2142 left = x;
2143 top = y;
2144 width = (int)rect.size.width;
2145 height = (int)rect.size.height;
2146 }
2147 else
2148 {
2149 left = top = 0;
2150 GetSize( width, height );
2151 }
2152 }
2153
2154 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2155 {
2156 if ( where )
2157 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2158 else
2159 [m_osxView setNeedsDisplay:YES];
2160 }
2161
2162 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2163 {
2164 return [m_osxView needsDisplay];
2165 }
2166
2167 bool wxWidgetCocoaImpl::CanFocus() const
2168 {
2169 return [m_osxView canBecomeKeyView] == YES;
2170 }
2171
2172 bool wxWidgetCocoaImpl::HasFocus() const
2173 {
2174 return ( FindFocus() == m_osxView );
2175 }
2176
2177 bool wxWidgetCocoaImpl::SetFocus()
2178 {
2179 if ( !CanFocus() )
2180 return false;
2181
2182 // TODO remove if no issues arise: should not raise the window, only assign focus
2183 //[[m_osxView window] makeKeyAndOrderFront:nil] ;
2184 [[m_osxView window] makeFirstResponder: m_osxView] ;
2185 return true;
2186 }
2187
2188 void wxWidgetCocoaImpl::SetDropTarget(wxDropTarget* target)
2189 {
2190 [m_osxView unregisterDraggedTypes];
2191
2192 if ( target == NULL )
2193 return;
2194
2195 wxDataObject* dobj = target->GetDataObject();
2196
2197 if( dobj )
2198 {
2199 CFMutableArrayRef typesarray = CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
2200 dobj->AddSupportedTypes(typesarray);
2201 NSView* targetView = m_osxView;
2202 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2203 targetView = [(NSScrollView*) m_osxView documentView];
2204
2205 [targetView registerForDraggedTypes:(NSArray*)typesarray];
2206 CFRelease(typesarray);
2207 }
2208 }
2209
2210 void wxWidgetCocoaImpl::RemoveFromParent()
2211 {
2212 [m_osxView removeFromSuperview];
2213 }
2214
2215 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2216 {
2217 NSView* container = parent->GetWXWidget() ;
2218 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2219 [container addSubview:m_osxView];
2220
2221 if( m_wxPeer->IsFrozen() )
2222 [[m_osxView window] disableFlushWindow];
2223 }
2224
2225 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2226 {
2227 NSView* targetView = m_osxView;
2228 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2229 targetView = [(NSScrollView*) m_osxView documentView];
2230
2231 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2232 {
2233 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2234 green:(CGFloat) (col.Green() / 255.0)
2235 blue:(CGFloat) (col.Blue() / 255.0)
2236 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2237 }
2238 }
2239
2240 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2241 {
2242 BOOL opaque = ( style == wxBG_STYLE_PAINT );
2243
2244 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2245 {
2246 [m_osxView setOpaque: opaque];
2247 }
2248
2249 return true ;
2250 }
2251
2252 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2253 {
2254 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2255 {
2256 wxCFStringRef cf( title , encoding );
2257 [m_osxView setTitle:cf.AsNSString()];
2258 }
2259 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2260 {
2261 wxCFStringRef cf( title , encoding );
2262 [m_osxView setStringValue:cf.AsNSString()];
2263 }
2264 }
2265
2266
2267 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2268 {
2269 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2270 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2271 *pt = wxFromNSPoint( to->GetWXWidget(), p );
2272 }
2273
2274 wxInt32 wxWidgetCocoaImpl::GetValue() const
2275 {
2276 return [(NSControl*)m_osxView intValue];
2277 }
2278
2279 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2280 {
2281 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
2282 {
2283 [m_osxView setIntValue:v];
2284 }
2285 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2286 {
2287 [m_osxView setFloatValue:(double)v];
2288 }
2289 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2290 {
2291 [m_osxView setDoubleValue:(double)v];
2292 }
2293 }
2294
2295 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2296 {
2297 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
2298 {
2299 [m_osxView setMinValue:(double)v];
2300 }
2301 }
2302
2303 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2304 {
2305 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2306 {
2307 [m_osxView setMaxValue:(double)v];
2308 }
2309 }
2310
2311 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2312 {
2313 if ( [m_osxView respondsToSelector:@selector(minValue)] )
2314 {
2315 return (int)[m_osxView minValue];
2316 }
2317 return 0;
2318 }
2319
2320 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2321 {
2322 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
2323 {
2324 return (int)[m_osxView maxValue];
2325 }
2326 return 0;
2327 }
2328
2329 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2330 {
2331 wxBitmap bmp;
2332
2333 // TODO: how to create a wxBitmap from NSImage?
2334 #if 0
2335 if ( [m_osxView respondsToSelector:@selector(image:)] )
2336 bmp = [m_osxView image];
2337 #endif
2338
2339 return bmp;
2340 }
2341
2342 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2343 {
2344 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
2345 {
2346 if (bitmap.IsOk())
2347 [m_osxView setImage:bitmap.GetNSImage()];
2348 else
2349 [m_osxView setImage:nil];
2350
2351 [m_osxView setNeedsDisplay:YES];
2352 }
2353 }
2354
2355 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2356 {
2357 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2358 {
2359 NSCellImagePosition pos;
2360 switch ( dir )
2361 {
2362 case wxLEFT:
2363 pos = NSImageLeft;
2364 break;
2365
2366 case wxRIGHT:
2367 pos = NSImageRight;
2368 break;
2369
2370 case wxTOP:
2371 pos = NSImageAbove;
2372 break;
2373
2374 case wxBOTTOM:
2375 pos = NSImageBelow;
2376 break;
2377
2378 default:
2379 wxFAIL_MSG( "invalid image position" );
2380 pos = NSNoImage;
2381 }
2382
2383 [m_osxView setImagePosition:pos];
2384 }
2385 }
2386
2387 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2388 {
2389 // implementation in subclass
2390 }
2391
2392 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2393 {
2394 r->x = r->y = r->width = r->height = 0;
2395
2396 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2397 {
2398 NSRect former = [m_osxView frame];
2399 [m_osxView sizeToFit];
2400 NSRect best = [m_osxView frame];
2401 [m_osxView setFrame:former];
2402 r->width = (int)best.size.width;
2403 r->height = (int)best.size.height;
2404 }
2405 }
2406
2407 bool wxWidgetCocoaImpl::IsEnabled() const
2408 {
2409 NSView* targetView = m_osxView;
2410 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2411 targetView = [(NSScrollView*) m_osxView documentView];
2412
2413 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2414 return [targetView isEnabled];
2415 return true;
2416 }
2417
2418 void wxWidgetCocoaImpl::Enable( bool enable )
2419 {
2420 NSView* targetView = m_osxView;
2421 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2422 targetView = [(NSScrollView*) m_osxView documentView];
2423
2424 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2425 [targetView setEnabled:enable];
2426 }
2427
2428 void wxWidgetCocoaImpl::PulseGauge()
2429 {
2430 }
2431
2432 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2433 {
2434 }
2435
2436 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2437 {
2438 NSControlSize size = NSRegularControlSize;
2439
2440 switch ( variant )
2441 {
2442 case wxWINDOW_VARIANT_NORMAL :
2443 size = NSRegularControlSize;
2444 break ;
2445
2446 case wxWINDOW_VARIANT_SMALL :
2447 size = NSSmallControlSize;
2448 break ;
2449
2450 case wxWINDOW_VARIANT_MINI :
2451 size = NSMiniControlSize;
2452 break ;
2453
2454 case wxWINDOW_VARIANT_LARGE :
2455 size = NSRegularControlSize;
2456 break ;
2457
2458 default:
2459 wxFAIL_MSG(wxT("unexpected window variant"));
2460 break ;
2461 }
2462 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2463 [m_osxView setControlSize:size];
2464 else if ([m_osxView respondsToSelector:@selector(cell)])
2465 {
2466 id cell = [(id)m_osxView cell];
2467 if ([cell respondsToSelector:@selector(setControlSize:)])
2468 [cell setControlSize:size];
2469 }
2470
2471 // we need to propagate this to inner views as well
2472 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2473 {
2474 NSView* targetView = [(NSScrollView*) m_osxView documentView];
2475
2476 if ( [targetView respondsToSelector:@selector(setControlSize:)] )
2477 [targetView setControlSize:size];
2478 else if ([targetView respondsToSelector:@selector(cell)])
2479 {
2480 id cell = [(id)targetView cell];
2481 if ([cell respondsToSelector:@selector(setControlSize:)])
2482 [cell setControlSize:size];
2483 }
2484 }
2485 }
2486
2487 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2488 {
2489 NSView* targetView = m_osxView;
2490 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2491 targetView = [(NSScrollView*) m_osxView documentView];
2492
2493 if ([targetView respondsToSelector:@selector(setFont:)])
2494 [targetView setFont: font.OSXGetNSFont()];
2495 if ([targetView respondsToSelector:@selector(setTextColor:)])
2496 [targetView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2497 green:(CGFloat) (col.Green() / 255.0)
2498 blue:(CGFloat) (col.Blue() / 255.0)
2499 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2500 }
2501
2502 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2503 {
2504 if ( tooltip )
2505 {
2506 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2507 [m_osxView setToolTip: cf.AsNSString()];
2508 }
2509 else
2510 {
2511 [m_osxView setToolTip:nil];
2512 }
2513 }
2514
2515 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2516 {
2517 WXWidget c = control ? control : (WXWidget) m_osxView;
2518 wxWidgetImpl::Associate( c, this ) ;
2519 if ([c respondsToSelector:@selector(setAction:)])
2520 {
2521 [c setTarget: c];
2522 if ( dynamic_cast<wxRadioButton*>(GetWXPeer()) )
2523 {
2524 // everything already set up
2525 }
2526 else
2527 [c setAction: @selector(controlAction:)];
2528
2529 if ([c respondsToSelector:@selector(setDoubleAction:)])
2530 {
2531 [c setDoubleAction: @selector(controlDoubleAction:)];
2532 }
2533
2534 }
2535 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingCursorUpdate|NSTrackingMouseMoved|NSTrackingActiveAlways|NSTrackingInVisibleRect;
2536 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: NSZeroRect options: options owner: m_osxView userInfo: nil];
2537 [m_osxView addTrackingArea: area];
2538 [area release];
2539 }
2540
2541 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2542 {
2543 wxKeyEvent wxevent(wxEVT_CHAR);
2544 SetupKeyEvent( wxevent, event, text );
2545
2546 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2547 }
2548
2549 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2550 {
2551 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2552 SetupKeyEvent( wxevent, event );
2553
2554 // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2555 // the key is pressed, not when it's released (the type of wxevent is
2556 // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2557 if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2558 {
2559 wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2560 if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2561 && !eventHook.IsNextEventAllowed() )
2562 return true;
2563 }
2564
2565 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2566
2567 // this will fire higher level events, like insertText, to help
2568 // us handle EVT_CHAR, etc.
2569
2570 if ( !result )
2571 {
2572 if ( [event type] == NSKeyDown)
2573 {
2574 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2575
2576 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2577 {
2578 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2579 wxKeyEvent wxevent2(wxevent) ;
2580 wxevent2.SetEventType(wxEVT_CHAR);
2581 SetupKeyEvent( wxevent2, event );
2582 wxevent2.m_keyCode = keycode;
2583 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2584 }
2585 else if (wxevent.CmdDown())
2586 {
2587 wxKeyEvent wxevent2(wxevent) ;
2588 wxevent2.SetEventType(wxEVT_CHAR);
2589 SetupKeyEvent( wxevent2, event );
2590 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2591 }
2592 else
2593 {
2594 if ( IsUserPane() && !wxevent.CmdDown() )
2595 {
2596 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2597 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2598 else
2599 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2600 result = true;
2601 }
2602 }
2603 }
2604 }
2605
2606 return result;
2607 }
2608
2609 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2610 {
2611 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2612 SetupMouseEvent(wxevent , event) ;
2613 bool result = GetWXPeer()->HandleWindowEvent(wxevent);
2614
2615 (void)SetupCursor(event);
2616
2617 return result;
2618 }
2619
2620 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2621 {
2622 wxWindow* thisWindow = GetWXPeer();
2623 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2624 {
2625 thisWindow->MacInvalidateBorders();
2626 }
2627
2628 if ( receivedFocus )
2629 {
2630 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2631 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2632 thisWindow->HandleWindowEvent(eventFocus);
2633
2634 #if wxUSE_CARET
2635 if ( thisWindow->GetCaret() )
2636 thisWindow->GetCaret()->OnSetFocus();
2637 #endif
2638
2639 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2640 event.SetEventObject(thisWindow);
2641 if (otherWindow)
2642 event.SetWindow(otherWindow->GetWXPeer());
2643 thisWindow->HandleWindowEvent(event) ;
2644 }
2645 else // !receivedFocus
2646 {
2647 #if wxUSE_CARET
2648 if ( thisWindow->GetCaret() )
2649 thisWindow->GetCaret()->OnKillFocus();
2650 #endif
2651
2652 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2653
2654 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2655 event.SetEventObject(thisWindow);
2656 if (otherWindow)
2657 event.SetWindow(otherWindow->GetWXPeer());
2658 thisWindow->HandleWindowEvent(event) ;
2659 }
2660 }
2661
2662 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2663 {
2664 if ( !wxIsBusy() )
2665 {
2666 NSPoint location = [NSEvent mouseLocation];
2667 location = [[m_osxView window] convertScreenToBase:location];
2668 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2669
2670 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2671 {
2672 [(NSCursor*)cursor.GetHCURSOR() set];
2673 }
2674 }
2675 }
2676
2677 void wxWidgetCocoaImpl::CaptureMouse()
2678 {
2679 // TODO remove if we don't get into problems with cursor settings
2680 // [[m_osxView window] disableCursorRects];
2681 }
2682
2683 void wxWidgetCocoaImpl::ReleaseMouse()
2684 {
2685 // TODO remove if we don't get into problems with cursor settings
2686 // [[m_osxView window] enableCursorRects];
2687 }
2688
2689 #if !wxOSX_USE_NATIVE_FLIPPED
2690
2691 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2692 {
2693 m_isFlipped = flipped;
2694 }
2695
2696 #endif
2697
2698 void wxWidgetCocoaImpl::SetDrawingEnabled(bool enabled)
2699 {
2700 if ( enabled )
2701 {
2702 [[m_osxView window] enableFlushWindow];
2703 [m_osxView setNeedsDisplay:YES];
2704 }
2705 else
2706 {
2707 [[m_osxView window] disableFlushWindow];
2708 }
2709 }
2710 //
2711 // Factory methods
2712 //
2713
2714 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2715 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2716 long WXUNUSED(style), long WXUNUSED(extraStyle))
2717 {
2718 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2719 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2720
2721 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2722 return c;
2723 }
2724
2725 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2726 {
2727 NSWindow* tlw = now->GetWXWindow();
2728
2729 wxWidgetCocoaImpl* c = NULL;
2730 if ( now->IsNativeWindowWrapper() )
2731 {
2732 NSView* cv = [tlw contentView];
2733 c = new wxWidgetCocoaImpl( now, cv, true );
2734 if ( cv != nil )
2735 {
2736 // increase ref count, because the impl destructor will decrement it again
2737 CFRetain(cv);
2738 if ( !now->IsShown() )
2739 [cv setHidden:NO];
2740 }
2741 }
2742 else
2743 {
2744 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2745 c = new wxWidgetCocoaImpl( now, v, true );
2746 c->InstallEventHandler();
2747 [tlw setContentView:v];
2748 }
2749 return c;
2750 }