1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/mac/carbon/app.cpp
4 // Author: Stefan Csomor
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
20 #include "wx/window.h"
23 #include "wx/button.h"
27 #include "wx/palette.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"
37 #include "wx/module.h"
38 #include "wx/tooltip.h"
39 #include "wx/docview.h"
40 #include "wx/filename.h"
52 // #include "apprsrc.h"
54 #include "wx/mac/uma.h"
55 #include "wx/mac/macnotfy.h"
58 # include <CoreServices/CoreServices.h>
59 # if defined(WXMAKINGDLL_CORE)
60 # include <mach-o/dyld.h>
65 # include <ToolUtils.h>
66 # include <DiskInit.h>
71 extern size_t g_numberOfThreads
;
74 // statics for implementation
75 static bool s_inYield
= false;
76 static bool s_inReceiveEvent
= false ;
77 static EventTime sleepTime
= kEventDurationNoWait
;
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
)
88 // platform specific static variables
89 const short kMacMinHeap
= (29 * 1024) ;
90 const short kwxMacMenuBarResource
= 1 ;
91 const short kwxMacAppleMenuId
= 1 ;
93 WXHRGN
wxApp::s_macCursorRgn
= NULL
;
94 wxWindow
* wxApp::s_captureWindow
= NULL
;
95 int wxApp::s_lastMouseDown
= 0 ;
96 long wxApp::sm_lastMessageTime
= 0;
97 long wxApp::s_lastModifiers
= 0 ;
99 bool wxApp::s_macSupportPCMenuShortcuts
= true ;
100 long wxApp::s_macAboutMenuItemId
= wxID_ABOUT
;
101 long wxApp::s_macPreferencesMenuItemId
= wxID_PREFERENCES
;
102 long wxApp::s_macExitMenuItemId
= wxID_EXIT
;
103 wxString
wxApp::s_macHelpMenuTitleName
= wxT("&Help") ;
105 bool wxApp::sm_isEmbedded
= false; // Normally we're not a plugin
107 //----------------------------------------------------------------------
108 // Core Apple Event Support
109 //----------------------------------------------------------------------
111 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
112 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
113 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
114 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
115 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
117 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
119 return wxTheApp
->MacHandleAEODoc( (AppleEvent
*) event
, reply
) ;
122 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
124 return wxTheApp
->MacHandleAEOApp( (AppleEvent
*) event
, reply
) ;
127 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
129 return wxTheApp
->MacHandleAEPDoc( (AppleEvent
*) event
, reply
) ;
132 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
134 return wxTheApp
->MacHandleAEQuit( (AppleEvent
*) event
, reply
) ;
137 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
139 return wxTheApp
->MacHandleAERApp( (AppleEvent
*) event
, reply
) ;
142 // AEODoc Calls MacOpenFile on each of the files passed
144 short wxApp::MacHandleAEODoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
148 DescType returnedType
;
154 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
158 err
= AECountItems(&docList
, &itemsInList
);
162 ProcessSerialNumber PSN
;
163 PSN
.highLongOfPSN
= 0 ;
164 PSN
.lowLongOfPSN
= kCurrentProcess
;
165 SetFrontProcess( &PSN
) ;
170 for (i
= 1; i
<= itemsInList
; i
++)
173 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
174 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
175 fName
= wxMacFSRefToPath( &theRef
) ;
183 // AEPDoc Calls MacPrintFile on each of the files passed
185 short wxApp::MacHandleAEPDoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
189 DescType returnedType
;
195 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
199 err
= AECountItems(&docList
, &itemsInList
);
203 ProcessSerialNumber PSN
;
204 PSN
.highLongOfPSN
= 0 ;
205 PSN
.lowLongOfPSN
= kCurrentProcess
;
206 SetFrontProcess( &PSN
) ;
211 for (i
= 1; i
<= itemsInList
; i
++)
214 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
215 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
216 fName
= wxMacFSRefToPath( &theRef
) ;
224 // AEOApp calls MacNewFile
226 short wxApp::MacHandleAEOApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
232 // AEQuit attempts to quit the application
234 short wxApp::MacHandleAEQuit(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
236 wxWindow
* win
= GetTopWindow() ;
239 wxCommandEvent
exitEvent(wxEVT_COMMAND_MENU_SELECTED
, s_macExitMenuItemId
);
240 if (!win
->ProcessEvent(exitEvent
))
251 // AEROApp calls MacReopenApp
253 short wxApp::MacHandleAERApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
260 //----------------------------------------------------------------------
261 // Support Routines linking the Mac...File Calls to the Document Manager
262 //----------------------------------------------------------------------
264 void wxApp::MacOpenFile(const wxString
& fileName
)
266 #if wxUSE_DOC_VIEW_ARCHITECTURE
267 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
269 dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
274 void wxApp::MacPrintFile(const wxString
& fileName
)
276 #if wxUSE_DOC_VIEW_ARCHITECTURE
278 #if wxUSE_PRINTING_ARCHITECTURE
279 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
282 wxDocument
*doc
= dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
285 wxView
* view
= doc
->GetFirstView() ;
288 wxPrintout
*printout
= view
->OnCreatePrintout();
292 printer
.Print(view
->GetFrame(), printout
, true);
299 doc
->DeleteAllViews();
300 dm
->RemoveDocument(doc
) ;
311 void wxApp::MacNewFile()
315 void wxApp::MacReopenApp()
318 // if there is no open window -> create a new one
319 // if all windows are hidden -> show the first
320 // if some windows are not hidden -> do nothing
322 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetFirst();
329 wxTopLevelWindow
* firstIconized
= NULL
;
332 wxTopLevelWindow
* win
= (wxTopLevelWindow
*) node
->GetData();
333 if ( !win
->IsIconized() )
335 firstIconized
= NULL
;
340 if ( firstIconized
== NULL
)
341 firstIconized
= win
;
344 node
= node
->GetNext();
348 firstIconized
->Iconize( false ) ;
352 //----------------------------------------------------------------------
353 // Macintosh CommandID support - converting between native and wx IDs
354 //----------------------------------------------------------------------
356 // if no native match they just return the passed-in id
364 IdPair gCommandIds
[] =
366 { kHICommandCut
, wxID_CUT
} ,
367 { kHICommandCopy
, wxID_COPY
} ,
368 { kHICommandPaste
, wxID_PASTE
} ,
369 { kHICommandSelectAll
, wxID_SELECTALL
} ,
370 { kHICommandClear
, wxID_CLEAR
} ,
371 { kHICommandUndo
, wxID_UNDO
} ,
372 { kHICommandRedo
, wxID_REDO
} ,
375 int wxMacCommandToId( UInt32 macCommandId
)
379 switch ( macCommandId
)
381 case kHICommandPreferences
:
382 wxid
= wxApp::s_macPreferencesMenuItemId
;
385 case kHICommandQuit
:
386 wxid
= wxApp::s_macExitMenuItemId
;
389 case kHICommandAbout
:
390 wxid
= wxApp::s_macAboutMenuItemId
;
395 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
397 if ( gCommandIds
[i
].macId
== macCommandId
)
399 wxid
= gCommandIds
[i
].wxId
;
408 wxid
= (int) macCommandId
;
413 UInt32
wxIdToMacCommand( int wxId
)
417 if ( wxId
== wxApp::s_macPreferencesMenuItemId
)
418 macId
= kHICommandPreferences
;
419 else if (wxId
== wxApp::s_macExitMenuItemId
)
420 macId
= kHICommandQuit
;
421 else if (wxId
== wxApp::s_macAboutMenuItemId
)
422 macId
= kHICommandAbout
;
425 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
427 if ( gCommandIds
[i
].wxId
== wxId
)
429 macId
= gCommandIds
[i
].macId
;
441 wxMenu
* wxFindMenuFromMacCommand( const HICommand
&command
, wxMenuItem
* &item
)
443 wxMenu
* itemMenu
= NULL
;
446 // for 'standard' commands which don't have a wx-menu
447 if ( command
.commandID
== kHICommandPreferences
|| command
.commandID
== kHICommandQuit
|| command
.commandID
== kHICommandAbout
)
449 id
= wxMacCommandToId( command
.commandID
) ;
451 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
453 item
= mbar
->FindItem( id
, &itemMenu
) ;
455 else if ( command
.commandID
!= 0 && command
.menu
.menuRef
!= 0 && command
.menu
.menuItemIndex
!= 0 )
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
;
463 if ( UMAGetHelpMenu( &mh
, &firstUserHelpMenuItem
) != noErr
)
467 // is it part of the application or the Help menu, then look for the id directly
468 if ( ( GetMenuHandle( kwxMacAppleMenuId
) != NULL
&& command
.menu
.menuRef
== GetMenuHandle( kwxMacAppleMenuId
) ) ||
469 ( mh
!= NULL
&& command
.menu
.menuRef
== mh
) )
471 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
473 item
= mbar
->FindItem( id
, &itemMenu
) ;
479 GetMenuItemRefCon( command
.menu
.menuRef
, command
.menu
.menuItemIndex
, &refCon
) ;
480 itemMenu
= wxFindMenuFromMacMenu( command
.menu
.menuRef
) ;
481 if ( itemMenu
!= NULL
)
482 item
= (wxMenuItem
*) refCon
;
489 //----------------------------------------------------------------------
490 // Carbon Event Handler
491 //----------------------------------------------------------------------
493 static const EventTypeSpec eventList
[] =
495 { kEventClassCommand
, kEventProcessCommand
} ,
496 { kEventClassCommand
, kEventCommandUpdateStatus
} ,
498 { kEventClassMenu
, kEventMenuOpening
},
499 { kEventClassMenu
, kEventMenuClosed
},
500 { kEventClassMenu
, kEventMenuTargetItem
},
502 { kEventClassApplication
, kEventAppActivated
} ,
503 { kEventClassApplication
, kEventAppDeactivated
} ,
504 // handling the quit event is not recommended by apple
505 // rather using the quit apple event - which we do
507 { kEventClassAppleEvent
, kEventAppleEvent
} ,
509 { kEventClassMouse
, kEventMouseDown
} ,
510 { kEventClassMouse
, kEventMouseMoved
} ,
511 { kEventClassMouse
, kEventMouseUp
} ,
512 { kEventClassMouse
, kEventMouseDragged
} ,
516 static pascal OSStatus
517 wxMacAppMenuEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
519 wxMacCarbonEvent
cEvent( event
) ;
520 MenuRef menuRef
= cEvent
.GetParameter
<MenuRef
>(kEventParamDirectObject
) ;
521 wxMenu
* menu
= wxFindMenuFromMacMenu( menuRef
) ;
527 switch (GetEventKind(event
))
529 case kEventMenuOpening
:
530 type
= wxEVT_MENU_OPEN
;
533 case kEventMenuClosed
:
534 type
= wxEVT_MENU_CLOSE
;
537 case kEventMenuTargetItem
:
538 cmd
= cEvent
.GetParameter
<MenuCommand
>(kEventParamMenuCommand
,typeMenuCommand
) ;
540 type
= wxEVT_MENU_HIGHLIGHT
;
544 wxFAIL_MSG(wxT("Unexpected menu event kind"));
550 wxMenuEvent
wxevent(type
, cmd
, menu
);
551 wxevent
.SetEventObject(menu
);
553 wxEvtHandler
* handler
= menu
->GetEventHandler();
554 if (handler
&& handler
->ProcessEvent(wxevent
))
560 wxWindow
*win
= menu
->GetInvokingWindow();
562 win
->GetEventHandler()->ProcessEvent(wxevent
);
567 return eventNotHandledErr
;
570 static pascal OSStatus
wxMacAppCommandEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
572 OSStatus result
= eventNotHandledErr
;
576 wxMacCarbonEvent
cEvent( event
) ;
577 cEvent
.GetParameter
<HICommand
>(kEventParamDirectObject
,typeHICommand
,&command
) ;
579 wxMenuItem
* item
= NULL
;
580 wxMenu
* itemMenu
= wxFindMenuFromMacCommand( command
, item
) ;
581 int id
= wxMacCommandToId( command
.commandID
) ;
585 wxASSERT( itemMenu
!= NULL
) ;
587 switch ( cEvent
.GetKind() )
589 case kEventProcessCommand
:
591 if (item
->IsCheckable())
592 item
->Check( !item
->IsChecked() ) ;
594 if ( itemMenu
->SendEvent( id
, item
->IsCheckable() ? item
->IsChecked() : -1 ) )
599 case kEventCommandUpdateStatus
:
601 wxUpdateUIEvent
event(id
);
602 event
.SetEventObject( itemMenu
);
604 bool processed
= false;
606 // Try the menu's event handler
608 wxEvtHandler
*handler
= itemMenu
->GetEventHandler();
610 processed
= handler
->ProcessEvent(event
);
613 // Try the window the menu was popped up from
614 // (and up through the hierarchy)
617 const wxMenuBase
*menu
= itemMenu
;
620 wxWindow
*win
= menu
->GetInvokingWindow();
623 processed
= win
->GetEventHandler()->ProcessEvent(event
);
627 menu
= menu
->GetParent();
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());
653 static pascal OSStatus
wxMacAppApplicationEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
655 OSStatus result
= eventNotHandledErr
;
656 switch ( GetEventKind( event
) )
658 case kEventAppActivated
:
660 wxTheApp
->SetActive( true , NULL
) ;
664 case kEventAppDeactivated
:
666 wxTheApp
->SetActive( false , NULL
) ;
677 pascal OSStatus
wxMacAppEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
679 EventRef formerEvent
= (EventRef
) wxTheApp
->MacGetCurrentEvent() ;
680 EventHandlerCallRef formerEventHandlerCallRef
= (EventHandlerCallRef
) wxTheApp
->MacGetCurrentEventHandlerCallRef() ;
681 wxTheApp
->MacSetCurrentEvent( event
, handler
) ;
683 OSStatus result
= eventNotHandledErr
;
684 switch ( GetEventClass( event
) )
686 case kEventClassCommand
:
687 result
= wxMacAppCommandEventHandler( handler
, event
, data
) ;
690 case kEventClassApplication
:
691 result
= wxMacAppApplicationEventHandler( handler
, event
, data
) ;
694 case kEventClassMenu
:
695 result
= wxMacAppMenuEventHandler( handler
, event
, data
) ;
698 case kEventClassMouse
:
700 wxMacCarbonEvent
cEvent( event
) ;
703 Point screenMouseLocation
= cEvent
.GetParameter
<Point
>(kEventParamMouseLocation
) ;
704 ::FindWindow(screenMouseLocation
, &window
);
705 // only send this event in case it had not already been sent to a tlw, as we get
706 // double events otherwise (in case event.skip) was called
707 if ( window
== NULL
)
708 result
= wxMacTopLevelMouseEventHandler( handler
, event
, NULL
) ;
712 case kEventClassAppleEvent
:
716 wxMacConvertEventToRecord( event
, &rec
) ;
717 result
= AEProcessAppleEvent( &rec
) ;
725 wxTheApp
->MacSetCurrentEvent( formerEvent
, formerEventHandlerCallRef
) ;
730 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler
)
734 pascal static void wxMacAssertOutputHandler(OSType componentSignature
, UInt32 options
,
735 const char *assertionString
, const char *exceptionLabelString
,
736 const char *errorString
, const char *fileName
, long lineNumber
, void *value
, ConstStr255Param outputMsg
)
738 // flow into assert handling
739 wxString fileNameStr
;
740 wxString assertionStr
;
741 wxString exceptionStr
;
745 fileNameStr
= wxString(fileName
, wxConvLocal
);
746 assertionStr
= wxString(assertionString
, wxConvLocal
);
747 exceptionStr
= wxString((exceptionLabelString
!=0) ? exceptionLabelString
: "", wxConvLocal
) ;
748 errorStr
= wxString((errorString
!=0) ? errorString
: "", wxConvLocal
) ;
750 fileNameStr
= fileName
;
751 assertionStr
= assertionString
;
752 exceptionStr
= (exceptionLabelString
!=0) ? exceptionLabelString
: "" ;
753 errorStr
= (errorString
!=0) ? errorString
: "" ;
758 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
759 assertionStr
.c_str() ,
760 exceptionStr
.c_str() ,
762 fileNameStr
.c_str(), lineNumber
,
766 wxOnAssert(fileNameStr
, lineNumber
, assertionStr
,
767 wxString::Format( wxT("%s %s value (%p)") , exceptionStr
, errorStr
, value
) ) ;
776 // m_macEventPosted run loop source callback:
777 void macPostedEventCallback(void *unused
);
780 void macPostedEventCallback(void *unused
)
782 wxTheApp
->ProcessPendingEvents();
786 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
791 InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler
) );
794 UMAInitToolbox( 4, sm_isEmbedded
) ;
795 SetEventMask( everyEvent
) ;
796 UMAShowWatchCursor() ;
799 # if __option(profile)
800 ProfilerInit( collectDetailed
, bestTimeBase
, 40000 , 50 ) ;
805 // now avoid exceptions thrown for new (bad_alloc)
806 // FIXME CS for some changes outside wxMac does not compile anymore
808 std::__throws_bad_alloc
= 0 ;
813 s_macCursorRgn
= ::NewRgn() ;
815 // Mac OS X passes a process serial number command line argument when
816 // the application is launched from the Finder. This argument must be
817 // removed from the command line arguments before being handled by the
818 // application (otherwise applications would need to handle it)
821 static const wxChar
*ARG_PSN
= _T("-psn_");
822 if ( wxStrncmp(argv
[1], ARG_PSN
, wxStrlen(ARG_PSN
)) == 0 )
824 // remove this argument
826 memmove(argv
+ 1, argv
+ 2, argc
* sizeof(char *));
830 if ( !wxAppBase::Initialize(argc
, argv
) )
834 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
837 #if TARGET_API_MAC_OSX
838 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
839 wxString startupCwd
= wxGetCwd() ;
840 if ( startupCwd
== wxT("/") || startupCwd
.Right(15) == wxT("/Contents/MacOS") )
842 CFURLRef url
= CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
843 CFURLRef urlParent
= CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault
, url
) ;
845 CFStringRef path
= CFURLCopyFileSystemPath ( urlParent
, kCFURLPOSIXPathStyle
) ;
846 CFRelease( urlParent
) ;
847 wxString cwd
= wxMacCFStringHolder(path
).AsString(wxLocale::GetSystemEncoding());
848 wxSetWorkingDirectory( cwd
) ;
852 wxMacCreateNotifierTable() ;
855 /* connect posted events to common-mode run loop so that wxPostEvent events
856 are handled even while we're in the menu or on a scrollbar */
857 CFRunLoopSourceContext event_posted_context
= {0};
858 event_posted_context
.perform
= macPostedEventCallback
;
859 m_macEventPosted
= CFRunLoopSourceCreate(NULL
,0,&event_posted_context
);
860 CFRunLoopAddSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
863 UMAShowArrowCursor() ;
868 AEEventHandlerUPP sODocHandler
= NULL
;
869 AEEventHandlerUPP sOAppHandler
= NULL
;
870 AEEventHandlerUPP sPDocHandler
= NULL
;
871 AEEventHandlerUPP sRAppHandler
= NULL
;
872 AEEventHandlerUPP sQuitHandler
= NULL
;
874 bool wxApp::OnInitGui()
876 if ( !wxAppBase::OnInitGui() )
879 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
883 InstallApplicationEventHandler(
884 GetwxMacAppEventHandlerUPP(),
885 GetEventTypeCount(eventList
), eventList
, wxTheApp
, (EventHandlerRef
*)&(wxTheApp
->m_macEventHandler
));
890 sODocHandler
= NewAEEventHandlerUPP(AEHandleODoc
) ;
891 sOAppHandler
= NewAEEventHandlerUPP(AEHandleOApp
) ;
892 sPDocHandler
= NewAEEventHandlerUPP(AEHandlePDoc
) ;
893 sRAppHandler
= NewAEEventHandlerUPP(AEHandleRApp
) ;
894 sQuitHandler
= NewAEEventHandlerUPP(AEHandleQuit
) ;
896 AEInstallEventHandler( kCoreEventClass
, kAEOpenDocuments
,
897 sODocHandler
, 0 , FALSE
) ;
898 AEInstallEventHandler( kCoreEventClass
, kAEOpenApplication
,
899 sOAppHandler
, 0 , FALSE
) ;
900 AEInstallEventHandler( kCoreEventClass
, kAEPrintDocuments
,
901 sPDocHandler
, 0 , FALSE
) ;
902 AEInstallEventHandler( kCoreEventClass
, kAEReopenApplication
,
903 sRAppHandler
, 0 , FALSE
) ;
904 AEInstallEventHandler( kCoreEventClass
, kAEQuitApplication
,
905 sQuitHandler
, 0 , FALSE
) ;
911 void wxApp::CleanUp()
914 wxToolTip::RemoveToolTips() ;
918 if (m_macEventPosted
)
919 CFRelease(m_macEventPosted
);
920 m_macEventPosted
= NULL
;
923 // One last chance for pending objects to be cleaned up
924 wxTheApp
->DeletePendingObjects();
926 wxMacDestroyNotifierTable() ;
929 # if __option(profile)
930 ProfilerDump( (StringPtr
)"\papp.prof" ) ;
935 UMACleanupToolbox() ;
937 ::DisposeRgn((RgnHandle
)s_macCursorRgn
);
940 RemoveEventHandler( (EventHandlerRef
)(wxTheApp
->m_macEventHandler
) );
944 AERemoveEventHandler( kCoreEventClass
, kAEOpenDocuments
,
945 sODocHandler
, FALSE
) ;
946 AERemoveEventHandler( kCoreEventClass
, kAEOpenApplication
,
947 sOAppHandler
, FALSE
) ;
948 AERemoveEventHandler( kCoreEventClass
, kAEPrintDocuments
,
949 sPDocHandler
, FALSE
) ;
950 AERemoveEventHandler( kCoreEventClass
, kAEReopenApplication
,
951 sRAppHandler
, FALSE
) ;
952 AERemoveEventHandler( kCoreEventClass
, kAEQuitApplication
,
953 sQuitHandler
, FALSE
) ;
955 DisposeAEEventHandlerUPP( sODocHandler
) ;
956 DisposeAEEventHandlerUPP( sOAppHandler
) ;
957 DisposeAEEventHandlerUPP( sPDocHandler
) ;
958 DisposeAEEventHandlerUPP( sRAppHandler
) ;
959 DisposeAEEventHandlerUPP( sQuitHandler
) ;
962 wxAppBase::CleanUp();
965 //----------------------------------------------------------------------
966 // misc initialization stuff
967 //----------------------------------------------------------------------
969 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
971 // for shared libraries we have to manually get the correct resource
972 // ref num upon initializing and releasing when terminating, therefore
973 // the __wxinitialize and __wxterminate must be used
977 void __sinit(void); // (generated by linker)
978 pascal OSErr
__initialize(const CFragInitBlock
*theInitBlock
);
979 pascal void __terminate(void);
982 pascal OSErr
__wxinitialize(const CFragInitBlock
*theInitBlock
)
984 return __initialize( theInitBlock
) ;
987 pascal void __wxterminate(void)
992 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
994 bool wxMacConvertEventToRecord( EventRef event
, EventRecord
*rec
)
996 OSStatus err
= noErr
;
997 bool converted
= ConvertEventRefToEventRecord( event
, rec
) ;
1001 switch ( GetEventClass( event
) )
1003 case kEventClassKeyboard
:
1006 switch ( GetEventKind(event
) )
1008 case kEventRawKeyDown
:
1009 rec
->what
= keyDown
;
1012 case kEventRawKeyRepeat
:
1013 rec
->what
= autoKey
;
1016 case kEventRawKeyUp
:
1020 case kEventRawKeyModifiersChanged
:
1021 rec
->what
= nullEvent
;
1032 unsigned char charCode
;
1034 GetMouse( &rec
->where
) ;
1036 err
= GetEventParameter(event
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1037 err
= GetEventParameter(event
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1038 err
= GetEventParameter(event
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1039 rec
->modifiers
= modifiers
;
1040 rec
->message
= (keyCode
<< 8 ) + charCode
;
1045 case kEventClassTextInput
:
1047 switch ( GetEventKind( event
) )
1049 case kEventTextInputUnicodeForKeyEvent
:
1052 err
= GetEventParameter(
1053 event
, kEventParamTextInputSendKeyboardEvent
, typeEventRef
, NULL
,
1054 sizeof(rawEvent
), NULL
, &rawEvent
) ;
1058 UInt32 keyCode
, modifiers
;
1059 unsigned char charCode
;
1061 GetMouse( &rec
->where
) ;
1062 rec
->what
= keyDown
;
1063 err
= GetEventParameter(rawEvent
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1064 err
= GetEventParameter(rawEvent
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1065 err
= GetEventParameter(rawEvent
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1066 rec
->modifiers
= modifiers
;
1067 rec
->message
= (keyCode
<< 8 ) + charCode
;
1088 m_printMode
= wxPRINT_WINDOWS
;
1090 m_macCurrentEvent
= NULL
;
1091 m_macCurrentEventHandlerCallRef
= NULL
;
1093 #ifdef __WXMAC_OSX__
1094 m_macEventPosted
= NULL
;
1098 void wxApp::OnIdle(wxIdleEvent
& event
)
1100 wxAppBase::OnIdle(event
);
1102 // If they are pending events, we must process them: pending events are
1103 // either events to the threads other than main or events posted with
1104 // wxPostEvent() functions
1105 wxMacProcessNotifierAndPendingEvents();
1107 if (!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1108 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1111 void wxApp::WakeUpIdle()
1113 #ifdef __WXMAC_OSX__
1114 if (m_macEventPosted
)
1116 CFRunLoopSourceSignal(m_macEventPosted
);
1123 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1126 GetTopWindow()->Close(true);
1129 // Default behaviour: close the application with prompts. The
1130 // user can veto the close, and therefore the end session.
1131 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1135 if (!GetTopWindow()->Close(!event
.CanVeto()))
1140 extern "C" void wxCYield() ;
1146 // Yield to other processes
1148 bool wxApp::Yield(bool onlyIfNeeded
)
1152 if ( !onlyIfNeeded
)
1154 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1162 // by definition yield should handle all non-processed events
1166 OSStatus status
= noErr
;
1168 while ( status
== noErr
)
1170 s_inReceiveEvent
= true ;
1171 status
= ReceiveNextEvent(0, NULL
,kEventDurationNoWait
,true,&theEvent
) ;
1172 s_inReceiveEvent
= false ;
1174 if ( status
== eventLoopTimedOutErr
)
1176 // make sure next time the event loop will trigger idle events
1177 sleepTime
= kEventDurationNoWait
;
1179 else if ( status
== eventLoopQuitErr
)
1181 // according to QA1061 this may also occur when a WakeUp Process
1186 MacHandleOneEvent( theEvent
) ;
1187 ReleaseEvent(theEvent
);
1191 wxMacProcessNotifierAndPendingEvents() ;
1197 void wxApp::MacDoOneEvent()
1201 s_inReceiveEvent
= true ;
1202 OSStatus status
= ReceiveNextEvent(0, NULL
, sleepTime
, true, &theEvent
) ;
1203 s_inReceiveEvent
= false ;
1207 case eventLoopTimedOutErr
:
1208 if ( wxTheApp
->ProcessIdle() )
1209 sleepTime
= kEventDurationNoWait
;
1211 sleepTime
= kEventDurationSecond
;
1214 case eventLoopQuitErr
:
1215 // according to QA1061 this may also occur
1216 // when a WakeUp Process is executed
1220 MacHandleOneEvent( theEvent
) ;
1221 ReleaseEvent( theEvent
);
1222 sleepTime
= kEventDurationNoWait
;
1227 DeletePendingObjects() ;
1228 wxMacProcessNotifierAndPendingEvents() ;
1232 void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr
)
1234 // Override to process unhandled events as you please
1237 void wxApp::MacHandleOneEvent( WXEVENTREF evr
)
1239 EventTargetRef theTarget
;
1240 theTarget
= GetEventDispatcherTarget();
1241 m_macCurrentEvent
= evr
;
1243 OSStatus status
= SendEventToEventTarget((EventRef
) evr
, theTarget
);
1244 if (status
== eventNotHandledErr
)
1245 MacHandleUnhandledEvent(evr
);
1247 wxMacProcessNotifierAndPendingEvents() ;
1250 wxMutexGuiLeaveOrEnter();
1251 #endif // wxUSE_THREADS
1254 long wxMacTranslateKey(unsigned char key
, unsigned char code
)
1259 case kHomeCharCode
:
1263 case kEnterCharCode
:
1264 retval
= WXK_RETURN
;
1270 case kHelpCharCode
:
1274 case kBackspaceCharCode
:
1282 case kPageUpCharCode
:
1283 retval
= WXK_PAGEUP
;
1286 case kPageDownCharCode
:
1287 retval
= WXK_PAGEDOWN
;
1290 case kReturnCharCode
:
1291 retval
= WXK_RETURN
;
1294 case kFunctionKeyCharCode
:
1364 case kEscapeCharCode
:
1365 retval
= WXK_ESCAPE
;
1368 case kLeftArrowCharCode
:
1372 case kRightArrowCharCode
:
1373 retval
= WXK_RIGHT
;
1376 case kUpArrowCharCode
:
1380 case kDownArrowCharCode
:
1384 case kDeleteCharCode
:
1385 retval
= WXK_DELETE
;
1395 int wxMacKeyCodeToModifier(wxKeyCode key
)
1421 bool wxGetKeyState(wxKeyCode key
) //virtual key code if < 10.2.x, else see below
1423 wxASSERT_MSG(key
!= WXK_LBUTTON
&& key
!= WXK_RBUTTON
&& key
!=
1424 WXK_MBUTTON
, wxT("can't use wxGetKeyState() for mouse buttons"));
1426 //if OS X > 10.2 (i.e. 10.2.x)
1427 //a known apple bug prevents the system from determining led
1428 //states with GetKeys... can only determine caps lock led
1429 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key
));
1431 // KeyMapByteArray keymap;
1432 // GetKeys((BigEndianLong*)keymap);
1433 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1438 wxMouseState
wxGetMouseState()
1442 wxPoint pt
= wxGetMousePosition();
1446 #if TARGET_API_MAC_OSX
1447 UInt32 buttons
= GetCurrentButtonState();
1448 ms
.SetLeftDown( (buttons
& 0x01) != 0 );
1449 ms
.SetMiddleDown( (buttons
& 0x04) != 0 );
1450 ms
.SetRightDown( (buttons
& 0x02) != 0 );
1452 ms
.SetLeftDown( Button() );
1453 ms
.SetMiddleDown( 0 );
1454 ms
.SetRightDown( 0 );
1457 UInt32 modifiers
= GetCurrentKeyModifiers();
1458 ms
.SetControlDown(modifiers
& controlKey
);
1459 ms
.SetShiftDown(modifiers
& shiftKey
);
1460 ms
.SetAltDown(modifiers
& optionKey
);
1461 ms
.SetMetaDown(modifiers
& cmdKey
);
1466 // TODO : once the new key/char handling is tested, move all the code to wxWindow
1468 bool wxApp::MacSendKeyDownEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1474 wxKeyEvent
event(wxEVT_KEY_DOWN
) ;
1475 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1477 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1478 if ( handled
&& event
.GetSkipped() )
1484 wxWindow
*ancestor
= focus
;
1487 int command
= ancestor
->GetAcceleratorTable()->GetCommand( event
);
1490 wxCommandEvent
command_event( wxEVT_COMMAND_MENU_SELECTED
, command
);
1491 handled
= ancestor
->GetEventHandler()->ProcessEvent( command_event
);
1495 if (ancestor
->IsTopLevel())
1498 ancestor
= ancestor
->GetParent();
1501 #endif // wxUSE_ACCEL
1506 bool wxApp::MacSendKeyUpEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1512 wxKeyEvent
event( wxEVT_KEY_UP
) ;
1513 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1514 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1519 bool wxApp::MacSendCharEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1524 wxKeyEvent
event(wxEVT_CHAR
) ;
1525 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1526 long keyval
= event
.m_keyCode
;
1528 bool handled
= false ;
1530 wxTopLevelWindowMac
*tlw
= focus
->MacGetTopLevelWindow() ;
1534 event
.SetEventType( wxEVT_CHAR_HOOK
);
1535 handled
= tlw
->GetEventHandler()->ProcessEvent( event
);
1536 if ( handled
&& event
.GetSkipped() )
1542 event
.SetEventType( wxEVT_CHAR
);
1543 event
.Skip( false ) ;
1544 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1547 if ( !handled
&& (keyval
== WXK_TAB
) )
1549 wxWindow
* iter
= focus
->GetParent() ;
1550 while ( iter
&& !handled
)
1552 if ( iter
->HasFlag( wxTAB_TRAVERSAL
) )
1554 wxNavigationKeyEvent new_event
;
1555 new_event
.SetEventObject( focus
);
1556 new_event
.SetDirection( !event
.ShiftDown() );
1557 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1558 new_event
.SetWindowChange( event
.ControlDown() );
1559 new_event
.SetCurrentFocus( focus
);
1560 handled
= focus
->GetParent()->GetEventHandler()->ProcessEvent( new_event
);
1561 if ( handled
&& new_event
.GetSkipped() )
1565 iter
= iter
->GetParent() ;
1569 // backdoor handler for default return and command escape
1570 if ( !handled
&& (!focus
->IsKindOf(CLASSINFO(wxControl
) ) || !focus
->MacCanFocus() ) )
1572 // if window is not having a focus still testing for default enter or cancel
1573 // TODO: add the UMA version for ActiveNonFloatingWindow
1574 wxWindow
* focus
= wxFindWinFromMacWindow( FrontWindow() ) ;
1577 if ( keyval
== WXK_RETURN
)
1579 wxTopLevelWindow
*tlw
= wxDynamicCast(wxGetTopLevelParent(focus
), wxTopLevelWindow
);
1580 if ( tlw
&& tlw
->GetDefaultItem() )
1582 wxButton
*def
= wxDynamicCast(tlw
->GetDefaultItem(), wxButton
);
1583 if ( def
&& def
->IsEnabled() )
1585 wxCommandEvent
event(wxEVT_COMMAND_BUTTON_CLICKED
, def
->GetId() );
1586 event
.SetEventObject(def
);
1587 def
->Command(event
);
1593 else if (keyval
== WXK_ESCAPE
|| (keyval
== '.' && modifiers
& cmdKey
) )
1595 // generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs)
1596 wxCommandEvent
new_event(wxEVT_COMMAND_BUTTON_CLICKED
,wxID_CANCEL
);
1597 new_event
.SetEventObject( focus
);
1598 handled
= focus
->GetEventHandler()->ProcessEvent( new_event
);
1605 // This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
1606 void wxApp::MacCreateKeyEvent( wxKeyEvent
& event
, wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1608 short keycode
, keychar
;
1610 keychar
= short(keymessage
& charCodeMask
);
1611 keycode
= short(keymessage
& keyCodeMask
) >> 8 ;
1612 if ( !(event
.GetEventType() == wxEVT_CHAR
) && (modifiers
& (controlKey
| shiftKey
| optionKey
) ) )
1614 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1615 // and look at the character after
1617 UInt32 keyInfo
= KeyTranslate((Ptr
)GetScriptManagerVariable(smKCHRCache
), ( modifiers
& (~(controlKey
| shiftKey
| optionKey
))) | keycode
, &state
);
1618 keychar
= short(keyInfo
& charCodeMask
);
1621 long keyval
= wxMacTranslateKey(keychar
, keycode
) ;
1622 if ( keyval
== keychar
&& ( event
.GetEventType() == wxEVT_KEY_UP
|| event
.GetEventType() == wxEVT_KEY_DOWN
) )
1623 keyval
= wxToupper( keyval
) ;
1625 // Check for NUMPAD keys
1626 if (keyval
>= '0' && keyval
<= '9' && keycode
>= 82 && keycode
<= 92)
1628 keyval
= (keyval
- '0') + WXK_NUMPAD0
;
1630 else if (keycode
>= 67 && keycode
<= 81)
1635 keyval
= WXK_NUMPAD_ENTER
;
1639 keyval
= WXK_NUMPAD_EQUAL
;
1643 keyval
= WXK_NUMPAD_MULTIPLY
;
1647 keyval
= WXK_NUMPAD_DIVIDE
;
1651 keyval
= WXK_NUMPAD_SUBTRACT
;
1655 keyval
= WXK_NUMPAD_ADD
;
1659 keyval
= WXK_NUMPAD_DECIMAL
;
1667 event
.m_shiftDown
= modifiers
& shiftKey
;
1668 event
.m_controlDown
= modifiers
& controlKey
;
1669 event
.m_altDown
= modifiers
& optionKey
;
1670 event
.m_metaDown
= modifiers
& cmdKey
;
1671 event
.m_keyCode
= keyval
;
1673 event
.m_uniChar
= uniChar
;
1676 event
.m_rawCode
= keymessage
;
1677 event
.m_rawFlags
= modifiers
;
1680 event
.SetTimestamp(when
);
1681 event
.SetEventObject(focus
);