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