making SetFocus bringing TLW to front as Carbon, see #10876
[wxWidgets.git] / src / osx / cocoa / window.mm
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
7 // RCS-ID:      $Id: window.mm 48805 2007-09-19 14:52:25Z SC $
8 // Copyright:   (c) Stefan Csomor
9 // Licence:     wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/wxprec.h"
13
14 #ifndef WX_PRECOMP
15     #include "wx/dcclient.h"
16     #include "wx/nonownedwnd.h"
17     #include "wx/log.h"
18 #endif
19
20 #ifdef __WXMAC__
21     #include "wx/osx/private.h"
22 #endif
23
24 #if wxUSE_CARET
25     #include "wx/caret.h"
26 #endif
27
28 #if wxUSE_DRAG_AND_DROP
29     #include "wx/dnd.h"
30 #endif
31
32 #include <objc/objc-runtime.h>
33
34 // Get the window with the focus
35
36 WXWidget wxWidgetImpl::FindFocus()
37 {
38     NSView* focusedView = nil;
39     NSWindow* keyWindow = [[NSApplication sharedApplication] keyWindow];
40     if ( keyWindow != nil )
41     {
42         NSResponder* responder = [keyWindow firstResponder];
43         if ( [responder isKindOfClass:[NSTextView class]] && 
44             [keyWindow fieldEditor:NO forObject:nil] != nil )
45         {
46             focusedView = [(NSTextView*)responder delegate];
47         }
48         else
49         {
50             if ( [responder isKindOfClass:[NSView class]] )
51                 focusedView = (NSView*) responder;
52         }
53     }
54     return focusedView;
55 }
56
57 NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
58 {
59     int x, y, w, h ;
60
61     window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
62     wxRect bounds(x,y,w,h);
63     NSView* sv = (window->GetParent()->GetHandle() );
64
65     return wxToNSRect( sv, bounds );
66 }
67
68 @interface wxNSView : NSView
69 {
70     NSTrackingRectTag rectTag;
71 }
72
73 // the tracking tag is needed to track mouse enter / exit events 
74 - (void) setTrackingTag: (NSTrackingRectTag)tag;
75 - (NSTrackingRectTag) trackingTag;
76 @end // wxNSView
77
78 @interface NSView(PossibleMethods) 
79 - (void)setTitle:(NSString *)aString;
80 - (void)setStringValue:(NSString *)aString;
81 - (void)setIntValue:(int)anInt;
82 - (void)setFloatValue:(float)aFloat;
83 - (void)setDoubleValue:(double)aDouble;
84
85 - (double)minValue;
86 - (double)maxValue;
87 - (void)setMinValue:(double)aDouble;
88 - (void)setMaxValue:(double)aDouble;
89
90 - (void)sizeToFit;
91
92 - (BOOL)isEnabled;
93 - (void)setEnabled:(BOOL)flag;
94
95 - (void)setImage:(NSImage *)image;
96 - (void)setControlSize:(NSControlSize)size;
97
98 - (void)setFont:(NSFont *)fontObject;
99
100 - (id)contentView;
101
102 - (void)setTarget:(id)anObject;
103 - (void)setAction:(SEL)aSelector;
104 - (void)setDoubleAction:(SEL)aSelector;
105 @end 
106
107 long wxOSXTranslateCocoaKey( NSEvent* event )
108 {
109     long retval = 0;
110
111     if ([event type] != NSFlagsChanged)
112     {    
113         NSString* s = [event charactersIgnoringModifiers];
114         // backspace char reports as delete w/modifiers for some reason
115         if ([s length] == 1)
116         {
117             switch ( [s characterAtIndex:0] )
118             {
119                 // backspace key
120                 case 0x7F :
121                 case 8 : 
122                     retval = WXK_BACK;
123                     break;
124                 case NSUpArrowFunctionKey :
125                     retval = WXK_UP;
126                     break;
127                 case NSDownArrowFunctionKey :
128                     retval = WXK_DOWN;
129                     break;
130                 case NSLeftArrowFunctionKey :
131                     retval = WXK_LEFT;
132                     break;
133                 case NSRightArrowFunctionKey :
134                     retval = WXK_RIGHT;
135                     break;
136                 case NSInsertFunctionKey  :
137                     retval = WXK_INSERT;
138                     break;
139                 case NSDeleteFunctionKey  :
140                     retval = WXK_DELETE;
141                     break;
142                 case NSHomeFunctionKey  :
143                     retval = WXK_HOME;
144                     break;
145         //        case NSBeginFunctionKey  :
146         //            retval = WXK_BEGIN;
147         //            break;
148                 case NSEndFunctionKey  :
149                     retval = WXK_END;
150                     break;
151                 case NSPageUpFunctionKey  :
152                     retval = WXK_PAGEUP;
153                     break;
154                case NSPageDownFunctionKey  :
155                     retval = WXK_PAGEDOWN;
156                     break;
157                case NSHelpFunctionKey  :
158                     retval = WXK_HELP;
159                     break;
160                 default:
161                     int intchar = [s characterAtIndex: 0];
162                     if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
163                         retval = WXK_F1 + (intchar - NSF1FunctionKey );
164                     break;
165             }
166         }
167     }
168     
169     // Some keys don't seem to have constants. The code mimics the approach
170     // taken by WebKit. See:
171     // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
172     switch( [event keyCode] )
173     {
174         // command key
175         case 54:
176         case 55:
177             retval = WXK_COMMAND;
178             break;
179         // caps locks key
180         case 57: // Capslock
181             retval = WXK_CAPITAL;
182             break;
183         // shift key
184         case 56: // Left Shift
185         case 60: // Right Shift
186             retval = WXK_SHIFT;
187             break;
188         // alt key
189         case 58: // Left Alt
190         case 61: // Right Alt
191             retval = WXK_ALT;
192             break;
193         // ctrl key
194         case 59: // Left Ctrl
195         case 62: // Right Ctrl
196             retval = WXK_CONTROL;
197             break;
198         // clear key
199         case 71: 
200             retval = WXK_CLEAR;
201             break;
202         // tab key
203         case 48: 
204             retval = WXK_TAB;
205             break;
206
207         case 75: // /
208             retval = WXK_NUMPAD_DIVIDE;
209             break;            
210         case 67: // *
211             retval = WXK_NUMPAD_MULTIPLY;
212             break;
213         case 78: // -
214             retval = WXK_NUMPAD_SUBTRACT;
215             break;
216         case 69: // +
217             retval = WXK_NUMPAD_ADD;
218             break;
219         case 76: // Enter
220             retval = WXK_NUMPAD_ENTER;
221             break;
222         case 65: // .
223             retval = WXK_NUMPAD_DECIMAL;
224             break;
225         case 82: // 0
226             retval = WXK_NUMPAD0;
227             break;
228         case 83: // 1
229             retval = WXK_NUMPAD1;
230             break;
231         case 84: // 2
232             retval = WXK_NUMPAD2;
233             break;
234         case 85: // 3
235             retval = WXK_NUMPAD3;
236             break;
237         case 86: // 4
238             retval = WXK_NUMPAD4;
239             break;
240         case 87: // 5
241             retval = WXK_NUMPAD5;
242             break;
243         case 88: // 6
244             retval = WXK_NUMPAD6;
245             break;
246         case 89: // 7
247             retval = WXK_NUMPAD7;
248             break;
249         case 91: // 8
250             retval = WXK_NUMPAD8;
251             break;
252         case 92: // 9
253             retval = WXK_NUMPAD9;
254             break;
255         default:
256             //retval = [event keyCode];
257             break;
258     }
259     return retval;
260 }
261
262 void SetupKeyEvent( wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString = NULL )
263 {
264     UInt32 modifiers = [nsEvent modifierFlags] ;
265     int eventType = [nsEvent type];
266
267     wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
268     wxevent.m_controlDown = modifiers & NSControlKeyMask;
269     wxevent.m_altDown = modifiers & NSAlternateKeyMask;
270     wxevent.m_metaDown = modifiers & NSCommandKeyMask;
271     
272     wxevent.m_rawCode = [nsEvent keyCode];
273     wxevent.m_rawFlags = modifiers;
274     
275     wxevent.SetTimestamp( [nsEvent timestamp] * 1000.0 ) ;
276
277     wxString chars;
278     if ( eventType != NSFlagsChanged )
279     {
280         NSString* nschars = (wxevent.GetEventType() != wxEVT_CHAR) ? [nsEvent charactersIgnoringModifiers] : [nsEvent characters];
281         if ( charString )
282         {
283             // if charString is set, it did not come from key up / key down
284             wxevent.SetEventType( wxEVT_CHAR );
285             wxCFStringRef cfchars((CFStringRef)[charString retain]);
286             chars = cfchars.AsString();
287         }
288         else if ( nschars )
289         {
290             wxCFStringRef cfchars((CFStringRef)[nschars retain]);
291             chars = cfchars.AsString();
292         }
293     }
294     
295     int aunichar = chars.Length() > 0 ? chars[0] : 0;
296     long keyval = 0;
297     
298     if (wxevent.GetEventType() != wxEVT_CHAR)
299     {
300         keyval = wxOSXTranslateCocoaKey(nsEvent) ;
301         switch (eventType)
302         {
303             case NSKeyDown :
304                 wxevent.SetEventType( wxEVT_KEY_DOWN )  ;
305                 break;
306             case NSKeyUp :
307                 wxevent.SetEventType( wxEVT_KEY_UP )  ;
308                 break;
309             case NSFlagsChanged :
310                 switch (keyval)
311                 {
312                     case WXK_CONTROL:
313                         wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
314                         break;
315                     case WXK_SHIFT:
316                         wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
317                         break;
318                     case WXK_ALT:
319                         wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
320                         break;
321                     case WXK_COMMAND:
322                         wxevent.SetEventType( wxevent.m_metaDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
323                         break;
324                 }
325                 break;
326             default :
327                 break ;
328         }
329     }
330
331     if ( !keyval )
332     {
333         if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
334             keyval = wxToupper( aunichar ) ;
335         else
336             keyval = aunichar;
337     }
338     
339 #if wxUSE_UNICODE
340     wxevent.m_uniChar = aunichar;
341 #endif
342     wxevent.m_keyCode = keyval;
343 }
344
345 UInt32 g_lastButton = 0 ;
346 bool g_lastButtonWasFakeRight = false ;
347
348 void SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
349 {
350     int eventType = [nsEvent type];
351     UInt32 modifiers = [nsEvent modifierFlags] ;
352     wxPoint screenMouseLocation = wxFromNSPoint( NULL, [nsEvent locationInWindow]);
353
354     // these parameters are not given for all events
355     UInt32 button = [nsEvent buttonNumber];
356     UInt32 clickCount = 0;
357
358     wxevent.m_x = screenMouseLocation.x;
359     wxevent.m_y = screenMouseLocation.y;
360     wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
361     wxevent.m_controlDown = modifiers & NSControlKeyMask;
362     wxevent.m_altDown = modifiers & NSAlternateKeyMask;
363     wxevent.m_metaDown = modifiers & NSCommandKeyMask;
364     wxevent.SetTimestamp( [nsEvent timestamp] * 1000.0 ) ;
365
366     UInt32 mouseChord = 0; 
367
368     switch (eventType)
369     {
370         case NSLeftMouseDown :
371         case NSLeftMouseDragged :
372             mouseChord = 1U;
373             break;
374         case NSRightMouseDown :
375         case NSRightMouseDragged :
376             mouseChord = 2U;
377             break;
378         case NSOtherMouseDown :
379         case NSOtherMouseDragged :
380             mouseChord = 4U;
381             break;
382     }
383
384     // a control click is interpreted as a right click
385     bool thisButtonIsFakeRight = false ;
386     if ( button == 0 && (modifiers & NSControlKeyMask) )
387     {
388         button = 1 ;
389         thisButtonIsFakeRight = true ;
390     }
391
392     // otherwise we report double clicks by connecting a left click with a ctrl-left click
393     if ( clickCount > 1 && button != g_lastButton )
394         clickCount = 1 ;
395
396     // we must make sure that our synthetic 'right' button corresponds in
397     // mouse down, moved and mouse up, and does not deliver a right down and left up
398     switch (eventType)
399     {
400         case NSLeftMouseDown :
401         case NSRightMouseDown :
402         case NSOtherMouseDown :
403             g_lastButton = button ;
404             g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
405             break;
406      }
407
408     if ( button == 0 )
409     {
410         g_lastButton = 0 ;
411         g_lastButtonWasFakeRight = false ;
412     }
413     else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
414         button = g_lastButton ;
415
416     // Adjust the chord mask to remove the primary button and add the
417     // secondary button.  It is possible that the secondary button is
418     // already pressed, e.g. on a mouse connected to a laptop, but this
419     // possibility is ignored here:
420     if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
421         mouseChord = ((mouseChord & ~1U) | 2U);
422
423     if(mouseChord & 1U)
424                 wxevent.m_leftDown = true ;
425     if(mouseChord & 2U)
426                 wxevent.m_rightDown = true ;
427     if(mouseChord & 4U)
428                 wxevent.m_middleDown = true ;
429
430     // translate into wx types
431     switch (eventType)
432     {
433         case NSLeftMouseDown :
434         case NSRightMouseDown :
435         case NSOtherMouseDown :
436             clickCount = [nsEvent clickCount];
437             switch ( button )
438             {
439                 case 0 :
440                     wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN )  ;
441                     break ;
442
443                 case 1 :
444                     wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
445                     break ;
446
447                 case 2 :
448                     wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
449                     break ;
450
451                 default:
452                     break ;
453             }
454             break ;
455
456         case NSLeftMouseUp :
457         case NSRightMouseUp :
458         case NSOtherMouseUp :
459             clickCount = [nsEvent clickCount];
460             switch ( button )
461             {
462                 case 0 :
463                     wxevent.SetEventType( wxEVT_LEFT_UP )  ;
464                     break ;
465
466                 case 1 :
467                     wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
468                     break ;
469
470                 case 2 :
471                     wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
472                     break ;
473
474                 default:
475                     break ;
476             }
477             break ;
478
479      case NSScrollWheel :
480         {
481             wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
482             wxevent.m_wheelDelta = 10;
483             wxevent.m_linesPerAction = 1;
484
485             if ( fabs([nsEvent deltaX]) > fabs([nsEvent deltaY]) )
486             {
487                 wxevent.m_wheelAxis = 1;
488                 wxevent.m_wheelRotation = [nsEvent deltaX] * 10.0;
489             }
490             else
491             {
492                 wxevent.m_wheelRotation = [nsEvent deltaY] * 10.0;
493             }
494         }
495         break ;
496
497         case NSMouseEntered :
498             wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
499             break;
500         case NSMouseExited :
501             wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
502             break;
503         case NSLeftMouseDragged :
504         case NSRightMouseDragged :
505         case NSOtherMouseDragged :
506         case NSMouseMoved :
507             wxevent.SetEventType( wxEVT_MOTION ) ;
508             break;
509         default :
510             break ;
511     }
512     
513     wxevent.m_clickCount = clickCount;
514     
515 }
516
517 @implementation wxNSView
518
519 + (void)initialize
520 {
521     static BOOL initialized = NO;
522     if (!initialized) 
523     {
524         initialized = YES;
525         wxOSXCocoaClassAddWXMethods( self );
526     }
527 }
528
529 - (void) setTrackingTag: (NSTrackingRectTag)tag
530 {
531     rectTag = tag;
532 }
533
534 - (NSTrackingRectTag) trackingTag
535 {
536     return rectTag;
537 }
538
539 @end // wxNSView
540
541 //
542 // event handlers
543 //
544
545 #if wxUSE_DRAG_AND_DROP
546
547 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
548 // for details on the NSPasteboard -> PasteboardRef conversion
549
550 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
551 {
552     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
553     if (impl == NULL)
554         return NSDragOperationNone;
555         
556     return impl->draggingEntered(sender, self, _cmd);
557 }
558
559 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
560 {
561     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
562     if (impl == NULL)
563         return ;
564         
565     return impl->draggingExited(sender, self, _cmd);
566 }
567
568 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
569 {
570     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
571     if (impl == NULL)
572         return NSDragOperationNone;
573         
574     return impl->draggingUpdated(sender, self, _cmd);
575 }
576
577 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
578 {
579     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
580     if (impl == NULL)
581         return NSDragOperationNone;
582         
583     return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
584 }
585
586 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event) 
587 {
588     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
589     if (impl == NULL)
590         return;
591         
592     impl->mouseEvent(event, self, _cmd);
593 }
594
595 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event) 
596 {
597     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
598     if (impl == NULL)
599         return;
600         
601     impl->keyEvent(event, self, _cmd);
602 }
603
604 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text) 
605 {
606     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
607     if (impl == NULL)
608         return;
609         
610     impl->insertText(text, self, _cmd);
611 }
612
613 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event) 
614 {
615     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
616     if (impl == NULL)
617         return NO;
618         
619     return impl->performKeyEquivalent(event, self, _cmd);
620 }
621
622 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
623 {
624     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
625     if (impl == NULL)
626         return NO;
627         
628     return impl->acceptsFirstResponder(self, _cmd);
629 }
630
631 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
632 {
633     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
634     if (impl == NULL)
635         return NO;
636         
637     return impl->becomeFirstResponder(self, _cmd);
638 }
639
640 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
641 {
642     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
643     if (impl == NULL)
644         return NO;
645         
646     return impl->resignFirstResponder(self, _cmd);
647 }
648
649 void wxOSX_resetCursorRects(NSView* self, SEL _cmd)
650 {
651     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
652     if (impl == NULL)
653         return;
654         
655     impl->resetCursorRects(self, _cmd);
656 }
657
658 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
659 {
660     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
661     if (impl == NULL)
662         return NO;
663         
664     return impl->isFlipped(self, _cmd) ? YES:NO;
665 }
666
667 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
668 {
669     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
670     if (impl == NULL)
671         return;
672         
673     return impl->drawRect(&rect, self, _cmd);
674 }
675
676 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
677 {
678     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
679     if (impl == NULL)
680         return;
681         
682     impl->controlAction(self, _cmd, sender);
683 }
684
685 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
686 {
687     wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
688     if (impl == NULL)
689         return;
690         
691     impl->controlDoubleAction(self, _cmd, sender);
692 }
693
694 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
695 {
696     id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
697     NSPasteboard *pboard = [sender draggingPasteboard];
698     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
699     
700     wxWindow* wxpeer = GetWXPeer();
701     if ( wxpeer == NULL )
702         return NSDragOperationNone;
703         
704     wxDropTarget* target = wxpeer->GetDropTarget();
705     if ( target == NULL )
706         return NSDragOperationNone;
707
708     wxDragResult result = wxDragNone;
709     NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
710     wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
711
712     if ( sourceDragMask & NSDragOperationLink )
713         result = wxDragLink;
714     else if ( sourceDragMask & NSDragOperationCopy )
715         result = wxDragCopy;
716     else if ( sourceDragMask & NSDragOperationMove )
717         result = wxDragMove;
718
719     PasteboardRef pboardRef;    
720     PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
721     target->SetCurrentDragPasteboard(pboardRef);
722     result = target->OnEnter(pt.x, pt.y, result);
723     CFRelease(pboardRef);
724      
725     NSDragOperation nsresult = NSDragOperationNone;
726     switch (result )
727     {
728         case wxDragLink:
729             nsresult = NSDragOperationLink;
730         case wxDragMove:
731             nsresult = NSDragOperationMove;
732         case wxDragCopy:
733             nsresult = NSDragOperationCopy;
734         default :
735             break;
736     }
737     return nsresult;
738 }
739
740 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
741 {
742     id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
743     NSPasteboard *pboard = [sender draggingPasteboard];
744     
745     wxWindow* wxpeer = GetWXPeer();
746     if ( wxpeer == NULL )
747         return;
748         
749     wxDropTarget* target = wxpeer->GetDropTarget();
750     if ( target == NULL )
751         return;
752         
753     PasteboardRef pboardRef;    
754     PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
755     target->SetCurrentDragPasteboard(pboardRef);
756     target->OnLeave();
757     CFRelease(pboardRef);
758  }
759
760 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
761 {
762     id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
763     NSPasteboard *pboard = [sender draggingPasteboard];
764     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
765         
766     wxWindow* wxpeer = GetWXPeer();
767     if ( wxpeer == NULL )
768         return NSDragOperationNone;
769         
770     wxDropTarget* target = wxpeer->GetDropTarget();
771     if ( target == NULL )
772         return NSDragOperationNone;
773
774     wxDragResult result = wxDragNone;
775     NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
776     wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
777
778     if ( sourceDragMask & NSDragOperationLink )
779         result = wxDragLink;
780     else if ( sourceDragMask & NSDragOperationCopy )
781         result = wxDragCopy;
782     else if ( sourceDragMask & NSDragOperationMove )
783         result = wxDragMove;
784
785     PasteboardRef pboardRef;    
786     PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
787     target->SetCurrentDragPasteboard(pboardRef);
788     result = target->OnDragOver(pt.x, pt.y, result);
789     CFRelease(pboardRef);
790      
791     NSDragOperation nsresult = NSDragOperationNone;
792     switch (result )
793     {
794         case wxDragLink:
795             nsresult = NSDragOperationLink;
796         case wxDragMove:
797             nsresult = NSDragOperationMove;
798         case wxDragCopy:
799             nsresult = NSDragOperationCopy;
800         default :
801             break;
802     }
803     return nsresult;
804 }
805
806 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
807 {
808     id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
809
810     NSPasteboard *pboard = [sender draggingPasteboard];
811     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
812     
813     wxWindow* wxpeer = GetWXPeer();
814     wxDropTarget* target = wxpeer->GetDropTarget();
815     wxDragResult result = wxDragNone;
816     NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
817     wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
818
819     if ( sourceDragMask & NSDragOperationLink )
820         result = wxDragLink;
821     else if ( sourceDragMask & NSDragOperationCopy )
822         result = wxDragCopy;
823     else if ( sourceDragMask & NSDragOperationMove )
824         result = wxDragMove;
825
826     PasteboardRef pboardRef;    
827     PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
828     target->SetCurrentDragPasteboard(pboardRef);
829
830     if (target->OnDrop(pt.x, pt.y))
831         result = target->OnData(pt.x, pt.y, result);
832
833     CFRelease(pboardRef);
834      
835     return result != wxDragNone;
836 }
837
838 #endif
839
840 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
841 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
842 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
843 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
844 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
845 typedef BOOL (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
846
847 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
848 {
849     if ( !DoHandleMouseEvent(event) )
850     {
851         // for plain NSView mouse events would propagate to parents otherwise
852         if (!m_wxPeer->MacIsUserPane())
853         {
854             wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
855             superimpl(slf, (SEL)_cmd, event);
856         }
857     }
858 }
859
860 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
861 {
862     if ( [[slf window] firstResponder] != slf || !DoHandleKeyEvent(event) )
863     {
864         wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
865         superimpl(slf, (SEL)_cmd, event);
866     }
867 }
868
869 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
870 {
871     if (m_lastKeyDownEvent && !DoHandleCharEvent(m_lastKeyDownEvent, text) )
872     {
873         wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
874         superimpl(slf, (SEL)_cmd, text);
875     }
876     m_lastKeyDownEvent = NULL;
877 }
878
879
880 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
881 {
882     wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
883     return superimpl(slf, (SEL)_cmd, event);
884 }
885
886 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
887 {
888     if ( m_wxPeer->MacIsUserPane() )
889         return m_wxPeer->AcceptsFocus();
890     else
891     {
892         wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
893         return superimpl(slf, (SEL)_cmd);
894     }
895 }
896
897 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
898 {
899     wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
900     // get the current focus before running becomeFirstResponder
901     NSView* otherView = FindFocus(); 
902     wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
903     BOOL r = superimpl(slf, (SEL)_cmd);
904     if ( r )
905     {
906         DoNotifyFocusEvent( true, otherWindow );
907     }
908     return r;
909 }
910
911 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
912 {
913     wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
914     BOOL r = superimpl(slf, (SEL)_cmd);
915     // get the current focus after running resignFirstResponder
916     NSView* otherView = FindFocus(); 
917     wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
918     // NSTextViews have an editor as true responder, therefore the might get the
919     // resign notification if their editor takes over, don't trigger any event hen
920     if ( r && otherWindow != this)
921     {
922         DoNotifyFocusEvent( false, otherWindow );
923     }
924     return r;
925 }
926
927 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
928 {
929     wxWindow* wxpeer = GetWXPeer();
930     if ( wxpeer )
931     {
932         NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
933         if (cursor == NULL)
934         {
935             wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
936             superimpl(slf, (SEL)_cmd);
937         }
938         else
939         {
940             [slf addCursorRect: [slf bounds]
941                 cursor: cursor];
942         }
943     }
944 }
945   
946 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
947 {
948     return m_isFlipped;
949 }
950
951
952 #define OSX_DEBUG_DRAWING 0
953
954 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
955 {
956     CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
957     CGContextSaveGState( context );
958     
959 #if OSX_DEBUG_DRAWING
960     CGContextBeginPath( context );
961     CGContextMoveToPoint(context, 0, 0);
962     NSRect bounds = [self bounds];
963     CGContextAddLineToPoint(context, 10, 0);
964     CGContextMoveToPoint(context, 0, 0);
965     CGContextAddLineToPoint(context, 0, 10);
966     CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
967     CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
968     CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
969     CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
970     CGContextClosePath( context );
971     CGContextStrokePath(context);
972 #endif
973
974     if ( !m_isFlipped )
975     {
976         CGContextTranslateCTM( context, 0,  [m_osxView bounds].size.height );
977         CGContextScaleCTM( context, 1, -1 );
978     }
979     
980     wxRegion updateRgn;
981     const NSRect *rects;
982     NSInteger count;
983
984     [slf getRectsBeingDrawn:&rects count:&count];
985     for ( int i = 0 ; i < count ; ++i )
986     {
987         updateRgn.Union(wxFromNSRect(slf, rects[i]) );
988     }
989
990     wxWindow* wxpeer = GetWXPeer();
991     wxpeer->GetUpdateRegion() = updateRgn;
992     wxpeer->MacSetCGContextRef( context );
993     
994     bool handled = wxpeer->MacDoRedraw( 0 );
995             
996     CGContextRestoreGState( context );
997
998     CGContextSaveGState( context );
999     if ( !handled )
1000     {
1001         // call super
1002         SEL _cmd = @selector(drawRect:);
1003         wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1004         superimpl(slf, _cmd, *(NSRect*)rect);
1005         CGContextRestoreGState( context );
1006         CGContextSaveGState( context );
1007     }
1008     wxpeer->MacPaintChildrenBorders();
1009     wxpeer->MacSetCGContextRef( NULL );
1010     CGContextRestoreGState( context );
1011 }
1012
1013 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1014 {
1015     wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1016     if ( wxpeer )
1017         wxpeer->OSXHandleClicked(0);
1018 }
1019
1020 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1021 {
1022 }
1023
1024 // 
1025
1026 #if OBJC_API_VERSION >= 2
1027
1028 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1029     class_addMethod(c, s, i, t );
1030
1031 #else
1032
1033 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1034     { s, t, i },
1035
1036 #endif
1037
1038 void wxOSXCocoaClassAddWXMethods(Class c)
1039 {
1040
1041 #if OBJC_API_VERSION < 2
1042     static objc_method wxmethods[] =
1043     {
1044 #endif
1045
1046     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1047     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1048     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1049
1050     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1051     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1052     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1053
1054     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1055
1056     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1057     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1058     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1059
1060     wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1061     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1062     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1063     
1064     wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1065     wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1066     wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1067     
1068     wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1069
1070     wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "v@:@" )
1071
1072     wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1073     wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1074     wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1075     wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
1076
1077     wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1078     wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1079
1080     wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1081     wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1082
1083 #if wxUSE_DRAG_AND_DROP
1084     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1085     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1086     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1087     wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1088 #endif     
1089         
1090 #if OBJC_API_VERSION < 2
1091     } ;
1092     static int method_count = WXSIZEOF( wxmethods );
1093     static objc_method_list *wxmethodlist = NULL;
1094     if ( wxmethodlist == NULL )
1095     {
1096         wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1097         memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1098         wxmethodlist->method_count = method_count;
1099         wxmethodlist->obsolete = 0;
1100     }
1101     class_addMethods( c, wxmethodlist );
1102 #endif
1103 }
1104
1105 //
1106 // C++ implementation class
1107 //
1108
1109 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1110
1111 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl ) :
1112     wxWidgetImpl( peer, isRootControl )
1113 {
1114     Init();
1115     m_osxView = w;
1116 }
1117
1118 wxWidgetCocoaImpl::wxWidgetCocoaImpl() 
1119 {
1120     Init();
1121 }
1122
1123 void wxWidgetCocoaImpl::Init()
1124 {
1125     m_osxView = NULL;
1126     m_isFlipped = true;
1127     m_lastKeyDownEvent = NULL;
1128 }
1129
1130 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1131 {
1132     RemoveAssociations( this );
1133
1134     if ( !IsRootControl() )
1135     {
1136         NSView *sv = [m_osxView superview];
1137         if ( sv != nil )
1138             [m_osxView removeFromSuperview];
1139     }
1140     [m_osxView release];
1141 }
1142     
1143 bool wxWidgetCocoaImpl::IsVisible() const 
1144 {
1145     return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1146 }
1147
1148 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1149 {
1150     [m_osxView setHidden:(visible ? NO:YES)];
1151 }
1152
1153 void wxWidgetCocoaImpl::Raise()
1154 {
1155 }
1156     
1157 void wxWidgetCocoaImpl::Lower()
1158 {
1159 }
1160
1161 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1162 {
1163 #if 1
1164     SetNeedsDisplay() ;
1165 #else
1166     // We should do something like this, but it wasn't working in 10.4.
1167     if (GetNeedsDisplay() )
1168     {
1169         SetNeedsDisplay() ;
1170     }
1171     NSRect r = wxToNSRect( [m_osxView superview], *rect );
1172     NSSize offset = NSMakeSize((float)dx, (float)dy);
1173     [m_osxView scrollRect:r by:offset];
1174 #endif
1175 }
1176
1177 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1178 {
1179     wxWindowMac* parent = GetWXPeer()->GetParent();
1180     // under Cocoa we might have a contentView in the wxParent to which we have to 
1181     // adjust the coordinates
1182     if (parent && [m_osxView superview] != parent->GetHandle() )
1183     {
1184         int cx = 0,cy = 0,cw = 0,ch = 0;
1185         if ( parent->GetPeer() )
1186         {
1187             parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1188             x -= cx;
1189             y -= cy;
1190         }
1191     }
1192     [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
1193     NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
1194     [m_osxView setFrame:r];
1195     [[m_osxView superview] setNeedsDisplayInRect:r]; 
1196     
1197     if ([m_osxView respondsToSelector:@selector(trackingTag)] )
1198     {
1199         if ( [(wxNSView*)m_osxView trackingTag] )
1200             [m_osxView removeTrackingRect: [(wxNSView*)m_osxView trackingTag]];
1201         
1202         [(wxNSView*)m_osxView setTrackingTag: [m_osxView addTrackingRect: [m_osxView bounds] owner: m_osxView userData: nil assumeInside: NO]];
1203     }
1204 }
1205
1206 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
1207 {
1208     wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
1209     x = r.GetLeft();
1210     y = r.GetTop();
1211 }
1212
1213 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
1214 {
1215     NSRect rect = [m_osxView frame];
1216     width = rect.size.width;
1217     height = rect.size.height;
1218 }
1219
1220 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
1221 {
1222     if ( [m_osxView respondsToSelector:@selector(contentView) ] )
1223     {
1224         NSView* cv = [m_osxView contentView];
1225      
1226         NSRect bounds = [m_osxView bounds];
1227         NSRect rect = [cv frame];
1228         
1229         int y = rect.origin.y;
1230         int x = rect.origin.x;
1231         if ( ![ m_osxView isFlipped ] )
1232             y = bounds.size.height - (rect.origin.y + rect.size.height);
1233         left = x;
1234         top = y;
1235         width = rect.size.width;
1236         height = rect.size.height;
1237     }
1238     else
1239     {
1240         left = top = 0;
1241         GetSize( width, height );
1242     }
1243 }
1244
1245 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
1246 {
1247     if ( where )
1248         [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
1249     else
1250         [m_osxView setNeedsDisplay:YES];
1251 }
1252
1253 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
1254 {
1255     return [m_osxView needsDisplay];
1256 }
1257
1258 bool wxWidgetCocoaImpl::CanFocus() const
1259 {
1260     return [m_osxView canBecomeKeyView] == YES;
1261 }
1262
1263 bool wxWidgetCocoaImpl::HasFocus() const
1264 {
1265     return ( FindFocus() == m_osxView );
1266 }
1267
1268 bool wxWidgetCocoaImpl::SetFocus() 
1269 {
1270     if ( [m_osxView canBecomeKeyView] == NO )
1271         return false;
1272         
1273     [[m_osxView window] makeFirstResponder: m_osxView] ;
1274     [[m_osxView window] makeKeyAndOrderFront:nil] ;
1275     return true;
1276 }
1277
1278
1279 void wxWidgetCocoaImpl::RemoveFromParent()
1280 {
1281     [m_osxView removeFromSuperview];
1282 }
1283
1284 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
1285 {
1286     NSView* container = parent->GetWXWidget() ;
1287     wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
1288     [container addSubview:m_osxView];
1289 }
1290
1291 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &WXUNUSED(col) )
1292 {
1293     // m_osxView.backgroundColor = [[UIColor alloc] initWithCGColor:col.GetCGColor()];
1294 }
1295
1296 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
1297 {
1298     if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
1299     {
1300         wxCFStringRef cf( title , encoding );
1301         [m_osxView setTitle:cf.AsNSString()];
1302     }
1303     else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
1304     {
1305         wxCFStringRef cf( title , encoding );
1306         [m_osxView setStringValue:cf.AsNSString()];
1307     }
1308 }
1309     
1310
1311 void  wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
1312 {
1313     NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
1314     p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ]; 
1315     *pt = wxFromNSPoint( to->GetWXWidget(), p );
1316 }
1317
1318 wxInt32 wxWidgetCocoaImpl::GetValue() const 
1319 {
1320     return [(NSControl*)m_osxView intValue];
1321 }
1322
1323 void wxWidgetCocoaImpl::SetValue( wxInt32 v ) 
1324 {
1325     if (  [m_osxView respondsToSelector:@selector(setIntValue:)] )
1326     {
1327         [m_osxView setIntValue:v];
1328     }
1329     else if (  [m_osxView respondsToSelector:@selector(setFloatValue:)] )
1330     {
1331         [m_osxView setFloatValue:(double)v];
1332     }
1333     else if (  [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
1334     {
1335         [m_osxView setDoubleValue:(double)v];
1336     }
1337 }
1338
1339 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v ) 
1340 {
1341     if (  [m_osxView respondsToSelector:@selector(setMinValue:)] )
1342     {
1343         [m_osxView setMinValue:(double)v];
1344     }
1345 }
1346
1347 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v ) 
1348 {
1349     if (  [m_osxView respondsToSelector:@selector(setMaxValue:)] )
1350     {
1351         [m_osxView setMaxValue:(double)v];
1352     }
1353 }
1354
1355 wxInt32 wxWidgetCocoaImpl::GetMinimum() const 
1356 {
1357     if (  [m_osxView respondsToSelector:@selector(getMinValue:)] )
1358     {
1359         return [m_osxView minValue];
1360     }
1361     return 0;
1362 }
1363
1364 wxInt32 wxWidgetCocoaImpl::GetMaximum() const 
1365 {
1366     if (  [m_osxView respondsToSelector:@selector(getMaxValue:)] )
1367     {
1368         return [m_osxView maxValue];
1369     }
1370     return 0;
1371 }
1372
1373 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
1374 {
1375     if (  [m_osxView respondsToSelector:@selector(setImage:)] )
1376     {
1377         [m_osxView setImage:bitmap.GetNSImage()];
1378     }
1379 }
1380
1381 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
1382 {
1383     // implementation in subclass
1384 }
1385
1386 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
1387 {
1388     r->x = r->y = r->width = r->height = 0;
1389
1390     if (  [m_osxView respondsToSelector:@selector(sizeToFit)] )
1391     {
1392         NSRect former = [m_osxView frame];
1393         [m_osxView sizeToFit];
1394         NSRect best = [m_osxView frame];
1395         [m_osxView setFrame:former];
1396         r->width = best.size.width;
1397         r->height = best.size.height;
1398     }
1399 }
1400
1401 bool wxWidgetCocoaImpl::IsEnabled() const
1402 {
1403     if ( [m_osxView respondsToSelector:@selector(isEnabled) ] )
1404         return [m_osxView isEnabled];
1405     return true;
1406 }
1407
1408 void wxWidgetCocoaImpl::Enable( bool enable )
1409 {
1410     if ( [m_osxView respondsToSelector:@selector(setEnabled:) ] )
1411         [m_osxView setEnabled:enable];
1412 }
1413
1414 void wxWidgetCocoaImpl::PulseGauge()
1415 {
1416 }
1417
1418 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
1419 {
1420 }
1421
1422 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant ) 
1423 {
1424     NSControlSize size = NSRegularControlSize;
1425     
1426     switch ( variant )
1427     {
1428         case wxWINDOW_VARIANT_NORMAL :
1429             size = NSRegularControlSize;
1430             break ;
1431
1432         case wxWINDOW_VARIANT_SMALL :
1433             size = NSSmallControlSize;
1434             break ;
1435
1436         case wxWINDOW_VARIANT_MINI :
1437             size = NSMiniControlSize;
1438             break ;
1439
1440         case wxWINDOW_VARIANT_LARGE :
1441             size = NSRegularControlSize;
1442             break ;
1443
1444         default:
1445             wxFAIL_MSG(_T("unexpected window variant"));
1446             break ;
1447     }
1448     if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
1449         [m_osxView setControlSize:size];
1450 }
1451
1452 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&, long, bool)
1453 {
1454     if ([m_osxView respondsToSelector:@selector(setFont:)])
1455         [m_osxView setFont: font.OSXGetNSFont()];
1456 }
1457
1458 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
1459 {
1460     WXWidget c =  control ? control : (WXWidget) m_osxView;
1461     wxWidgetImpl::Associate( c, this ) ;
1462     if ([c respondsToSelector:@selector(setAction:)])
1463     {
1464         [c setTarget: c];
1465         [c setAction: @selector(controlAction:)];
1466         if ([c respondsToSelector:@selector(setDoubleAction:)])
1467         {
1468             [c setDoubleAction: @selector(controlDoubleAction:)];
1469         }
1470         
1471     }
1472 }
1473
1474 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
1475 {
1476     wxKeyEvent wxevent(wxEVT_CHAR);
1477     SetupKeyEvent( wxevent, event, text );
1478     wxevent.SetEventObject(GetWXPeer());  
1479
1480     return GetWXPeer()->OSXHandleKeyEvent(wxevent);
1481 }
1482
1483 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
1484 {
1485     wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1486     SetupKeyEvent( wxevent, event );
1487     wxevent.SetEventObject(GetWXPeer());    
1488     bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
1489
1490     // this will fire higher level events, like insertText, to help
1491     // us handle EVT_CHAR, etc.
1492     if ([event type] == NSKeyDown)
1493     {
1494         m_lastKeyDownEvent = event;
1495         if ( !result )
1496             [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
1497     }
1498     return result;
1499 }
1500
1501 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
1502 {
1503     NSPoint clickLocation; 
1504     clickLocation = [m_osxView convertPoint:[event locationInWindow] fromView:nil]; 
1505     wxPoint pt = wxFromNSPoint( m_osxView, clickLocation );
1506     wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1507     SetupMouseEvent( wxevent , event ) ;
1508     wxevent.SetEventObject(GetWXPeer());
1509     wxevent.m_x = pt.x;
1510     wxevent.m_y = pt.y;
1511
1512     return GetWXPeer()->HandleWindowEvent(wxevent);
1513 }
1514
1515 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
1516 {
1517     wxWindow* thisWindow = GetWXPeer();
1518     if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
1519     {
1520         thisWindow->MacInvalidateBorders();
1521     }
1522
1523     if ( receivedFocus )
1524     {
1525         wxLogTrace(_T("Focus"), _T("focus set(%p)"), static_cast<void*>(thisWindow));
1526         wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
1527         thisWindow->HandleWindowEvent(eventFocus);
1528
1529 #if wxUSE_CARET
1530         if ( thisWindow->GetCaret() )
1531             thisWindow->GetCaret()->OnSetFocus();
1532 #endif
1533
1534         wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
1535         event.SetEventObject(thisWindow);
1536         if (otherWindow)
1537             event.SetWindow(otherWindow->GetWXPeer());
1538         thisWindow->HandleWindowEvent(event) ;
1539     }
1540     else // !receivedFocuss
1541     {
1542 #if wxUSE_CARET
1543         if ( thisWindow->GetCaret() )
1544             thisWindow->GetCaret()->OnKillFocus();
1545 #endif
1546
1547         wxLogTrace(_T("Focus"), _T("focus lost(%p)"), static_cast<void*>(thisWindow));
1548                     
1549         wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
1550         event.SetEventObject(thisWindow);
1551         if (otherWindow)
1552             event.SetWindow(otherWindow->GetWXPeer());
1553         thisWindow->HandleWindowEvent(event) ;
1554     }
1555 }
1556
1557 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
1558 {
1559     NSPoint location = [NSEvent mouseLocation];
1560     location = [[m_osxView window] convertScreenToBase:location];
1561     NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
1562
1563     if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
1564     {
1565         [(NSCursor*)cursor.GetHCURSOR() set];
1566     }
1567     [[m_osxView window] invalidateCursorRectsForView:m_osxView];
1568 }
1569
1570 void wxWidgetCocoaImpl::CaptureMouse()
1571 {
1572     [[m_osxView window] disableCursorRects];
1573 }
1574
1575 void wxWidgetCocoaImpl::ReleaseMouse()
1576 {
1577     [[m_osxView window] enableCursorRects];
1578 }
1579
1580 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
1581 {
1582     m_isFlipped = flipped;
1583 }
1584
1585 //
1586 // Factory methods
1587 //
1588
1589 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent), 
1590     wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
1591     long WXUNUSED(style), long WXUNUSED(extraStyle))
1592 {
1593     NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
1594     wxNSView* v = [[wxNSView alloc] initWithFrame:r];
1595
1596     // temporary hook for dnd
1597     [v registerForDraggedTypes:[NSArray arrayWithObjects:
1598         NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
1599         
1600     wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v );
1601     return c;
1602 }
1603
1604 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now ) 
1605 {
1606     NSWindow* tlw = now->GetWXWindow();
1607     wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
1608     wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( now, v, true );
1609     c->InstallEventHandler();
1610     [tlw setContentView:v];
1611     return c;
1612 }