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