1 /////////////////////////////////////////////////////////////////////////////
4 // Author: Stefan Csomor
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "app.h"
18 #include "wx/window.h"
20 #include "wx/button.h"
23 #include "wx/gdicmn.h"
26 #include "wx/cursor.h"
29 #include "wx/palette.h"
31 #include "wx/dialog.h"
32 #include "wx/msgdlg.h"
34 #include "wx/module.h"
35 #include "wx/memory.h"
36 #include "wx/tooltip.h"
37 #include "wx/textctrl.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>
70 extern wxList wxPendingDelete
;
72 // set wxMAC_USE_RAEL to 1 if RunApplicationEventLoop should be used
73 // if 0 the lower level CarbonEventLoop will be used
74 // on the long run RAEL should replace the low level event loop
75 // we will have to clean up event handling to make sure we don't
76 // miss handling of things like pending events etc
77 // perhaps we will also have to pipe events through an ueber-event-handler
78 // to make sure we have one place to do all these house-keeping functions
80 #define wxMAC_USE_RAEL 0
83 extern size_t g_numberOfThreads
;
84 #endif // wxUSE_THREADS
86 // statics for implementation
88 static bool s_inYield
= FALSE
;
90 static bool s_inReceiveEvent
= FALSE
;
91 static EventTime sleepTime
= kEventDurationNoWait
;
93 #if !USE_SHARED_LIBRARY
94 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
95 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
96 EVT_IDLE(wxApp::OnIdle
)
97 EVT_END_SESSION(wxApp::OnEndSession
)
98 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
103 const short kMacMinHeap
= (29 * 1024) ;
104 // platform specific static variables
106 const short kwxMacMenuBarResource
= 1 ;
107 const short kwxMacAppleMenuId
= 1 ;
109 WXHRGN
wxApp::s_macCursorRgn
= NULL
;
110 wxWindow
* wxApp::s_captureWindow
= NULL
;
111 int wxApp::s_lastMouseDown
= 0 ;
112 long wxApp::sm_lastMessageTime
= 0;
113 long wxApp::s_lastModifiers
= 0 ;
116 bool wxApp::s_macSupportPCMenuShortcuts
= true ;
117 long wxApp::s_macAboutMenuItemId
= wxID_ABOUT
;
118 long wxApp::s_macPreferencesMenuItemId
= wxID_PREFERENCES
;
119 long wxApp::s_macExitMenuItemId
= wxID_EXIT
;
120 wxString
wxApp::s_macHelpMenuTitleName
= wxT("&Help") ;
122 // Normally we're not a plugin
123 bool wxApp::sm_isEmbedded
= false;
124 //----------------------------------------------------------------------
125 // Core Apple Event Support
126 //----------------------------------------------------------------------
128 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
129 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
130 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
131 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
132 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
134 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
136 return wxTheApp
->MacHandleAEODoc( (AppleEvent
*) event
, reply
) ;
139 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
141 return wxTheApp
->MacHandleAEOApp( (AppleEvent
*) event
, reply
) ;
144 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
146 return wxTheApp
->MacHandleAEPDoc( (AppleEvent
*) event
, reply
) ;
149 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
151 return wxTheApp
->MacHandleAEQuit( (AppleEvent
*) event
, reply
) ;
154 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
156 return wxTheApp
->MacHandleAERApp( (AppleEvent
*) event
, reply
) ;
159 // AEODoc Calls MacOpenFile on each of the files passed
161 short wxApp::MacHandleAEODoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
165 DescType returnedType
;
171 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
175 err
= AECountItems(&docList
, &itemsInList
);
179 ProcessSerialNumber PSN
;
180 PSN
.highLongOfPSN
= 0 ;
181 PSN
.lowLongOfPSN
= kCurrentProcess
;
182 SetFrontProcess( &PSN
) ;
184 for (i
= 1; i
<= itemsInList
; i
++) {
185 AEGetNthPtr(&docList
, i
, typeFSS
, &keywd
, &returnedType
,
186 (Ptr
) & theSpec
, sizeof(theSpec
), &actualSize
);
187 wxString fName
= wxMacFSSpec2MacFilename(&theSpec
);
193 // AEPDoc Calls MacPrintFile on each of the files passed
195 short wxApp::MacHandleAEPDoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
199 DescType returnedType
;
205 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
209 err
= AECountItems(&docList
, &itemsInList
);
213 ProcessSerialNumber PSN
;
214 PSN
.highLongOfPSN
= 0 ;
215 PSN
.lowLongOfPSN
= kCurrentProcess
;
216 SetFrontProcess( &PSN
) ;
218 for (i
= 1; i
<= itemsInList
; i
++) {
219 AEGetNthPtr(&docList
, i
, typeFSS
, &keywd
, &returnedType
,
220 (Ptr
) & theSpec
, sizeof(theSpec
), &actualSize
);
221 wxString fName
= wxMacFSSpec2MacFilename(&theSpec
);
227 // AEOApp calls MacNewFile
229 short wxApp::MacHandleAEOApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
235 // AEQuit attempts to quit the application
237 short wxApp::MacHandleAEQuit(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
239 wxWindow
* win
= GetTopWindow() ;
242 wxCommandEvent
exitEvent(wxEVT_COMMAND_MENU_SELECTED
, s_macExitMenuItemId
);
243 if (!win
->ProcessEvent(exitEvent
))
253 // AEROApp calls MacReopenApp
255 short wxApp::MacHandleAERApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
262 //----------------------------------------------------------------------
263 // Support Routines linking the Mac...File Calls to the Document Manager
264 //----------------------------------------------------------------------
266 void wxApp::MacOpenFile(const wxString
& fileName
)
268 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
270 dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
273 void wxApp::MacPrintFile(const wxString
& fileName
)
275 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
278 wxDocument
*doc
= dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
281 wxView
* view
= doc
->GetFirstView() ;
284 wxPrintout
*printout
= view
->OnCreatePrintout();
288 printer
.Print(view
->GetFrame(), printout
, TRUE
);
294 doc
->DeleteAllViews();
295 dm
->RemoveDocument(doc
) ;
301 void wxApp::MacNewFile()
305 void wxApp::MacReopenApp()
308 // if there is no open window -> create a new one
309 // if all windows are hidden -> show the first
310 // if some windows are not hidden -> do nothing
312 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetFirst();
319 wxTopLevelWindow
* firstIconized
= NULL
;
322 wxTopLevelWindow
* win
= (wxTopLevelWindow
*) node
->GetData();
323 if ( win
->IsIconized() == false )
325 firstIconized
= NULL
;
330 if ( firstIconized
== NULL
)
331 firstIconized
= win
;
333 node
= node
->GetNext();
336 firstIconized
->Iconize( false ) ;
340 //----------------------------------------------------------------------
341 // Carbon Event Handler
342 //----------------------------------------------------------------------
344 static const EventTypeSpec eventList
[] =
346 { kEventClassCommand
, kEventProcessCommand
} ,
347 { kEventClassCommand
, kEventCommandUpdateStatus
} ,
349 { kEventClassMenu
, kEventMenuOpening
},
350 { kEventClassMenu
, kEventMenuClosed
},
351 { kEventClassMenu
, kEventMenuTargetItem
},
353 { kEventClassApplication
, kEventAppActivated
} ,
354 { kEventClassApplication
, kEventAppDeactivated
} ,
355 // handling the quit event is not recommended by apple
356 // rather using the quit apple event - which we do
358 { kEventClassAppleEvent
, kEventAppleEvent
} ,
360 { kEventClassMouse
, kEventMouseDown
} ,
361 { kEventClassMouse
, kEventMouseMoved
} ,
362 { kEventClassMouse
, kEventMouseUp
} ,
363 { kEventClassMouse
, kEventMouseDragged
} ,
367 static pascal OSStatus
368 wxMacAppMenuEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
370 EventRef formerEvent
= (EventRef
) wxTheApp
->MacGetCurrentEvent() ;
371 EventHandlerCallRef formerEventHandlerCallRef
= (EventHandlerCallRef
) wxTheApp
->MacGetCurrentEventHandlerCallRef() ;
372 wxTheApp
->MacSetCurrentEvent( event
, handler
) ;
374 wxMacCarbonEvent
cEvent( event
) ;
375 MenuRef menuRef
= cEvent
.GetParameter
<MenuRef
>(kEventParamDirectObject
) ;
376 wxMenu
* menu
= wxFindMenuFromMacMenu( menuRef
) ;
382 switch (GetEventKind(event
))
384 case kEventMenuOpening
:
385 type
= wxEVT_MENU_OPEN
;
387 case kEventMenuClosed
:
388 type
= wxEVT_MENU_CLOSE
;
390 case kEventMenuTargetItem
:
391 cmd
= cEvent
.GetParameter
<MenuCommand
>(kEventParamMenuCommand
,typeMenuCommand
) ;
393 type
= wxEVT_MENU_HIGHLIGHT
;
396 wxFAIL_MSG(wxT("Unexpected menu event kind"));
402 wxMenuEvent
wxevent(type
, cmd
);
403 wxevent
.SetEventObject(menu
);
405 wxEvtHandler
* handler
= menu
->GetEventHandler();
406 if (handler
&& handler
->ProcessEvent(wxevent
))
412 wxWindow
*win
= menu
->GetInvokingWindow();
414 win
->GetEventHandler()->ProcessEvent(wxevent
);
419 wxTheApp
->MacSetCurrentEvent( formerEvent
, formerEventHandlerCallRef
) ;
421 return eventNotHandledErr
;
424 static pascal OSStatus
wxMacAppCommandEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
426 OSStatus result
= eventNotHandledErr
;
430 wxMacCarbonEvent
cEvent( event
) ;
431 cEvent
.GetParameter
<HICommand
>(kEventParamDirectObject
,typeHICommand
,&command
) ;
433 wxMenuItem
* item
= NULL
;
434 MenuCommand id
= command
.commandID
;
435 // for items we don't really control
436 if ( id
== kHICommandPreferences
)
438 id
= wxApp::s_macPreferencesMenuItemId
;
440 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
443 wxMenu
* menu
= NULL
;
444 item
= mbar
->FindItem( id
, &menu
) ;
447 else if ( id
!= 0 && command
.menu
.menuRef
!= 0 && command
.menu
.menuItemIndex
!= 0 )
449 GetMenuItemRefCon( command
.menu
.menuRef
, command
.menu
.menuItemIndex
, (UInt32
*) &item
) ;
454 switch( cEvent
.GetKind() )
456 case kEventProcessCommand
:
458 if (item
->IsCheckable())
460 item
->Check( !item
->IsChecked() ) ;
463 item
->GetMenu()->SendEvent( id
, item
->IsCheckable() ? item
->IsChecked() : -1 ) ;
467 case kEventCommandUpdateStatus
:
468 // eventually trigger an updateui round
478 static pascal OSStatus
wxMacAppApplicationEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
480 OSStatus result
= eventNotHandledErr
;
481 switch ( GetEventKind( event
) )
483 case kEventAppActivated
:
486 wxTheApp
->SetActive( true , NULL
) ;
490 case kEventAppDeactivated
:
493 wxTheApp
->SetActive( false , NULL
) ;
503 pascal OSStatus
wxMacAppEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
505 OSStatus result
= eventNotHandledErr
;
506 switch( GetEventClass( event
) )
508 case kEventClassCommand
:
509 result
= wxMacAppCommandEventHandler( handler
, event
, data
) ;
511 case kEventClassApplication
:
512 result
= wxMacAppApplicationEventHandler( handler
, event
, data
) ;
514 case kEventClassMenu
:
515 result
= wxMacAppMenuEventHandler( handler
, event
, data
) ;
517 case kEventClassMouse
:
518 result
= wxMacTopLevelMouseEventHandler( handler
, event
, NULL
) ;
520 case kEventClassAppleEvent
:
523 wxMacConvertEventToRecord( event
, &rec
) ;
524 result
= AEProcessAppleEvent( &rec
) ;
534 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler
)
536 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
537 // we know it's there ;-)
538 WXIMPORT
char std::__throws_bad_alloc
;
541 pascal static void wxMacAssertOutputHandler(OSType componentSignature
, UInt32 options
,
542 const char *assertionString
, const char *exceptionLabelString
,
543 const char *errorString
, const char *fileName
, long lineNumber
, void *value
, ConstStr255Param outputMsg
)
545 // flow into assert handling
546 wxString fileNameStr
;
547 wxString assertionStr
;
548 wxString exceptionStr
;
551 fileNameStr
= wxString(fileName
, wxConvLocal
);
552 assertionStr
= wxString(assertionString
, wxConvLocal
);
553 exceptionStr
= wxString((exceptionLabelString
!=0) ? exceptionLabelString
: "", wxConvLocal
) ;
554 errorStr
= wxString((errorString
!=0) ? errorString
: "", wxConvLocal
) ;
556 fileNameStr
= fileName
;
557 assertionStr
= assertionString
;
558 exceptionStr
= (exceptionLabelString
!=0) ? exceptionLabelString
: "" ;
559 errorStr
= (errorString
!=0) ? errorString
: "" ;
564 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
565 assertionStr
.c_str() ,
566 exceptionStr
.c_str() ,
568 fileNameStr
.c_str(), lineNumber
,
572 wxOnAssert(fileNameStr
, lineNumber
, assertionStr
,
573 wxString::Format( wxT("%s %s value (%p)") ,exceptionStr
, errorStr
, value
) ) ;
577 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
582 InstallDebugAssertOutputHandler ( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler
) );
584 UMAInitToolbox( 4, sm_isEmbedded
) ;
585 SetEventMask( everyEvent
) ;
586 UMAShowWatchCursor() ;
588 #if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
589 // open shared library resources from here since we don't have
590 // __wxinitialize in Mach-O shared libraries
591 wxStAppResource::OpenSharedLibraryResource(NULL
);
595 # if __option(profile)
596 ProfilerInit( collectDetailed
, bestTimeBase
, 40000 , 50 ) ;
601 // now avoid exceptions thrown for new (bad_alloc)
602 // FIXME CS for some changes outside wxMac does not compile anymore
604 std::__throws_bad_alloc
= 0 ;
609 s_macCursorRgn
= ::NewRgn() ;
611 // Mac OS X passes a process serial number command line argument when
612 // the application is launched from the Finder. This argument must be
613 // removed from the command line arguments before being handled by the
614 // application (otherwise applications would need to handle it)
617 static const wxChar
*ARG_PSN
= _T("-psn_");
618 if ( wxStrncmp(argv
[1], ARG_PSN
, wxStrlen(ARG_PSN
)) == 0 )
620 // remove this argument
622 memmove(argv
+ 1, argv
+ 2, argc
* sizeof(char *));
626 if ( !wxAppBase::Initialize(argc
, argv
) )
630 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
633 #if TARGET_API_MAC_OSX
634 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
635 wxString startupCwd
= wxGetCwd() ;
636 if ( startupCwd
== wxT("/") || startupCwd
.Right(15) == wxT("/Contents/MacOS") )
638 CFURLRef url
= CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
639 CFURLRef urlParent
= CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault
, url
) ;
641 CFStringRef path
= CFURLCopyFileSystemPath ( urlParent
, kCFURLPOSIXPathStyle
) ;
642 CFRelease( urlParent
) ;
643 wxString cwd
= wxMacCFStringHolder(path
).AsString(wxLocale::GetSystemEncoding());
644 wxSetWorkingDirectory( cwd
) ;
648 wxMacCreateNotifierTable() ;
650 UMAShowArrowCursor() ;
655 bool wxApp::OnInitGui()
657 if( !wxAppBase::OnInitGui() )
660 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
664 InstallApplicationEventHandler(
665 GetwxMacAppEventHandlerUPP(),
666 GetEventTypeCount(eventList
), eventList
, wxTheApp
, (EventHandlerRef
*)&(wxTheApp
->m_macEventHandler
));
671 AEInstallEventHandler( kCoreEventClass
, kAEOpenDocuments
,
672 NewAEEventHandlerUPP(AEHandleODoc
) ,
674 AEInstallEventHandler( kCoreEventClass
, kAEOpenApplication
,
675 NewAEEventHandlerUPP(AEHandleOApp
) ,
677 AEInstallEventHandler( kCoreEventClass
, kAEPrintDocuments
,
678 NewAEEventHandlerUPP(AEHandlePDoc
) ,
680 AEInstallEventHandler( kCoreEventClass
, kAEReopenApplication
,
681 NewAEEventHandlerUPP(AEHandleRApp
) ,
683 AEInstallEventHandler( kCoreEventClass
, kAEQuitApplication
,
684 NewAEEventHandlerUPP(AEHandleQuit
) ,
691 void wxApp::CleanUp()
693 wxToolTip::RemoveToolTips() ;
695 // One last chance for pending objects to be cleaned up
696 wxTheApp
->DeletePendingObjects();
698 wxMacDestroyNotifierTable() ;
701 # if __option(profile)
702 ProfilerDump( (StringPtr
)"\papp.prof" ) ;
707 #if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
708 // close shared library resources from here since we don't have
709 // __wxterminate in Mach-O shared libraries
710 wxStAppResource::CloseSharedLibraryResource();
713 UMACleanupToolbox() ;
714 if (s_macCursorRgn
) {
715 ::DisposeRgn((RgnHandle
)s_macCursorRgn
);
722 wxAppBase::CleanUp();
725 //----------------------------------------------------------------------
726 // misc initialization stuff
727 //----------------------------------------------------------------------
729 // extern variable for shared library resource id
730 // need to be able to find it with NSLookupAndBindSymbol
731 short gSharedLibraryResource
= kResFileNotOpened
;
733 #if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
734 CFBundleRef gSharedLibraryBundle
= NULL
;
735 #endif /* WXMAKINGDLL_CORE && __DARWIN__ */
737 wxStAppResource::wxStAppResource()
739 m_currentRefNum
= CurResFile() ;
740 if ( gSharedLibraryResource
!= kResFileNotOpened
)
742 UseResFile( gSharedLibraryResource
) ;
746 wxStAppResource::~wxStAppResource()
748 if ( m_currentRefNum
!= kResFileNotOpened
)
750 UseResFile( m_currentRefNum
) ;
754 void wxStAppResource::OpenSharedLibraryResource(const void *initBlock
)
756 gSharedLibraryResource
= kResFileNotOpened
;
758 #ifdef WXMAKINGDLL_CORE
759 if ( initBlock
!= NULL
) {
760 const CFragInitBlock
*theInitBlock
= (const CFragInitBlock
*)initBlock
;
761 FSSpec
*fileSpec
= NULL
;
763 if (theInitBlock
->fragLocator
.where
== kDataForkCFragLocator
) {
764 fileSpec
= theInitBlock
->fragLocator
.u
.onDisk
.fileSpec
;
766 else if (theInitBlock
->fragLocator
.where
== kResourceCFragLocator
) {
767 fileSpec
= theInitBlock
->fragLocator
.u
.inSegs
.fileSpec
;
770 if (fileSpec
!= NULL
) {
771 gSharedLibraryResource
= FSpOpenResFile(fileSpec
, fsRdPerm
);
776 // Open the shared library resource file if it is not yet open
779 const char *theLibPath
;
781 gSharedLibraryBundle
= CFBundleGetBundleWithIdentifier(CFSTR("com.wxwindows.wxWidgets"));
782 if (gSharedLibraryBundle
!= NULL
) {
783 // wxWidgets has been bundled into a framework
784 // load the framework resources
786 gSharedLibraryResource
= CFBundleOpenBundleResourceMap(gSharedLibraryBundle
);
789 // wxWidgets is a simple dynamic shared library
790 // load the resources from the data fork of a separate resource file
794 OSErr theErr
= noErr
;
796 // get the library path
797 theSymbol
= NSLookupAndBindSymbol("_gSharedLibraryResource");
798 theModule
= NSModuleForSymbol(theSymbol
);
799 theLibPath
= NSLibraryNameForModule(theModule
);
801 // if we call wxLogDebug from here then, as wxTheApp hasn't been
802 // created yet when we're called from wxApp::Initialize(), wxLog
803 // is going to create a default stderr-based log target instead of
804 // the expected normal GUI one -- don't do it, if we really want
805 // to see this message just use fprintf() here
807 wxLogDebug( wxT("wxMac library installation name is '%s'"),
811 // allocate copy to replace .dylib.* extension with .rsrc
812 if (theLibPath
!= NULL
) {
814 theResPath
= wxString(theLibPath
, wxConvLocal
);
816 theResPath
= wxString(theLibPath
);
818 // replace '_core' with '' in case of multi-lib build
819 theResPath
.Replace(wxT("_core"), wxEmptyString
);
820 // replace ".dylib" shared library extension with ".rsrc"
821 theResPath
.Replace(wxT(".dylib"), wxT(".rsrc"));
822 // Find the begining of the filename
823 theName
= theResPath
.AfterLast('/');
826 wxLogDebug( wxT("wxMac resources file name is '%s'"),
827 theResPath
.mb_str() );
830 theErr
= FSPathMakeRef((UInt8
*) theResPath
.mb_str(), &theResRef
, false);
831 if (theErr
!= noErr
) {
832 // try in current directory (using name only)
833 theErr
= FSPathMakeRef((UInt8
*) theName
.mb_str(), &theResRef
, false);
836 // open the resource file
837 if (theErr
== noErr
) {
838 theErr
= FSOpenResourceFile( &theResRef
, 0, NULL
, fsRdPerm
,
839 &gSharedLibraryResource
);
841 if (theErr
!= noErr
) {
843 wxLogDebug( wxT("unable to open wxMac resource file '%s'\n"),
844 theResPath
.mb_str() );
845 #endif // __WXDEBUG__
850 #endif /* __DARWIN__ */
852 #endif /* WXMAKINGDLL_CORE */
855 void wxStAppResource::CloseSharedLibraryResource()
857 #ifdef WXMAKINGDLL_CORE
858 // Close the shared library resource file
859 if (gSharedLibraryResource
!= kResFileNotOpened
) {
861 if (gSharedLibraryBundle
!= NULL
) {
862 CFBundleCloseBundleResourceMap(gSharedLibraryBundle
,
863 gSharedLibraryResource
);
864 gSharedLibraryBundle
= NULL
;
867 #endif /* __DARWIN__ */
869 CloseResFile(gSharedLibraryResource
);
871 gSharedLibraryResource
= kResFileNotOpened
;
873 #endif /* WXMAKINGDLL_CORE */
876 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
878 // for shared libraries we have to manually get the correct resource
879 // ref num upon initializing and releasing when terminating, therefore
880 // the __wxinitialize and __wxterminate must be used
883 void __sinit(void); /* (generated by linker) */
884 pascal OSErr
__initialize(const CFragInitBlock
*theInitBlock
);
885 pascal void __terminate(void);
888 pascal OSErr
__wxinitialize(const CFragInitBlock
*theInitBlock
)
890 wxStAppResource::OpenSharedLibraryResource( theInitBlock
) ;
891 return __initialize( theInitBlock
) ;
894 pascal void __wxterminate(void)
896 wxStAppResource::CloseSharedLibraryResource() ;
900 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
902 bool wxMacConvertEventToRecord( EventRef event
, EventRecord
*rec
)
904 bool converted
= ConvertEventRefToEventRecord( event
,rec
) ;
905 OSStatus err
= noErr
;
908 switch( GetEventClass( event
) )
910 case kEventClassKeyboard
:
913 switch( GetEventKind(event
) )
915 case kEventRawKeyDown
:
916 rec
->what
= keyDown
;
918 case kEventRawKeyRepeat
:
919 rec
->what
= autoKey
;
921 case kEventRawKeyUp
:
924 case kEventRawKeyModifiersChanged
:
925 rec
->what
= nullEvent
;
934 unsigned char charCode
;
936 GetMouse( &rec
->where
) ;
938 err
= GetEventParameter(event
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
939 err
= GetEventParameter(event
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
940 err
= GetEventParameter(event
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
941 rec
->modifiers
= modifiers
;
942 rec
->message
= (keyCode
<< 8 ) + charCode
;
946 case kEventClassTextInput
:
948 switch( GetEventKind( event
) )
950 case kEventTextInputUnicodeForKeyEvent
:
953 err
= GetEventParameter( event
, kEventParamTextInputSendKeyboardEvent
,typeEventRef
,NULL
,sizeof(rawEvent
),NULL
,&rawEvent
) ;
957 unsigned char charCode
;
959 GetMouse( &rec
->where
) ;
960 rec
->what
= keyDown
;
961 err
= GetEventParameter(rawEvent
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
962 err
= GetEventParameter(rawEvent
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
963 err
= GetEventParameter(rawEvent
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
964 rec
->modifiers
= modifiers
;
965 rec
->message
= (keyCode
<< 8 ) + charCode
;
982 m_printMode
= wxPRINT_WINDOWS
;
984 m_macCurrentEvent
= NULL
;
985 m_macCurrentEventHandlerCallRef
= NULL
;
988 int wxApp::MainLoop()
992 RunApplicationEventLoop() ;
1002 void wxApp::ExitMainLoop()
1004 m_keepGoing
= FALSE
;
1006 QuitApplicationEventLoop() ;
1010 // Is a message/event pending?
1011 bool wxApp::Pending()
1013 // without the receive event (with pull param = false ) nothing is ever reported
1015 ReceiveNextEvent (0, NULL
, kEventDurationNoWait
, false, &theEvent
);
1016 return GetNumEventsInQueue( GetMainEventQueue() ) > 0 ;
1019 // Dispatch a message.
1020 bool wxApp::Dispatch()
1027 void wxApp::OnIdle(wxIdleEvent
& event
)
1029 wxAppBase::OnIdle(event
);
1031 // If they are pending events, we must process them: pending events are
1032 // either events to the threads other than main or events posted with
1033 // wxPostEvent() functions
1034 wxMacProcessNotifierAndPendingEvents();
1036 if(!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1037 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1040 void wxApp::WakeUpIdle()
1051 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1054 GetTopWindow()->Close(TRUE
);
1057 // Default behaviour: close the application with prompts. The
1058 // user can veto the close, and therefore the end session.
1059 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1063 if (!GetTopWindow()->Close(!event
.CanVeto()))
1068 extern "C" void wxCYield() ;
1074 // Yield to other processes
1076 bool wxApp::Yield(bool onlyIfNeeded
)
1080 if ( !onlyIfNeeded
)
1082 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1090 // by definition yield should handle all non-processed events
1094 OSStatus status
= noErr
;
1097 s_inReceiveEvent
= true ;
1098 status
= ReceiveNextEvent(0, NULL
,kEventDurationNoWait
,true,&theEvent
) ;
1099 s_inReceiveEvent
= false ;
1101 if ( status
== eventLoopTimedOutErr
)
1103 // make sure next time the event loop will trigger idle events
1104 sleepTime
= kEventDurationNoWait
;
1106 else if ( status
== eventLoopQuitErr
)
1108 // according to QA1061 this may also occur when a WakeUp Process
1113 MacHandleOneEvent( theEvent
) ;
1114 ReleaseEvent(theEvent
);
1116 } while( status
== noErr
) ;
1118 wxMacProcessNotifierAndPendingEvents() ;
1124 void wxApp::MacDoOneEvent()
1128 s_inReceiveEvent
= true ;
1129 OSStatus status
= ReceiveNextEvent(0, NULL
,sleepTime
,true,&theEvent
) ;
1130 s_inReceiveEvent
= false ;
1131 if ( status
== eventLoopTimedOutErr
)
1133 if ( wxTheApp
->ProcessIdle() )
1134 sleepTime
= kEventDurationNoWait
;
1136 sleepTime
= kEventDurationSecond
;
1138 else if ( status
== eventLoopQuitErr
)
1140 // according to QA1061 this may also occur when a WakeUp Process
1145 MacHandleOneEvent( theEvent
) ;
1146 ReleaseEvent(theEvent
);
1147 sleepTime
= kEventDurationNoWait
;
1151 DeletePendingObjects() ;
1152 wxMacProcessNotifierAndPendingEvents() ;
1155 /*virtual*/ void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr
)
1157 // Override to process unhandled events as you please
1160 void wxApp::MacHandleOneEvent( WXEVENTREF evr
)
1162 EventTargetRef theTarget
;
1163 theTarget
= GetEventDispatcherTarget();
1164 m_macCurrentEvent
= evr
;
1165 OSStatus status
= SendEventToEventTarget ((EventRef
) evr
, theTarget
);
1166 if(status
== eventNotHandledErr
)
1168 MacHandleUnhandledEvent(evr
);
1170 wxMacProcessNotifierAndPendingEvents() ;
1172 wxMutexGuiLeaveOrEnter();
1173 #endif // wxUSE_THREADS
1176 long wxMacTranslateKey(unsigned char key
, unsigned char code
) ;
1177 long wxMacTranslateKey(unsigned char key
, unsigned char code
)
1182 case kHomeCharCode
:
1185 case kEnterCharCode
:
1186 retval
= WXK_RETURN
;
1191 case kHelpCharCode
:
1194 case kBackspaceCharCode
:
1200 case kPageUpCharCode
:
1201 retval
= WXK_PAGEUP
;
1203 case kPageDownCharCode
:
1204 retval
= WXK_PAGEDOWN
;
1206 case kReturnCharCode
:
1207 retval
= WXK_RETURN
;
1209 case kFunctionKeyCharCode
:
1261 case kEscapeCharCode
:
1262 retval
= WXK_ESCAPE
;
1264 case kLeftArrowCharCode
:
1267 case kRightArrowCharCode
:
1268 retval
= WXK_RIGHT
;
1270 case kUpArrowCharCode
:
1273 case kDownArrowCharCode
:
1276 case kDeleteCharCode
:
1277 retval
= WXK_DELETE
;
1285 int wxMacKeyCodeToModifier(wxKeyCode key
)
1310 bool wxGetKeyState(wxKeyCode key
) //virtual key code if < 10.2.x, else see below
1313 // wxHIDKeyboard keyboard;
1314 // return keyboard.IsActive(key);
1316 // TODO: Have it use HID Manager on OSX...
1317 //if OS X > 10.2 (i.e. 10.2.x)
1318 //a known apple bug prevents the system from determining led
1319 //states with GetKeys... can only determine caps lock led
1320 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key
));
1322 // KeyMapByteArray keymap;
1323 // GetKeys((BigEndianLong*)keymap);
1324 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1329 bool wxApp::MacSendKeyDownEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
)
1336 keychar
= short(keymessage
& charCodeMask
);
1337 keycode
= short(keymessage
& keyCodeMask
) >> 8 ;
1339 if ( modifiers
& ( controlKey
|shiftKey
|optionKey
) )
1341 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1342 // and look at the character after
1344 UInt32 keyInfo
= KeyTranslate((Ptr
)GetScriptManagerVariable(smKCHRCache
), ( modifiers
& (~(controlKey
|shiftKey
|optionKey
))) | keycode
, &state
);
1345 keychar
= short(keyInfo
& charCodeMask
);
1346 keycode
= short(keyInfo
& keyCodeMask
) >> 8 ;
1348 long keyval
= wxMacTranslateKey(keychar
, keycode
) ;
1349 long realkeyval
= keyval
;
1350 if ( keyval
== keychar
)
1352 // 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)
1353 realkeyval
= short(keymessage
& charCodeMask
) ;
1354 keyval
= wxToupper( keyval
) ;
1357 wxKeyEvent
event(wxEVT_KEY_DOWN
);
1358 bool handled
= false ;
1359 event
.m_shiftDown
= modifiers
& shiftKey
;
1360 event
.m_controlDown
= modifiers
& controlKey
;
1361 event
.m_altDown
= modifiers
& optionKey
;
1362 event
.m_metaDown
= modifiers
& cmdKey
;
1363 event
.m_keyCode
= keyval
;
1367 event
.m_timeStamp
= when
;
1368 event
.SetEventObject(focus
);
1369 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1370 if ( handled
&& event
.GetSkipped() )
1377 wxWindow
*ancestor
= focus
;
1380 int command
= ancestor
->GetAcceleratorTable()->GetCommand( event
);
1383 wxCommandEvent
command_event( wxEVT_COMMAND_MENU_SELECTED
, command
);
1384 handled
= ancestor
->GetEventHandler()->ProcessEvent( command_event
);
1387 if (ancestor
->IsTopLevel())
1389 ancestor
= ancestor
->GetParent();
1392 #endif // wxUSE_ACCEL
1396 event
.Skip( FALSE
) ;
1397 event
.SetEventType( wxEVT_CHAR
) ;
1399 event
.m_keyCode
= realkeyval
;
1401 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1402 if ( handled
&& event
.GetSkipped() )
1405 if ( !handled
&& (keyval
== WXK_TAB
) )
1407 wxWindow
* iter
= focus
->GetParent() ;
1408 while( iter
&& !handled
)
1410 if ( iter
->HasFlag( wxTAB_TRAVERSAL
) )
1412 wxNavigationKeyEvent new_event
;
1413 new_event
.SetEventObject( focus
);
1414 new_event
.SetDirection( !event
.ShiftDown() );
1415 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1416 new_event
.SetWindowChange( event
.ControlDown() );
1417 new_event
.SetCurrentFocus( focus
);
1418 handled
= focus
->GetParent()->GetEventHandler()->ProcessEvent( new_event
);
1419 if ( handled
&& new_event
.GetSkipped() )
1422 iter
= iter
->GetParent() ;
1425 // backdoor handler for default return and command escape
1426 if ( !handled
&& (!focus
->IsKindOf(CLASSINFO(wxControl
) ) || !focus
->MacCanFocus() ) )
1428 // if window is not having a focus still testing for default enter or cancel
1429 // TODO add the UMA version for ActiveNonFloatingWindow
1430 wxWindow
* focus
= wxFindWinFromMacWindow( FrontWindow() ) ;
1433 if ( keyval
== WXK_RETURN
)
1435 wxButton
*def
= wxDynamicCast(focus
->GetDefaultItem(),
1437 if ( def
&& def
->IsEnabled() )
1439 wxCommandEvent
event(wxEVT_COMMAND_BUTTON_CLICKED
, def
->GetId() );
1440 event
.SetEventObject(def
);
1441 def
->Command(event
);
1445 /* generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs) */
1446 else if (keyval
== WXK_ESCAPE
|| (keyval
== '.' && modifiers
& cmdKey
) )
1448 wxCommandEvent
new_event(wxEVT_COMMAND_BUTTON_CLICKED
,wxID_CANCEL
);
1449 new_event
.SetEventObject( focus
);
1450 handled
= focus
->GetEventHandler()->ProcessEvent( new_event
);
1457 bool wxApp::MacSendKeyUpEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
)
1464 keychar
= short(keymessage
& charCodeMask
);
1465 keycode
= short(keymessage
& keyCodeMask
) >> 8 ;
1466 if ( modifiers
& ( controlKey
|shiftKey
|optionKey
) )
1468 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1469 // and look at the character after
1471 UInt32 keyInfo
= KeyTranslate((Ptr
)GetScriptManagerVariable(smKCHRCache
), ( modifiers
& (~(controlKey
|shiftKey
|optionKey
))) | keycode
, &state
);
1472 keychar
= short(keyInfo
& charCodeMask
);
1473 keycode
= short(keyInfo
& keyCodeMask
) >> 8 ;
1475 long keyval
= wxMacTranslateKey(keychar
, keycode
) ;
1477 if ( keyval
== keychar
)
1479 keyval
= wxToupper( keyval
) ;
1481 bool handled
= false ;
1483 wxKeyEvent
event(wxEVT_KEY_UP
);
1484 event
.m_shiftDown
= modifiers
& shiftKey
;
1485 event
.m_controlDown
= modifiers
& controlKey
;
1486 event
.m_altDown
= modifiers
& optionKey
;
1487 event
.m_metaDown
= modifiers
& cmdKey
;
1488 event
.m_keyCode
= keyval
;
1492 event
.m_timeStamp
= when
;
1493 event
.SetEventObject(focus
);
1494 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;