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