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