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"
35 #include "wx/module.h"
38 #include "wx/tooltip.h"
39 #include "wx/docview.h"
40 #include "wx/filename.h"
53 // #include "apprsrc.h"
55 #include "wx/mac/uma.h"
56 #include "wx/mac/macnotfy.h"
59 # include <CoreServices/CoreServices.h>
60 # if defined(WXMAKINGDLL_CORE)
61 # include <mach-o/dyld.h>
66 # include <ToolUtils.h>
67 # include <DiskInit.h>
71 // Keep linker from discarding wxStockGDIMac
72 wxFORCE_LINK_MODULE(gdiobj
)
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 static const short kwxMacAppleMenuId
= 1 ;
91 wxWindow
* wxApp::s_captureWindow
= NULL
;
92 long wxApp::s_lastModifiers
= 0 ;
94 long wxApp::s_macAboutMenuItemId
= wxID_ABOUT
;
95 long wxApp::s_macPreferencesMenuItemId
= wxID_PREFERENCES
;
96 long wxApp::s_macExitMenuItemId
= wxID_EXIT
;
97 wxString
wxApp::s_macHelpMenuTitleName
= wxT("&Help") ;
99 bool wxApp::sm_isEmbedded
= false; // Normally we're not a plugin
101 //----------------------------------------------------------------------
102 // Core Apple Event Support
103 //----------------------------------------------------------------------
105 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
106 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
107 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
108 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
109 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
111 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
113 return wxTheApp
->MacHandleAEODoc( (AppleEvent
*) event
, reply
) ;
116 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
118 return wxTheApp
->MacHandleAEOApp( (AppleEvent
*) event
, reply
) ;
121 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
123 return wxTheApp
->MacHandleAEPDoc( (AppleEvent
*) event
, reply
) ;
126 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
128 return wxTheApp
->MacHandleAEQuit( (AppleEvent
*) event
, reply
) ;
131 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
133 return wxTheApp
->MacHandleAERApp( (AppleEvent
*) event
, reply
) ;
136 pascal OSErr
AEHandleGURL( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
138 return wxTheApp
->MacHandleAEGURL((WXEVENTREF
*)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 // AEODoc Calls MacOpenURL on the url passed
185 short wxApp::MacHandleAEGURL(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
187 DescType returnedType
;
190 OSErr err
= AEGetParamPtr((AppleEvent
*)event
, keyDirectObject
, typeChar
,
191 &returnedType
, url
, sizeof(url
)-1,
196 url
[actualSize
] = '\0'; // Terminate the C string
198 ProcessSerialNumber PSN
;
199 PSN
.highLongOfPSN
= 0 ;
200 PSN
.lowLongOfPSN
= kCurrentProcess
;
201 SetFrontProcess( &PSN
) ;
203 MacOpenURL(wxString(url
, wxConvUTF8
));
208 // AEPDoc Calls MacPrintFile on each of the files passed
210 short wxApp::MacHandleAEPDoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
214 DescType returnedType
;
220 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
224 err
= AECountItems(&docList
, &itemsInList
);
228 ProcessSerialNumber PSN
;
229 PSN
.highLongOfPSN
= 0 ;
230 PSN
.lowLongOfPSN
= kCurrentProcess
;
231 SetFrontProcess( &PSN
) ;
236 for (i
= 1; i
<= itemsInList
; i
++)
239 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
240 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
241 fName
= wxMacFSRefToPath( &theRef
) ;
249 // AEOApp calls MacNewFile
251 short wxApp::MacHandleAEOApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
257 // AEQuit attempts to quit the application
259 short wxApp::MacHandleAEQuit(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
261 wxWindow
* win
= GetTopWindow() ;
264 wxCommandEvent
exitEvent(wxEVT_COMMAND_MENU_SELECTED
, s_macExitMenuItemId
);
265 if (!win
->ProcessEvent(exitEvent
))
276 // AEROApp calls MacReopenApp
278 short wxApp::MacHandleAERApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
285 //----------------------------------------------------------------------
286 // Support Routines linking the Mac...File Calls to the Document Manager
287 //----------------------------------------------------------------------
289 void wxApp::MacOpenFile(const wxString
& fileName
)
291 #if wxUSE_DOC_VIEW_ARCHITECTURE
292 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
294 dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
298 void wxApp::MacOpenURL(const wxString
& WXUNUSED(url
) )
302 void wxApp::MacPrintFile(const wxString
& fileName
)
304 #if wxUSE_DOC_VIEW_ARCHITECTURE
306 #if wxUSE_PRINTING_ARCHITECTURE
307 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
310 wxDocument
*doc
= dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
313 wxView
* view
= doc
->GetFirstView() ;
316 wxPrintout
*printout
= view
->OnCreatePrintout();
320 printer
.Print(view
->GetFrame(), printout
, true);
327 doc
->DeleteAllViews();
328 dm
->RemoveDocument(doc
) ;
339 void wxApp::MacNewFile()
343 void wxApp::MacReopenApp()
346 // if there is no open window -> create a new one
347 // if all windows are hidden -> show the first
348 // if some windows are not hidden -> do nothing
350 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetFirst();
357 wxTopLevelWindow
* firstIconized
= NULL
;
358 wxTopLevelWindow
* firstHidden
= NULL
;
361 wxTopLevelWindow
* win
= (wxTopLevelWindow
*) node
->GetData();
362 if ( !win
->IsShown() )
364 // make sure we don't show 'virtual toplevel windows' like wxTaskBarIconWindow
365 if ( firstHidden
== NULL
&& ( wxDynamicCast( win
, wxFrame
) || wxDynamicCast( win
, wxDialog
) ) )
368 else if ( win
->IsIconized() )
370 if ( firstIconized
== NULL
)
371 firstIconized
= win
;
375 // we do have a visible, non-iconized toplevelwindow -> do nothing
379 node
= node
->GetNext();
383 firstIconized
->Iconize( false ) ;
384 else if ( firstHidden
)
385 firstHidden
->Show( true );
389 //----------------------------------------------------------------------
390 // Macintosh CommandID support - converting between native and wx IDs
391 //----------------------------------------------------------------------
393 // if no native match they just return the passed-in id
401 IdPair gCommandIds
[] =
403 { kHICommandCut
, wxID_CUT
} ,
404 { kHICommandCopy
, wxID_COPY
} ,
405 { kHICommandPaste
, wxID_PASTE
} ,
406 { kHICommandSelectAll
, wxID_SELECTALL
} ,
407 { kHICommandClear
, wxID_CLEAR
} ,
408 { kHICommandUndo
, wxID_UNDO
} ,
409 { kHICommandRedo
, wxID_REDO
} ,
412 int wxMacCommandToId( UInt32 macCommandId
)
416 switch ( macCommandId
)
418 case kHICommandPreferences
:
419 wxid
= wxApp::s_macPreferencesMenuItemId
;
422 case kHICommandQuit
:
423 wxid
= wxApp::s_macExitMenuItemId
;
426 case kHICommandAbout
:
427 wxid
= wxApp::s_macAboutMenuItemId
;
432 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
434 if ( gCommandIds
[i
].macId
== macCommandId
)
436 wxid
= gCommandIds
[i
].wxId
;
445 wxid
= (int) macCommandId
;
450 UInt32
wxIdToMacCommand( int wxId
)
454 if ( wxId
== wxApp::s_macPreferencesMenuItemId
)
455 macId
= kHICommandPreferences
;
456 else if (wxId
== wxApp::s_macExitMenuItemId
)
457 macId
= kHICommandQuit
;
458 else if (wxId
== wxApp::s_macAboutMenuItemId
)
459 macId
= kHICommandAbout
;
462 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
464 if ( gCommandIds
[i
].wxId
== wxId
)
466 macId
= gCommandIds
[i
].macId
;
478 wxMenu
* wxFindMenuFromMacCommand( const HICommand
&command
, wxMenuItem
* &item
)
480 wxMenu
* itemMenu
= NULL
;
481 #ifndef __WXUNIVERSAL__
484 // for 'standard' commands which don't have a wx-menu
485 if ( command
.commandID
== kHICommandPreferences
|| command
.commandID
== kHICommandQuit
|| command
.commandID
== kHICommandAbout
)
487 id
= wxMacCommandToId( command
.commandID
) ;
489 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
491 item
= mbar
->FindItem( id
, &itemMenu
) ;
493 else if ( command
.commandID
!= 0 && command
.menu
.menuRef
!= 0 && command
.menu
.menuItemIndex
!= 0 )
495 id
= wxMacCommandToId( command
.commandID
) ;
496 // make sure it is one of our own menus, or of the 'synthetic' apple and help menus , otherwise don't touch
497 MenuItemIndex firstUserHelpMenuItem
;
498 static MenuHandle helpMenuHandle
= NULL
;
499 if ( helpMenuHandle
== NULL
)
501 if ( UMAGetHelpMenuDontCreate( &helpMenuHandle
, &firstUserHelpMenuItem
) != noErr
)
502 helpMenuHandle
= NULL
;
505 // is it part of the application or the Help menu, then look for the id directly
506 if ( ( GetMenuHandle( kwxMacAppleMenuId
) != NULL
&& command
.menu
.menuRef
== GetMenuHandle( kwxMacAppleMenuId
) ) ||
507 ( helpMenuHandle
!= NULL
&& command
.menu
.menuRef
== helpMenuHandle
) ||
508 wxMenuBar::MacGetWindowMenuHMenu() != NULL
&& command
.menu
.menuRef
== wxMenuBar::MacGetWindowMenuHMenu() )
510 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
512 item
= mbar
->FindItem( id
, &itemMenu
) ;
518 GetMenuItemRefCon( command
.menu
.menuRef
, command
.menu
.menuItemIndex
, &refCon
) ;
519 itemMenu
= wxFindMenuFromMacMenu( command
.menu
.menuRef
) ;
520 if ( itemMenu
!= NULL
)
521 item
= (wxMenuItem
*) refCon
;
528 //----------------------------------------------------------------------
529 // Carbon Event Handler
530 //----------------------------------------------------------------------
532 static const EventTypeSpec eventList
[] =
534 { kEventClassCommand
, kEventProcessCommand
} ,
535 { kEventClassCommand
, kEventCommandUpdateStatus
} ,
537 { kEventClassMenu
, kEventMenuOpening
},
538 { kEventClassMenu
, kEventMenuClosed
},
539 { kEventClassMenu
, kEventMenuTargetItem
},
541 { kEventClassApplication
, kEventAppActivated
} ,
542 { kEventClassApplication
, kEventAppDeactivated
} ,
543 // handling the quit event is not recommended by apple
544 // rather using the quit apple event - which we do
546 { kEventClassAppleEvent
, kEventAppleEvent
} ,
548 { kEventClassMouse
, kEventMouseDown
} ,
549 { kEventClassMouse
, kEventMouseMoved
} ,
550 { kEventClassMouse
, kEventMouseUp
} ,
551 { kEventClassMouse
, kEventMouseDragged
} ,
555 static pascal OSStatus
556 wxMacAppMenuEventHandler( EventHandlerCallRef
WXUNUSED(handler
),
558 void *WXUNUSED(data
) )
560 wxMacCarbonEvent
cEvent( event
) ;
561 MenuRef menuRef
= cEvent
.GetParameter
<MenuRef
>(kEventParamDirectObject
) ;
562 #ifndef __WXUNIVERSAL__
563 wxMenu
* menu
= wxFindMenuFromMacMenu( menuRef
) ;
569 switch (GetEventKind(event
))
571 case kEventMenuOpening
:
572 type
= wxEVT_MENU_OPEN
;
575 case kEventMenuClosed
:
576 type
= wxEVT_MENU_CLOSE
;
579 case kEventMenuTargetItem
:
580 cmd
= cEvent
.GetParameter
<MenuCommand
>(kEventParamMenuCommand
,typeMenuCommand
) ;
582 type
= wxEVT_MENU_HIGHLIGHT
;
586 wxFAIL_MSG(wxT("Unexpected menu event kind"));
592 wxMenuEvent
wxevent(type
, cmd
, menu
);
593 wxevent
.SetEventObject(menu
);
595 wxEvtHandler
* handler
= menu
->GetEventHandler();
596 if (handler
&& handler
->ProcessEvent(wxevent
))
602 wxWindow
*win
= menu
->GetInvokingWindow();
604 win
->GetEventHandler()->ProcessEvent(wxevent
);
609 return eventNotHandledErr
;
612 static pascal OSStatus
613 wxMacAppCommandEventHandler( EventHandlerCallRef
WXUNUSED(handler
) ,
615 void *WXUNUSED(data
) )
617 OSStatus result
= eventNotHandledErr
;
621 wxMacCarbonEvent
cEvent( event
) ;
622 cEvent
.GetParameter
<HICommand
>(kEventParamDirectObject
,typeHICommand
,&command
) ;
624 wxMenuItem
* item
= NULL
;
625 wxMenu
* itemMenu
= wxFindMenuFromMacCommand( command
, item
) ;
626 int id
= wxMacCommandToId( command
.commandID
) ;
630 wxASSERT( itemMenu
!= NULL
) ;
632 switch ( cEvent
.GetKind() )
634 case kEventProcessCommand
:
635 result
= itemMenu
->MacHandleCommandProcess( item
, id
);
638 case kEventCommandUpdateStatus
:
639 result
= itemMenu
->MacHandleCommandUpdateStatus( item
, id
);
649 static pascal OSStatus
650 wxMacAppApplicationEventHandler( EventHandlerCallRef
WXUNUSED(handler
) ,
652 void *WXUNUSED(data
) )
654 OSStatus result
= eventNotHandledErr
;
655 switch ( GetEventKind( event
) )
657 case kEventAppActivated
:
659 wxTheApp
->SetActive( true , NULL
) ;
663 case kEventAppDeactivated
:
665 wxTheApp
->SetActive( false , NULL
) ;
676 pascal OSStatus
wxMacAppEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
678 EventRef formerEvent
= (EventRef
) wxTheApp
->MacGetCurrentEvent() ;
679 EventHandlerCallRef formerEventHandlerCallRef
= (EventHandlerCallRef
) wxTheApp
->MacGetCurrentEventHandlerCallRef() ;
680 wxTheApp
->MacSetCurrentEvent( event
, handler
) ;
682 OSStatus result
= eventNotHandledErr
;
683 switch ( GetEventClass( event
) )
685 case kEventClassCommand
:
686 result
= wxMacAppCommandEventHandler( handler
, event
, data
) ;
689 case kEventClassApplication
:
690 result
= wxMacAppApplicationEventHandler( handler
, event
, data
) ;
693 case kEventClassMenu
:
694 result
= wxMacAppMenuEventHandler( handler
, event
, data
) ;
697 case kEventClassMouse
:
699 wxMacCarbonEvent
cEvent( event
) ;
702 Point screenMouseLocation
= cEvent
.GetParameter
<Point
>(kEventParamMouseLocation
) ;
703 ::FindWindow(screenMouseLocation
, &window
);
704 // only send this event in case it had not already been sent to a tlw, as we get
705 // double events otherwise (in case event.skip) was called
706 if ( window
== NULL
)
707 result
= wxMacTopLevelMouseEventHandler( handler
, event
, NULL
) ;
711 case kEventClassAppleEvent
:
715 wxMacConvertEventToRecord( event
, &rec
) ;
716 result
= AEProcessAppleEvent( &rec
) ;
724 wxTheApp
->MacSetCurrentEvent( formerEvent
, formerEventHandlerCallRef
) ;
729 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler
)
734 wxMacAssertOutputHandler(OSType
WXUNUSED(componentSignature
),
735 UInt32
WXUNUSED(options
),
736 const char *assertionString
,
737 const char *exceptionLabelString
,
738 const char *errorString
,
739 const char *fileName
,
742 ConstStr255Param
WXUNUSED(outputMsg
))
744 // flow into assert handling
745 wxString fileNameStr
;
746 wxString assertionStr
;
747 wxString exceptionStr
;
751 fileNameStr
= wxString(fileName
, wxConvLocal
);
752 assertionStr
= wxString(assertionString
, wxConvLocal
);
753 exceptionStr
= wxString((exceptionLabelString
!=0) ? exceptionLabelString
: "", wxConvLocal
) ;
754 errorStr
= wxString((errorString
!=0) ? errorString
: "", wxConvLocal
) ;
756 fileNameStr
= fileName
;
757 assertionStr
= assertionString
;
758 exceptionStr
= (exceptionLabelString
!=0) ? exceptionLabelString
: "" ;
759 errorStr
= (errorString
!=0) ? errorString
: "" ;
764 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
765 assertionStr
.c_str() ,
766 exceptionStr
.c_str() ,
768 fileNameStr
.c_str(), lineNumber
,
772 wxOnAssert(fileNameStr
, lineNumber
, assertionStr
,
773 wxString::Format( wxT("%s %s value (%p)") , exceptionStr
, errorStr
, value
) ) ;
780 extern "C" void macPostedEventCallback(void *WXUNUSED(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 // Mac OS X passes a process serial number command line argument when
814 // the application is launched from the Finder. This argument must be
815 // removed from the command line arguments before being handled by the
816 // application (otherwise applications would need to handle it)
819 static const wxChar
*ARG_PSN
= _T("-psn_");
820 if ( wxStrncmp(argv
[1], ARG_PSN
, wxStrlen(ARG_PSN
)) == 0 )
822 // remove this argument
824 memmove(argv
+ 1, argv
+ 2, argc
* sizeof(char *));
828 if ( !wxAppBase::Initialize(argc
, argv
) )
832 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
835 #if TARGET_API_MAC_OSX
836 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
837 wxString startupCwd
= wxGetCwd() ;
838 if ( startupCwd
== wxT("/") || startupCwd
.Right(15) == wxT("/Contents/MacOS") )
840 CFURLRef url
= CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
841 CFURLRef urlParent
= CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault
, url
) ;
843 CFStringRef path
= CFURLCopyFileSystemPath ( urlParent
, kCFURLPOSIXPathStyle
) ;
844 CFRelease( urlParent
) ;
845 wxString cwd
= wxMacCFStringHolder(path
).AsString(wxLocale::GetSystemEncoding());
846 wxSetWorkingDirectory( cwd
) ;
850 wxMacCreateNotifierTable() ;
853 /* connect posted events to common-mode run loop so that wxPostEvent events
854 are handled even while we're in the menu or on a scrollbar */
855 CFRunLoopSourceContext event_posted_context
= {0};
856 event_posted_context
.perform
= macPostedEventCallback
;
857 m_macEventPosted
= CFRunLoopSourceCreate(NULL
,0,&event_posted_context
);
858 CFRunLoopAddSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
859 // run loop takes ownership
860 CFRelease(m_macEventPosted
);
863 UMAShowArrowCursor() ;
868 AEEventHandlerUPP sODocHandler
= NULL
;
869 AEEventHandlerUPP sGURLHandler
= NULL
;
870 AEEventHandlerUPP sOAppHandler
= NULL
;
871 AEEventHandlerUPP sPDocHandler
= NULL
;
872 AEEventHandlerUPP sRAppHandler
= NULL
;
873 AEEventHandlerUPP sQuitHandler
= NULL
;
875 bool wxApp::OnInitGui()
877 if ( !wxAppBase::OnInitGui() )
880 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
884 InstallApplicationEventHandler(
885 GetwxMacAppEventHandlerUPP(),
886 GetEventTypeCount(eventList
), eventList
, wxTheApp
, (EventHandlerRef
*)&(wxTheApp
->m_macEventHandler
));
891 sODocHandler
= NewAEEventHandlerUPP(AEHandleODoc
) ;
892 sGURLHandler
= NewAEEventHandlerUPP(AEHandleGURL
) ;
893 sOAppHandler
= NewAEEventHandlerUPP(AEHandleOApp
) ;
894 sPDocHandler
= NewAEEventHandlerUPP(AEHandlePDoc
) ;
895 sRAppHandler
= NewAEEventHandlerUPP(AEHandleRApp
) ;
896 sQuitHandler
= NewAEEventHandlerUPP(AEHandleQuit
) ;
898 AEInstallEventHandler( kCoreEventClass
, kAEOpenDocuments
,
899 sODocHandler
, 0 , FALSE
) ;
900 AEInstallEventHandler( kInternetEventClass
, kAEGetURL
,
901 sGURLHandler
, 0 , FALSE
) ;
902 AEInstallEventHandler( kCoreEventClass
, kAEOpenApplication
,
903 sOAppHandler
, 0 , FALSE
) ;
904 AEInstallEventHandler( kCoreEventClass
, kAEPrintDocuments
,
905 sPDocHandler
, 0 , FALSE
) ;
906 AEInstallEventHandler( kCoreEventClass
, kAEReopenApplication
,
907 sRAppHandler
, 0 , FALSE
) ;
908 AEInstallEventHandler( kCoreEventClass
, kAEQuitApplication
,
909 sQuitHandler
, 0 , FALSE
) ;
912 if ( !wxMacInitCocoa() )
918 void wxApp::CleanUp()
921 wxToolTip::RemoveToolTips() ;
925 if (m_macEventPosted
)
927 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
928 m_macEventPosted
= NULL
;
932 // One last chance for pending objects to be cleaned up
933 wxTheApp
->DeletePendingObjects();
935 wxMacDestroyNotifierTable() ;
938 # if __option(profile)
939 ProfilerDump( (StringPtr
)"\papp.prof" ) ;
944 UMACleanupToolbox() ;
947 RemoveEventHandler( (EventHandlerRef
)(wxTheApp
->m_macEventHandler
) );
951 AERemoveEventHandler( kCoreEventClass
, kAEOpenDocuments
,
952 sODocHandler
, FALSE
) ;
953 AERemoveEventHandler( kInternetEventClass
, kAEGetURL
,
954 sGURLHandler
, FALSE
) ;
955 AERemoveEventHandler( kCoreEventClass
, kAEOpenApplication
,
956 sOAppHandler
, FALSE
) ;
957 AERemoveEventHandler( kCoreEventClass
, kAEPrintDocuments
,
958 sPDocHandler
, FALSE
) ;
959 AERemoveEventHandler( kCoreEventClass
, kAEReopenApplication
,
960 sRAppHandler
, FALSE
) ;
961 AERemoveEventHandler( kCoreEventClass
, kAEQuitApplication
,
962 sQuitHandler
, FALSE
) ;
964 DisposeAEEventHandlerUPP( sODocHandler
) ;
965 DisposeAEEventHandlerUPP( sGURLHandler
) ;
966 DisposeAEEventHandlerUPP( sOAppHandler
) ;
967 DisposeAEEventHandlerUPP( sPDocHandler
) ;
968 DisposeAEEventHandlerUPP( sRAppHandler
) ;
969 DisposeAEEventHandlerUPP( sQuitHandler
) ;
972 wxAppBase::CleanUp();
975 //----------------------------------------------------------------------
976 // misc initialization stuff
977 //----------------------------------------------------------------------
979 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
981 // for shared libraries we have to manually get the correct resource
982 // ref num upon initializing and releasing when terminating, therefore
983 // the __wxinitialize and __wxterminate must be used
987 void __sinit(void); // (generated by linker)
988 pascal OSErr
__initialize(const CFragInitBlock
*theInitBlock
);
989 pascal void __terminate(void);
992 pascal OSErr
__wxinitialize(const CFragInitBlock
*theInitBlock
)
994 return __initialize( theInitBlock
) ;
997 pascal void __wxterminate(void)
1002 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
1004 bool wxMacConvertEventToRecord( EventRef event
, EventRecord
*rec
)
1006 OSStatus err
= noErr
;
1007 bool converted
= ConvertEventRefToEventRecord( event
, rec
) ;
1011 switch ( GetEventClass( event
) )
1013 case kEventClassKeyboard
:
1016 switch ( GetEventKind(event
) )
1018 case kEventRawKeyDown
:
1019 rec
->what
= keyDown
;
1022 case kEventRawKeyRepeat
:
1023 rec
->what
= autoKey
;
1026 case kEventRawKeyUp
:
1030 case kEventRawKeyModifiersChanged
:
1031 rec
->what
= nullEvent
;
1042 unsigned char charCode
;
1045 GetMouse( &rec
->where
) ;
1047 err
= GetEventParameter(event
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1048 err
= GetEventParameter(event
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1049 err
= GetEventParameter(event
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1050 rec
->modifiers
= modifiers
;
1051 rec
->message
= (keyCode
<< 8 ) + charCode
;
1056 case kEventClassTextInput
:
1058 switch ( GetEventKind( event
) )
1060 case kEventTextInputUnicodeForKeyEvent
:
1063 err
= GetEventParameter(
1064 event
, kEventParamTextInputSendKeyboardEvent
, typeEventRef
, NULL
,
1065 sizeof(rawEvent
), NULL
, &rawEvent
) ;
1069 UInt32 keyCode
, modifiers
;
1070 unsigned char charCode
;
1073 GetMouse( &rec
->where
) ;
1075 rec
->what
= keyDown
;
1076 err
= GetEventParameter(rawEvent
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1077 err
= GetEventParameter(rawEvent
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1078 err
= GetEventParameter(rawEvent
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1079 rec
->modifiers
= modifiers
;
1080 rec
->message
= (keyCode
<< 8 ) + charCode
;
1101 m_printMode
= wxPRINT_WINDOWS
;
1103 m_macCurrentEvent
= NULL
;
1104 m_macCurrentEventHandlerCallRef
= NULL
;
1106 #ifdef __WXMAC_OSX__
1107 m_macEventPosted
= NULL
;
1111 void wxApp::OnIdle(wxIdleEvent
& WXUNUSED(event
))
1113 // If they are pending events, we must process them: pending events are
1114 // either events to the threads other than main or events posted with
1115 // wxPostEvent() functions
1116 wxMacProcessNotifierAndPendingEvents();
1117 #ifndef __WXUNIVERSAL__
1118 if (!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1119 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1123 void wxApp::WakeUpIdle()
1125 #ifdef __WXMAC_OSX__
1126 if (m_macEventPosted
)
1128 CFRunLoopSourceSignal(m_macEventPosted
);
1135 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1138 GetTopWindow()->Close(true);
1141 // Default behaviour: close the application with prompts. The
1142 // user can veto the close, and therefore the end session.
1143 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1147 if (!GetTopWindow()->Close(!event
.CanVeto()))
1152 extern "C" void wxCYield() ;
1158 // Yield to other processes
1160 bool wxApp::Yield(bool onlyIfNeeded
)
1164 if ( !onlyIfNeeded
)
1166 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1173 // Yielding from a non-gui thread needs to bail out, otherwise we end up
1174 // possibly sending events in the thread too.
1175 if ( !wxThread::IsMain() )
1179 #endif // wxUSE_THREADS
1183 // by definition yield should handle all non-processed events
1187 OSStatus status
= noErr
;
1189 while ( status
== noErr
)
1191 s_inReceiveEvent
= true ;
1192 status
= ReceiveNextEvent(0, NULL
,kEventDurationNoWait
,true,&theEvent
) ;
1193 s_inReceiveEvent
= false ;
1195 if ( status
== eventLoopTimedOutErr
)
1197 // make sure next time the event loop will trigger idle events
1198 sleepTime
= kEventDurationNoWait
;
1200 else if ( status
== eventLoopQuitErr
)
1202 // according to QA1061 this may also occur when a WakeUp Process
1207 MacHandleOneEvent( theEvent
) ;
1208 ReleaseEvent(theEvent
);
1212 wxMacProcessNotifierAndPendingEvents() ;
1218 void wxApp::MacDoOneEvent()
1220 wxMacAutoreleasePool autoreleasepool
;
1223 s_inReceiveEvent
= true ;
1224 OSStatus status
= ReceiveNextEvent(0, NULL
, sleepTime
, true, &theEvent
) ;
1225 s_inReceiveEvent
= false ;
1229 case eventLoopTimedOutErr
:
1230 if ( wxTheApp
->ProcessIdle() )
1231 sleepTime
= kEventDurationNoWait
;
1233 sleepTime
= kEventDurationSecond
;
1236 case eventLoopQuitErr
:
1237 // according to QA1061 this may also occur
1238 // when a WakeUp Process is executed
1242 MacHandleOneEvent( theEvent
) ;
1243 ReleaseEvent( theEvent
);
1244 sleepTime
= kEventDurationNoWait
;
1249 DeletePendingObjects() ;
1250 wxMacProcessNotifierAndPendingEvents() ;
1254 void wxApp::MacHandleUnhandledEvent( WXEVENTREF
WXUNUSED(evr
) )
1256 // Override to process unhandled events as you please
1259 CFMutableArrayRef
GetAutoReleaseArray()
1261 static CFMutableArrayRef array
= 0;
1263 array
= CFArrayCreateMutable(kCFAllocatorDefault
,0,&kCFTypeArrayCallBacks
);
1267 void wxApp::MacHandleOneEvent( WXEVENTREF evr
)
1269 EventTargetRef theTarget
;
1270 theTarget
= GetEventDispatcherTarget();
1271 m_macCurrentEvent
= evr
;
1273 OSStatus status
= SendEventToEventTarget((EventRef
) evr
, theTarget
);
1274 if (status
== eventNotHandledErr
)
1275 MacHandleUnhandledEvent(evr
);
1277 wxMacProcessNotifierAndPendingEvents() ;
1280 wxMutexGuiLeaveOrEnter();
1281 #endif // wxUSE_THREADS
1283 CFArrayRemoveAllValues( GetAutoReleaseArray() );
1286 void wxApp::MacAddToAutorelease( void* cfrefobj
)
1288 CFArrayAppendValue( GetAutoReleaseArray(), cfrefobj
);
1291 long wxMacTranslateKey(unsigned char key
, unsigned char code
)
1296 case kHomeCharCode
:
1300 case kEnterCharCode
:
1301 retval
= WXK_RETURN
;
1307 case kHelpCharCode
:
1311 case kBackspaceCharCode
:
1319 case kPageUpCharCode
:
1320 retval
= WXK_PAGEUP
;
1323 case kPageDownCharCode
:
1324 retval
= WXK_PAGEDOWN
;
1327 case kReturnCharCode
:
1328 retval
= WXK_RETURN
;
1331 case kFunctionKeyCharCode
:
1401 case kEscapeCharCode
:
1402 retval
= WXK_ESCAPE
;
1405 case kLeftArrowCharCode
:
1409 case kRightArrowCharCode
:
1410 retval
= WXK_RIGHT
;
1413 case kUpArrowCharCode
:
1417 case kDownArrowCharCode
:
1421 case kDeleteCharCode
:
1422 retval
= WXK_DELETE
;
1432 int wxMacKeyCodeToModifier(wxKeyCode key
)
1458 bool wxGetKeyState(wxKeyCode key
) //virtual key code if < 10.2.x, else see below
1460 wxASSERT_MSG(key
!= WXK_LBUTTON
&& key
!= WXK_RBUTTON
&& key
!=
1461 WXK_MBUTTON
, wxT("can't use wxGetKeyState() for mouse buttons"));
1463 //if OS X > 10.2 (i.e. 10.2.x)
1464 //a known apple bug prevents the system from determining led
1465 //states with GetKeys... can only determine caps lock led
1466 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key
));
1468 // KeyMapByteArray keymap;
1469 // GetKeys((BigEndianLong*)keymap);
1470 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1475 wxMouseState
wxGetMouseState()
1479 wxPoint pt
= wxGetMousePosition();
1483 #if TARGET_API_MAC_OSX
1484 UInt32 buttons
= GetCurrentButtonState();
1485 ms
.SetLeftDown( (buttons
& 0x01) != 0 );
1486 ms
.SetMiddleDown( (buttons
& 0x04) != 0 );
1487 ms
.SetRightDown( (buttons
& 0x02) != 0 );
1489 ms
.SetLeftDown( Button() );
1490 ms
.SetMiddleDown( 0 );
1491 ms
.SetRightDown( 0 );
1494 UInt32 modifiers
= GetCurrentKeyModifiers();
1495 ms
.SetControlDown(modifiers
& controlKey
);
1496 ms
.SetShiftDown(modifiers
& shiftKey
);
1497 ms
.SetAltDown(modifiers
& optionKey
);
1498 ms
.SetMetaDown(modifiers
& cmdKey
);
1503 // TODO : once the new key/char handling is tested, move all the code to wxWindow
1505 bool wxApp::MacSendKeyDownEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1511 wxKeyEvent
event(wxEVT_KEY_DOWN
) ;
1512 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1514 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1515 if ( handled
&& event
.GetSkipped() )
1521 wxWindow
*ancestor
= focus
;
1524 int command
= ancestor
->GetAcceleratorTable()->GetCommand( event
);
1527 wxEvtHandler
* const handler
= ancestor
->GetEventHandler();
1529 wxCommandEvent
command_event( wxEVT_COMMAND_MENU_SELECTED
, command
);
1530 handled
= handler
->ProcessEvent( command_event
);
1534 // accelerators can also be used with buttons, try them too
1535 command_event
.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED
);
1536 handled
= handler
->ProcessEvent( command_event
);
1542 if (ancestor
->IsTopLevel())
1545 ancestor
= ancestor
->GetParent();
1548 #endif // wxUSE_ACCEL
1553 bool wxApp::MacSendKeyUpEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1559 wxKeyEvent
event( wxEVT_KEY_UP
) ;
1560 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1561 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1566 bool wxApp::MacSendCharEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1571 wxKeyEvent
event(wxEVT_CHAR
) ;
1572 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1573 long keyval
= event
.m_keyCode
;
1575 bool handled
= false ;
1577 wxTopLevelWindowMac
*tlw
= focus
->MacGetTopLevelWindow() ;
1581 event
.SetEventType( wxEVT_CHAR_HOOK
);
1582 handled
= tlw
->GetEventHandler()->ProcessEvent( event
);
1583 if ( handled
&& event
.GetSkipped() )
1589 event
.SetEventType( wxEVT_CHAR
);
1590 event
.Skip( false ) ;
1591 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1594 if ( !handled
&& (keyval
== WXK_TAB
) )
1596 wxWindow
* iter
= focus
->GetParent() ;
1597 while ( iter
&& !handled
)
1599 if ( iter
->HasFlag( wxTAB_TRAVERSAL
) )
1601 wxNavigationKeyEvent new_event
;
1602 new_event
.SetEventObject( focus
);
1603 new_event
.SetDirection( !event
.ShiftDown() );
1604 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1605 new_event
.SetWindowChange( event
.ControlDown() );
1606 new_event
.SetCurrentFocus( focus
);
1607 handled
= focus
->GetParent()->GetEventHandler()->ProcessEvent( new_event
);
1608 if ( handled
&& new_event
.GetSkipped() )
1612 iter
= iter
->GetParent() ;
1616 // backdoor handler for default return and command escape
1617 if ( !handled
&& (!focus
->IsKindOf(CLASSINFO(wxControl
) ) || !focus
->MacCanFocus() ) )
1619 // if window is not having a focus still testing for default enter or cancel
1620 // TODO: add the UMA version for ActiveNonFloatingWindow
1621 wxWindow
* focus
= wxFindWinFromMacWindow( FrontWindow() ) ;
1624 if ( keyval
== WXK_RETURN
|| keyval
== WXK_NUMPAD_ENTER
)
1626 wxTopLevelWindow
*tlw
= wxDynamicCast(wxGetTopLevelParent(focus
), wxTopLevelWindow
);
1627 if ( tlw
&& tlw
->GetDefaultItem() )
1629 wxButton
*def
= wxDynamicCast(tlw
->GetDefaultItem(), wxButton
);
1630 if ( def
&& def
->IsEnabled() )
1632 wxCommandEvent
event(wxEVT_COMMAND_BUTTON_CLICKED
, def
->GetId() );
1633 event
.SetEventObject(def
);
1634 def
->Command(event
);
1640 else if (keyval
== WXK_ESCAPE
|| (keyval
== '.' && modifiers
& cmdKey
) )
1642 // generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs)
1643 wxCommandEvent
new_event(wxEVT_COMMAND_BUTTON_CLICKED
,wxID_CANCEL
);
1644 new_event
.SetEventObject( focus
);
1645 handled
= focus
->GetEventHandler()->ProcessEvent( new_event
);
1652 // This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
1653 void wxApp::MacCreateKeyEvent( wxKeyEvent
& event
, wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1655 short keycode
, keychar
;
1657 keychar
= short(keymessage
& charCodeMask
);
1658 keycode
= short(keymessage
& keyCodeMask
) >> 8 ;
1659 if ( !(event
.GetEventType() == wxEVT_CHAR
) && (modifiers
& (controlKey
| shiftKey
| optionKey
) ) )
1661 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1662 // and look at the character after
1664 // TODO new implementation using TextInputSources
1667 UInt32 keyInfo
= KeyTranslate((Ptr
)GetScriptManagerVariable(smKCHRCache
), ( modifiers
& (~(controlKey
| shiftKey
| optionKey
))) | keycode
, &state
);
1668 keychar
= short(keyInfo
& charCodeMask
);
1672 long keyval
= wxMacTranslateKey(keychar
, keycode
) ;
1673 if ( keyval
== keychar
&& ( event
.GetEventType() == wxEVT_KEY_UP
|| event
.GetEventType() == wxEVT_KEY_DOWN
) )
1674 keyval
= wxToupper( keyval
) ;
1676 // Check for NUMPAD keys. For KEY_UP/DOWN events we need to use the
1677 // WXK_NUMPAD constants, but for the CHAR event we want to use the
1678 // standard ascii values
1679 if ( event
.GetEventType() != wxEVT_CHAR
)
1681 if (keyval
>= '0' && keyval
<= '9' && keycode
>= 82 && keycode
<= 92)
1683 keyval
= (keyval
- '0') + WXK_NUMPAD0
;
1685 else if (keycode
>= 65 && keycode
<= 81)
1690 keyval
= WXK_NUMPAD_ENTER
;
1694 keyval
= WXK_NUMPAD_EQUAL
;
1698 keyval
= WXK_NUMPAD_MULTIPLY
;
1702 keyval
= WXK_NUMPAD_DIVIDE
;
1706 keyval
= WXK_NUMPAD_SUBTRACT
;
1710 keyval
= WXK_NUMPAD_ADD
;
1714 keyval
= WXK_NUMPAD_DECIMAL
;
1722 event
.m_shiftDown
= modifiers
& shiftKey
;
1723 event
.m_controlDown
= modifiers
& controlKey
;
1724 event
.m_altDown
= modifiers
& optionKey
;
1725 event
.m_metaDown
= modifiers
& cmdKey
;
1726 event
.m_keyCode
= keyval
;
1728 event
.m_uniChar
= uniChar
;
1731 event
.m_rawCode
= keymessage
;
1732 event
.m_rawFlags
= modifiers
;
1735 event
.SetTimestamp(when
);
1736 event
.SetEventObject(focus
);