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
, long 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
& 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
;
360 wxTopLevelWindow
* win
= (wxTopLevelWindow
*) node
->GetData();
361 if ( !win
->IsIconized() )
363 firstIconized
= NULL
;
368 if ( firstIconized
== NULL
)
369 firstIconized
= win
;
372 node
= node
->GetNext();
376 firstIconized
->Iconize( false ) ;
380 //----------------------------------------------------------------------
381 // Macintosh CommandID support - converting between native and wx IDs
382 //----------------------------------------------------------------------
384 // if no native match they just return the passed-in id
392 IdPair gCommandIds
[] =
394 { kHICommandCut
, wxID_CUT
} ,
395 { kHICommandCopy
, wxID_COPY
} ,
396 { kHICommandPaste
, wxID_PASTE
} ,
397 { kHICommandSelectAll
, wxID_SELECTALL
} ,
398 { kHICommandClear
, wxID_CLEAR
} ,
399 { kHICommandUndo
, wxID_UNDO
} ,
400 { kHICommandRedo
, wxID_REDO
} ,
403 int wxMacCommandToId( UInt32 macCommandId
)
407 switch ( macCommandId
)
409 case kHICommandPreferences
:
410 wxid
= wxApp::s_macPreferencesMenuItemId
;
413 case kHICommandQuit
:
414 wxid
= wxApp::s_macExitMenuItemId
;
417 case kHICommandAbout
:
418 wxid
= wxApp::s_macAboutMenuItemId
;
423 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
425 if ( gCommandIds
[i
].macId
== macCommandId
)
427 wxid
= gCommandIds
[i
].wxId
;
436 wxid
= (int) macCommandId
;
441 UInt32
wxIdToMacCommand( int wxId
)
445 if ( wxId
== wxApp::s_macPreferencesMenuItemId
)
446 macId
= kHICommandPreferences
;
447 else if (wxId
== wxApp::s_macExitMenuItemId
)
448 macId
= kHICommandQuit
;
449 else if (wxId
== wxApp::s_macAboutMenuItemId
)
450 macId
= kHICommandAbout
;
453 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
455 if ( gCommandIds
[i
].wxId
== wxId
)
457 macId
= gCommandIds
[i
].macId
;
469 wxMenu
* wxFindMenuFromMacCommand( const HICommand
&command
, wxMenuItem
* &item
)
471 wxMenu
* itemMenu
= NULL
;
474 // for 'standard' commands which don't have a wx-menu
475 if ( command
.commandID
== kHICommandPreferences
|| command
.commandID
== kHICommandQuit
|| command
.commandID
== kHICommandAbout
)
477 id
= wxMacCommandToId( command
.commandID
) ;
479 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
481 item
= mbar
->FindItem( id
, &itemMenu
) ;
483 else if ( command
.commandID
!= 0 && command
.menu
.menuRef
!= 0 && command
.menu
.menuItemIndex
!= 0 )
485 id
= wxMacCommandToId( command
.commandID
) ;
486 // make sure it is one of our own menus, or of the 'synthetic' apple and help menus , otherwise don't touch
487 MenuItemIndex firstUserHelpMenuItem
;
488 static MenuHandle helpMenuHandle
= NULL
;
489 if ( helpMenuHandle
== NULL
)
491 if ( UMAGetHelpMenuDontCreate( &helpMenuHandle
, &firstUserHelpMenuItem
) != noErr
)
492 helpMenuHandle
= NULL
;
495 // is it part of the application or the Help menu, then look for the id directly
496 if ( ( GetMenuHandle( kwxMacAppleMenuId
) != NULL
&& command
.menu
.menuRef
== GetMenuHandle( kwxMacAppleMenuId
) ) ||
497 ( helpMenuHandle
!= NULL
&& command
.menu
.menuRef
== helpMenuHandle
) ||
498 wxMenuBar::MacGetWindowMenuHMenu() != NULL
&& command
.menu
.menuRef
== wxMenuBar::MacGetWindowMenuHMenu() )
500 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
502 item
= mbar
->FindItem( id
, &itemMenu
) ;
508 GetMenuItemRefCon( command
.menu
.menuRef
, command
.menu
.menuItemIndex
, &refCon
) ;
509 itemMenu
= wxFindMenuFromMacMenu( command
.menu
.menuRef
) ;
510 if ( itemMenu
!= NULL
)
511 item
= (wxMenuItem
*) refCon
;
518 //----------------------------------------------------------------------
519 // Carbon Event Handler
520 //----------------------------------------------------------------------
522 static const EventTypeSpec eventList
[] =
524 { kEventClassCommand
, kEventProcessCommand
} ,
525 { kEventClassCommand
, kEventCommandUpdateStatus
} ,
527 { kEventClassMenu
, kEventMenuOpening
},
528 { kEventClassMenu
, kEventMenuClosed
},
529 { kEventClassMenu
, kEventMenuTargetItem
},
531 { kEventClassApplication
, kEventAppActivated
} ,
532 { kEventClassApplication
, kEventAppDeactivated
} ,
533 // handling the quit event is not recommended by apple
534 // rather using the quit apple event - which we do
536 { kEventClassAppleEvent
, kEventAppleEvent
} ,
538 { kEventClassMouse
, kEventMouseDown
} ,
539 { kEventClassMouse
, kEventMouseMoved
} ,
540 { kEventClassMouse
, kEventMouseUp
} ,
541 { kEventClassMouse
, kEventMouseDragged
} ,
545 static pascal OSStatus
546 wxMacAppMenuEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
548 wxMacCarbonEvent
cEvent( event
) ;
549 MenuRef menuRef
= cEvent
.GetParameter
<MenuRef
>(kEventParamDirectObject
) ;
550 wxMenu
* menu
= wxFindMenuFromMacMenu( menuRef
) ;
556 switch (GetEventKind(event
))
558 case kEventMenuOpening
:
559 type
= wxEVT_MENU_OPEN
;
562 case kEventMenuClosed
:
563 type
= wxEVT_MENU_CLOSE
;
566 case kEventMenuTargetItem
:
567 cmd
= cEvent
.GetParameter
<MenuCommand
>(kEventParamMenuCommand
,typeMenuCommand
) ;
569 type
= wxEVT_MENU_HIGHLIGHT
;
573 wxFAIL_MSG(wxT("Unexpected menu event kind"));
579 wxMenuEvent
wxevent(type
, cmd
, menu
);
580 wxevent
.SetEventObject(menu
);
582 wxEvtHandler
* handler
= menu
->GetEventHandler();
583 if (handler
&& handler
->ProcessEvent(wxevent
))
589 wxWindow
*win
= menu
->GetInvokingWindow();
591 win
->GetEventHandler()->ProcessEvent(wxevent
);
596 return eventNotHandledErr
;
599 static pascal OSStatus
wxMacAppCommandEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
601 OSStatus result
= eventNotHandledErr
;
605 wxMacCarbonEvent
cEvent( event
) ;
606 cEvent
.GetParameter
<HICommand
>(kEventParamDirectObject
,typeHICommand
,&command
) ;
608 wxMenuItem
* item
= NULL
;
609 wxMenu
* itemMenu
= wxFindMenuFromMacCommand( command
, item
) ;
610 int id
= wxMacCommandToId( command
.commandID
) ;
614 wxASSERT( itemMenu
!= NULL
) ;
616 switch ( cEvent
.GetKind() )
618 case kEventProcessCommand
:
620 if (item
->IsCheckable())
621 item
->Check( !item
->IsChecked() ) ;
623 if ( itemMenu
->SendEvent( id
, item
->IsCheckable() ? item
->IsChecked() : -1 ) )
628 case kEventCommandUpdateStatus
:
630 wxUpdateUIEvent
event(id
);
631 event
.SetEventObject( itemMenu
);
633 bool processed
= false;
635 // Try the menu's event handler
637 wxEvtHandler
*handler
= itemMenu
->GetEventHandler();
639 processed
= handler
->ProcessEvent(event
);
642 // Try the window the menu was popped up from
643 // (and up through the hierarchy)
646 const wxMenuBase
*menu
= itemMenu
;
649 wxWindow
*win
= menu
->GetInvokingWindow();
652 processed
= win
->GetEventHandler()->ProcessEvent(event
);
656 menu
= menu
->GetParent();
662 // if anything changed, update the changed attribute
663 if (event
.GetSetText())
664 itemMenu
->SetLabel(id
, event
.GetText());
665 if (event
.GetSetChecked())
666 itemMenu
->Check(id
, event
.GetChecked());
667 if (event
.GetSetEnabled())
668 itemMenu
->Enable(id
, event
.GetEnabled());
682 static pascal OSStatus
wxMacAppApplicationEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
684 OSStatus result
= eventNotHandledErr
;
685 switch ( GetEventKind( event
) )
687 case kEventAppActivated
:
689 wxTheApp
->SetActive( true , NULL
) ;
693 case kEventAppDeactivated
:
695 wxTheApp
->SetActive( false , NULL
) ;
706 pascal OSStatus
wxMacAppEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
708 EventRef formerEvent
= (EventRef
) wxTheApp
->MacGetCurrentEvent() ;
709 EventHandlerCallRef formerEventHandlerCallRef
= (EventHandlerCallRef
) wxTheApp
->MacGetCurrentEventHandlerCallRef() ;
710 wxTheApp
->MacSetCurrentEvent( event
, handler
) ;
712 OSStatus result
= eventNotHandledErr
;
713 switch ( GetEventClass( event
) )
715 case kEventClassCommand
:
716 result
= wxMacAppCommandEventHandler( handler
, event
, data
) ;
719 case kEventClassApplication
:
720 result
= wxMacAppApplicationEventHandler( handler
, event
, data
) ;
723 case kEventClassMenu
:
724 result
= wxMacAppMenuEventHandler( handler
, event
, data
) ;
727 case kEventClassMouse
:
729 wxMacCarbonEvent
cEvent( event
) ;
732 Point screenMouseLocation
= cEvent
.GetParameter
<Point
>(kEventParamMouseLocation
) ;
733 ::FindWindow(screenMouseLocation
, &window
);
734 // only send this event in case it had not already been sent to a tlw, as we get
735 // double events otherwise (in case event.skip) was called
736 if ( window
== NULL
)
737 result
= wxMacTopLevelMouseEventHandler( handler
, event
, NULL
) ;
741 case kEventClassAppleEvent
:
745 wxMacConvertEventToRecord( event
, &rec
) ;
746 result
= AEProcessAppleEvent( &rec
) ;
754 wxTheApp
->MacSetCurrentEvent( formerEvent
, formerEventHandlerCallRef
) ;
759 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler
)
763 pascal static void wxMacAssertOutputHandler(OSType componentSignature
, UInt32 options
,
764 const char *assertionString
, const char *exceptionLabelString
,
765 const char *errorString
, const char *fileName
, long lineNumber
, void *value
, ConstStr255Param outputMsg
)
767 // flow into assert handling
768 wxString fileNameStr
;
769 wxString assertionStr
;
770 wxString exceptionStr
;
774 fileNameStr
= wxString(fileName
, wxConvLocal
);
775 assertionStr
= wxString(assertionString
, wxConvLocal
);
776 exceptionStr
= wxString((exceptionLabelString
!=0) ? exceptionLabelString
: "", wxConvLocal
) ;
777 errorStr
= wxString((errorString
!=0) ? errorString
: "", wxConvLocal
) ;
779 fileNameStr
= fileName
;
780 assertionStr
= assertionString
;
781 exceptionStr
= (exceptionLabelString
!=0) ? exceptionLabelString
: "" ;
782 errorStr
= (errorString
!=0) ? errorString
: "" ;
787 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
788 assertionStr
.c_str() ,
789 exceptionStr
.c_str() ,
791 fileNameStr
.c_str(), lineNumber
,
795 wxOnAssert(fileNameStr
, lineNumber
, assertionStr
,
796 wxString::Format( wxT("%s %s value (%p)") , exceptionStr
, errorStr
, value
) ) ;
805 // m_macEventPosted run loop source callback:
806 void macPostedEventCallback(void *unused
);
809 void macPostedEventCallback(void *unused
)
811 wxTheApp
->ProcessPendingEvents();
815 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
820 InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler
) );
823 UMAInitToolbox( 4, sm_isEmbedded
) ;
824 SetEventMask( everyEvent
) ;
825 UMAShowWatchCursor() ;
828 # if __option(profile)
829 ProfilerInit( collectDetailed
, bestTimeBase
, 40000 , 50 ) ;
834 // now avoid exceptions thrown for new (bad_alloc)
835 // FIXME CS for some changes outside wxMac does not compile anymore
837 std::__throws_bad_alloc
= 0 ;
842 // Mac OS X passes a process serial number command line argument when
843 // the application is launched from the Finder. This argument must be
844 // removed from the command line arguments before being handled by the
845 // application (otherwise applications would need to handle it)
848 static const wxChar
*ARG_PSN
= _T("-psn_");
849 if ( wxStrncmp(argv
[1], ARG_PSN
, wxStrlen(ARG_PSN
)) == 0 )
851 // remove this argument
853 memmove(argv
+ 1, argv
+ 2, argc
* sizeof(char *));
857 if ( !wxAppBase::Initialize(argc
, argv
) )
861 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
864 #if TARGET_API_MAC_OSX
865 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
866 wxString startupCwd
= wxGetCwd() ;
867 if ( startupCwd
== wxT("/") || startupCwd
.Right(15) == wxT("/Contents/MacOS") )
869 CFURLRef url
= CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
870 CFURLRef urlParent
= CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault
, url
) ;
872 CFStringRef path
= CFURLCopyFileSystemPath ( urlParent
, kCFURLPOSIXPathStyle
) ;
873 CFRelease( urlParent
) ;
874 wxString cwd
= wxMacCFStringHolder(path
).AsString(wxLocale::GetSystemEncoding());
875 wxSetWorkingDirectory( cwd
) ;
879 wxMacCreateNotifierTable() ;
882 /* connect posted events to common-mode run loop so that wxPostEvent events
883 are handled even while we're in the menu or on a scrollbar */
884 CFRunLoopSourceContext event_posted_context
= {0};
885 event_posted_context
.perform
= macPostedEventCallback
;
886 m_macEventPosted
= CFRunLoopSourceCreate(NULL
,0,&event_posted_context
);
887 CFRunLoopAddSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
888 // run loop takes ownership
889 CFRelease(m_macEventPosted
);
892 UMAShowArrowCursor() ;
897 AEEventHandlerUPP sODocHandler
= NULL
;
898 AEEventHandlerUPP sGURLHandler
= NULL
;
899 AEEventHandlerUPP sOAppHandler
= NULL
;
900 AEEventHandlerUPP sPDocHandler
= NULL
;
901 AEEventHandlerUPP sRAppHandler
= NULL
;
902 AEEventHandlerUPP sQuitHandler
= NULL
;
904 bool wxApp::OnInitGui()
906 if ( !wxAppBase::OnInitGui() )
909 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
913 InstallApplicationEventHandler(
914 GetwxMacAppEventHandlerUPP(),
915 GetEventTypeCount(eventList
), eventList
, wxTheApp
, (EventHandlerRef
*)&(wxTheApp
->m_macEventHandler
));
920 sODocHandler
= NewAEEventHandlerUPP(AEHandleODoc
) ;
921 sGURLHandler
= NewAEEventHandlerUPP(AEHandleGURL
) ;
922 sOAppHandler
= NewAEEventHandlerUPP(AEHandleOApp
) ;
923 sPDocHandler
= NewAEEventHandlerUPP(AEHandlePDoc
) ;
924 sRAppHandler
= NewAEEventHandlerUPP(AEHandleRApp
) ;
925 sQuitHandler
= NewAEEventHandlerUPP(AEHandleQuit
) ;
927 AEInstallEventHandler( kCoreEventClass
, kAEOpenDocuments
,
928 sODocHandler
, 0 , FALSE
) ;
929 AEInstallEventHandler( kInternetEventClass
, kAEGetURL
,
930 sGURLHandler
, 0 , FALSE
) ;
931 AEInstallEventHandler( kCoreEventClass
, kAEOpenApplication
,
932 sOAppHandler
, 0 , FALSE
) ;
933 AEInstallEventHandler( kCoreEventClass
, kAEPrintDocuments
,
934 sPDocHandler
, 0 , FALSE
) ;
935 AEInstallEventHandler( kCoreEventClass
, kAEReopenApplication
,
936 sRAppHandler
, 0 , FALSE
) ;
937 AEInstallEventHandler( kCoreEventClass
, kAEQuitApplication
,
938 sQuitHandler
, 0 , FALSE
) ;
944 void wxApp::CleanUp()
947 wxToolTip::RemoveToolTips() ;
951 if (m_macEventPosted
)
953 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
954 m_macEventPosted
= NULL
;
958 // One last chance for pending objects to be cleaned up
959 wxTheApp
->DeletePendingObjects();
961 wxMacDestroyNotifierTable() ;
964 # if __option(profile)
965 ProfilerDump( (StringPtr
)"\papp.prof" ) ;
970 UMACleanupToolbox() ;
973 RemoveEventHandler( (EventHandlerRef
)(wxTheApp
->m_macEventHandler
) );
977 AERemoveEventHandler( kCoreEventClass
, kAEOpenDocuments
,
978 sODocHandler
, FALSE
) ;
979 AERemoveEventHandler( kInternetEventClass
, kAEGetURL
,
980 sGURLHandler
, FALSE
) ;
981 AERemoveEventHandler( kCoreEventClass
, kAEOpenApplication
,
982 sOAppHandler
, FALSE
) ;
983 AERemoveEventHandler( kCoreEventClass
, kAEPrintDocuments
,
984 sPDocHandler
, FALSE
) ;
985 AERemoveEventHandler( kCoreEventClass
, kAEReopenApplication
,
986 sRAppHandler
, FALSE
) ;
987 AERemoveEventHandler( kCoreEventClass
, kAEQuitApplication
,
988 sQuitHandler
, FALSE
) ;
990 DisposeAEEventHandlerUPP( sODocHandler
) ;
991 DisposeAEEventHandlerUPP( sGURLHandler
) ;
992 DisposeAEEventHandlerUPP( sOAppHandler
) ;
993 DisposeAEEventHandlerUPP( sPDocHandler
) ;
994 DisposeAEEventHandlerUPP( sRAppHandler
) ;
995 DisposeAEEventHandlerUPP( sQuitHandler
) ;
998 wxAppBase::CleanUp();
1001 //----------------------------------------------------------------------
1002 // misc initialization stuff
1003 //----------------------------------------------------------------------
1005 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
1007 // for shared libraries we have to manually get the correct resource
1008 // ref num upon initializing and releasing when terminating, therefore
1009 // the __wxinitialize and __wxterminate must be used
1013 void __sinit(void); // (generated by linker)
1014 pascal OSErr
__initialize(const CFragInitBlock
*theInitBlock
);
1015 pascal void __terminate(void);
1018 pascal OSErr
__wxinitialize(const CFragInitBlock
*theInitBlock
)
1020 return __initialize( theInitBlock
) ;
1023 pascal void __wxterminate(void)
1028 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
1030 bool wxMacConvertEventToRecord( EventRef event
, EventRecord
*rec
)
1032 OSStatus err
= noErr
;
1033 bool converted
= ConvertEventRefToEventRecord( event
, rec
) ;
1037 switch ( GetEventClass( event
) )
1039 case kEventClassKeyboard
:
1042 switch ( GetEventKind(event
) )
1044 case kEventRawKeyDown
:
1045 rec
->what
= keyDown
;
1048 case kEventRawKeyRepeat
:
1049 rec
->what
= autoKey
;
1052 case kEventRawKeyUp
:
1056 case kEventRawKeyModifiersChanged
:
1057 rec
->what
= nullEvent
;
1068 unsigned char charCode
;
1071 GetMouse( &rec
->where
) ;
1073 err
= GetEventParameter(event
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1074 err
= GetEventParameter(event
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1075 err
= GetEventParameter(event
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1076 rec
->modifiers
= modifiers
;
1077 rec
->message
= (keyCode
<< 8 ) + charCode
;
1082 case kEventClassTextInput
:
1084 switch ( GetEventKind( event
) )
1086 case kEventTextInputUnicodeForKeyEvent
:
1089 err
= GetEventParameter(
1090 event
, kEventParamTextInputSendKeyboardEvent
, typeEventRef
, NULL
,
1091 sizeof(rawEvent
), NULL
, &rawEvent
) ;
1095 UInt32 keyCode
, modifiers
;
1096 unsigned char charCode
;
1099 GetMouse( &rec
->where
) ;
1101 rec
->what
= keyDown
;
1102 err
= GetEventParameter(rawEvent
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1103 err
= GetEventParameter(rawEvent
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1104 err
= GetEventParameter(rawEvent
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1105 rec
->modifiers
= modifiers
;
1106 rec
->message
= (keyCode
<< 8 ) + charCode
;
1127 m_printMode
= wxPRINT_WINDOWS
;
1129 m_macCurrentEvent
= NULL
;
1130 m_macCurrentEventHandlerCallRef
= NULL
;
1132 #ifdef __WXMAC_OSX__
1133 m_macEventPosted
= NULL
;
1137 void wxApp::OnIdle(wxIdleEvent
& event
)
1139 wxAppBase::OnIdle(event
);
1141 // If they are pending events, we must process them: pending events are
1142 // either events to the threads other than main or events posted with
1143 // wxPostEvent() functions
1144 wxMacProcessNotifierAndPendingEvents();
1146 if (!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1147 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1150 void wxApp::WakeUpIdle()
1152 #ifdef __WXMAC_OSX__
1153 if (m_macEventPosted
)
1155 CFRunLoopSourceSignal(m_macEventPosted
);
1162 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1165 GetTopWindow()->Close(true);
1168 // Default behaviour: close the application with prompts. The
1169 // user can veto the close, and therefore the end session.
1170 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1174 if (!GetTopWindow()->Close(!event
.CanVeto()))
1179 extern "C" void wxCYield() ;
1185 // Yield to other processes
1187 bool wxApp::Yield(bool onlyIfNeeded
)
1191 if ( !onlyIfNeeded
)
1193 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1200 // Yielding from a non-gui thread needs to bail out, otherwise we end up
1201 // possibly sending events in the thread too.
1202 if ( !wxThread::IsMain() )
1206 #endif // wxUSE_THREADS
1210 // by definition yield should handle all non-processed events
1214 OSStatus status
= noErr
;
1216 while ( status
== noErr
)
1218 s_inReceiveEvent
= true ;
1219 status
= ReceiveNextEvent(0, NULL
,kEventDurationNoWait
,true,&theEvent
) ;
1220 s_inReceiveEvent
= false ;
1222 if ( status
== eventLoopTimedOutErr
)
1224 // make sure next time the event loop will trigger idle events
1225 sleepTime
= kEventDurationNoWait
;
1227 else if ( status
== eventLoopQuitErr
)
1229 // according to QA1061 this may also occur when a WakeUp Process
1234 MacHandleOneEvent( theEvent
) ;
1235 ReleaseEvent(theEvent
);
1239 wxMacProcessNotifierAndPendingEvents() ;
1245 void wxApp::MacDoOneEvent()
1249 s_inReceiveEvent
= true ;
1250 OSStatus status
= ReceiveNextEvent(0, NULL
, sleepTime
, true, &theEvent
) ;
1251 s_inReceiveEvent
= false ;
1255 case eventLoopTimedOutErr
:
1256 if ( wxTheApp
->ProcessIdle() )
1257 sleepTime
= kEventDurationNoWait
;
1259 sleepTime
= kEventDurationSecond
;
1262 case eventLoopQuitErr
:
1263 // according to QA1061 this may also occur
1264 // when a WakeUp Process is executed
1268 MacHandleOneEvent( theEvent
) ;
1269 ReleaseEvent( theEvent
);
1270 sleepTime
= kEventDurationNoWait
;
1275 DeletePendingObjects() ;
1276 wxMacProcessNotifierAndPendingEvents() ;
1280 void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr
)
1282 // Override to process unhandled events as you please
1285 CFMutableArrayRef
GetAutoReleaseArray()
1287 static CFMutableArrayRef array
= 0;
1289 array
= CFArrayCreateMutable(kCFAllocatorDefault
,0,&kCFTypeArrayCallBacks
);
1293 void wxApp::MacHandleOneEvent( WXEVENTREF evr
)
1295 EventTargetRef theTarget
;
1296 theTarget
= GetEventDispatcherTarget();
1297 m_macCurrentEvent
= evr
;
1299 OSStatus status
= SendEventToEventTarget((EventRef
) evr
, theTarget
);
1300 if (status
== eventNotHandledErr
)
1301 MacHandleUnhandledEvent(evr
);
1303 wxMacProcessNotifierAndPendingEvents() ;
1306 wxMutexGuiLeaveOrEnter();
1307 #endif // wxUSE_THREADS
1309 CFArrayRemoveAllValues( GetAutoReleaseArray() );
1312 void wxApp::MacAddToAutorelease( void* cfrefobj
)
1314 CFArrayAppendValue( GetAutoReleaseArray(), cfrefobj
);
1317 long wxMacTranslateKey(unsigned char key
, unsigned char code
)
1322 case kHomeCharCode
:
1326 case kEnterCharCode
:
1327 retval
= WXK_RETURN
;
1333 case kHelpCharCode
:
1337 case kBackspaceCharCode
:
1345 case kPageUpCharCode
:
1346 retval
= WXK_PAGEUP
;
1349 case kPageDownCharCode
:
1350 retval
= WXK_PAGEDOWN
;
1353 case kReturnCharCode
:
1354 retval
= WXK_RETURN
;
1357 case kFunctionKeyCharCode
:
1427 case kEscapeCharCode
:
1428 retval
= WXK_ESCAPE
;
1431 case kLeftArrowCharCode
:
1435 case kRightArrowCharCode
:
1436 retval
= WXK_RIGHT
;
1439 case kUpArrowCharCode
:
1443 case kDownArrowCharCode
:
1447 case kDeleteCharCode
:
1448 retval
= WXK_DELETE
;
1458 int wxMacKeyCodeToModifier(wxKeyCode key
)
1484 bool wxGetKeyState(wxKeyCode key
) //virtual key code if < 10.2.x, else see below
1486 wxASSERT_MSG(key
!= WXK_LBUTTON
&& key
!= WXK_RBUTTON
&& key
!=
1487 WXK_MBUTTON
, wxT("can't use wxGetKeyState() for mouse buttons"));
1489 //if OS X > 10.2 (i.e. 10.2.x)
1490 //a known apple bug prevents the system from determining led
1491 //states with GetKeys... can only determine caps lock led
1492 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key
));
1494 // KeyMapByteArray keymap;
1495 // GetKeys((BigEndianLong*)keymap);
1496 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1501 wxMouseState
wxGetMouseState()
1505 wxPoint pt
= wxGetMousePosition();
1509 #if TARGET_API_MAC_OSX
1510 UInt32 buttons
= GetCurrentButtonState();
1511 ms
.SetLeftDown( (buttons
& 0x01) != 0 );
1512 ms
.SetMiddleDown( (buttons
& 0x04) != 0 );
1513 ms
.SetRightDown( (buttons
& 0x02) != 0 );
1515 ms
.SetLeftDown( Button() );
1516 ms
.SetMiddleDown( 0 );
1517 ms
.SetRightDown( 0 );
1520 UInt32 modifiers
= GetCurrentKeyModifiers();
1521 ms
.SetControlDown(modifiers
& controlKey
);
1522 ms
.SetShiftDown(modifiers
& shiftKey
);
1523 ms
.SetAltDown(modifiers
& optionKey
);
1524 ms
.SetMetaDown(modifiers
& cmdKey
);
1529 // TODO : once the new key/char handling is tested, move all the code to wxWindow
1531 bool wxApp::MacSendKeyDownEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1537 wxKeyEvent
event(wxEVT_KEY_DOWN
) ;
1538 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1540 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1541 if ( handled
&& event
.GetSkipped() )
1547 wxWindow
*ancestor
= focus
;
1550 int command
= ancestor
->GetAcceleratorTable()->GetCommand( event
);
1553 wxEvtHandler
* const handler
= ancestor
->GetEventHandler();
1555 wxCommandEvent
command_event( wxEVT_COMMAND_MENU_SELECTED
, command
);
1556 handled
= handler
->ProcessEvent( command_event
);
1560 // accelerators can also be used with buttons, try them too
1561 command_event
.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED
);
1562 handled
= handler
->ProcessEvent( command_event
);
1568 if (ancestor
->IsTopLevel())
1571 ancestor
= ancestor
->GetParent();
1574 #endif // wxUSE_ACCEL
1579 bool wxApp::MacSendKeyUpEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1585 wxKeyEvent
event( wxEVT_KEY_UP
) ;
1586 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1587 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1592 bool wxApp::MacSendCharEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1597 wxKeyEvent
event(wxEVT_CHAR
) ;
1598 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1599 long keyval
= event
.m_keyCode
;
1601 bool handled
= false ;
1603 wxTopLevelWindowMac
*tlw
= focus
->MacGetTopLevelWindow() ;
1607 event
.SetEventType( wxEVT_CHAR_HOOK
);
1608 handled
= tlw
->GetEventHandler()->ProcessEvent( event
);
1609 if ( handled
&& event
.GetSkipped() )
1615 event
.SetEventType( wxEVT_CHAR
);
1616 event
.Skip( false ) ;
1617 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1620 if ( !handled
&& (keyval
== WXK_TAB
) )
1622 wxWindow
* iter
= focus
->GetParent() ;
1623 while ( iter
&& !handled
)
1625 if ( iter
->HasFlag( wxTAB_TRAVERSAL
) )
1627 wxNavigationKeyEvent new_event
;
1628 new_event
.SetEventObject( focus
);
1629 new_event
.SetDirection( !event
.ShiftDown() );
1630 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1631 new_event
.SetWindowChange( event
.ControlDown() );
1632 new_event
.SetCurrentFocus( focus
);
1633 handled
= focus
->GetParent()->GetEventHandler()->ProcessEvent( new_event
);
1634 if ( handled
&& new_event
.GetSkipped() )
1638 iter
= iter
->GetParent() ;
1642 // backdoor handler for default return and command escape
1643 if ( !handled
&& (!focus
->IsKindOf(CLASSINFO(wxControl
) ) || !focus
->MacCanFocus() ) )
1645 // if window is not having a focus still testing for default enter or cancel
1646 // TODO: add the UMA version for ActiveNonFloatingWindow
1647 wxWindow
* focus
= wxFindWinFromMacWindow( FrontWindow() ) ;
1650 if ( keyval
== WXK_RETURN
|| keyval
== WXK_NUMPAD_ENTER
)
1652 wxTopLevelWindow
*tlw
= wxDynamicCast(wxGetTopLevelParent(focus
), wxTopLevelWindow
);
1653 if ( tlw
&& tlw
->GetDefaultItem() )
1655 wxButton
*def
= wxDynamicCast(tlw
->GetDefaultItem(), wxButton
);
1656 if ( def
&& def
->IsEnabled() )
1658 wxCommandEvent
event(wxEVT_COMMAND_BUTTON_CLICKED
, def
->GetId() );
1659 event
.SetEventObject(def
);
1660 def
->Command(event
);
1666 else if (keyval
== WXK_ESCAPE
|| (keyval
== '.' && modifiers
& cmdKey
) )
1668 // generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs)
1669 wxCommandEvent
new_event(wxEVT_COMMAND_BUTTON_CLICKED
,wxID_CANCEL
);
1670 new_event
.SetEventObject( focus
);
1671 handled
= focus
->GetEventHandler()->ProcessEvent( new_event
);
1678 // This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
1679 void wxApp::MacCreateKeyEvent( wxKeyEvent
& event
, wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1681 short keycode
, keychar
;
1683 keychar
= short(keymessage
& charCodeMask
);
1684 keycode
= short(keymessage
& keyCodeMask
) >> 8 ;
1685 if ( !(event
.GetEventType() == wxEVT_CHAR
) && (modifiers
& (controlKey
| shiftKey
| optionKey
) ) )
1687 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1688 // and look at the character after
1690 UInt32 keyInfo
= KeyTranslate((Ptr
)GetScriptManagerVariable(smKCHRCache
), ( modifiers
& (~(controlKey
| shiftKey
| optionKey
))) | keycode
, &state
);
1691 keychar
= short(keyInfo
& charCodeMask
);
1694 long keyval
= wxMacTranslateKey(keychar
, keycode
) ;
1695 if ( keyval
== keychar
&& ( event
.GetEventType() == wxEVT_KEY_UP
|| event
.GetEventType() == wxEVT_KEY_DOWN
) )
1696 keyval
= wxToupper( keyval
) ;
1698 // Check for NUMPAD keys
1699 if (keyval
>= '0' && keyval
<= '9' && keycode
>= 82 && keycode
<= 92)
1701 keyval
= (keyval
- '0') + WXK_NUMPAD0
;
1703 else if (keycode
>= 67 && keycode
<= 81)
1708 keyval
= WXK_NUMPAD_ENTER
;
1712 keyval
= WXK_NUMPAD_EQUAL
;
1716 keyval
= WXK_NUMPAD_MULTIPLY
;
1720 keyval
= WXK_NUMPAD_DIVIDE
;
1724 keyval
= WXK_NUMPAD_SUBTRACT
;
1728 keyval
= WXK_NUMPAD_ADD
;
1732 keyval
= WXK_NUMPAD_DECIMAL
;
1740 event
.m_shiftDown
= modifiers
& shiftKey
;
1741 event
.m_controlDown
= modifiers
& controlKey
;
1742 event
.m_altDown
= modifiers
& optionKey
;
1743 event
.m_metaDown
= modifiers
& cmdKey
;
1744 event
.m_keyCode
= keyval
;
1746 event
.m_uniChar
= uniChar
;
1749 event
.m_rawCode
= keymessage
;
1750 event
.m_rawFlags
= modifiers
;
1753 event
.SetTimestamp(when
);
1754 event
.SetEventObject(focus
);