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