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