fixing coordinates for dnd, 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     result = target->OnData(pt.x, pt.y, result);
830     CFRelease(pboardRef);
831      
832     return result != wxDragNone;
833 }
834
835 #endif
836
837 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
838 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
839 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
840 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
841 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
842 typedef BOOL (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
843
844 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
845 {
846     if ( !DoHandleMouseEvent(event) )
847     {
848         wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
849         superimpl(slf, (SEL)_cmd, event);
850     }
851 }
852
853 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
854 {
855     if ( [[slf window] firstResponder] != slf || !DoHandleKeyEvent(event) )
856     {
857         wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
858         superimpl(slf, (SEL)_cmd, event);
859     }
860 }
861
862 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
863 {
864     if (m_lastKeyDownEvent && !DoHandleCharEvent(m_lastKeyDownEvent, text) )
865     {
866             wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
867             superimpl(slf, (SEL)_cmd, text);
868     }
869     m_lastKeyDownEvent = NULL;
870 }
871
872
873 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
874 {
875     wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
876     return superimpl(slf, (SEL)_cmd, event);
877 }
878
879 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
880 {
881     if ( m_wxPeer->MacIsUserPane() )
882         return m_wxPeer->AcceptsFocus();
883     else
884     {
885         wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
886         return superimpl(slf, (SEL)_cmd);
887     }
888 }
889
890 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
891 {
892     wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
893     // get the current focus before running becomeFirstResponder
894     NSView* otherView = FindFocus(); 
895     wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
896     BOOL r = superimpl(slf, (SEL)_cmd);
897     if ( r )
898     {
899         DoNotifyFocusEvent( true, otherWindow );
900     }
901     return r;
902 }
903
904 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
905 {
906     wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
907     BOOL r = superimpl(slf, (SEL)_cmd);
908     // get the current focus after running resignFirstResponder
909     NSView* otherView = FindFocus(); 
910     wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
911     // NSTextViews have an editor as true responder, therefore the might get the
912     // resign notification if their editor takes over, don't trigger any event hen
913     if ( r && otherWindow != this)
914     {
915         DoNotifyFocusEvent( false, otherWindow );
916     }
917     return r;
918 }
919
920 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
921 {
922     wxWindow* wxpeer = GetWXPeer();
923     if ( wxpeer )
924     {
925         NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
926         if (cursor == NULL)
927         {
928             wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
929             superimpl(slf, (SEL)_cmd);
930         }
931         else
932         {
933             [slf addCursorRect: [slf bounds]
934                 cursor: cursor];
935         }
936     }
937 }
938   
939 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
940 {
941     return m_isFlipped;
942 }
943
944
945 #define OSX_DEBUG_DRAWING 0
946
947 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
948 {
949     CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
950     CGContextSaveGState( context );
951     
952 #if OSX_DEBUG_DRAWING
953     CGContextBeginPath( context );
954     CGContextMoveToPoint(context, 0, 0);
955     NSRect bounds = [self bounds];
956     CGContextAddLineToPoint(context, 10, 0);
957     CGContextMoveToPoint(context, 0, 0);
958     CGContextAddLineToPoint(context, 0, 10);
959     CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
960     CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
961     CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
962     CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
963     CGContextClosePath( context );
964     CGContextStrokePath(context);
965 #endif
966
967     if ( !m_isFlipped )
968     {
969         CGContextTranslateCTM( context, 0,  [m_osxView bounds].size.height );
970         CGContextScaleCTM( context, 1, -1 );
971     }
972     
973     wxRegion updateRgn;
974     const NSRect *rects;
975     NSInteger count;
976
977     [slf getRectsBeingDrawn:&rects count:&count];
978     for ( int i = 0 ; i < count ; ++i )
979     {
980         updateRgn.Union(wxFromNSRect(slf, rects[i]) );
981     }
982
983     wxWindow* wxpeer = GetWXPeer();
984     wxpeer->GetUpdateRegion() = updateRgn;
985     wxpeer->MacSetCGContextRef( context );
986     
987     bool handled = wxpeer->MacDoRedraw( 0 );
988             
989     CGContextRestoreGState( context );
990
991     CGContextSaveGState( context );
992     if ( !handled )
993     {
994         // call super
995         SEL _cmd = @selector(drawRect:);
996         wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
997         superimpl(slf, _cmd, *(NSRect*)rect);
998         CGContextRestoreGState( context );
999         CGContextSaveGState( context );
1000     }
1001     wxpeer->MacPaintChildrenBorders();
1002     wxpeer->MacSetCGContextRef( NULL );
1003     CGContextRestoreGState( context );
1004 }
1005
1006 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1007 {
1008     wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1009     if ( wxpeer )
1010         wxpeer->OSXHandleClicked(0);
1011 }
1012
1013 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1014 {
1015 }
1016
1017 // 
1018
1019 #if OBJC_API_VERSION >= 2
1020
1021 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1022     class_addMethod(c, s, i, t );
1023
1024 #else
1025
1026 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1027     { s, t, i },
1028
1029 #endif
1030
1031 void wxOSXCocoaClassAddWXMethods(Class c)
1032 {
1033
1034 #if OBJC_API_VERSION < 2
1035     static objc_method wxmethods[] =
1036     {
1037 #endif
1038
1039     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1040     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1041     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1042
1043     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1044     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1045     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1046
1047     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1048
1049     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1050     wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1051     wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1052
1053     wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1054     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1055     wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1056     
1057     wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1058     wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1059     wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1060     
1061     wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1062
1063     wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "v@:@" )
1064
1065     wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1066     wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1067     wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1068     wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
1069
1070     wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1071     wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1072
1073     wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1074     wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1075
1076 #if wxUSE_DRAG_AND_DROP
1077     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1078     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1079     wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1080     wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1081 #endif     
1082         
1083 #if OBJC_API_VERSION < 2
1084     } ;
1085     static int method_count = WXSIZEOF( wxmethods );
1086     static objc_method_list *wxmethodlist = NULL;
1087     if ( wxmethodlist == NULL )
1088     {
1089         wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1090         memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1091         wxmethodlist->method_count = method_count;
1092         wxmethodlist->obsolete = 0;
1093     }
1094     class_addMethods( c, wxmethodlist );
1095 #endif
1096 }
1097
1098 //
1099 // C++ implementation class
1100 //
1101
1102 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1103
1104 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl ) :
1105     wxWidgetImpl( peer, isRootControl )
1106 {
1107     Init();
1108     m_osxView = w;
1109 }
1110
1111 wxWidgetCocoaImpl::wxWidgetCocoaImpl() 
1112 {
1113     Init();
1114 }
1115
1116 void wxWidgetCocoaImpl::Init()
1117 {
1118     m_osxView = NULL;
1119     m_isFlipped = true;
1120     m_lastKeyDownEvent = NULL;
1121 }
1122
1123 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1124 {
1125     RemoveAssociations( this );
1126
1127     if ( !IsRootControl() )
1128     {
1129         NSView *sv = [m_osxView superview];
1130         if ( sv != nil )
1131             [m_osxView removeFromSuperview];
1132     }
1133     [m_osxView release];
1134 }
1135     
1136 bool wxWidgetCocoaImpl::IsVisible() const 
1137 {
1138     return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1139 }
1140
1141 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1142 {
1143     [m_osxView setHidden:(visible ? NO:YES)];
1144 }
1145
1146 void wxWidgetCocoaImpl::Raise()
1147 {
1148 }
1149     
1150 void wxWidgetCocoaImpl::Lower()
1151 {
1152 }
1153
1154 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1155 {
1156 #if 1
1157     SetNeedsDisplay() ;
1158 #else
1159     // We should do something like this, but it wasn't working in 10.4.
1160     if (GetNeedsDisplay() )
1161     {
1162         SetNeedsDisplay() ;
1163     }
1164     NSRect r = wxToNSRect( [m_osxView superview], *rect );
1165     NSSize offset = NSMakeSize((float)dx, (float)dy);
1166     [m_osxView scrollRect:r by:offset];
1167 #endif
1168 }
1169
1170 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1171 {
1172     wxWindowMac* parent = GetWXPeer()->GetParent();
1173     // under Cocoa we might have a contentView in the wxParent to which we have to 
1174     // adjust the coordinates
1175     if (parent && [m_osxView superview] != parent->GetHandle() )
1176     {
1177         int cx = 0,cy = 0,cw = 0,ch = 0;
1178         if ( parent->GetPeer() )
1179         {
1180             parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1181             x -= cx;
1182             y -= cy;
1183         }
1184     }
1185     [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
1186     NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
1187     [m_osxView setFrame:r];
1188     [[m_osxView superview] setNeedsDisplayInRect:r]; 
1189     
1190     if ([m_osxView respondsToSelector:@selector(trackingTag)] )
1191     {
1192         if ( [(wxNSView*)m_osxView trackingTag] )
1193             [m_osxView removeTrackingRect: [(wxNSView*)m_osxView trackingTag]];
1194         
1195         [(wxNSView*)m_osxView setTrackingTag: [m_osxView addTrackingRect: [m_osxView bounds] owner: m_osxView userData: nil assumeInside: NO]];
1196     }
1197 }
1198
1199 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
1200 {
1201     wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
1202     x = r.GetLeft();
1203     y = r.GetTop();
1204 }
1205
1206 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
1207 {
1208     NSRect rect = [m_osxView frame];
1209     width = rect.size.width;
1210     height = rect.size.height;
1211 }
1212
1213 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
1214 {
1215     if ( [m_osxView respondsToSelector:@selector(contentView) ] )
1216     {
1217         NSView* cv = [m_osxView contentView];
1218      
1219         NSRect bounds = [m_osxView bounds];
1220         NSRect rect = [cv frame];
1221         
1222         int y = rect.origin.y;
1223         int x = rect.origin.x;
1224         if ( ![ m_osxView isFlipped ] )
1225             y = bounds.size.height - (rect.origin.y + rect.size.height);
1226         left = x;
1227         top = y;
1228         width = rect.size.width;
1229         height = rect.size.height;
1230     }
1231     else
1232     {
1233         left = top = 0;
1234         GetSize( width, height );
1235     }
1236 }
1237
1238 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
1239 {
1240     if ( where )
1241         [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
1242     else
1243         [m_osxView setNeedsDisplay:YES];
1244 }
1245
1246 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
1247 {
1248     return [m_osxView needsDisplay];
1249 }
1250
1251 bool wxWidgetCocoaImpl::CanFocus() const
1252 {
1253     return [m_osxView canBecomeKeyView] == YES;
1254 }
1255
1256 bool wxWidgetCocoaImpl::HasFocus() const
1257 {
1258     return ( FindFocus() == m_osxView );
1259 }
1260
1261 bool wxWidgetCocoaImpl::SetFocus() 
1262 {
1263     if ( [m_osxView canBecomeKeyView] == NO )
1264         return false;
1265         
1266     [[m_osxView window] makeFirstResponder: m_osxView] ;
1267     return true;
1268 }
1269
1270
1271 void wxWidgetCocoaImpl::RemoveFromParent()
1272 {
1273     [m_osxView removeFromSuperview];
1274 }
1275
1276 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
1277 {
1278     NSView* container = parent->GetWXWidget() ;
1279     wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
1280     [container addSubview:m_osxView];
1281 }
1282
1283 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &WXUNUSED(col) )
1284 {
1285     // m_osxView.backgroundColor = [[UIColor alloc] initWithCGColor:col.GetCGColor()];
1286 }
1287
1288 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
1289 {
1290     if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
1291     {
1292         wxCFStringRef cf( title , encoding );
1293         [m_osxView setTitle:cf.AsNSString()];
1294     }
1295     else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
1296     {
1297         wxCFStringRef cf( title , encoding );
1298         [m_osxView setStringValue:cf.AsNSString()];
1299     }
1300 }
1301     
1302
1303 void  wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
1304 {
1305     NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
1306     p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ]; 
1307     *pt = wxFromNSPoint( to->GetWXWidget(), p );
1308 }
1309
1310 wxInt32 wxWidgetCocoaImpl::GetValue() const 
1311 {
1312     return [(NSControl*)m_osxView intValue];
1313 }
1314
1315 void wxWidgetCocoaImpl::SetValue( wxInt32 v ) 
1316 {
1317     if (  [m_osxView respondsToSelector:@selector(setIntValue:)] )
1318     {
1319         [m_osxView setIntValue:v];
1320     }
1321     else if (  [m_osxView respondsToSelector:@selector(setFloatValue:)] )
1322     {
1323         [m_osxView setFloatValue:(double)v];
1324     }
1325     else if (  [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
1326     {
1327         [m_osxView setDoubleValue:(double)v];
1328     }
1329 }
1330
1331 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v ) 
1332 {
1333     if (  [m_osxView respondsToSelector:@selector(setMinValue:)] )
1334     {
1335         [m_osxView setMinValue:(double)v];
1336     }
1337 }
1338
1339 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v ) 
1340 {
1341     if (  [m_osxView respondsToSelector:@selector(setMaxValue:)] )
1342     {
1343         [m_osxView setMaxValue:(double)v];
1344     }
1345 }
1346
1347 wxInt32 wxWidgetCocoaImpl::GetMinimum() const 
1348 {
1349     if (  [m_osxView respondsToSelector:@selector(getMinValue:)] )
1350     {
1351         return [m_osxView minValue];
1352     }
1353     return 0;
1354 }
1355
1356 wxInt32 wxWidgetCocoaImpl::GetMaximum() const 
1357 {
1358     if (  [m_osxView respondsToSelector:@selector(getMaxValue:)] )
1359     {
1360         return [m_osxView maxValue];
1361     }
1362     return 0;
1363 }
1364
1365 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
1366 {
1367     if (  [m_osxView respondsToSelector:@selector(setImage:)] )
1368     {
1369         [m_osxView setImage:bitmap.GetNSImage()];
1370     }
1371 }
1372
1373 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
1374 {
1375     // implementation in subclass
1376 }
1377
1378 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
1379 {
1380     r->x = r->y = r->width = r->height = 0;
1381
1382     if (  [m_osxView respondsToSelector:@selector(sizeToFit)] )
1383     {
1384         NSRect former = [m_osxView frame];
1385         [m_osxView sizeToFit];
1386         NSRect best = [m_osxView frame];
1387         [m_osxView setFrame:former];
1388         r->width = best.size.width;
1389         r->height = best.size.height;
1390     }
1391 }
1392
1393 bool wxWidgetCocoaImpl::IsEnabled() const
1394 {
1395     if ( [m_osxView respondsToSelector:@selector(isEnabled) ] )
1396         return [m_osxView isEnabled];
1397     return true;
1398 }
1399
1400 void wxWidgetCocoaImpl::Enable( bool enable )
1401 {
1402     if ( [m_osxView respondsToSelector:@selector(setEnabled:) ] )
1403         [m_osxView setEnabled:enable];
1404 }
1405
1406 void wxWidgetCocoaImpl::PulseGauge()
1407 {
1408 }
1409
1410 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
1411 {
1412 }
1413
1414 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant ) 
1415 {
1416     NSControlSize size = NSRegularControlSize;
1417     
1418     switch ( variant )
1419     {
1420         case wxWINDOW_VARIANT_NORMAL :
1421             size = NSRegularControlSize;
1422             break ;
1423
1424         case wxWINDOW_VARIANT_SMALL :
1425             size = NSSmallControlSize;
1426             break ;
1427
1428         case wxWINDOW_VARIANT_MINI :
1429             size = NSMiniControlSize;
1430             break ;
1431
1432         case wxWINDOW_VARIANT_LARGE :
1433             size = NSRegularControlSize;
1434             break ;
1435
1436         default:
1437             wxFAIL_MSG(_T("unexpected window variant"));
1438             break ;
1439     }
1440     if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
1441         [m_osxView setControlSize:size];
1442 }
1443
1444 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&, long, bool)
1445 {
1446     if ([m_osxView respondsToSelector:@selector(setFont:)])
1447         [m_osxView setFont: font.OSXGetNSFont()];
1448 }
1449
1450 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
1451 {
1452     WXWidget c =  control ? control : (WXWidget) m_osxView;
1453     wxWidgetImpl::Associate( c, this ) ;
1454     if ([c respondsToSelector:@selector(setAction:)])
1455     {
1456         [c setTarget: c];
1457         [c setAction: @selector(controlAction:)];
1458         if ([c respondsToSelector:@selector(setDoubleAction:)])
1459         {
1460             [c setDoubleAction: @selector(controlDoubleAction:)];
1461         }
1462         
1463     }
1464 }
1465
1466 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
1467 {
1468     wxKeyEvent wxevent(wxEVT_CHAR);
1469     SetupKeyEvent( wxevent, event, text );
1470     wxevent.SetEventObject(GetWXPeer());  
1471
1472     return GetWXPeer()->OSXHandleKeyEvent(wxevent);
1473 }
1474
1475 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
1476 {
1477     wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1478     SetupKeyEvent( wxevent, event );
1479     wxevent.SetEventObject(GetWXPeer());    
1480     bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
1481
1482     // this will fire higher level events, like insertText, to help
1483     // us handle EVT_CHAR, etc.
1484     if ([event type] == NSKeyDown)
1485     {
1486         m_lastKeyDownEvent = event;
1487         if ( !result )
1488             [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
1489     }
1490     return result;
1491 }
1492
1493 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
1494 {
1495     NSPoint clickLocation; 
1496     clickLocation = [m_osxView convertPoint:[event locationInWindow] fromView:nil]; 
1497     wxPoint pt = wxFromNSPoint( m_osxView, clickLocation );
1498     wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1499     SetupMouseEvent( wxevent , event ) ;
1500     wxevent.SetEventObject(GetWXPeer());
1501     wxevent.m_x = pt.x;
1502     wxevent.m_y = pt.y;
1503
1504     return GetWXPeer()->HandleWindowEvent(wxevent);
1505 }
1506
1507 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
1508 {
1509     wxWindow* thisWindow = GetWXPeer();
1510     if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
1511     {
1512         thisWindow->MacInvalidateBorders();
1513     }
1514
1515     if ( receivedFocus )
1516     {
1517         wxLogTrace(_T("Focus"), _T("focus set(%p)"), static_cast<void*>(thisWindow));
1518         wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
1519         thisWindow->HandleWindowEvent(eventFocus);
1520
1521 #if wxUSE_CARET
1522         if ( thisWindow->GetCaret() )
1523             thisWindow->GetCaret()->OnSetFocus();
1524 #endif
1525
1526         wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
1527         event.SetEventObject(thisWindow);
1528         if (otherWindow)
1529             event.SetWindow(otherWindow->GetWXPeer());
1530         thisWindow->HandleWindowEvent(event) ;
1531     }
1532     else // !receivedFocuss
1533     {
1534 #if wxUSE_CARET
1535         if ( thisWindow->GetCaret() )
1536             thisWindow->GetCaret()->OnKillFocus();
1537 #endif
1538
1539         wxLogTrace(_T("Focus"), _T("focus lost(%p)"), static_cast<void*>(thisWindow));
1540                     
1541         wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
1542         event.SetEventObject(thisWindow);
1543         if (otherWindow)
1544             event.SetWindow(otherWindow->GetWXPeer());
1545         thisWindow->HandleWindowEvent(event) ;
1546     }
1547 }
1548
1549 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
1550 {
1551     NSPoint location = [NSEvent mouseLocation];
1552     location = [[m_osxView window] convertScreenToBase:location];
1553     NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
1554
1555     if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
1556     {
1557         [(NSCursor*)cursor.GetHCURSOR() set];
1558     }
1559     [[m_osxView window] invalidateCursorRectsForView:m_osxView];
1560 }
1561
1562 void wxWidgetCocoaImpl::CaptureMouse()
1563 {
1564     [[m_osxView window] disableCursorRects];
1565 }
1566
1567 void wxWidgetCocoaImpl::ReleaseMouse()
1568 {
1569     [[m_osxView window] enableCursorRects];
1570 }
1571
1572 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
1573 {
1574     m_isFlipped = flipped;
1575 }
1576
1577 //
1578 // Factory methods
1579 //
1580
1581 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent), 
1582     wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
1583     long WXUNUSED(style), long WXUNUSED(extraStyle))
1584 {
1585     NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
1586     wxNSView* v = [[wxNSView alloc] initWithFrame:r];
1587
1588     // temporary hook for dnd
1589     [v registerForDraggedTypes:[NSArray arrayWithObjects:
1590         NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
1591         
1592     wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v );
1593     return c;
1594 }
1595
1596 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now ) 
1597 {
1598     NSWindow* tlw = now->GetWXWindow();
1599     wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
1600     wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( now, v, true );
1601     c->InstallEventHandler();
1602     [tlw setContentView:v];
1603     return c;
1604 }