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