]> git.saurik.com Git - wxWidgets.git/blob - src/mac/carbon/app.cpp
Fix bug with m_current causing EVT_LIST_KEY_DOWN events not to fire in virtual mode...
[wxWidgets.git] / src / mac / carbon / app.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/mac/carbon/app.cpp
3 // Purpose: wxApp
4 // Author: Stefan Csomor
5 // Modified by:
6 // Created: 1998-01-01
7 // RCS-ID: $Id$
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/wxprec.h"
13
14 #include "wx/app.h"
15
16 #ifndef WX_PRECOMP
17 #include "wx/intl.h"
18 #include "wx/log.h"
19 #include "wx/utils.h"
20 #include "wx/window.h"
21 #include "wx/frame.h"
22 #include "wx/dc.h"
23 #include "wx/button.h"
24 #include "wx/menu.h"
25 #include "wx/pen.h"
26 #include "wx/brush.h"
27 #include "wx/palette.h"
28 #include "wx/icon.h"
29 #include "wx/cursor.h"
30 #include "wx/dialog.h"
31 #include "wx/msgdlg.h"
32 #include "wx/textctrl.h"
33 #include "wx/memory.h"
34 #include "wx/gdicmn.h"
35 #include "wx/module.h"
36 #endif
37
38 #include "wx/tooltip.h"
39 #include "wx/docview.h"
40 #include "wx/filename.h"
41 #include "wx/link.h"
42
43 #include <string.h>
44
45 // mac
46
47 #ifndef __DARWIN__
48 #if __option(profile)
49 #include <profiler.h>
50 #endif
51 #endif
52
53 // #include "apprsrc.h"
54
55 #include "wx/mac/uma.h"
56 #include "wx/mac/macnotfy.h"
57
58 #ifdef __DARWIN__
59 # include <CoreServices/CoreServices.h>
60 # if defined(WXMAKINGDLL_CORE)
61 # include <mach-o/dyld.h>
62 # endif
63 #else
64 # include <Sound.h>
65 # include <Threads.h>
66 # include <ToolUtils.h>
67 # include <DiskInit.h>
68 # include <Devices.h>
69 #endif
70
71 // Keep linker from discarding wxStockGDIMac
72 wxFORCE_LINK_MODULE(gdiobj)
73
74 // statics for implementation
75 static bool s_inYield = false;
76 static bool s_inReceiveEvent = false ;
77 static EventTime sleepTime = kEventDurationNoWait ;
78
79
80 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
81 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
82 EVT_IDLE(wxApp::OnIdle)
83 EVT_END_SESSION(wxApp::OnEndSession)
84 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
85 END_EVENT_TABLE()
86
87
88 // platform specific static variables
89 static const short kwxMacAppleMenuId = 1 ;
90
91 wxWindow* wxApp::s_captureWindow = NULL ;
92 long wxApp::s_lastModifiers = 0 ;
93
94 long wxApp::s_macAboutMenuItemId = wxID_ABOUT ;
95 long wxApp::s_macPreferencesMenuItemId = wxID_PREFERENCES ;
96 long wxApp::s_macExitMenuItemId = wxID_EXIT ;
97 wxString wxApp::s_macHelpMenuTitleName = wxT("&Help") ;
98
99 bool wxApp::sm_isEmbedded = false; // Normally we're not a plugin
100
101 //----------------------------------------------------------------------
102 // Core Apple Event Support
103 //----------------------------------------------------------------------
104
105 pascal OSErr AEHandleODoc( const AppleEvent *event , AppleEvent *reply , SRefCon refcon ) ;
106 pascal OSErr AEHandleOApp( const AppleEvent *event , AppleEvent *reply , SRefCon refcon ) ;
107 pascal OSErr AEHandlePDoc( const AppleEvent *event , AppleEvent *reply , SRefCon refcon ) ;
108 pascal OSErr AEHandleQuit( const AppleEvent *event , AppleEvent *reply , SRefCon refcon ) ;
109 pascal OSErr AEHandleRApp( const AppleEvent *event , AppleEvent *reply , SRefCon refcon ) ;
110
111 pascal OSErr AEHandleODoc( const AppleEvent *event , AppleEvent *reply , SRefCon WXUNUSED(refcon) )
112 {
113 return wxTheApp->MacHandleAEODoc( (AppleEvent*) event , reply) ;
114 }
115
116 pascal OSErr AEHandleOApp( const AppleEvent *event , AppleEvent *reply , SRefCon WXUNUSED(refcon) )
117 {
118 return wxTheApp->MacHandleAEOApp( (AppleEvent*) event , reply ) ;
119 }
120
121 pascal OSErr AEHandlePDoc( const AppleEvent *event , AppleEvent *reply , SRefCon WXUNUSED(refcon) )
122 {
123 return wxTheApp->MacHandleAEPDoc( (AppleEvent*) event , reply ) ;
124 }
125
126 pascal OSErr AEHandleQuit( const AppleEvent *event , AppleEvent *reply , SRefCon WXUNUSED(refcon) )
127 {
128 return wxTheApp->MacHandleAEQuit( (AppleEvent*) event , reply) ;
129 }
130
131 pascal OSErr AEHandleRApp( const AppleEvent *event , AppleEvent *reply , SRefCon WXUNUSED(refcon) )
132 {
133 return wxTheApp->MacHandleAERApp( (AppleEvent*) event , reply) ;
134 }
135
136 pascal OSErr AEHandleGURL( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
137 {
138 return wxTheApp->MacHandleAEGURL((WXEVENTREF *)event , reply) ;
139 }
140
141
142 // AEODoc Calls MacOpenFile on each of the files passed
143
144 short wxApp::MacHandleAEODoc(const WXEVENTREF event, WXEVENTREF WXUNUSED(reply))
145 {
146 AEDescList docList;
147 AEKeyword keywd;
148 DescType returnedType;
149 Size actualSize;
150 long itemsInList;
151 OSErr err;
152 short i;
153
154 err = AEGetParamDesc((AppleEvent *)event, keyDirectObject, typeAEList,&docList);
155 if (err != noErr)
156 return err;
157
158 err = AECountItems(&docList, &itemsInList);
159 if (err != noErr)
160 return err;
161
162 ProcessSerialNumber PSN ;
163 PSN.highLongOfPSN = 0 ;
164 PSN.lowLongOfPSN = kCurrentProcess ;
165 SetFrontProcess( &PSN ) ;
166
167 wxString fName ;
168 FSRef theRef ;
169
170 for (i = 1; i <= itemsInList; i++)
171 {
172 AEGetNthPtr(
173 &docList, i, typeFSRef, &keywd, &returnedType,
174 (Ptr)&theRef, sizeof(theRef), &actualSize);
175 fName = wxMacFSRefToPath( &theRef ) ;
176
177 MacOpenFile(fName);
178 }
179
180 return noErr;
181 }
182
183 // AEODoc Calls MacOpenURL on the url passed
184
185 short wxApp::MacHandleAEGURL(const WXEVENTREF event, WXEVENTREF WXUNUSED(reply))
186 {
187 DescType returnedType;
188 Size actualSize;
189 char url[255];
190 OSErr err = AEGetParamPtr((AppleEvent *)event, keyDirectObject, typeChar,
191 &returnedType, url, sizeof(url)-1,
192 &actualSize);
193 if (err != noErr)
194 return err;
195
196 url[actualSize] = '\0'; // Terminate the C string
197
198 ProcessSerialNumber PSN ;
199 PSN.highLongOfPSN = 0 ;
200 PSN.lowLongOfPSN = kCurrentProcess ;
201 SetFrontProcess( &PSN ) ;
202
203 MacOpenURL(wxString(url, wxConvUTF8));
204
205 return noErr;
206 }
207
208 // AEPDoc Calls MacPrintFile on each of the files passed
209
210 short wxApp::MacHandleAEPDoc(const WXEVENTREF event , WXEVENTREF WXUNUSED(reply))
211 {
212 AEDescList docList;
213 AEKeyword keywd;
214 DescType returnedType;
215 Size actualSize;
216 long itemsInList;
217 OSErr err;
218 short i;
219
220 err = AEGetParamDesc((AppleEvent *)event, keyDirectObject, typeAEList,&docList);
221 if (err != noErr)
222 return err;
223
224 err = AECountItems(&docList, &itemsInList);
225 if (err != noErr)
226 return err;
227
228 ProcessSerialNumber PSN ;
229 PSN.highLongOfPSN = 0 ;
230 PSN.lowLongOfPSN = kCurrentProcess ;
231 SetFrontProcess( &PSN ) ;
232
233 wxString fName ;
234 FSRef theRef ;
235
236 for (i = 1; i <= itemsInList; i++)
237 {
238 AEGetNthPtr(
239 &docList, i, typeFSRef, &keywd, &returnedType,
240 (Ptr)&theRef, sizeof(theRef), &actualSize);
241 fName = wxMacFSRefToPath( &theRef ) ;
242
243 MacPrintFile(fName);
244 }
245
246 return noErr;
247 }
248
249 // AEOApp calls MacNewFile
250
251 short wxApp::MacHandleAEOApp(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
252 {
253 MacNewFile() ;
254 return noErr ;
255 }
256
257 // AEQuit attempts to quit the application
258
259 short wxApp::MacHandleAEQuit(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
260 {
261 wxWindow* win = GetTopWindow() ;
262 if ( win )
263 {
264 wxCommandEvent exitEvent(wxEVT_COMMAND_MENU_SELECTED, s_macExitMenuItemId);
265 if (!win->ProcessEvent(exitEvent))
266 win->Close(true) ;
267 }
268 else
269 {
270 ExitMainLoop() ;
271 }
272
273 return noErr ;
274 }
275
276 // AEROApp calls MacReopenApp
277
278 short wxApp::MacHandleAERApp(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
279 {
280 MacReopenApp() ;
281
282 return noErr ;
283 }
284
285 //----------------------------------------------------------------------
286 // Support Routines linking the Mac...File Calls to the Document Manager
287 //----------------------------------------------------------------------
288
289 void wxApp::MacOpenFile(const wxString & fileName )
290 {
291 #if wxUSE_DOC_VIEW_ARCHITECTURE
292 wxDocManager* dm = wxDocManager::GetDocumentManager() ;
293 if ( dm )
294 dm->CreateDocument(fileName , wxDOC_SILENT ) ;
295 #endif
296 }
297
298 void wxApp::MacOpenURL(const wxString & url )
299 {
300 }
301
302 void wxApp::MacPrintFile(const wxString & fileName )
303 {
304 #if wxUSE_DOC_VIEW_ARCHITECTURE
305
306 #if wxUSE_PRINTING_ARCHITECTURE
307 wxDocManager* dm = wxDocManager::GetDocumentManager() ;
308 if ( dm )
309 {
310 wxDocument *doc = dm->CreateDocument(fileName , wxDOC_SILENT ) ;
311 if ( doc )
312 {
313 wxView* view = doc->GetFirstView() ;
314 if ( view )
315 {
316 wxPrintout *printout = view->OnCreatePrintout();
317 if (printout)
318 {
319 wxPrinter printer;
320 printer.Print(view->GetFrame(), printout, true);
321 delete printout;
322 }
323 }
324
325 if (doc->Close())
326 {
327 doc->DeleteAllViews();
328 dm->RemoveDocument(doc) ;
329 }
330 }
331 }
332 #endif //print
333
334 #endif //docview
335 }
336
337
338
339 void wxApp::MacNewFile()
340 {
341 }
342
343 void wxApp::MacReopenApp()
344 {
345 // HIG says :
346 // if there is no open window -> create a new one
347 // if all windows are hidden -> show the first
348 // if some windows are not hidden -> do nothing
349
350 wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst();
351 if ( node == NULL )
352 {
353 MacNewFile() ;
354 }
355 else
356 {
357 wxTopLevelWindow* firstIconized = NULL ;
358 while (node)
359 {
360 wxTopLevelWindow* win = (wxTopLevelWindow*) node->GetData();
361 if ( !win->IsIconized() )
362 {
363 firstIconized = NULL ;
364 break ;
365 }
366 else
367 {
368 if ( firstIconized == NULL )
369 firstIconized = win ;
370 }
371
372 node = node->GetNext();
373 }
374
375 if ( firstIconized )
376 firstIconized->Iconize( false ) ;
377 }
378 }
379
380 //----------------------------------------------------------------------
381 // Macintosh CommandID support - converting between native and wx IDs
382 //----------------------------------------------------------------------
383
384 // if no native match they just return the passed-in id
385
386 struct IdPair
387 {
388 UInt32 macId ;
389 int wxId ;
390 } ;
391
392 IdPair gCommandIds [] =
393 {
394 { kHICommandCut , wxID_CUT } ,
395 { kHICommandCopy , wxID_COPY } ,
396 { kHICommandPaste , wxID_PASTE } ,
397 { kHICommandSelectAll , wxID_SELECTALL } ,
398 { kHICommandClear , wxID_CLEAR } ,
399 { kHICommandUndo , wxID_UNDO } ,
400 { kHICommandRedo , wxID_REDO } ,
401 } ;
402
403 int wxMacCommandToId( UInt32 macCommandId )
404 {
405 int wxid = 0 ;
406
407 switch ( macCommandId )
408 {
409 case kHICommandPreferences :
410 wxid = wxApp::s_macPreferencesMenuItemId ;
411 break ;
412
413 case kHICommandQuit :
414 wxid = wxApp::s_macExitMenuItemId ;
415 break ;
416
417 case kHICommandAbout :
418 wxid = wxApp::s_macAboutMenuItemId ;
419 break ;
420
421 default :
422 {
423 for ( size_t i = 0 ; i < WXSIZEOF(gCommandIds) ; ++i )
424 {
425 if ( gCommandIds[i].macId == macCommandId )
426 {
427 wxid = gCommandIds[i].wxId ;
428 break ;
429 }
430 }
431 }
432 break ;
433 }
434
435 if ( wxid == 0 )
436 wxid = (int) macCommandId ;
437
438 return wxid ;
439 }
440
441 UInt32 wxIdToMacCommand( int wxId )
442 {
443 UInt32 macId = 0 ;
444
445 if ( wxId == wxApp::s_macPreferencesMenuItemId )
446 macId = kHICommandPreferences ;
447 else if (wxId == wxApp::s_macExitMenuItemId)
448 macId = kHICommandQuit ;
449 else if (wxId == wxApp::s_macAboutMenuItemId)
450 macId = kHICommandAbout ;
451 else
452 {
453 for ( size_t i = 0 ; i < WXSIZEOF(gCommandIds) ; ++i )
454 {
455 if ( gCommandIds[i].wxId == wxId )
456 {
457 macId = gCommandIds[i].macId ;
458 break ;
459 }
460 }
461 }
462
463 if ( macId == 0 )
464 macId = (int) wxId ;
465
466 return macId ;
467 }
468
469 wxMenu* wxFindMenuFromMacCommand( const HICommand &command , wxMenuItem* &item )
470 {
471 wxMenu* itemMenu = NULL ;
472 int id = 0 ;
473
474 // for 'standard' commands which don't have a wx-menu
475 if ( command.commandID == kHICommandPreferences || command.commandID == kHICommandQuit || command.commandID == kHICommandAbout )
476 {
477 id = wxMacCommandToId( command.commandID ) ;
478
479 wxMenuBar* mbar = wxMenuBar::MacGetInstalledMenuBar() ;
480 if ( mbar )
481 item = mbar->FindItem( id , &itemMenu ) ;
482 }
483 else if ( command.commandID != 0 && command.menu.menuRef != 0 && command.menu.menuItemIndex != 0 )
484 {
485 id = wxMacCommandToId( command.commandID ) ;
486 // make sure it is one of our own menus, or of the 'synthetic' apple and help menus , otherwise don't touch
487 MenuItemIndex firstUserHelpMenuItem ;
488 static MenuHandle helpMenuHandle = NULL ;
489 if ( helpMenuHandle == NULL )
490 {
491 if ( UMAGetHelpMenuDontCreate( &helpMenuHandle , &firstUserHelpMenuItem) != noErr )
492 helpMenuHandle = NULL ;
493 }
494
495 // is it part of the application or the Help menu, then look for the id directly
496 if ( ( GetMenuHandle( kwxMacAppleMenuId ) != NULL && command.menu.menuRef == GetMenuHandle( kwxMacAppleMenuId ) ) ||
497 ( helpMenuHandle != NULL && command.menu.menuRef == helpMenuHandle ) )
498 {
499 wxMenuBar* mbar = wxMenuBar::MacGetInstalledMenuBar() ;
500 if ( mbar )
501 item = mbar->FindItem( id , &itemMenu ) ;
502 }
503 else
504 {
505 URefCon refCon ;
506
507 GetMenuItemRefCon( command.menu.menuRef , command.menu.menuItemIndex , &refCon ) ;
508 itemMenu = wxFindMenuFromMacMenu( command.menu.menuRef ) ;
509 if ( itemMenu != NULL )
510 item = (wxMenuItem*) refCon ;
511 }
512 }
513
514 return itemMenu ;
515 }
516
517 //----------------------------------------------------------------------
518 // Carbon Event Handler
519 //----------------------------------------------------------------------
520
521 static const EventTypeSpec eventList[] =
522 {
523 { kEventClassCommand, kEventProcessCommand } ,
524 { kEventClassCommand, kEventCommandUpdateStatus } ,
525
526 { kEventClassMenu, kEventMenuOpening },
527 { kEventClassMenu, kEventMenuClosed },
528 { kEventClassMenu, kEventMenuTargetItem },
529
530 { kEventClassApplication , kEventAppActivated } ,
531 { kEventClassApplication , kEventAppDeactivated } ,
532 // handling the quit event is not recommended by apple
533 // rather using the quit apple event - which we do
534
535 { kEventClassAppleEvent , kEventAppleEvent } ,
536
537 { kEventClassMouse , kEventMouseDown } ,
538 { kEventClassMouse , kEventMouseMoved } ,
539 { kEventClassMouse , kEventMouseUp } ,
540 { kEventClassMouse , kEventMouseDragged } ,
541 { 'WXMC' , 'WXMC' }
542 } ;
543
544 static pascal OSStatus
545 wxMacAppMenuEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
546 {
547 wxMacCarbonEvent cEvent( event ) ;
548 MenuRef menuRef = cEvent.GetParameter<MenuRef>(kEventParamDirectObject) ;
549 wxMenu* menu = wxFindMenuFromMacMenu( menuRef ) ;
550
551 if ( menu )
552 {
553 wxEventType type=0;
554 MenuCommand cmd=0;
555 switch (GetEventKind(event))
556 {
557 case kEventMenuOpening:
558 type = wxEVT_MENU_OPEN;
559 break;
560
561 case kEventMenuClosed:
562 type = wxEVT_MENU_CLOSE;
563 break;
564
565 case kEventMenuTargetItem:
566 cmd = cEvent.GetParameter<MenuCommand>(kEventParamMenuCommand,typeMenuCommand) ;
567 if (cmd != 0)
568 type = wxEVT_MENU_HIGHLIGHT;
569 break;
570
571 default:
572 wxFAIL_MSG(wxT("Unexpected menu event kind"));
573 break;
574 }
575
576 if ( type )
577 {
578 wxMenuEvent wxevent(type, cmd, menu);
579 wxevent.SetEventObject(menu);
580
581 wxEvtHandler* handler = menu->GetEventHandler();
582 if (handler && handler->ProcessEvent(wxevent))
583 {
584 // handled
585 }
586 else
587 {
588 wxWindow *win = menu->GetInvokingWindow();
589 if (win)
590 win->GetEventHandler()->ProcessEvent(wxevent);
591 }
592 }
593 }
594
595 return eventNotHandledErr;
596 }
597
598 static pascal OSStatus wxMacAppCommandEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
599 {
600 OSStatus result = eventNotHandledErr ;
601
602 HICommand command ;
603
604 wxMacCarbonEvent cEvent( event ) ;
605 cEvent.GetParameter<HICommand>(kEventParamDirectObject,typeHICommand,&command) ;
606
607 wxMenuItem* item = NULL ;
608 wxMenu* itemMenu = wxFindMenuFromMacCommand( command , item ) ;
609 int id = wxMacCommandToId( command.commandID ) ;
610
611 if ( item )
612 {
613 wxASSERT( itemMenu != NULL ) ;
614
615 switch ( cEvent.GetKind() )
616 {
617 case kEventProcessCommand :
618 {
619 if (item->IsCheckable())
620 item->Check( !item->IsChecked() ) ;
621
622 if ( itemMenu->SendEvent( id , item->IsCheckable() ? item->IsChecked() : -1 ) )
623 result = noErr ;
624 }
625 break ;
626
627 case kEventCommandUpdateStatus:
628 {
629 wxUpdateUIEvent event(id);
630 event.SetEventObject( itemMenu );
631
632 bool processed = false;
633
634 // Try the menu's event handler
635 {
636 wxEvtHandler *handler = itemMenu->GetEventHandler();
637 if ( handler )
638 processed = handler->ProcessEvent(event);
639 }
640
641 // Try the window the menu was popped up from
642 // (and up through the hierarchy)
643 if ( !processed )
644 {
645 const wxMenuBase *menu = itemMenu;
646 while ( menu )
647 {
648 wxWindow *win = menu->GetInvokingWindow();
649 if ( win )
650 {
651 processed = win->GetEventHandler()->ProcessEvent(event);
652 break;
653 }
654
655 menu = menu->GetParent();
656 }
657 }
658
659 if ( processed )
660 {
661 // if anything changed, update the changed attribute
662 if (event.GetSetText())
663 itemMenu->SetLabel(id, event.GetText());
664 if (event.GetSetChecked())
665 itemMenu->Check(id, event.GetChecked());
666 if (event.GetSetEnabled())
667 itemMenu->Enable(id, event.GetEnabled());
668
669 result = noErr ;
670 }
671 }
672 break ;
673
674 default :
675 break ;
676 }
677 }
678 return result ;
679 }
680
681 static pascal OSStatus wxMacAppApplicationEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
682 {
683 OSStatus result = eventNotHandledErr ;
684 switch ( GetEventKind( event ) )
685 {
686 case kEventAppActivated :
687 if ( wxTheApp )
688 wxTheApp->SetActive( true , NULL ) ;
689 result = noErr ;
690 break ;
691
692 case kEventAppDeactivated :
693 if ( wxTheApp )
694 wxTheApp->SetActive( false , NULL ) ;
695 result = noErr ;
696 break ;
697
698 default :
699 break ;
700 }
701
702 return result ;
703 }
704
705 pascal OSStatus wxMacAppEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
706 {
707 EventRef formerEvent = (EventRef) wxTheApp->MacGetCurrentEvent() ;
708 EventHandlerCallRef formerEventHandlerCallRef = (EventHandlerCallRef) wxTheApp->MacGetCurrentEventHandlerCallRef() ;
709 wxTheApp->MacSetCurrentEvent( event , handler ) ;
710
711 OSStatus result = eventNotHandledErr ;
712 switch ( GetEventClass( event ) )
713 {
714 case kEventClassCommand :
715 result = wxMacAppCommandEventHandler( handler , event , data ) ;
716 break ;
717
718 case kEventClassApplication :
719 result = wxMacAppApplicationEventHandler( handler , event , data ) ;
720 break ;
721
722 case kEventClassMenu :
723 result = wxMacAppMenuEventHandler( handler , event , data ) ;
724 break ;
725
726 case kEventClassMouse :
727 {
728 wxMacCarbonEvent cEvent( event ) ;
729
730 WindowRef window ;
731 Point screenMouseLocation = cEvent.GetParameter<Point>(kEventParamMouseLocation) ;
732 ::FindWindow(screenMouseLocation, &window);
733 // only send this event in case it had not already been sent to a tlw, as we get
734 // double events otherwise (in case event.skip) was called
735 if ( window == NULL )
736 result = wxMacTopLevelMouseEventHandler( handler , event , NULL ) ;
737 }
738 break ;
739
740 case kEventClassAppleEvent :
741 {
742 EventRecord rec ;
743
744 wxMacConvertEventToRecord( event , &rec ) ;
745 result = AEProcessAppleEvent( &rec ) ;
746 }
747 break ;
748
749 default :
750 break ;
751 }
752
753 wxTheApp->MacSetCurrentEvent( formerEvent, formerEventHandlerCallRef ) ;
754
755 return result ;
756 }
757
758 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler )
759
760 #ifdef __WXDEBUG__
761
762 pascal static void wxMacAssertOutputHandler(OSType componentSignature, UInt32 options,
763 const char *assertionString, const char *exceptionLabelString,
764 const char *errorString, const char *fileName, long lineNumber, void *value, ConstStr255Param outputMsg)
765 {
766 // flow into assert handling
767 wxString fileNameStr ;
768 wxString assertionStr ;
769 wxString exceptionStr ;
770 wxString errorStr ;
771
772 #if wxUSE_UNICODE
773 fileNameStr = wxString(fileName, wxConvLocal);
774 assertionStr = wxString(assertionString, wxConvLocal);
775 exceptionStr = wxString((exceptionLabelString!=0) ? exceptionLabelString : "", wxConvLocal) ;
776 errorStr = wxString((errorString!=0) ? errorString : "", wxConvLocal) ;
777 #else
778 fileNameStr = fileName;
779 assertionStr = assertionString;
780 exceptionStr = (exceptionLabelString!=0) ? exceptionLabelString : "" ;
781 errorStr = (errorString!=0) ? errorString : "" ;
782 #endif
783
784 #if 1
785 // flow into log
786 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
787 assertionStr.c_str() ,
788 exceptionStr.c_str() ,
789 errorStr.c_str(),
790 fileNameStr.c_str(), lineNumber ,
791 value ) ;
792 #else
793
794 wxOnAssert(fileNameStr, lineNumber , assertionStr ,
795 wxString::Format( wxT("%s %s value (%p)") , exceptionStr, errorStr , value ) ) ;
796 #endif
797 }
798
799 #endif //__WXDEBUG__
800
801 #ifdef __WXMAC_OSX__
802 extern "C"
803 {
804 // m_macEventPosted run loop source callback:
805 void macPostedEventCallback(void *unused);
806 }
807
808 void macPostedEventCallback(void *unused)
809 {
810 wxTheApp->ProcessPendingEvents();
811 }
812 #endif
813
814 bool wxApp::Initialize(int& argc, wxChar **argv)
815 {
816 // Mac-specific
817
818 #ifdef __WXDEBUG__
819 InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler ) );
820 #endif
821
822 UMAInitToolbox( 4, sm_isEmbedded ) ;
823 SetEventMask( everyEvent ) ;
824 UMAShowWatchCursor() ;
825
826 #ifndef __DARWIN__
827 # if __option(profile)
828 ProfilerInit( collectDetailed, bestTimeBase , 40000 , 50 ) ;
829 # endif
830 #endif
831
832 #ifndef __DARWIN__
833 // now avoid exceptions thrown for new (bad_alloc)
834 // FIXME CS for some changes outside wxMac does not compile anymore
835 #if 0
836 std::__throws_bad_alloc = 0 ;
837 #endif
838
839 #endif
840
841 // Mac OS X passes a process serial number command line argument when
842 // the application is launched from the Finder. This argument must be
843 // removed from the command line arguments before being handled by the
844 // application (otherwise applications would need to handle it)
845 if ( argc > 1 )
846 {
847 static const wxChar *ARG_PSN = _T("-psn_");
848 if ( wxStrncmp(argv[1], ARG_PSN, wxStrlen(ARG_PSN)) == 0 )
849 {
850 // remove this argument
851 --argc;
852 memmove(argv + 1, argv + 2, argc * sizeof(char *));
853 }
854 }
855
856 if ( !wxAppBase::Initialize(argc, argv) )
857 return false;
858
859 #if wxUSE_INTL
860 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
861 #endif
862
863 #if TARGET_API_MAC_OSX
864 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
865 wxString startupCwd = wxGetCwd() ;
866 if ( startupCwd == wxT("/") || startupCwd.Right(15) == wxT("/Contents/MacOS") )
867 {
868 CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
869 CFURLRef urlParent = CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault , url ) ;
870 CFRelease( url ) ;
871 CFStringRef path = CFURLCopyFileSystemPath ( urlParent , kCFURLPOSIXPathStyle ) ;
872 CFRelease( urlParent ) ;
873 wxString cwd = wxMacCFStringHolder(path).AsString(wxLocale::GetSystemEncoding());
874 wxSetWorkingDirectory( cwd ) ;
875 }
876 #endif
877
878 wxMacCreateNotifierTable() ;
879
880 #ifdef __WXMAC_OSX__
881 /* connect posted events to common-mode run loop so that wxPostEvent events
882 are handled even while we're in the menu or on a scrollbar */
883 CFRunLoopSourceContext event_posted_context = {0};
884 event_posted_context.perform = macPostedEventCallback;
885 m_macEventPosted = CFRunLoopSourceCreate(NULL,0,&event_posted_context);
886 CFRunLoopAddSource(CFRunLoopGetCurrent(), m_macEventPosted, kCFRunLoopCommonModes);
887 // run loop takes ownership
888 CFRelease(m_macEventPosted);
889 #endif
890
891 UMAShowArrowCursor() ;
892
893 return true;
894 }
895
896 AEEventHandlerUPP sODocHandler = NULL ;
897 AEEventHandlerUPP sGURLHandler = NULL ;
898 AEEventHandlerUPP sOAppHandler = NULL ;
899 AEEventHandlerUPP sPDocHandler = NULL ;
900 AEEventHandlerUPP sRAppHandler = NULL ;
901 AEEventHandlerUPP sQuitHandler = NULL ;
902
903 bool wxApp::OnInitGui()
904 {
905 if ( !wxAppBase::OnInitGui() )
906 return false ;
907
908 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
909
910 if (!sm_isEmbedded)
911 {
912 InstallApplicationEventHandler(
913 GetwxMacAppEventHandlerUPP(),
914 GetEventTypeCount(eventList), eventList, wxTheApp, (EventHandlerRef *)&(wxTheApp->m_macEventHandler));
915 }
916
917 if (!sm_isEmbedded)
918 {
919 sODocHandler = NewAEEventHandlerUPP(AEHandleODoc) ;
920 sGURLHandler = NewAEEventHandlerUPP(AEHandleGURL) ;
921 sOAppHandler = NewAEEventHandlerUPP(AEHandleOApp) ;
922 sPDocHandler = NewAEEventHandlerUPP(AEHandlePDoc) ;
923 sRAppHandler = NewAEEventHandlerUPP(AEHandleRApp) ;
924 sQuitHandler = NewAEEventHandlerUPP(AEHandleQuit) ;
925
926 AEInstallEventHandler( kCoreEventClass , kAEOpenDocuments ,
927 sODocHandler , 0 , FALSE ) ;
928 AEInstallEventHandler( kInternetEventClass, kAEGetURL,
929 sGURLHandler , 0 , FALSE ) ;
930 AEInstallEventHandler( kCoreEventClass , kAEOpenApplication ,
931 sOAppHandler , 0 , FALSE ) ;
932 AEInstallEventHandler( kCoreEventClass , kAEPrintDocuments ,
933 sPDocHandler , 0 , FALSE ) ;
934 AEInstallEventHandler( kCoreEventClass , kAEReopenApplication ,
935 sRAppHandler , 0 , FALSE ) ;
936 AEInstallEventHandler( kCoreEventClass , kAEQuitApplication ,
937 sQuitHandler , 0 , FALSE ) ;
938 }
939
940 return true ;
941 }
942
943 void wxApp::CleanUp()
944 {
945 #if wxUSE_TOOLTIPS
946 wxToolTip::RemoveToolTips() ;
947 #endif
948
949 #ifdef __WXMAC_OSX__
950 if (m_macEventPosted)
951 {
952 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m_macEventPosted, kCFRunLoopCommonModes);
953 m_macEventPosted = NULL;
954 }
955 #endif
956
957 // One last chance for pending objects to be cleaned up
958 wxTheApp->DeletePendingObjects();
959
960 wxMacDestroyNotifierTable() ;
961
962 #ifndef __DARWIN__
963 # if __option(profile)
964 ProfilerDump( (StringPtr)"\papp.prof" ) ;
965 ProfilerTerm() ;
966 # endif
967 #endif
968
969 UMACleanupToolbox() ;
970
971 if (!sm_isEmbedded)
972 RemoveEventHandler( (EventHandlerRef)(wxTheApp->m_macEventHandler) );
973
974 if (!sm_isEmbedded)
975 {
976 AERemoveEventHandler( kCoreEventClass , kAEOpenDocuments ,
977 sODocHandler , FALSE ) ;
978 AERemoveEventHandler( kInternetEventClass, kAEGetURL,
979 sGURLHandler , FALSE ) ;
980 AERemoveEventHandler( kCoreEventClass , kAEOpenApplication ,
981 sOAppHandler , FALSE ) ;
982 AERemoveEventHandler( kCoreEventClass , kAEPrintDocuments ,
983 sPDocHandler , FALSE ) ;
984 AERemoveEventHandler( kCoreEventClass , kAEReopenApplication ,
985 sRAppHandler , FALSE ) ;
986 AERemoveEventHandler( kCoreEventClass , kAEQuitApplication ,
987 sQuitHandler , FALSE ) ;
988
989 DisposeAEEventHandlerUPP( sODocHandler ) ;
990 DisposeAEEventHandlerUPP( sGURLHandler ) ;
991 DisposeAEEventHandlerUPP( sOAppHandler ) ;
992 DisposeAEEventHandlerUPP( sPDocHandler ) ;
993 DisposeAEEventHandlerUPP( sRAppHandler ) ;
994 DisposeAEEventHandlerUPP( sQuitHandler ) ;
995 }
996
997 wxAppBase::CleanUp();
998 }
999
1000 //----------------------------------------------------------------------
1001 // misc initialization stuff
1002 //----------------------------------------------------------------------
1003
1004 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
1005
1006 // for shared libraries we have to manually get the correct resource
1007 // ref num upon initializing and releasing when terminating, therefore
1008 // the __wxinitialize and __wxterminate must be used
1009
1010 extern "C"
1011 {
1012 void __sinit(void); // (generated by linker)
1013 pascal OSErr __initialize(const CFragInitBlock *theInitBlock);
1014 pascal void __terminate(void);
1015 }
1016
1017 pascal OSErr __wxinitialize(const CFragInitBlock *theInitBlock)
1018 {
1019 return __initialize( theInitBlock ) ;
1020 }
1021
1022 pascal void __wxterminate(void)
1023 {
1024 __terminate() ;
1025 }
1026
1027 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
1028
1029 bool wxMacConvertEventToRecord( EventRef event , EventRecord *rec)
1030 {
1031 OSStatus err = noErr ;
1032 bool converted = ConvertEventRefToEventRecord( event, rec) ;
1033
1034 if ( !converted )
1035 {
1036 switch ( GetEventClass( event ) )
1037 {
1038 case kEventClassKeyboard :
1039 {
1040 converted = true ;
1041 switch ( GetEventKind(event) )
1042 {
1043 case kEventRawKeyDown :
1044 rec->what = keyDown ;
1045 break ;
1046
1047 case kEventRawKeyRepeat :
1048 rec->what = autoKey ;
1049 break ;
1050
1051 case kEventRawKeyUp :
1052 rec->what = keyUp ;
1053 break ;
1054
1055 case kEventRawKeyModifiersChanged :
1056 rec->what = nullEvent ;
1057 break ;
1058
1059 default :
1060 converted = false ;
1061 break ;
1062 }
1063
1064 if ( converted )
1065 {
1066 UInt32 keyCode ;
1067 unsigned char charCode ;
1068 UInt32 modifiers ;
1069 #ifndef __LP64__
1070 GetMouse( &rec->where) ;
1071 #endif
1072 err = GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL, 4, NULL, &modifiers);
1073 err = GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL, 4, NULL, &keyCode);
1074 err = GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL, 1, NULL, &charCode);
1075 rec->modifiers = modifiers ;
1076 rec->message = (keyCode << 8 ) + charCode ;
1077 }
1078 }
1079 break ;
1080
1081 case kEventClassTextInput :
1082 {
1083 switch ( GetEventKind( event ) )
1084 {
1085 case kEventTextInputUnicodeForKeyEvent :
1086 {
1087 EventRef rawEvent ;
1088 err = GetEventParameter(
1089 event, kEventParamTextInputSendKeyboardEvent, typeEventRef, NULL,
1090 sizeof(rawEvent), NULL, &rawEvent ) ;
1091 converted = true ;
1092
1093 {
1094 UInt32 keyCode, modifiers;
1095 unsigned char charCode ;
1096 #ifndef __LP64__
1097
1098 GetMouse( &rec->where) ;
1099 #endif
1100 rec->what = keyDown ;
1101 err = GetEventParameter(rawEvent, kEventParamKeyModifiers, typeUInt32, NULL, 4, NULL, &modifiers);
1102 err = GetEventParameter(rawEvent, kEventParamKeyCode, typeUInt32, NULL, 4, NULL, &keyCode);
1103 err = GetEventParameter(rawEvent, kEventParamKeyMacCharCodes, typeChar, NULL, 1, NULL, &charCode);
1104 rec->modifiers = modifiers ;
1105 rec->message = (keyCode << 8 ) + charCode ;
1106 }
1107 }
1108 break ;
1109
1110 default :
1111 break ;
1112 }
1113 }
1114 break ;
1115
1116 default :
1117 break ;
1118 }
1119 }
1120
1121 return converted ;
1122 }
1123
1124 wxApp::wxApp()
1125 {
1126 m_printMode = wxPRINT_WINDOWS;
1127
1128 m_macCurrentEvent = NULL ;
1129 m_macCurrentEventHandlerCallRef = NULL ;
1130
1131 #ifdef __WXMAC_OSX__
1132 m_macEventPosted = NULL ;
1133 #endif
1134 }
1135
1136 void wxApp::OnIdle(wxIdleEvent& event)
1137 {
1138 wxAppBase::OnIdle(event);
1139
1140 // If they are pending events, we must process them: pending events are
1141 // either events to the threads other than main or events posted with
1142 // wxPostEvent() functions
1143 wxMacProcessNotifierAndPendingEvents();
1144
1145 if (!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1146 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1147 }
1148
1149 void wxApp::WakeUpIdle()
1150 {
1151 #ifdef __WXMAC_OSX__
1152 if (m_macEventPosted)
1153 {
1154 CFRunLoopSourceSignal(m_macEventPosted);
1155 }
1156 #endif
1157
1158 wxMacWakeUp() ;
1159 }
1160
1161 void wxApp::OnEndSession(wxCloseEvent& WXUNUSED(event))
1162 {
1163 if (GetTopWindow())
1164 GetTopWindow()->Close(true);
1165 }
1166
1167 // Default behaviour: close the application with prompts. The
1168 // user can veto the close, and therefore the end session.
1169 void wxApp::OnQueryEndSession(wxCloseEvent& event)
1170 {
1171 if (GetTopWindow())
1172 {
1173 if (!GetTopWindow()->Close(!event.CanVeto()))
1174 event.Veto(true);
1175 }
1176 }
1177
1178 extern "C" void wxCYield() ;
1179 void wxCYield()
1180 {
1181 wxYield() ;
1182 }
1183
1184 // Yield to other processes
1185
1186 bool wxApp::Yield(bool onlyIfNeeded)
1187 {
1188 if (s_inYield)
1189 {
1190 if ( !onlyIfNeeded )
1191 {
1192 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1193 }
1194
1195 return false;
1196 }
1197
1198 s_inYield = true;
1199
1200 // by definition yield should handle all non-processed events
1201
1202 EventRef theEvent;
1203
1204 OSStatus status = noErr ;
1205
1206 while ( status == noErr )
1207 {
1208 s_inReceiveEvent = true ;
1209 status = ReceiveNextEvent(0, NULL,kEventDurationNoWait,true,&theEvent) ;
1210 s_inReceiveEvent = false ;
1211
1212 if ( status == eventLoopTimedOutErr )
1213 {
1214 // make sure next time the event loop will trigger idle events
1215 sleepTime = kEventDurationNoWait ;
1216 }
1217 else if ( status == eventLoopQuitErr )
1218 {
1219 // according to QA1061 this may also occur when a WakeUp Process
1220 // is executed
1221 }
1222 else
1223 {
1224 MacHandleOneEvent( theEvent ) ;
1225 ReleaseEvent(theEvent);
1226 }
1227 }
1228
1229 wxMacProcessNotifierAndPendingEvents() ;
1230 s_inYield = false;
1231
1232 return true;
1233 }
1234
1235 void wxApp::MacDoOneEvent()
1236 {
1237 EventRef theEvent;
1238
1239 s_inReceiveEvent = true ;
1240 OSStatus status = ReceiveNextEvent(0, NULL, sleepTime, true, &theEvent) ;
1241 s_inReceiveEvent = false ;
1242
1243 switch (status)
1244 {
1245 case eventLoopTimedOutErr :
1246 if ( wxTheApp->ProcessIdle() )
1247 sleepTime = kEventDurationNoWait ;
1248 else
1249 sleepTime = kEventDurationSecond;
1250 break;
1251
1252 case eventLoopQuitErr :
1253 // according to QA1061 this may also occur
1254 // when a WakeUp Process is executed
1255 break;
1256
1257 default:
1258 MacHandleOneEvent( theEvent ) ;
1259 ReleaseEvent( theEvent );
1260 sleepTime = kEventDurationNoWait ;
1261 break;
1262 }
1263 // repeaters
1264
1265 DeletePendingObjects() ;
1266 wxMacProcessNotifierAndPendingEvents() ;
1267 }
1268
1269 // virtual
1270 void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr )
1271 {
1272 // Override to process unhandled events as you please
1273 }
1274
1275 CFMutableArrayRef GetAutoReleaseArray()
1276 {
1277 static CFMutableArrayRef array = 0;
1278 if ( array == 0)
1279 array= CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
1280 return array;
1281 }
1282
1283 void wxApp::MacHandleOneEvent( WXEVENTREF evr )
1284 {
1285 EventTargetRef theTarget;
1286 theTarget = GetEventDispatcherTarget();
1287 m_macCurrentEvent = evr ;
1288
1289 OSStatus status = SendEventToEventTarget((EventRef) evr , theTarget);
1290 if (status == eventNotHandledErr)
1291 MacHandleUnhandledEvent(evr);
1292
1293 wxMacProcessNotifierAndPendingEvents() ;
1294
1295 #if wxUSE_THREADS
1296 wxMutexGuiLeaveOrEnter();
1297 #endif // wxUSE_THREADS
1298
1299 CFArrayRemoveAllValues( GetAutoReleaseArray() );
1300 }
1301
1302 void wxApp::MacAddToAutorelease( void* cfrefobj )
1303 {
1304 CFArrayAppendValue( GetAutoReleaseArray(), cfrefobj );
1305 }
1306
1307 long wxMacTranslateKey(unsigned char key, unsigned char code)
1308 {
1309 long retval = key ;
1310 switch (key)
1311 {
1312 case kHomeCharCode :
1313 retval = WXK_HOME;
1314 break;
1315
1316 case kEnterCharCode :
1317 retval = WXK_RETURN;
1318 break;
1319 case kEndCharCode :
1320 retval = WXK_END;
1321 break;
1322
1323 case kHelpCharCode :
1324 retval = WXK_HELP;
1325 break;
1326
1327 case kBackspaceCharCode :
1328 retval = WXK_BACK;
1329 break;
1330
1331 case kTabCharCode :
1332 retval = WXK_TAB;
1333 break;
1334
1335 case kPageUpCharCode :
1336 retval = WXK_PAGEUP;
1337 break;
1338
1339 case kPageDownCharCode :
1340 retval = WXK_PAGEDOWN;
1341 break;
1342
1343 case kReturnCharCode :
1344 retval = WXK_RETURN;
1345 break;
1346
1347 case kFunctionKeyCharCode :
1348 {
1349 switch ( code )
1350 {
1351 case 0x7a :
1352 retval = WXK_F1 ;
1353 break;
1354
1355 case 0x78 :
1356 retval = WXK_F2 ;
1357 break;
1358
1359 case 0x63 :
1360 retval = WXK_F3 ;
1361 break;
1362
1363 case 0x76 :
1364 retval = WXK_F4 ;
1365 break;
1366
1367 case 0x60 :
1368 retval = WXK_F5 ;
1369 break;
1370
1371 case 0x61 :
1372 retval = WXK_F6 ;
1373 break;
1374
1375 case 0x62:
1376 retval = WXK_F7 ;
1377 break;
1378
1379 case 0x64 :
1380 retval = WXK_F8 ;
1381 break;
1382
1383 case 0x65 :
1384 retval = WXK_F9 ;
1385 break;
1386
1387 case 0x6D :
1388 retval = WXK_F10 ;
1389 break;
1390
1391 case 0x67 :
1392 retval = WXK_F11 ;
1393 break;
1394
1395 case 0x6F :
1396 retval = WXK_F12 ;
1397 break;
1398
1399 case 0x69 :
1400 retval = WXK_F13 ;
1401 break;
1402
1403 case 0x6B :
1404 retval = WXK_F14 ;
1405 break;
1406
1407 case 0x71 :
1408 retval = WXK_F15 ;
1409 break;
1410
1411 default:
1412 break;
1413 }
1414 }
1415 break ;
1416
1417 case kEscapeCharCode :
1418 retval = WXK_ESCAPE ;
1419 break ;
1420
1421 case kLeftArrowCharCode :
1422 retval = WXK_LEFT ;
1423 break ;
1424
1425 case kRightArrowCharCode :
1426 retval = WXK_RIGHT ;
1427 break ;
1428
1429 case kUpArrowCharCode :
1430 retval = WXK_UP ;
1431 break ;
1432
1433 case kDownArrowCharCode :
1434 retval = WXK_DOWN ;
1435 break ;
1436
1437 case kDeleteCharCode :
1438 retval = WXK_DELETE ;
1439 break ;
1440
1441 default:
1442 break ;
1443 } // end switch
1444
1445 return retval;
1446 }
1447
1448 int wxMacKeyCodeToModifier(wxKeyCode key)
1449 {
1450 switch (key)
1451 {
1452 case WXK_START:
1453 case WXK_MENU:
1454 return cmdKey;
1455
1456 case WXK_SHIFT:
1457 return shiftKey;
1458
1459 case WXK_CAPITAL:
1460 return alphaLock;
1461
1462 case WXK_ALT:
1463 return optionKey;
1464
1465 case WXK_CONTROL:
1466 return controlKey;
1467
1468 default:
1469 return 0;
1470 }
1471 }
1472
1473 #ifndef __DARWIN__
1474 bool wxGetKeyState(wxKeyCode key) //virtual key code if < 10.2.x, else see below
1475 {
1476 wxASSERT_MSG(key != WXK_LBUTTON && key != WXK_RBUTTON && key !=
1477 WXK_MBUTTON, wxT("can't use wxGetKeyState() for mouse buttons"));
1478
1479 //if OS X > 10.2 (i.e. 10.2.x)
1480 //a known apple bug prevents the system from determining led
1481 //states with GetKeys... can only determine caps lock led
1482 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key));
1483 //else
1484 // KeyMapByteArray keymap;
1485 // GetKeys((BigEndianLong*)keymap);
1486 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1487 }
1488 #endif
1489
1490
1491 wxMouseState wxGetMouseState()
1492 {
1493 wxMouseState ms;
1494
1495 wxPoint pt = wxGetMousePosition();
1496 ms.SetX(pt.x);
1497 ms.SetY(pt.y);
1498
1499 #if TARGET_API_MAC_OSX
1500 UInt32 buttons = GetCurrentButtonState();
1501 ms.SetLeftDown( (buttons & 0x01) != 0 );
1502 ms.SetMiddleDown( (buttons & 0x04) != 0 );
1503 ms.SetRightDown( (buttons & 0x02) != 0 );
1504 #else
1505 ms.SetLeftDown( Button() );
1506 ms.SetMiddleDown( 0 );
1507 ms.SetRightDown( 0 );
1508 #endif
1509
1510 UInt32 modifiers = GetCurrentKeyModifiers();
1511 ms.SetControlDown(modifiers & controlKey);
1512 ms.SetShiftDown(modifiers & shiftKey);
1513 ms.SetAltDown(modifiers & optionKey);
1514 ms.SetMetaDown(modifiers & cmdKey);
1515
1516 return ms;
1517 }
1518
1519 // TODO : once the new key/char handling is tested, move all the code to wxWindow
1520
1521 bool wxApp::MacSendKeyDownEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey , wxChar uniChar )
1522 {
1523 if ( !focus )
1524 return false ;
1525
1526 bool handled;
1527 wxKeyEvent event(wxEVT_KEY_DOWN) ;
1528 MacCreateKeyEvent( event, focus , keymessage , modifiers , when , wherex , wherey , uniChar ) ;
1529
1530 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1531 if ( handled && event.GetSkipped() )
1532 handled = false ;
1533
1534 #if wxUSE_ACCEL
1535 if ( !handled )
1536 {
1537 wxWindow *ancestor = focus;
1538 while (ancestor)
1539 {
1540 int command = ancestor->GetAcceleratorTable()->GetCommand( event );
1541 if (command != -1)
1542 {
1543 wxEvtHandler * const handler = ancestor->GetEventHandler();
1544
1545 wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1546 handled = handler->ProcessEvent( command_event );
1547
1548 if ( !handled )
1549 {
1550 // accelerators can also be used with buttons, try them too
1551 command_event.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED);
1552 handled = handler->ProcessEvent( command_event );
1553 }
1554
1555 break;
1556 }
1557
1558 if (ancestor->IsTopLevel())
1559 break;
1560
1561 ancestor = ancestor->GetParent();
1562 }
1563 }
1564 #endif // wxUSE_ACCEL
1565
1566 return handled ;
1567 }
1568
1569 bool wxApp::MacSendKeyUpEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey , wxChar uniChar )
1570 {
1571 if ( !focus )
1572 return false ;
1573
1574 bool handled;
1575 wxKeyEvent event( wxEVT_KEY_UP ) ;
1576 MacCreateKeyEvent( event, focus , keymessage , modifiers , when , wherex , wherey , uniChar ) ;
1577 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1578
1579 return handled ;
1580 }
1581
1582 bool wxApp::MacSendCharEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey , wxChar uniChar )
1583 {
1584 if ( !focus )
1585 return false ;
1586
1587 wxKeyEvent event(wxEVT_CHAR) ;
1588 MacCreateKeyEvent( event, focus , keymessage , modifiers , when , wherex , wherey , uniChar ) ;
1589 long keyval = event.m_keyCode ;
1590
1591 bool handled = false ;
1592
1593 wxTopLevelWindowMac *tlw = focus->MacGetTopLevelWindow() ;
1594
1595 if (tlw)
1596 {
1597 event.SetEventType( wxEVT_CHAR_HOOK );
1598 handled = tlw->GetEventHandler()->ProcessEvent( event );
1599 if ( handled && event.GetSkipped() )
1600 handled = false ;
1601 }
1602
1603 if ( !handled )
1604 {
1605 event.SetEventType( wxEVT_CHAR );
1606 event.Skip( false ) ;
1607 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1608 }
1609
1610 if ( !handled && (keyval == WXK_TAB) )
1611 {
1612 wxWindow* iter = focus->GetParent() ;
1613 while ( iter && !handled )
1614 {
1615 if ( iter->HasFlag( wxTAB_TRAVERSAL ) )
1616 {
1617 wxNavigationKeyEvent new_event;
1618 new_event.SetEventObject( focus );
1619 new_event.SetDirection( !event.ShiftDown() );
1620 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1621 new_event.SetWindowChange( event.ControlDown() );
1622 new_event.SetCurrentFocus( focus );
1623 handled = focus->GetParent()->GetEventHandler()->ProcessEvent( new_event );
1624 if ( handled && new_event.GetSkipped() )
1625 handled = false ;
1626 }
1627
1628 iter = iter->GetParent() ;
1629 }
1630 }
1631
1632 // backdoor handler for default return and command escape
1633 if ( !handled && (!focus->IsKindOf(CLASSINFO(wxControl) ) || !focus->MacCanFocus() ) )
1634 {
1635 // if window is not having a focus still testing for default enter or cancel
1636 // TODO: add the UMA version for ActiveNonFloatingWindow
1637 wxWindow* focus = wxFindWinFromMacWindow( FrontWindow() ) ;
1638 if ( focus )
1639 {
1640 if ( keyval == WXK_RETURN || keyval == WXK_NUMPAD_ENTER )
1641 {
1642 wxTopLevelWindow *tlw = wxDynamicCast(wxGetTopLevelParent(focus), wxTopLevelWindow);
1643 if ( tlw && tlw->GetDefaultItem() )
1644 {
1645 wxButton *def = wxDynamicCast(tlw->GetDefaultItem(), wxButton);
1646 if ( def && def->IsEnabled() )
1647 {
1648 wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, def->GetId() );
1649 event.SetEventObject(def);
1650 def->Command(event);
1651
1652 return true ;
1653 }
1654 }
1655 }
1656 else if (keyval == WXK_ESCAPE || (keyval == '.' && modifiers & cmdKey ) )
1657 {
1658 // generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs)
1659 wxCommandEvent new_event(wxEVT_COMMAND_BUTTON_CLICKED,wxID_CANCEL);
1660 new_event.SetEventObject( focus );
1661 handled = focus->GetEventHandler()->ProcessEvent( new_event );
1662 }
1663 }
1664 }
1665 return handled ;
1666 }
1667
1668 // This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
1669 void wxApp::MacCreateKeyEvent( wxKeyEvent& event, wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey , wxChar uniChar )
1670 {
1671 short keycode, keychar ;
1672
1673 keychar = short(keymessage & charCodeMask);
1674 keycode = short(keymessage & keyCodeMask) >> 8 ;
1675 if ( !(event.GetEventType() == wxEVT_CHAR) && (modifiers & (controlKey | shiftKey | optionKey) ) )
1676 {
1677 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1678 // and look at the character after
1679 UInt32 state = 0;
1680 UInt32 keyInfo = KeyTranslate((Ptr)GetScriptManagerVariable(smKCHRCache), ( modifiers & (~(controlKey | shiftKey | optionKey))) | keycode, &state);
1681 keychar = short(keyInfo & charCodeMask);
1682 }
1683
1684 long keyval = wxMacTranslateKey(keychar, keycode) ;
1685 if ( keyval == keychar && ( event.GetEventType() == wxEVT_KEY_UP || event.GetEventType() == wxEVT_KEY_DOWN ) )
1686 keyval = wxToupper( keyval ) ;
1687
1688 // Check for NUMPAD keys
1689 if (keyval >= '0' && keyval <= '9' && keycode >= 82 && keycode <= 92)
1690 {
1691 keyval = (keyval - '0') + WXK_NUMPAD0;
1692 }
1693 else if (keycode >= 67 && keycode <= 81)
1694 {
1695 switch (keycode)
1696 {
1697 case 76 :
1698 keyval = WXK_NUMPAD_ENTER;
1699 break;
1700
1701 case 81:
1702 keyval = WXK_NUMPAD_EQUAL;
1703 break;
1704
1705 case 67:
1706 keyval = WXK_NUMPAD_MULTIPLY;
1707 break;
1708
1709 case 75:
1710 keyval = WXK_NUMPAD_DIVIDE;
1711 break;
1712
1713 case 78:
1714 keyval = WXK_NUMPAD_SUBTRACT;
1715 break;
1716
1717 case 69:
1718 keyval = WXK_NUMPAD_ADD;
1719 break;
1720
1721 case 65:
1722 keyval = WXK_NUMPAD_DECIMAL;
1723 break;
1724
1725 default:
1726 break;
1727 } // end switch
1728 }
1729
1730 event.m_shiftDown = modifiers & shiftKey;
1731 event.m_controlDown = modifiers & controlKey;
1732 event.m_altDown = modifiers & optionKey;
1733 event.m_metaDown = modifiers & cmdKey;
1734 event.m_keyCode = keyval ;
1735 #if wxUSE_UNICODE
1736 event.m_uniChar = uniChar ;
1737 #endif
1738
1739 event.m_rawCode = keymessage;
1740 event.m_rawFlags = modifiers;
1741 event.m_x = wherex;
1742 event.m_y = wherey;
1743 event.SetTimestamp(when);
1744 event.SetEventObject(focus);
1745 }