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