]> git.saurik.com Git - wxWidgets.git/blame - src/osx/cocoa/window.mm
guarding open combo box against AppDefined NSEvents issued by wxEventLoop::WakeUp...
[wxWidgets.git] / src / osx / cocoa / window.mm
CommitLineData
33e90275
SC
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
a9a4f229 7// RCS-ID: $Id$
33e90275
SC
8// Copyright: (c) Stefan Csomor
9// Licence: wxWindows licence
10/////////////////////////////////////////////////////////////////////////////
11
12#include "wx/wxprec.h"
13
05cf95ed 14#ifndef WX_PRECOMP
f487501a 15 #include "wx/dcclient.h"
ca9047f7 16 #include "wx/frame.h"
c583fa5a 17 #include "wx/log.h"
75a2c6a1 18 #include "wx/textctrl.h"
4275201b 19 #include "wx/combobox.h"
05cf95ed 20#endif
33e90275
SC
21
22#ifdef __WXMAC__
4dd9fdf8 23 #include "wx/osx/private.h"
33e90275
SC
24#endif
25
f2be0678 26#include "wx/evtloop.h"
ab9a0b84 27
0c530e5a
SC
28#if wxUSE_CARET
29 #include "wx/caret.h"
30#endif
31
4dd9fdf8
SC
32#if wxUSE_DRAG_AND_DROP
33 #include "wx/dnd.h"
34#endif
35
a7b9865d
KO
36#if wxUSE_TOOLTIPS
37 #include "wx/tooltip.h"
38#endif
39
4dd9fdf8
SC
40#include <objc/objc-runtime.h>
41
f06e0fea
SC
42// Get the window with the focus
43
ba0cf6af 44NSView* wxOSXGetViewFromResponder( NSResponder* responder )
f06e0fea 45{
7cb2a241
SC
46 NSView* view = nil;
47 if ( [responder isKindOfClass:[NSTextView class]] )
f06e0fea 48 {
c8fdb345 49 NSView* delegate = (NSView*) [(NSTextView*)responder delegate];
7cb2a241
SC
50 if ( [delegate isKindOfClass:[NSTextField class] ] )
51 view = delegate;
f06e0fea 52 else
7cb2a241 53 view = (NSView*) responder;
f06e0fea 54 }
7cb2a241
SC
55 else
56 {
57 if ( [responder isKindOfClass:[NSView class]] )
58 view = (NSView*) responder;
59 }
60 return view;
61}
62
63NSView* GetFocusedViewInWindow( NSWindow* keyWindow )
64{
65 NSView* focusedView = nil;
66 if ( keyWindow != nil )
ba0cf6af 67 focusedView = wxOSXGetViewFromResponder([keyWindow firstResponder]);
7cb2a241 68
f06e0fea
SC
69 return focusedView;
70}
71
7cb2a241
SC
72WXWidget wxWidgetImpl::FindFocus()
73{
09ffaca3 74 return GetFocusedViewInWindow( [NSApp keyWindow] );;
7cb2a241
SC
75}
76
09ffaca3
SC
77wxWidgetImpl* wxWidgetImpl::FindBestFromWXWidget(WXWidget control)
78{
79 wxWidgetImpl* impl = FindFromWXWidget(control);
80
81 // NSScrollViews can have their subviews like NSClipView
82 // therefore check and use the NSScrollView peer in that case
83 if ( impl == NULL && [[control superview] isKindOfClass:[NSScrollView class]])
84 impl = FindFromWXWidget([control superview]);
85
86 return impl;
87}
88
89
dbeddfb9
SC
90NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
91{
92 int x, y, w, h ;
93
94 window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
95 wxRect bounds(x,y,w,h);
96 NSView* sv = (window->GetParent()->GetHandle() );
97
98 return wxToNSRect( sv, bounds );
99}
33e90275
SC
100
101@interface wxNSView : NSView
102{
20111900
SC
103 BOOL _hasToolTip;
104 NSTrackingRectTag _lastToolTipTrackTag;
105 id _lastToolTipOwner;
106 void* _lastUserData;
107
33e90275
SC
108}
109
33e90275
SC
110@end // wxNSView
111
03647350 112@interface NSView(PossibleMethods)
ffad7b0d
SC
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
19c7ac3d
SC
119- (double)minValue;
120- (double)maxValue;
ffad7b0d
SC
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;
0c530e5a 131
6ac636dd
SC
132- (void)setFont:(NSFont *)fontObject;
133
0c530e5a 134- (id)contentView;
4dd9fdf8
SC
135
136- (void)setTarget:(id)anObject;
137- (void)setAction:(SEL)aSelector;
138- (void)setDoubleAction:(SEL)aSelector;
3b2527c7 139- (void)setBackgroundColor:(NSColor*)aColor;
bc5c09a3 140- (void)setOpaque:(BOOL)opaque;
1a289c62 141- (void)setTextColor:(NSColor *)color;
3b2527c7 142- (void)setImagePosition:(NSCellImagePosition)aPosition;
03647350 143@end
ffad7b0d 144
0309327e
SC
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
a8fc3508 201long wxOSXTranslateCocoaKey( NSEvent* event, int eventType )
524c47aa 202{
63a6419c
KO
203 long retval = 0;
204
205 if ([event type] != NSFlagsChanged)
03647350 206 {
0309327e 207 NSString* s = [event charactersIgnoringModifiersIncludingShift];
63a6419c
KO
208 // backspace char reports as delete w/modifiers for some reason
209 if ([s length] == 1)
210 {
a8fc3508 211 if ( eventType == wxEVT_CHAR && ([event modifierFlags] & NSControlKeyMask) && ( [s characterAtIndex:0] >= 'a' && [s characterAtIndex:0] <= 'z' ) )
63a6419c 212 {
a8fc3508
SC
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 );
99d67201
SC
264 else if ( intchar > 0 && intchar < 32 )
265 retval = intchar;
a8fc3508
SC
266 break;
267 }
63a6419c
KO
268 }
269 }
270 }
03647350 271
63a6419c
KO
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] )
524c47aa 276 {
63a6419c
KO
277 // command key
278 case 54:
279 case 55:
68065b91 280 retval = WXK_CONTROL;
524c47aa 281 break;
63a6419c
KO
282 // caps locks key
283 case 57: // Capslock
284 retval = WXK_CAPITAL;
524c47aa 285 break;
63a6419c
KO
286 // shift key
287 case 56: // Left Shift
288 case 60: // Right Shift
289 retval = WXK_SHIFT;
524c47aa 290 break;
63a6419c
KO
291 // alt key
292 case 58: // Left Alt
293 case 61: // Right Alt
294 retval = WXK_ALT;
524c47aa 295 break;
63a6419c
KO
296 // ctrl key
297 case 59: // Left Ctrl
298 case 62: // Right Ctrl
68065b91 299 retval = WXK_RAW_CONTROL;
524c47aa 300 break;
63a6419c 301 // clear key
03647350 302 case 71:
63a6419c 303 retval = WXK_CLEAR;
524c47aa 304 break;
63a6419c 305 // tab key
03647350 306 case 48:
63a6419c 307 retval = WXK_TAB;
524c47aa 308 break;
4d61ae5f 309 default:
524c47aa
SC
310 break;
311 }
33f3e2b3
SC
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 }
524c47aa
SC
373 return retval;
374}
375
ddbc8ac9 376void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
524c47aa
SC
377{
378 UInt32 modifiers = [nsEvent modifierFlags] ;
fc39cf72 379 int eventType = [nsEvent type];
524c47aa
SC
380
381 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
dd9ec596 382 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
524c47aa 383 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
dd9ec596 384 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
03647350 385
19c7ac3d 386 wxevent.m_rawCode = [nsEvent keyCode];
524c47aa 387 wxevent.m_rawFlags = modifiers;
03647350 388
e490b0d2 389 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
19c7ac3d
SC
390
391 wxString chars;
392 if ( eventType != NSFlagsChanged )
393 {
0309327e 394 NSString* nschars = [[nsEvent charactersIgnoringModifiersIncludingShift] uppercaseString];
f0e0116e 395 if ( charString )
63a6419c
KO
396 {
397 // if charString is set, it did not come from key up / key down
398 wxevent.SetEventType( wxEVT_CHAR );
f66ecdc4 399 chars = wxCFStringRef::AsString(charString);
63a6419c
KO
400 }
401 else if ( nschars )
19c7ac3d 402 {
f66ecdc4 403 chars = wxCFStringRef::AsString(nschars);
19c7ac3d
SC
404 }
405 }
03647350 406
63a6419c
KO
407 int aunichar = chars.Length() > 0 ? chars[0] : 0;
408 long keyval = 0;
03647350 409
63a6419c 410 if (wxevent.GetEventType() != wxEVT_CHAR)
4d61ae5f 411 {
a8fc3508 412 keyval = wxOSXTranslateCocoaKey(nsEvent, wxevent.GetEventType()) ;
4d61ae5f
SC
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;
a8fc3508
SC
433 case WXK_RAW_CONTROL:
434 wxevent.SetEventType( wxevent.m_rawControlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
4d61ae5f
SC
435 break;
436 }
437 break;
438 default :
439 break ;
440 }
441 }
19c7ac3d 442
63a6419c
KO
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 }
03647350 450
19c7ac3d 451#if wxUSE_UNICODE
e999b903
VZ
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;
19c7ac3d
SC
462#endif
463 wxevent.m_keyCode = keyval;
ddbc8ac9
SC
464
465 wxWindowMac* peer = GetWXPeer();
466 if ( peer )
467 {
468 wxevent.SetEventObject(peer);
469 wxevent.SetId(peer->GetId()) ;
470 }
524c47aa
SC
471}
472
54f11060
SC
473UInt32 g_lastButton = 0 ;
474bool g_lastButtonWasFakeRight = false ;
475
83ffdd71
SC
476// better scroll wheel support
477// see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
478
479@interface NSEvent (DeviceDelta)
b2b61216
VZ
480- (CGFloat)deviceDeltaX;
481- (CGFloat)deviceDeltaY;
28a62eec
SC
482
483// 10.7+
484- (BOOL)hasPreciseScrollingDeltas;
485- (CGFloat)scrollingDeltaX;
486- (CGFloat)scrollingDeltaY;
83ffdd71
SC
487@end
488
094fa9e9 489void wxWidgetCocoaImpl::SetupCoordinates(wxCoord &x, wxCoord &y, NSEvent* nsEvent)
33e90275 490{
58110007
SC
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];
094fa9e9 498
58110007
SC
499 if ( [m_osxView window] != nil )
500 locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
501 }
094fa9e9 502
58110007
SC
503 NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
504 wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
094fa9e9
SC
505
506 x = locationInViewWX.x;
507 y = locationInViewWX.y;
508
509}
510
511void 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);
33e90275
SC
517
518 // these parameters are not given for all events
519 UInt32 button = [nsEvent buttonNumber];
4800ca79 520 UInt32 clickCount = 0;
33e90275 521
33e90275 522 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
dd9ec596 523 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
33e90275 524 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
dd9ec596 525 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
e490b0d2 526 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
54f11060 527
03647350 528 UInt32 mouseChord = 0;
54f11060
SC
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
33e90275
SC
546 // a control click is interpreted as a right click
547 bool thisButtonIsFakeRight = false ;
54f11060 548 if ( button == 0 && (modifiers & NSControlKeyMask) )
33e90275 549 {
54f11060 550 button = 1 ;
33e90275
SC
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 ;
54f11060 557
33e90275
SC
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
54f11060 560 switch (eventType)
33e90275 561 {
54f11060
SC
562 case NSLeftMouseDown :
563 case NSRightMouseDown :
564 case NSOtherMouseDown :
565 g_lastButton = button ;
566 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
567 break;
568 }
33e90275
SC
569
570 if ( button == 0 )
571 {
572 g_lastButton = 0 ;
573 g_lastButtonWasFakeRight = false ;
574 }
54f11060 575 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
33e90275
SC
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
33e90275 592 // translate into wx types
33e90275
SC
593 switch (eventType)
594 {
595 case NSLeftMouseDown :
596 case NSRightMouseDown :
597 case NSOtherMouseDown :
08c1b134 598 clickCount = [nsEvent clickCount];
33e90275
SC
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 :
08c1b134 621 clickCount = [nsEvent clickCount];
33e90275
SC
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 {
a533f050
SC
643 float deltaX = 0.0;
644 float deltaY = 0.0;
645
33e90275 646 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
a533f050 647
28a62eec 648 if ( UMAGetSystemVersion() >= 0x1070 )
a533f050 649 {
28a62eec
SC
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 }
a533f050
SC
660 }
661 else
662 {
28a62eec
SC
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 }
a533f050
SC
681 }
682
e32090ba 683 wxevent.m_wheelDelta = 10;
33e90275 684 wxevent.m_linesPerAction = 1;
5833988c 685 wxevent.m_columnsPerAction = 1;
a533f050
SC
686
687 if ( fabs(deltaX) > fabs(deltaY) )
4800ca79 688 {
41469c9e 689 wxevent.m_wheelAxis = wxMOUSE_WHEEL_HORIZONTAL;
a533f050 690 wxevent.m_wheelRotation = (int)deltaX;
4800ca79
SC
691 }
692 else
693 {
a533f050 694 wxevent.m_wheelRotation = (int)deltaY;
4800ca79 695 }
a533f050 696
33e90275
SC
697 }
698 break ;
699
700 case NSMouseEntered :
f1f15003
KO
701 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
702 break;
33e90275 703 case NSMouseExited :
f1f15003
KO
704 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
705 break;
33e90275
SC
706 case NSLeftMouseDragged :
707 case NSRightMouseDragged :
708 case NSOtherMouseDragged :
709 case NSMouseMoved :
710 wxevent.SetEventType( wxEVT_MOTION ) ;
711 break;
712 default :
713 break ;
714 }
03647350 715
08c1b134 716 wxevent.m_clickCount = clickCount;
ddbc8ac9
SC
717 wxWindowMac* peer = GetWXPeer();
718 if ( peer )
719 {
720 wxevent.SetEventObject(peer);
721 wxevent.SetId(peer->GetId()) ;
722 }
33e90275
SC
723}
724
725@implementation wxNSView
726
4dd9fdf8
SC
727+ (void)initialize
728{
729 static BOOL initialized = NO;
03647350 730 if (!initialized)
4dd9fdf8
SC
731 {
732 initialized = YES;
733 wxOSXCocoaClassAddWXMethods( self );
734 }
735}
736
20111900
SC
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}
2c31fcd7
SC
818
819#if wxOSX_USE_NATIVE_FLIPPED
820- (BOOL)isFlipped
821{
822 return YES;
823}
824#endif
825
a5777be7
SC
826- (BOOL) canBecomeKeyView
827{
828 wxWidgetCocoaImpl* viewimpl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
b09857ae 829 if ( viewimpl && viewimpl->IsUserPane() && viewimpl->GetWXPeer() )
a5777be7
SC
830 return viewimpl->GetWXPeer()->AcceptsFocus();
831 return NO;
832}
833
4dd9fdf8
SC
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
845NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
846{
847 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
848 if (impl == NULL)
849 return NSDragOperationNone;
03647350 850
4dd9fdf8
SC
851 return impl->draggingEntered(sender, self, _cmd);
852}
853
854void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
855{
856 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
857 if (impl == NULL)
858 return ;
03647350 859
4dd9fdf8
SC
860 return impl->draggingExited(sender, self, _cmd);
861}
862
863NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
864{
865 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
866 if (impl == NULL)
867 return NSDragOperationNone;
03647350 868
4dd9fdf8
SC
869 return impl->draggingUpdated(sender, self, _cmd);
870}
871
872BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
873{
874 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
875 if (impl == NULL)
876 return NSDragOperationNone;
03647350 877
4dd9fdf8
SC
878 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
879}
880
7cb2a241
SC
881#endif
882
03647350 883void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
4dd9fdf8
SC
884{
885 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
886 if (impl == NULL)
887 return;
03647350 888
4dd9fdf8
SC
889 impl->mouseEvent(event, self, _cmd);
890}
891
3a176763
SC
892void 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
849252d5 901BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
5a900d50
KO
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
03647350 908void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
4dd9fdf8
SC
909{
910 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
911 if (impl == NULL)
912 return;
03647350 913
4dd9fdf8
SC
914 impl->keyEvent(event, self, _cmd);
915}
916
03647350 917void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
f0e0116e
KO
918{
919 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
920 if (impl == NULL)
921 return;
03647350 922
f0e0116e
KO
923 impl->insertText(text, self, _cmd);
924}
925
03647350 926BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
4dd9fdf8
SC
927{
928 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
929 if (impl == NULL)
930 return NO;
03647350 931
4dd9fdf8
SC
932 return impl->performKeyEquivalent(event, self, _cmd);
933}
934
09a9eb20
KO
935BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
936{
937 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
938 if (impl == NULL)
939 return NO;
03647350 940
09a9eb20
KO
941 return impl->acceptsFirstResponder(self, _cmd);
942}
943
4dd9fdf8
SC
944BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
945{
946 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
947 if (impl == NULL)
948 return NO;
03647350 949
4dd9fdf8
SC
950 return impl->becomeFirstResponder(self, _cmd);
951}
952
953BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
954{
955 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
956 if (impl == NULL)
957 return NO;
03647350 958
4dd9fdf8
SC
959 return impl->resignFirstResponder(self, _cmd);
960}
961
c551dc29
SC
962#if !wxOSX_USE_NATIVE_FLIPPED
963
4dd9fdf8
SC
964BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
965{
966 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
967 if (impl == NULL)
968 return NO;
03647350 969
4dd9fdf8
SC
970 return impl->isFlipped(self, _cmd) ? YES:NO;
971}
972
c551dc29
SC
973#endif
974
c71096a0
VZ
975typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
976
4dd9fdf8
SC
977void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
978{
979 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
980 if (impl == NULL)
981 return;
03647350 982
32b183b5 983#if wxUSE_THREADS
c71096a0
VZ
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 {
d4a4ef90
SC
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());
a3c22212
SC
1003 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
1004 CGContextFillRect( context, r );
d4a4ef90
SC
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
c71096a0
VZ
1019 return;
1020 }
1021#endif // wxUSE_THREADS
1022
4dd9fdf8
SC
1023 return impl->drawRect(&rect, self, _cmd);
1024}
1025
e32090ba 1026void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
4dd9fdf8
SC
1027{
1028 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1029 if (impl == NULL)
1030 return;
03647350 1031
e32090ba 1032 impl->controlAction(self, _cmd, sender);
4dd9fdf8
SC
1033}
1034
e32090ba 1035void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
4dd9fdf8
SC
1036{
1037 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1038 if (impl == NULL)
1039 return;
03647350 1040
e32090ba 1041 impl->controlDoubleAction(self, _cmd, sender);
4dd9fdf8 1042}
dbeddfb9 1043
d8207702 1044unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
33e90275 1045{
4dd9fdf8
SC
1046 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1047 NSPasteboard *pboard = [sender draggingPasteboard];
1048 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
03647350 1049
4dd9fdf8
SC
1050 wxWindow* wxpeer = GetWXPeer();
1051 if ( wxpeer == NULL )
1052 return NSDragOperationNone;
03647350 1053
4dd9fdf8
SC
1054 wxDropTarget* target = wxpeer->GetDropTarget();
1055 if ( target == NULL )
1056 return NSDragOperationNone;
1057
1058 wxDragResult result = wxDragNone;
e6b3143a
SC
1059 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1060 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
4dd9fdf8
SC
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
03647350 1069 PasteboardRef pboardRef;
4dd9fdf8
SC
1070 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1071 target->SetCurrentDragPasteboard(pboardRef);
1072 result = target->OnEnter(pt.x, pt.y, result);
1073 CFRelease(pboardRef);
03647350 1074
4dd9fdf8
SC
1075 NSDragOperation nsresult = NSDragOperationNone;
1076 switch (result )
33e90275 1077 {
4dd9fdf8
SC
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}
33e90275 1089
d8207702 1090void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
4dd9fdf8
SC
1091{
1092 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1093 NSPasteboard *pboard = [sender draggingPasteboard];
03647350 1094
4dd9fdf8
SC
1095 wxWindow* wxpeer = GetWXPeer();
1096 if ( wxpeer == NULL )
1097 return;
03647350 1098
4dd9fdf8
SC
1099 wxDropTarget* target = wxpeer->GetDropTarget();
1100 if ( target == NULL )
1101 return;
03647350
VZ
1102
1103 PasteboardRef pboardRef;
4dd9fdf8
SC
1104 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1105 target->SetCurrentDragPasteboard(pboardRef);
1106 target->OnLeave();
1107 CFRelease(pboardRef);
1108 }
1109
d8207702 1110unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
4dd9fdf8
SC
1111{
1112 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1113 NSPasteboard *pboard = [sender draggingPasteboard];
1114 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
03647350 1115
4dd9fdf8
SC
1116 wxWindow* wxpeer = GetWXPeer();
1117 if ( wxpeer == NULL )
1118 return NSDragOperationNone;
03647350 1119
4dd9fdf8
SC
1120 wxDropTarget* target = wxpeer->GetDropTarget();
1121 if ( target == NULL )
1122 return NSDragOperationNone;
1123
1124 wxDragResult result = wxDragNone;
e6b3143a
SC
1125 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1126 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
4dd9fdf8
SC
1127
1128 if ( sourceDragMask & NSDragOperationLink )
1129 result = wxDragLink;
1130 else if ( sourceDragMask & NSDragOperationCopy )
1131 result = wxDragCopy;
1132 else if ( sourceDragMask & NSDragOperationMove )
1133 result = wxDragMove;
808cbd17 1134
03647350 1135 PasteboardRef pboardRef;
4dd9fdf8
SC
1136 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1137 target->SetCurrentDragPasteboard(pboardRef);
1138 result = target->OnDragOver(pt.x, pt.y, result);
1139 CFRelease(pboardRef);
03647350 1140
4dd9fdf8
SC
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
d8207702 1156bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
4dd9fdf8
SC
1157{
1158 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
dbeddfb9 1159
4dd9fdf8
SC
1160 NSPasteboard *pboard = [sender draggingPasteboard];
1161 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
03647350 1162
4dd9fdf8
SC
1163 wxWindow* wxpeer = GetWXPeer();
1164 wxDropTarget* target = wxpeer->GetDropTarget();
1165 wxDragResult result = wxDragNone;
e6b3143a
SC
1166 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1167 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
4dd9fdf8
SC
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
03647350 1176 PasteboardRef pboardRef;
4dd9fdf8
SC
1177 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1178 target->SetCurrentDragPasteboard(pboardRef);
5646fba6
SC
1179
1180 if (target->OnDrop(pt.x, pt.y))
1181 result = target->OnData(pt.x, pt.y, result);
1182
4dd9fdf8 1183 CFRelease(pboardRef);
03647350 1184
4dd9fdf8
SC
1185 return result != wxDragNone;
1186}
1187
63a6419c 1188typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
4dd9fdf8
SC
1189typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1190typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1191typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
4dd9fdf8
SC
1192
1193void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1194{
ebeac3a7
SC
1195 // we are getting moved events for all windows in the hierarchy, not something wx expects
1196 // therefore we only handle it for the deepest child in the hierarchy
bc6626eb 1197 if ( [event type] == NSMouseMoved )
ebeac3a7
SC
1198 {
1199 NSView* hitview = [[[slf window] contentView] hitTest:[event locationInWindow]];
1200 if ( hitview == NULL || hitview != slf)
1201 return;
1202 }
1203
4dd9fdf8
SC
1204 if ( !DoHandleMouseEvent(event) )
1205 {
2e498654 1206 // for plain NSView mouse events would propagate to parents otherwise
b0cb9185
SC
1207 // scrollwheel events have to be propagated if not handled in all cases
1208 if (!IsUserPane() || [event type] == NSScrollWheel )
2e498654
SC
1209 {
1210 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1211 superimpl(slf, (SEL)_cmd, event);
b54a793b
SC
1212
1213 // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
4ca0bca0 1214 // only trigger if at this moment the mouse is already up
f6669958 1215 if ( [ event type] == NSLeftMouseDown && !wxGetMouseState().LeftIsDown() )
b54a793b
SC
1216 {
1217 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1218 SetupMouseEvent(wxevent , event) ;
1219 wxevent.SetEventType(wxEVT_LEFT_UP);
1220
1221 GetWXPeer()->HandleWindowEvent(wxevent);
1222 }
2e498654 1223 }
4dd9fdf8
SC
1224 }
1225}
1226
3a176763
SC
1227void wxWidgetCocoaImpl::cursorUpdate(WX_NSEvent event, WXWidget slf, void *_cmd)
1228{
094fa9e9 1229 if ( !SetupCursor(event) )
3a176763
SC
1230 {
1231 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
094fa9e9 1232 superimpl(slf, (SEL)_cmd, event);
3a176763 1233 }
094fa9e9
SC
1234 }
1235
1236bool wxWidgetCocoaImpl::SetupCursor(WX_NSEvent event)
1237{
1238 extern wxCursor gGlobalCursor;
1239
1240 if ( gGlobalCursor.IsOk() )
3a176763 1241 {
094fa9e9
SC
1242 gGlobalCursor.MacInstall();
1243 return true;
1244 }
1245 else
1246 {
1247 wxWindow* cursorTarget = GetWXPeer();
1248 wxCoord x,y;
1249 SetupCoordinates(x, y, event);
1250 wxPoint cursorPoint( x , y ) ;
1251
1252 while ( cursorTarget && !cursorTarget->MacSetupCursor( cursorPoint ) )
1253 {
f1d0d07d
SC
1254 // at least in GTK cursor events are not propagated either ...
1255#if 1
1256 cursorTarget = NULL;
1257#else
094fa9e9
SC
1258 cursorTarget = cursorTarget->GetParent() ;
1259 if ( cursorTarget )
1260 cursorPoint += cursorTarget->GetPosition();
f1d0d07d 1261#endif
094fa9e9
SC
1262 }
1263
1264 return cursorTarget != NULL;
3a176763
SC
1265 }
1266}
1267
4dd9fdf8
SC
1268void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1269{
715824d5 1270 if ( [event type] == NSKeyDown )
8c0e92cd
SC
1271 {
1272 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1273 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1274 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1275 return;
1276
715824d5 1277 m_lastKeyDownEvent = event;
8c0e92cd
SC
1278 }
1279
7cb2a241 1280 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
4dd9fdf8
SC
1281 {
1282 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1283 superimpl(slf, (SEL)_cmd, event);
1284 }
715824d5 1285 m_lastKeyDownEvent = NULL;
4dd9fdf8
SC
1286}
1287
f0e0116e 1288void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
4dd9fdf8 1289{
7cb2a241 1290 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
4dd9fdf8 1291 {
2e498654
SC
1292 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1293 superimpl(slf, (SEL)_cmd, text);
4dd9fdf8 1294 }
f0e0116e 1295}
4dd9fdf8 1296
f0e0116e
KO
1297
1298bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1299{
8c0e92cd
SC
1300 bool handled = false;
1301
1302 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1303 SetupKeyEvent( wxevent, event );
1304
1305 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1306 // walk up the ancestors ourselves but let cocoa do it
1307
1308 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1309 if (command != -1)
1310 {
1311 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1312
ce7fe42e 1313 wxCommandEvent command_event( wxEVT_MENU, command );
77dcae20 1314 command_event.SetEventObject( wxevent.GetEventObject() );
8c0e92cd
SC
1315 handled = handler->ProcessEvent( command_event );
1316
1317 if ( !handled )
1318 {
1319 // accelerators can also be used with buttons, try them too
ce7fe42e 1320 command_event.SetEventType(wxEVT_BUTTON);
8c0e92cd
SC
1321 handled = handler->ProcessEvent( command_event );
1322 }
1323 }
1324
1325 if ( !handled )
671b125b
SC
1326 {
1327 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1328 return superimpl(slf, (SEL)_cmd, event);
1329 }
1330 return YES;
4dd9fdf8
SC
1331}
1332
09a9eb20
KO
1333bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1334{
d15694e8 1335 if ( IsUserPane() )
f06e0fea
SC
1336 return m_wxPeer->AcceptsFocus();
1337 else
1338 {
1339 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1340 return superimpl(slf, (SEL)_cmd);
1341 }
09a9eb20
KO
1342}
1343
4dd9fdf8
SC
1344bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1345{
1346 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
b42865ce 1347 // get the current focus before running becomeFirstResponder
03647350 1348 NSView* otherView = FindFocus();
7cb2a241 1349
b42865ce 1350 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
4dd9fdf8
SC
1351 BOOL r = superimpl(slf, (SEL)_cmd);
1352 if ( r )
f06e0fea 1353 {
b42865ce 1354 DoNotifyFocusEvent( true, otherWindow );
f06e0fea 1355 }
7cb2a241 1356
4dd9fdf8
SC
1357 return r;
1358}
1359
1360bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1361{
1362 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1363 BOOL r = superimpl(slf, (SEL)_cmd);
60d66be3
SC
1364
1365 NSResponder * responder = wxNonOwnedWindowCocoaImpl::GetNextFirstResponder();
ba0cf6af 1366 NSView* otherView = wxOSXGetViewFromResponder(responder);
60d66be3 1367
e17d84e1 1368 wxWidgetImpl* otherWindow = FindBestFromWXWidget(otherView);
ea9ae179
SC
1369
1370 // It doesn't make sense to notify about the loss of focus if it's the same
1371 // control in the end, and just a different subview
45d1c40a
VZ
1372 if ( otherWindow == this )
1373 return r;
49ee8d1f 1374
f06e0fea 1375 // NSTextViews have an editor as true responder, therefore the might get the
7cb2a241
SC
1376 // resign notification if their editor takes over, don't trigger any event then
1377 if ( r && !m_hasEditor)
f06e0fea 1378 {
b42865ce 1379 DoNotifyFocusEvent( false, otherWindow );
f06e0fea 1380 }
4dd9fdf8
SC
1381 return r;
1382}
1383
c551dc29
SC
1384#if !wxOSX_USE_NATIVE_FLIPPED
1385
1386bool wxWidgetCocoaImpl::isFlipped(WXWidget slf, void *WXUNUSED(_cmd))
4dd9fdf8
SC
1387{
1388 return m_isFlipped;
1389}
33e90275 1390
c551dc29 1391#endif
4dd9fdf8
SC
1392
1393#define OSX_DEBUG_DRAWING 0
1394
d8207702 1395void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
4dd9fdf8 1396{
396f0e3d
SC
1397 // preparing the update region
1398
1399 wxRegion updateRgn;
c551dc29
SC
1400
1401 // since adding many rects to a region is a costly process, by default use the bounding rect
1402#if 0
396f0e3d
SC
1403 const NSRect *rects;
1404 NSInteger count;
396f0e3d
SC
1405 [slf getRectsBeingDrawn:&rects count:&count];
1406 for ( int i = 0 ; i < count ; ++i )
1407 {
1408 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1409 }
c551dc29
SC
1410#else
1411 updateRgn.Union(wxFromNSRect(slf,*(NSRect*)rect));
1412#endif
1413
396f0e3d
SC
1414 wxWindow* wxpeer = GetWXPeer();
1415
1416 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1417 {
1418 // as this update region is in native window locals we must adapt it to wx window local
1419 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1420 }
1421
caab08ee
VZ
1422 // Restrict the update region to the shape of the window, if any, and also
1423 // remember the region that we need to clear later.
1424 wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1425 const bool isTopLevel = tlwParent == wxpeer;
1426 wxRegion clearRgn;
1427 if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
396f0e3d 1428 {
caab08ee
VZ
1429 if ( isTopLevel )
1430 clearRgn = updateRgn;
1431
396f0e3d 1432 int xoffset = 0, yoffset = 0;
caab08ee 1433 wxRegion rgn = tlwParent->GetShape();
396f0e3d
SC
1434 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1435 rgn.Offset( xoffset, yoffset );
1436 updateRgn.Intersect(rgn);
caab08ee
VZ
1437
1438 if ( isTopLevel )
1439 {
1440 // Exclude the window shape from the region to be cleared below.
1441 rgn.Xor(wxpeer->GetSize());
1442 clearRgn.Intersect(rgn);
1443 }
396f0e3d
SC
1444 }
1445
1446 wxpeer->GetUpdateRegion() = updateRgn;
1447
1448 // setting up the drawing context
1449
4dd9fdf8
SC
1450 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1451 CGContextSaveGState( context );
396f0e3d 1452
4dd9fdf8
SC
1453#if OSX_DEBUG_DRAWING
1454 CGContextBeginPath( context );
1455 CGContextMoveToPoint(context, 0, 0);
2a2064f8 1456 NSRect bounds = [slf bounds];
4dd9fdf8
SC
1457 CGContextAddLineToPoint(context, 10, 0);
1458 CGContextMoveToPoint(context, 0, 0);
1459 CGContextAddLineToPoint(context, 0, 10);
1460 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1461 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1462 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1463 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1464 CGContextClosePath( context );
1465 CGContextStrokePath(context);
1466#endif
396f0e3d 1467
c551dc29 1468 if ( ![slf isFlipped] )
4dd9fdf8
SC
1469 {
1470 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1471 CGContextScaleCTM( context, 1, -1 );
1472 }
b61b8371 1473
4dd9fdf8 1474 wxpeer->MacSetCGContextRef( context );
03647350 1475
09489833 1476 bool handled = wxpeer->MacDoRedraw( 0 );
4dd9fdf8 1477 CGContextRestoreGState( context );
09489833
SC
1478
1479 CGContextSaveGState( context );
4dd9fdf8
SC
1480 if ( !handled )
1481 {
1482 // call super
1483 SEL _cmd = @selector(drawRect:);
1484 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1485 superimpl(slf, _cmd, *(NSRect*)rect);
09489833
SC
1486 CGContextRestoreGState( context );
1487 CGContextSaveGState( context );
33e90275 1488 }
7a69cf79 1489 // as we called restore above, we have to flip again if necessary
c551dc29 1490 if ( ![slf isFlipped] )
7a69cf79
SC
1491 {
1492 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1493 CGContextScaleCTM( context, 1, -1 );
1494 }
caab08ee
VZ
1495
1496 if ( isTopLevel )
1497 {
1498 // We also need to explicitly draw the part of the top level window
1499 // outside of its region with transparent colour to ensure that it is
1500 // really transparent.
1501 if ( clearRgn.IsOk() )
1502 {
1503 wxMacCGContextStateSaver saveState(context);
1504 wxWindowDC dc(wxpeer);
1505 dc.SetBackground(wxBrush(wxTransparentColour));
1506 dc.SetDeviceClippingRegion(clearRgn);
1507 dc.Clear();
1508 }
46ea442c
VZ
1509
1510#if wxUSE_GRAPHICS_CONTEXT
1511 // If the window shape is defined by a path, stroke the path to show
1512 // the window border.
1513 const wxGraphicsPath& path = tlwParent->GetShapePath();
1514 if ( !path.IsNull() )
1515 {
1516 CGContextSetLineWidth(context, 1);
1517 CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1518 CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1519 CGContextStrokePath(context);
1520 }
1521#endif // wxUSE_GRAPHICS_CONTEXT
caab08ee
VZ
1522 }
1523
09489833 1524 wxpeer->MacPaintChildrenBorders();
15fc716c 1525 wxpeer->MacSetCGContextRef( NULL );
09489833 1526 CGContextRestoreGState( context );
33e90275
SC
1527}
1528
d8207702 1529void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
4dd9fdf8
SC
1530{
1531 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1532 if ( wxpeer )
f731483d
SC
1533 {
1534 wxpeer->OSXSimulateFocusEvents();
4dd9fdf8 1535 wxpeer->OSXHandleClicked(0);
f731483d 1536 }
4dd9fdf8 1537}
33e90275 1538
d8207702 1539void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
524c47aa 1540{
524c47aa 1541}
33e90275 1542
75a2c6a1
KO
1543void wxWidgetCocoaImpl::controlTextDidChange()
1544{
1545 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1546 if ( wxpeer )
1547 {
4275201b
SC
1548 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1549 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1550 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1551 if ( tc )
1552 tc->SendTextUpdatedEventIfAllowed();
1553 else if ( cb )
1554 cb->SendTextUpdatedEventIfAllowed();
1555 else
1556 {
1557 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1558 }
75a2c6a1
KO
1559 }
1560}
1561
03647350 1562//
4dd9fdf8
SC
1563
1564#if OBJC_API_VERSION >= 2
1565
1566#define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1567 class_addMethod(c, s, i, t );
1568
1569#else
1570
1571#define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
68ebe5a0 1572 { s, (char*) t, i },
4dd9fdf8
SC
1573
1574#endif
1575
1576void wxOSXCocoaClassAddWXMethods(Class c)
1577{
1578
1579#if OBJC_API_VERSION < 2
1580 static objc_method wxmethods[] =
1581 {
1582#endif
1583
1584 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1585 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1586 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1587
1588 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1589 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1590 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1591
1592 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1593
1594 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1595 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1596 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
5a900d50
KO
1597
1598 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
4dd9fdf8
SC
1599
1600 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1601 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1602 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
03647350 1603
3a176763
SC
1604 wxOSX_CLASS_ADD_METHOD(c, @selector(cursorUpdate:), (IMP) wxOSX_cursorUpdate, "v@:@" )
1605
4dd9fdf8
SC
1606 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1607 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1608 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
03647350 1609
f0e0116e 1610 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
4dd9fdf8 1611
7cb2a241 1612 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
4dd9fdf8 1613
09a9eb20 1614 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
4dd9fdf8
SC
1615 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1616 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
4dd9fdf8 1617
c551dc29 1618#if !wxOSX_USE_NATIVE_FLIPPED
4dd9fdf8 1619 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
c551dc29 1620#endif
4dd9fdf8
SC
1621 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1622
e32090ba
SC
1623 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1624 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
4dd9fdf8
SC
1625
1626#if wxUSE_DRAG_AND_DROP
1627 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1628 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1629 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1630 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
03647350
VZ
1631#endif
1632
4dd9fdf8
SC
1633#if OBJC_API_VERSION < 2
1634 } ;
1635 static int method_count = WXSIZEOF( wxmethods );
1636 static objc_method_list *wxmethodlist = NULL;
1637 if ( wxmethodlist == NULL )
1638 {
1639 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1640 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1641 wxmethodlist->method_count = method_count;
1642 wxmethodlist->obsolete = 0;
1643 }
1644 class_addMethods( c, wxmethodlist );
1645#endif
1646}
1647
1648//
1649// C++ implementation class
1650//
33e90275
SC
1651
1652IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1653
415f4a01
SC
1654wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1655 wxWidgetImpl( peer, isRootControl, isUserPane )
33e90275 1656{
4dd9fdf8
SC
1657 Init();
1658 m_osxView = w;
d94e9b62
VZ
1659
1660 // check if the user wants to create the control initially hidden
1661 if ( !peer->IsShown() )
1662 SetVisibility(false);
1663
9a038ddc
SC
1664 // gc aware handling
1665 if ( m_osxView )
1666 CFRetain(m_osxView);
1667 [m_osxView release];
33e90275
SC
1668}
1669
03647350 1670wxWidgetCocoaImpl::wxWidgetCocoaImpl()
33e90275 1671{
4dd9fdf8 1672 Init();
33e90275
SC
1673}
1674
1675void wxWidgetCocoaImpl::Init()
1676{
1677 m_osxView = NULL;
c551dc29 1678#if !wxOSX_USE_NATIVE_FLIPPED
4dd9fdf8 1679 m_isFlipped = true;
c551dc29 1680#endif
f0e0116e 1681 m_lastKeyDownEvent = NULL;
7cb2a241 1682 m_hasEditor = false;
33e90275
SC
1683}
1684
1685wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1686{
4dd9fdf8
SC
1687 RemoveAssociations( this );
1688
dbeddfb9
SC
1689 if ( !IsRootControl() )
1690 {
1691 NSView *sv = [m_osxView superview];
1692 if ( sv != nil )
1693 [m_osxView removeFromSuperview];
1694 }
9a038ddc
SC
1695 // gc aware handling
1696 if ( m_osxView )
1697 CFRelease(m_osxView);
33e90275 1698}
03647350
VZ
1699
1700bool wxWidgetCocoaImpl::IsVisible() const
33e90275
SC
1701{
1702 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1703}
1704
dbeddfb9
SC
1705void wxWidgetCocoaImpl::SetVisibility( bool visible )
1706{
1707 [m_osxView setHidden:(visible ? NO:YES)];
1708}
1709
ab9a0b84
VZ
1710// ----------------------------------------------------------------------------
1711// window animation stuff
1712// ----------------------------------------------------------------------------
1713
f2be0678 1714// define a delegate used to refresh the window during animation
030495ec 1715@interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
ab9a0b84 1716{
ab9a0b84 1717 wxWindow *m_win;
f2be0678 1718 bool m_isDone;
ab9a0b84
VZ
1719}
1720
f2be0678
VZ
1721- (id)init:(wxWindow *)win;
1722
1723- (bool)isDone;
ab9a0b84
VZ
1724
1725// NSAnimationDelegate methods
f2be0678 1726- (void)animationDidEnd:(NSAnimation*)animation;
ab9a0b84
VZ
1727- (void)animation:(NSAnimation*)animation
1728 didReachProgressMark:(NSAnimationProgress)progress;
ab9a0b84
VZ
1729@end
1730
1731@implementation wxNSAnimationDelegate
1732
f2be0678 1733- (id)init:(wxWindow *)win
ab9a0b84 1734{
f599a415 1735 self = [super init];
ab9a0b84
VZ
1736
1737 m_win = win;
f2be0678
VZ
1738 m_isDone = false;
1739
ab9a0b84
VZ
1740 return self;
1741}
1742
f2be0678
VZ
1743- (bool)isDone
1744{
1745 return m_isDone;
1746}
1747
ab9a0b84
VZ
1748- (void)animation:(NSAnimation*)animation
1749 didReachProgressMark:(NSAnimationProgress)progress
1750{
1751 wxUnusedVar(animation);
1752 wxUnusedVar(progress);
1753
1754 m_win->SendSizeEvent();
1755}
1756
f2be0678 1757- (void)animationDidEnd:(NSAnimation*)animation
ab9a0b84 1758{
849252d5 1759 wxUnusedVar(animation);
f2be0678 1760 m_isDone = true;
ab9a0b84
VZ
1761}
1762
1763@end
1764
1765/* static */
1766bool
1767wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1768 bool show,
1769 wxShowEffect effect,
1770 unsigned timeout)
1771{
ab9a0b84
VZ
1772 // create the dictionary describing the animation to perform on this view
1773 NSObject * const
1774 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1775 NSMutableDictionary * const
1776 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1777 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1778
1779 // determine the start and end rectangles assuming we're hiding the window
f2be0678 1780 const wxRect rectOrig = win->GetRect();
ab9a0b84
VZ
1781 wxRect rectStart,
1782 rectEnd;
1783 rectStart =
f2be0678 1784 rectEnd = rectOrig;
ab9a0b84
VZ
1785
1786 if ( show )
1787 {
1788 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1789 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1790 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1791 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1792 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1793 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1794 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1795 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1796 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1797 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1798 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1799 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1800 }
1801
1802 switch ( effect )
1803 {
1804 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1805 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1806 rectEnd.width = 0;
1807 break;
1808
1809 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1810 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1811 rectEnd.x = rectStart.GetRight();
1812 rectEnd.width = 0;
1813 break;
1814
1815 case wxSHOW_EFFECT_ROLL_TO_TOP:
1816 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1817 rectEnd.height = 0;
1818 break;
1819
1820 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1821 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1822 rectEnd.y = rectStart.GetBottom();
1823 rectEnd.height = 0;
1824 break;
1825
1826 case wxSHOW_EFFECT_EXPAND:
1827 rectEnd.x = rectStart.x + rectStart.width / 2;
1828 rectEnd.y = rectStart.y + rectStart.height / 2;
1829 rectEnd.width =
1830 rectEnd.height = 0;
1831 break;
1832
1833 case wxSHOW_EFFECT_BLEND:
1834 [dict setObject:(show ? NSViewAnimationFadeInEffect
1835 : NSViewAnimationFadeOutEffect)
1836 forKey:NSViewAnimationEffectKey];
1837 break;
1838
1839 case wxSHOW_EFFECT_NONE:
1840 case wxSHOW_EFFECT_MAX:
1841 wxFAIL_MSG( "unexpected animation effect" );
1842 return false;
1843
1844 default:
1845 wxFAIL_MSG( "unknown animation effect" );
1846 return false;
1847 };
1848
1849 if ( show )
1850 {
1851 // we need to restore it to the original rectangle instead of making it
1852 // disappear
1853 wxSwap(rectStart, rectEnd);
1854
1855 // and as the window is currently hidden, we need to show it for the
1856 // animation to be visible at all (but don't restore it at its full
1857 // rectangle as it shouldn't appear immediately)
1858 win->SetSize(rectStart);
f2be0678 1859 win->Show();
ab9a0b84
VZ
1860 }
1861
1862 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1863 ? [(NSView *)viewOrWin superview]
1864 : nil;
1865 const NSRect rStart = wxToNSRect(parentView, rectStart);
1866 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1867
1868 [dict setObject:[NSValue valueWithRect:rStart]
1869 forKey:NSViewAnimationStartFrameKey];
1870 [dict setObject:[NSValue valueWithRect:rEnd]
1871 forKey:NSViewAnimationEndFrameKey];
1872
1873 // create an animation using the values in the above dictionary
ab9a0b84
VZ
1874 NSViewAnimation * const
1875 anim = [[NSViewAnimation alloc]
1876 initWithViewAnimations:[NSArray arrayWithObject:dict]];
ab9a0b84
VZ
1877
1878 if ( !timeout )
1879 {
1880 // what is a good default duration? Windows uses 200ms, Web frameworks
1881 // use anything from 250ms to 1s... choose something in the middle
1882 timeout = 500;
1883 }
1884
1885 [anim setDuration:timeout/1000.]; // duration is in seconds here
1886
1887 // if the window being animated changes its layout depending on its size
1888 // (which is almost always the case) we need to redo it during animation
1889 //
1890 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1891 // controls in wxInfoBar visibly jump around)
1892 const int NUM_LAYOUTS = 20;
1893 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1894 [anim addProgressMark:f];
1895
f2be0678
VZ
1896 wxNSAnimationDelegate * const
1897 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1898 [anim setDelegate:animDelegate];
ab9a0b84
VZ
1899 [anim startAnimation];
1900
f2be0678
VZ
1901 // Cocoa is capable of doing animation asynchronously or even from separate
1902 // thread but wx API doesn't provide any way to be notified about the
1903 // animation end and without this we really must ensure that the window has
1904 // the expected (i.e. the same as if a simple Show() had been used) size
1905 // when we return, so block here until the animation finishes
1906 //
1907 // notice that because the default animation mode is NSAnimationBlocking,
1908 // no user input events ought to be processed from here
dc72e2ad
VZ
1909 {
1910 wxEventLoopGuarantor ensureEventLoopExistence;
1911 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1912 while ( ![animDelegate isDone] )
1913 loop->Dispatch();
1914 }
f2be0678
VZ
1915
1916 if ( !show )
1917 {
1918 // NSViewAnimation is smart enough to hide the NSView being animated at
1919 // the end but we also must ensure that it's hidden for wx too
1920 win->Hide();
1921
1922 // and we must also restore its size because it isn't expected to
1923 // change just because the window was hidden
1924 win->SetSize(rectOrig);
1925 }
1926 else
1927 {
1928 // refresh it once again after the end to ensure that everything is in
1929 // place
1930 win->SendSizeEvent();
1931 }
1932
1933 [anim setDelegate:nil];
1934 [animDelegate release];
1935 [anim release];
1936
ab9a0b84
VZ
1937 return true;
1938}
1939
1940bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1941 wxShowEffect effect,
1942 unsigned timeout)
1943{
1944 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1945}
1946
b54a793b
SC
1947/* note that the drawing order between siblings is not defined under 10.4 */
1948/* only starting from 10.5 the subview order is respected */
1949
1950/* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1951 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
1952 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
1953 * expects a function returning the new non-enum NSComparsionResult.
1954 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1955 */
1956#if defined(NSINTEGER_DEFINED)
1957typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1958#else
1959typedef int CocoaWindowCompareFunctionResult;
1960#endif
1961
1962class CocoaWindowCompareContext
1963{
1964 wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1965public:
1966 CocoaWindowCompareContext(); // Not implemented
1967 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1968 {
1969 m_target = target;
1970 // Cocoa sorts subviews in-place.. make a copy
1971 m_subviews = [subviews copy];
1972 }
1973
1974 ~CocoaWindowCompareContext()
1975 { // release the copy
1976 [m_subviews release];
1977 }
1978 NSView* target()
1979 { return m_target; }
1980
1981 NSArray* subviews()
1982 { return m_subviews; }
1983
1984 /* Helper function that returns the comparison based off of the original ordering */
1985 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1986 {
1987 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1988 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1989 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1990 // likely compare higher than the other view which is reasonable considering the only way that
1991 // can happen is if the subview was added after our call to subviews but before the call to
1992 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
1993 // that case should never occur anyway because that would imply a multi-threaded GUI call
1994 // which is a big no-no with Cocoa.
1995
1996 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
1997 NSComparisonResult result = (firstI < secondI)
1998 ? NSOrderedAscending /* -1 */
1999 : (firstI > secondI)
2000 ? NSOrderedDescending /* 1 */
2001 : NSOrderedSame /* 0 */;
2002
2003 return result;
2004 }
2005private:
2006 /* The subview we are trying to Raise or Lower */
2007 NSView *m_target;
2008 /* A copy of the original array of subviews */
2009 NSArray *m_subviews;
2010};
2011
2012/* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
2013 * the target view is always higher than every other view. When comparing two views neither of
2014 * which is the target, it returns the correct response based on the original ordering
2015 */
2016static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
2017{
2018 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2019 // first should be ordered higher
2020 if(first==compareContext->target())
2021 return NSOrderedDescending;
2022 // second should be ordered higher
2023 if(second==compareContext->target())
2024 return NSOrderedAscending;
2025 return compareContext->CompareUsingOriginalOrdering(first,second);
2026}
2027
33e90275
SC
2028void wxWidgetCocoaImpl::Raise()
2029{
b54a793b
SC
2030 NSView* nsview = m_osxView;
2031
2032 NSView *superview = [nsview superview];
2033 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2034
2035 [superview sortSubviewsUsingFunction:
2036 CocoaRaiseWindowCompareFunction
2037 context: &compareContext];
2038
2039}
2040
2041/* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
2042 * the target view is always lower than every other view. When comparing two views neither of
2043 * which is the target, it returns the correct response based on the original ordering
2044 */
2045static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
2046{
2047 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2048 // first should be ordered lower
2049 if(first==compareContext->target())
2050 return NSOrderedAscending;
2051 // second should be ordered lower
2052 if(second==compareContext->target())
2053 return NSOrderedDescending;
2054 return compareContext->CompareUsingOriginalOrdering(first,second);
33e90275 2055}
03647350 2056
33e90275
SC
2057void wxWidgetCocoaImpl::Lower()
2058{
b54a793b
SC
2059 NSView* nsview = m_osxView;
2060
2061 NSView *superview = [nsview superview];
2062 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2063
2064 [superview sortSubviewsUsingFunction:
2065 CocoaLowerWindowCompareFunction
2066 context: &compareContext];
33e90275
SC
2067}
2068
d8207702 2069void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
33e90275 2070{
54f11060
SC
2071#if 1
2072 SetNeedsDisplay() ;
2073#else
2074 // We should do something like this, but it wasn't working in 10.4.
2075 if (GetNeedsDisplay() )
2076 {
2077 SetNeedsDisplay() ;
2078 }
2079 NSRect r = wxToNSRect( [m_osxView superview], *rect );
2080 NSSize offset = NSMakeSize((float)dx, (float)dy);
2081 [m_osxView scrollRect:r by:offset];
2082#endif
33e90275
SC
2083}
2084
2085void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
2086{
0c530e5a 2087 wxWindowMac* parent = GetWXPeer()->GetParent();
03647350 2088 // under Cocoa we might have a contentView in the wxParent to which we have to
0c530e5a 2089 // adjust the coordinates
ea468399 2090 if (parent && [m_osxView superview] != parent->GetHandle() )
0c530e5a 2091 {
57c0a8ac
SC
2092 int cx = 0,cy = 0,cw = 0,ch = 0;
2093 if ( parent->GetPeer() )
2094 {
2095 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2096 x -= cx;
2097 y -= cy;
2098 }
0c530e5a 2099 }
95fb3153 2100 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
33e90275
SC
2101 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
2102 [m_osxView setFrame:r];
03647350 2103 [[m_osxView superview] setNeedsDisplayInRect:r];
33e90275
SC
2104}
2105
2106void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
2107{
2108 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
2109 x = r.GetLeft();
2110 y = r.GetTop();
7a69cf79
SC
2111
2112 // under Cocoa we might have a contentView in the wxParent to which we have to
2113 // adjust the coordinates
2114 wxWindowMac* parent = GetWXPeer()->GetParent();
2115 if (parent && [m_osxView superview] != parent->GetHandle() )
2116 {
2117 int cx = 0,cy = 0,cw = 0,ch = 0;
2118 if ( parent->GetPeer() )
2119 {
2120 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2121 x += cx;
2122 y += cy;
2123 }
2124 }
33e90275
SC
2125}
2126
2127void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2128{
2129 NSRect rect = [m_osxView frame];
e490b0d2
VZ
2130 width = (int)rect.size.width;
2131 height = (int)rect.size.height;
33e90275
SC
2132}
2133
dbeddfb9 2134void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
33e90275 2135{
0c530e5a
SC
2136 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2137 {
2138 NSView* cv = [m_osxView contentView];
03647350 2139
0c530e5a
SC
2140 NSRect bounds = [m_osxView bounds];
2141 NSRect rect = [cv frame];
03647350 2142
e490b0d2
VZ
2143 int y = (int)rect.origin.y;
2144 int x = (int)rect.origin.x;
0c530e5a 2145 if ( ![ m_osxView isFlipped ] )
e490b0d2 2146 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
0c530e5a
SC
2147 left = x;
2148 top = y;
e490b0d2
VZ
2149 width = (int)rect.size.width;
2150 height = (int)rect.size.height;
0c530e5a
SC
2151 }
2152 else
2153 {
2154 left = top = 0;
2155 GetSize( width, height );
2156 }
33e90275
SC
2157}
2158
2159void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2160{
2161 if ( where )
2162 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2163 else
2164 [m_osxView setNeedsDisplay:YES];
2165}
2166
2167bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2168{
2169 return [m_osxView needsDisplay];
2170}
2171
dbeddfb9 2172bool wxWidgetCocoaImpl::CanFocus() const
33e90275 2173{
dbeddfb9 2174 return [m_osxView canBecomeKeyView] == YES;
33e90275
SC
2175}
2176
2177bool wxWidgetCocoaImpl::HasFocus() const
2178{
f06e0fea 2179 return ( FindFocus() == m_osxView );
33e90275
SC
2180}
2181
03647350 2182bool wxWidgetCocoaImpl::SetFocus()
33e90275 2183{
78a17075 2184 if ( !CanFocus() )
dbeddfb9 2185 return false;
03647350 2186
f897d9ed
SC
2187 // TODO remove if no issues arise: should not raise the window, only assign focus
2188 //[[m_osxView window] makeKeyAndOrderFront:nil] ;
c6d90011 2189 [[m_osxView window] makeFirstResponder: m_osxView] ;
dbeddfb9 2190 return true;
33e90275
SC
2191}
2192
14de8214
SC
2193void wxWidgetCocoaImpl::SetDropTarget(wxDropTarget* target)
2194{
2195 [m_osxView unregisterDraggedTypes];
2196
2197 if ( target == NULL )
2198 return;
2199
2200 wxDataObject* dobj = target->GetDataObject();
2201
2202 if( dobj )
2203 {
2204 CFMutableArrayRef typesarray = CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
d757ef93
SC
2205 dobj->AddSupportedTypes(typesarray);
2206 NSView* targetView = m_osxView;
2207 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2208 targetView = [(NSScrollView*) m_osxView documentView];
2209
2210 [targetView registerForDraggedTypes:(NSArray*)typesarray];
14de8214
SC
2211 CFRelease(typesarray);
2212 }
2213}
33e90275
SC
2214
2215void wxWidgetCocoaImpl::RemoveFromParent()
2216{
2217 [m_osxView removeFromSuperview];
2218}
2219
2220void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2221{
2222 NSView* container = parent->GetWXWidget() ;
2223 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2224 [container addSubview:m_osxView];
f321d0bc
SC
2225
2226 if( m_wxPeer->IsFrozen() )
2227 [[m_osxView window] disableFlushWindow];
33e90275
SC
2228}
2229
3b2527c7 2230void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
dbeddfb9 2231{
3b2527c7
SC
2232 NSView* targetView = m_osxView;
2233 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2234 targetView = [(NSScrollView*) m_osxView documentView];
2235
2236 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2237 {
2238 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2239 green:(CGFloat) (col.Green() / 255.0)
2240 blue:(CGFloat) (col.Blue() / 255.0)
2241 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2242 }
dbeddfb9
SC
2243}
2244
bc5c09a3
SC
2245bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2246{
2247 BOOL opaque = ( style == wxBG_STYLE_PAINT );
2248
2249 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2250 {
2251 [m_osxView setOpaque: opaque];
2252 }
2253
2254 return true ;
2255}
2256
dbeddfb9
SC
2257void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2258{
2259 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2260 {
d8207702 2261 wxCFStringRef cf( title , encoding );
dbeddfb9
SC
2262 [m_osxView setTitle:cf.AsNSString()];
2263 }
e32090ba
SC
2264 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2265 {
d8207702 2266 wxCFStringRef cf( title , encoding );
e32090ba
SC
2267 [m_osxView setStringValue:cf.AsNSString()];
2268 }
dbeddfb9 2269}
03647350 2270
dbeddfb9
SC
2271
2272void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2273{
2274 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
03647350 2275 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
dbeddfb9
SC
2276 *pt = wxFromNSPoint( to->GetWXWidget(), p );
2277}
2278
03647350 2279wxInt32 wxWidgetCocoaImpl::GetValue() const
dbeddfb9
SC
2280{
2281 return [(NSControl*)m_osxView intValue];
2282}
2283
03647350 2284void wxWidgetCocoaImpl::SetValue( wxInt32 v )
dbeddfb9
SC
2285{
2286 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
2287 {
2288 [m_osxView setIntValue:v];
2289 }
2290 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2291 {
2292 [m_osxView setFloatValue:(double)v];
2293 }
2294 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2295 {
2296 [m_osxView setDoubleValue:(double)v];
2297 }
2298}
2299
03647350 2300void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
dbeddfb9
SC
2301{
2302 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
2303 {
2304 [m_osxView setMinValue:(double)v];
2305 }
2306}
2307
03647350 2308void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
dbeddfb9
SC
2309{
2310 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2311 {
2312 [m_osxView setMaxValue:(double)v];
2313 }
2314}
2315
03647350 2316wxInt32 wxWidgetCocoaImpl::GetMinimum() const
19c7ac3d 2317{
f0c6b963 2318 if ( [m_osxView respondsToSelector:@selector(minValue)] )
19c7ac3d 2319 {
e490b0d2 2320 return (int)[m_osxView minValue];
19c7ac3d
SC
2321 }
2322 return 0;
2323}
2324
03647350 2325wxInt32 wxWidgetCocoaImpl::GetMaximum() const
19c7ac3d 2326{
f0c6b963 2327 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
19c7ac3d 2328 {
e490b0d2 2329 return (int)[m_osxView maxValue];
19c7ac3d
SC
2330 }
2331 return 0;
2332}
2333
e5d05b90
VZ
2334wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2335{
2336 wxBitmap bmp;
2337
2338 // TODO: how to create a wxBitmap from NSImage?
2339#if 0
2340 if ( [m_osxView respondsToSelector:@selector(image:)] )
2341 bmp = [m_osxView image];
2342#endif
2343
2344 return bmp;
2345}
2346
dbeddfb9
SC
2347void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2348{
2349 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
2350 {
b8702c67
SC
2351 if (bitmap.IsOk())
2352 [m_osxView setImage:bitmap.GetNSImage()];
2353 else
2354 [m_osxView setImage:nil];
2355
411a1c35 2356 [m_osxView setNeedsDisplay:YES];
dbeddfb9
SC
2357 }
2358}
2359
e5d05b90
VZ
2360void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2361{
2362 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2363 {
2364 NSCellImagePosition pos;
2365 switch ( dir )
2366 {
2367 case wxLEFT:
2368 pos = NSImageLeft;
2369 break;
2370
2371 case wxRIGHT:
2372 pos = NSImageRight;
2373 break;
2374
2375 case wxTOP:
2376 pos = NSImageAbove;
2377 break;
2378
2379 case wxBOTTOM:
2380 pos = NSImageBelow;
2381 break;
2382
2383 default:
2384 wxFAIL_MSG( "invalid image position" );
2385 pos = NSNoImage;
2386 }
2387
2388 [m_osxView setImagePosition:pos];
2389 }
2390}
2391
d8207702 2392void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
dbeddfb9
SC
2393{
2394 // implementation in subclass
2395}
2396
2397void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2398{
2399 r->x = r->y = r->width = r->height = 0;
09a9eb20 2400
dbeddfb9
SC
2401 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2402 {
2403 NSRect former = [m_osxView frame];
2404 [m_osxView sizeToFit];
2405 NSRect best = [m_osxView frame];
2406 [m_osxView setFrame:former];
e490b0d2
VZ
2407 r->width = (int)best.size.width;
2408 r->height = (int)best.size.height;
dbeddfb9
SC
2409 }
2410}
2411
2412bool wxWidgetCocoaImpl::IsEnabled() const
2413{
6ade9e89
SC
2414 NSView* targetView = m_osxView;
2415 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2416 targetView = [(NSScrollView*) m_osxView documentView];
2417
2418 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2419 return [targetView isEnabled];
0f9b48d1 2420 return true;
dbeddfb9
SC
2421}
2422
2423void wxWidgetCocoaImpl::Enable( bool enable )
2424{
6ade9e89
SC
2425 NSView* targetView = m_osxView;
2426 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2427 targetView = [(NSScrollView*) m_osxView documentView];
2428
2429 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2430 [targetView setEnabled:enable];
dbeddfb9
SC
2431}
2432
2433void wxWidgetCocoaImpl::PulseGauge()
2434{
2435}
2436
d8207702 2437void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
dbeddfb9
SC
2438{
2439}
33e90275 2440
03647350 2441void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
0f9b48d1
SC
2442{
2443 NSControlSize size = NSRegularControlSize;
03647350 2444
0f9b48d1
SC
2445 switch ( variant )
2446 {
2447 case wxWINDOW_VARIANT_NORMAL :
2448 size = NSRegularControlSize;
2449 break ;
2450
2451 case wxWINDOW_VARIANT_SMALL :
2452 size = NSSmallControlSize;
2453 break ;
2454
2455 case wxWINDOW_VARIANT_MINI :
2456 size = NSMiniControlSize;
2457 break ;
2458
2459 case wxWINDOW_VARIANT_LARGE :
2460 size = NSRegularControlSize;
2461 break ;
2462
2463 default:
9a83f860 2464 wxFAIL_MSG(wxT("unexpected window variant"));
0f9b48d1
SC
2465 break ;
2466 }
2467 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2468 [m_osxView setControlSize:size];
03647350
VZ
2469 else if ([m_osxView respondsToSelector:@selector(cell)])
2470 {
2471 id cell = [(id)m_osxView cell];
2472 if ([cell respondsToSelector:@selector(setControlSize:)])
2473 [cell setControlSize:size];
2474 }
49746f23
SC
2475
2476 // we need to propagate this to inner views as well
2477 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2478 {
2479 NSView* targetView = [(NSScrollView*) m_osxView documentView];
2480
2481 if ( [targetView respondsToSelector:@selector(setControlSize:)] )
2482 [targetView setControlSize:size];
2483 else if ([targetView respondsToSelector:@selector(cell)])
2484 {
2485 id cell = [(id)targetView cell];
2486 if ([cell respondsToSelector:@selector(setControlSize:)])
2487 [cell setControlSize:size];
2488 }
2489 }
0f9b48d1
SC
2490}
2491
1a289c62 2492void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
1e181c7a 2493{
49746f23
SC
2494 NSView* targetView = m_osxView;
2495 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2496 targetView = [(NSScrollView*) m_osxView documentView];
2497
2498 if ([targetView respondsToSelector:@selector(setFont:)])
2499 [targetView setFont: font.OSXGetNSFont()];
2500 if ([targetView respondsToSelector:@selector(setTextColor:)])
2501 [targetView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
1a289c62
SC
2502 green:(CGFloat) (col.Green() / 255.0)
2503 blue:(CGFloat) (col.Blue() / 255.0)
2504 alpha:(CGFloat) (col.Alpha() / 255.0)]];
1e181c7a
SC
2505}
2506
a7b9865d
KO
2507void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2508{
20111900 2509 if ( tooltip )
a7b9865d
KO
2510 {
2511 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2512 [m_osxView setToolTip: cf.AsNSString()];
2513 }
2514 else
0309327e 2515 {
20111900 2516 [m_osxView setToolTip:nil];
0309327e 2517 }
a7b9865d
KO
2518}
2519
c4825ef7
SC
2520void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2521{
4dd9fdf8
SC
2522 WXWidget c = control ? control : (WXWidget) m_osxView;
2523 wxWidgetImpl::Associate( c, this ) ;
2524 if ([c respondsToSelector:@selector(setAction:)])
2525 {
2526 [c setTarget: c];
e32090ba 2527 [c setAction: @selector(controlAction:)];
4dd9fdf8
SC
2528 if ([c respondsToSelector:@selector(setDoubleAction:)])
2529 {
e32090ba 2530 [c setDoubleAction: @selector(controlDoubleAction:)];
4dd9fdf8 2531 }
03647350 2532
4dd9fdf8 2533 }
3a176763 2534 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingCursorUpdate|NSTrackingMouseMoved|NSTrackingActiveAlways|NSTrackingInVisibleRect;
bc6626eb 2535 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: NSZeroRect options: options owner: m_osxView userInfo: nil];
94734b4e
SC
2536 [m_osxView addTrackingArea: area];
2537 [area release];
2538 }
c4825ef7 2539
f0e0116e
KO
2540bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2541{
4d61ae5f 2542 wxKeyEvent wxevent(wxEVT_CHAR);
f0e0116e 2543 SetupKeyEvent( wxevent, event, text );
f0e0116e
KO
2544
2545 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2546}
2547
ffad7b0d
SC
2548bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2549{
2550 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2551 SetupKeyEvent( wxevent, event );
edf5822a
VZ
2552
2553 // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2554 // the key is pressed, not when it's released (the type of wxevent is
2555 // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2556 if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2557 {
3a95f73c 2558 wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
4cf1a9bf
VZ
2559 if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2560 && !eventHook.IsNextEventAllowed() )
edf5822a
VZ
2561 return true;
2562 }
2563
f0e0116e 2564 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
19c7ac3d 2565
f0e0116e
KO
2566 // this will fire higher level events, like insertText, to help
2567 // us handle EVT_CHAR, etc.
715824d5 2568
cc710171 2569 if ( !result )
f0e0116e 2570 {
09e73165 2571 if ( [event type] == NSKeyDown)
7cb2a241 2572 {
a8fc3508
SC
2573 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2574
2575 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
849252d5
SC
2576 {
2577 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2578 wxKeyEvent wxevent2(wxevent) ;
68065b91 2579 wxevent2.SetEventType(wxEVT_CHAR);
09e73165 2580 SetupKeyEvent( wxevent2, event );
a8fc3508 2581 wxevent2.m_keyCode = keycode;
b895498c 2582 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
849252d5 2583 }
09e73165
SC
2584 else if (wxevent.CmdDown())
2585 {
2586 wxKeyEvent wxevent2(wxevent) ;
2587 wxevent2.SetEventType(wxEVT_CHAR);
2588 SetupKeyEvent( wxevent2, event );
2589 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2590 }
7cb2a241 2591 else
849252d5 2592 {
09e73165 2593 if ( IsUserPane() && !wxevent.CmdDown() )
b895498c
SC
2594 {
2595 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2596 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2597 else
2598 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2599 result = true;
2600 }
849252d5 2601 }
7cb2a241 2602 }
f0e0116e 2603 }
715824d5 2604
f0e0116e 2605 return result;
ffad7b0d
SC
2606}
2607
b466e85a 2608bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
4850cc8b 2609{
4850cc8b 2610 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
ddbc8ac9 2611 SetupMouseEvent(wxevent , event) ;
094fa9e9
SC
2612 bool result = GetWXPeer()->HandleWindowEvent(wxevent);
2613
2614 (void)SetupCursor(event);
2615
2616 return result;
4850cc8b
SC
2617}
2618
b42865ce 2619void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
0c530e5a
SC
2620{
2621 wxWindow* thisWindow = GetWXPeer();
2622 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2623 {
2624 thisWindow->MacInvalidateBorders();
2625 }
2626
2627 if ( receivedFocus )
2628 {
9a83f860 2629 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
0c530e5a
SC
2630 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2631 thisWindow->HandleWindowEvent(eventFocus);
2632
2633#if wxUSE_CARET
2634 if ( thisWindow->GetCaret() )
2635 thisWindow->GetCaret()->OnSetFocus();
2636#endif
2637
2638 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2639 event.SetEventObject(thisWindow);
b42865ce
KO
2640 if (otherWindow)
2641 event.SetWindow(otherWindow->GetWXPeer());
0c530e5a
SC
2642 thisWindow->HandleWindowEvent(event) ;
2643 }
9656c0dd 2644 else // !receivedFocus
0c530e5a
SC
2645 {
2646#if wxUSE_CARET
2647 if ( thisWindow->GetCaret() )
2648 thisWindow->GetCaret()->OnKillFocus();
2649#endif
2650
9a83f860 2651 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
03647350 2652
0c530e5a
SC
2653 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2654 event.SetEventObject(thisWindow);
b42865ce
KO
2655 if (otherWindow)
2656 event.SetWindow(otherWindow->GetWXPeer());
0c530e5a
SC
2657 thisWindow->HandleWindowEvent(event) ;
2658 }
2659}
2660
54f11060
SC
2661void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2662{
201c6db3 2663 if ( !wxIsBusy() )
54f11060 2664 {
201c6db3
SC
2665 NSPoint location = [NSEvent mouseLocation];
2666 location = [[m_osxView window] convertScreenToBase:location];
2667 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2668
2669 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2670 {
2671 [(NSCursor*)cursor.GetHCURSOR() set];
2672 }
54f11060 2673 }
54f11060
SC
2674}
2675
2676void wxWidgetCocoaImpl::CaptureMouse()
2677{
8bd6a7a0
SC
2678 // TODO remove if we don't get into problems with cursor settings
2679 // [[m_osxView window] disableCursorRects];
54f11060
SC
2680}
2681
2682void wxWidgetCocoaImpl::ReleaseMouse()
2683{
8bd6a7a0
SC
2684 // TODO remove if we don't get into problems with cursor settings
2685 // [[m_osxView window] enableCursorRects];
54f11060 2686}
4850cc8b 2687
c551dc29
SC
2688#if !wxOSX_USE_NATIVE_FLIPPED
2689
4dd9fdf8
SC
2690void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2691{
2692 m_isFlipped = flipped;
2693}
2694
c551dc29
SC
2695#endif
2696
2ab38025
SC
2697void wxWidgetCocoaImpl::SetDrawingEnabled(bool enabled)
2698{
2699 if ( enabled )
2700 {
2701 [[m_osxView window] enableFlushWindow];
2702 [m_osxView setNeedsDisplay:YES];
2703 }
2704 else
2705 {
2706 [[m_osxView window] disableFlushWindow];
2707 }
2708}
33e90275
SC
2709//
2710// Factory methods
2711//
2712
03647350 2713wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
d8207702
SC
2714 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2715 long WXUNUSED(style), long WXUNUSED(extraStyle))
33e90275 2716{
dbeddfb9 2717 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
33e90275 2718 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
4dd9fdf8 2719
d15694e8 2720 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
33e90275
SC
2721 return c;
2722}
2723
03647350 2724wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
33e90275
SC
2725{
2726 NSWindow* tlw = now->GetWXWindow();
17e2694c
SC
2727
2728 wxWidgetCocoaImpl* c = NULL;
2729 if ( now->IsNativeWindowWrapper() )
2730 {
bc5c09a3
SC
2731 NSView* cv = [tlw contentView];
2732 c = new wxWidgetCocoaImpl( now, cv, true );
094fa9e9
SC
2733 if ( cv != nil )
2734 {
2735 // increase ref count, because the impl destructor will decrement it again
2736 CFRetain(cv);
2737 if ( !now->IsShown() )
2738 [cv setHidden:NO];
2739 }
17e2694c
SC
2740 }
2741 else
2742 {
2743 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2744 c = new wxWidgetCocoaImpl( now, v, true );
2745 c->InstallEventHandler();
2746 [tlw setContentView:v];
2747 }
33e90275
SC
2748 return c;
2749}