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