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