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
) )
499 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
501 item
= mbar
->FindItem( id
, &itemMenu
) ;
507 GetMenuItemRefCon( command
.menu
.menuRef
, command
.menu
.menuItemIndex
, &refCon
) ;
508 itemMenu
= wxFindMenuFromMacMenu( command
.menu
.menuRef
) ;
509 if ( itemMenu
!= NULL
)
510 item
= (wxMenuItem
*) refCon
;
517 //----------------------------------------------------------------------
518 // Carbon Event Handler
519 //----------------------------------------------------------------------
521 static const EventTypeSpec eventList
[] =
523 { kEventClassCommand
, kEventProcessCommand
} ,
524 { kEventClassCommand
, kEventCommandUpdateStatus
} ,
526 { kEventClassMenu
, kEventMenuOpening
},
527 { kEventClassMenu
, kEventMenuClosed
},
528 { kEventClassMenu
, kEventMenuTargetItem
},
530 { kEventClassApplication
, kEventAppActivated
} ,
531 { kEventClassApplication
, kEventAppDeactivated
} ,
532 // handling the quit event is not recommended by apple
533 // rather using the quit apple event - which we do
535 { kEventClassAppleEvent
, kEventAppleEvent
} ,
537 { kEventClassMouse
, kEventMouseDown
} ,
538 { kEventClassMouse
, kEventMouseMoved
} ,
539 { kEventClassMouse
, kEventMouseUp
} ,
540 { kEventClassMouse
, kEventMouseDragged
} ,
544 static pascal OSStatus
545 wxMacAppMenuEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
547 wxMacCarbonEvent
cEvent( event
) ;
548 MenuRef menuRef
= cEvent
.GetParameter
<MenuRef
>(kEventParamDirectObject
) ;
549 wxMenu
* menu
= wxFindMenuFromMacMenu( menuRef
) ;
555 switch (GetEventKind(event
))
557 case kEventMenuOpening
:
558 type
= wxEVT_MENU_OPEN
;
561 case kEventMenuClosed
:
562 type
= wxEVT_MENU_CLOSE
;
565 case kEventMenuTargetItem
:
566 cmd
= cEvent
.GetParameter
<MenuCommand
>(kEventParamMenuCommand
,typeMenuCommand
) ;
568 type
= wxEVT_MENU_HIGHLIGHT
;
572 wxFAIL_MSG(wxT("Unexpected menu event kind"));
578 wxMenuEvent
wxevent(type
, cmd
, menu
);
579 wxevent
.SetEventObject(menu
);
581 wxEvtHandler
* handler
= menu
->GetEventHandler();
582 if (handler
&& handler
->ProcessEvent(wxevent
))
588 wxWindow
*win
= menu
->GetInvokingWindow();
590 win
->GetEventHandler()->ProcessEvent(wxevent
);
595 return eventNotHandledErr
;
598 static pascal OSStatus
wxMacAppCommandEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
600 OSStatus result
= eventNotHandledErr
;
604 wxMacCarbonEvent
cEvent( event
) ;
605 cEvent
.GetParameter
<HICommand
>(kEventParamDirectObject
,typeHICommand
,&command
) ;
607 wxMenuItem
* item
= NULL
;
608 wxMenu
* itemMenu
= wxFindMenuFromMacCommand( command
, item
) ;
609 int id
= wxMacCommandToId( command
.commandID
) ;
613 wxASSERT( itemMenu
!= NULL
) ;
615 switch ( cEvent
.GetKind() )
617 case kEventProcessCommand
:
619 if (item
->IsCheckable())
620 item
->Check( !item
->IsChecked() ) ;
622 if ( itemMenu
->SendEvent( id
, item
->IsCheckable() ? item
->IsChecked() : -1 ) )
627 case kEventCommandUpdateStatus
:
629 wxUpdateUIEvent
event(id
);
630 event
.SetEventObject( itemMenu
);
632 bool processed
= false;
634 // Try the menu's event handler
636 wxEvtHandler
*handler
= itemMenu
->GetEventHandler();
638 processed
= handler
->ProcessEvent(event
);
641 // Try the window the menu was popped up from
642 // (and up through the hierarchy)
645 const wxMenuBase
*menu
= itemMenu
;
648 wxWindow
*win
= menu
->GetInvokingWindow();
651 processed
= win
->GetEventHandler()->ProcessEvent(event
);
655 menu
= menu
->GetParent();
661 // if anything changed, update the changed attribute
662 if (event
.GetSetText())
663 itemMenu
->SetLabel(id
, event
.GetText());
664 if (event
.GetSetChecked())
665 itemMenu
->Check(id
, event
.GetChecked());
666 if (event
.GetSetEnabled())
667 itemMenu
->Enable(id
, event
.GetEnabled());
681 static pascal OSStatus
wxMacAppApplicationEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
683 OSStatus result
= eventNotHandledErr
;
684 switch ( GetEventKind( event
) )
686 case kEventAppActivated
:
688 wxTheApp
->SetActive( true , NULL
) ;
692 case kEventAppDeactivated
:
694 wxTheApp
->SetActive( false , NULL
) ;
705 pascal OSStatus
wxMacAppEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
707 EventRef formerEvent
= (EventRef
) wxTheApp
->MacGetCurrentEvent() ;
708 EventHandlerCallRef formerEventHandlerCallRef
= (EventHandlerCallRef
) wxTheApp
->MacGetCurrentEventHandlerCallRef() ;
709 wxTheApp
->MacSetCurrentEvent( event
, handler
) ;
711 OSStatus result
= eventNotHandledErr
;
712 switch ( GetEventClass( event
) )
714 case kEventClassCommand
:
715 result
= wxMacAppCommandEventHandler( handler
, event
, data
) ;
718 case kEventClassApplication
:
719 result
= wxMacAppApplicationEventHandler( handler
, event
, data
) ;
722 case kEventClassMenu
:
723 result
= wxMacAppMenuEventHandler( handler
, event
, data
) ;
726 case kEventClassMouse
:
728 wxMacCarbonEvent
cEvent( event
) ;
731 Point screenMouseLocation
= cEvent
.GetParameter
<Point
>(kEventParamMouseLocation
) ;
732 ::FindWindow(screenMouseLocation
, &window
);
733 // only send this event in case it had not already been sent to a tlw, as we get
734 // double events otherwise (in case event.skip) was called
735 if ( window
== NULL
)
736 result
= wxMacTopLevelMouseEventHandler( handler
, event
, NULL
) ;
740 case kEventClassAppleEvent
:
744 wxMacConvertEventToRecord( event
, &rec
) ;
745 result
= AEProcessAppleEvent( &rec
) ;
753 wxTheApp
->MacSetCurrentEvent( formerEvent
, formerEventHandlerCallRef
) ;
758 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler
)
762 pascal static void wxMacAssertOutputHandler(OSType componentSignature
, UInt32 options
,
763 const char *assertionString
, const char *exceptionLabelString
,
764 const char *errorString
, const char *fileName
, long lineNumber
, void *value
, ConstStr255Param outputMsg
)
766 // flow into assert handling
767 wxString fileNameStr
;
768 wxString assertionStr
;
769 wxString exceptionStr
;
773 fileNameStr
= wxString(fileName
, wxConvLocal
);
774 assertionStr
= wxString(assertionString
, wxConvLocal
);
775 exceptionStr
= wxString((exceptionLabelString
!=0) ? exceptionLabelString
: "", wxConvLocal
) ;
776 errorStr
= wxString((errorString
!=0) ? errorString
: "", wxConvLocal
) ;
778 fileNameStr
= fileName
;
779 assertionStr
= assertionString
;
780 exceptionStr
= (exceptionLabelString
!=0) ? exceptionLabelString
: "" ;
781 errorStr
= (errorString
!=0) ? errorString
: "" ;
786 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
787 assertionStr
.c_str() ,
788 exceptionStr
.c_str() ,
790 fileNameStr
.c_str(), lineNumber
,
794 wxOnAssert(fileNameStr
, lineNumber
, assertionStr
,
795 wxString::Format( wxT("%s %s value (%p)") , exceptionStr
, errorStr
, value
) ) ;
804 // m_macEventPosted run loop source callback:
805 void macPostedEventCallback(void *unused
);
808 void macPostedEventCallback(void *unused
)
810 wxTheApp
->ProcessPendingEvents();
814 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
819 InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler
) );
822 UMAInitToolbox( 4, sm_isEmbedded
) ;
823 SetEventMask( everyEvent
) ;
824 UMAShowWatchCursor() ;
827 # if __option(profile)
828 ProfilerInit( collectDetailed
, bestTimeBase
, 40000 , 50 ) ;
833 // now avoid exceptions thrown for new (bad_alloc)
834 // FIXME CS for some changes outside wxMac does not compile anymore
836 std::__throws_bad_alloc
= 0 ;
841 // Mac OS X passes a process serial number command line argument when
842 // the application is launched from the Finder. This argument must be
843 // removed from the command line arguments before being handled by the
844 // application (otherwise applications would need to handle it)
847 static const wxChar
*ARG_PSN
= _T("-psn_");
848 if ( wxStrncmp(argv
[1], ARG_PSN
, wxStrlen(ARG_PSN
)) == 0 )
850 // remove this argument
852 memmove(argv
+ 1, argv
+ 2, argc
* sizeof(char *));
856 if ( !wxAppBase::Initialize(argc
, argv
) )
860 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
863 #if TARGET_API_MAC_OSX
864 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
865 wxString startupCwd
= wxGetCwd() ;
866 if ( startupCwd
== wxT("/") || startupCwd
.Right(15) == wxT("/Contents/MacOS") )
868 CFURLRef url
= CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
869 CFURLRef urlParent
= CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault
, url
) ;
871 CFStringRef path
= CFURLCopyFileSystemPath ( urlParent
, kCFURLPOSIXPathStyle
) ;
872 CFRelease( urlParent
) ;
873 wxString cwd
= wxMacCFStringHolder(path
).AsString(wxLocale::GetSystemEncoding());
874 wxSetWorkingDirectory( cwd
) ;
878 wxMacCreateNotifierTable() ;
881 /* connect posted events to common-mode run loop so that wxPostEvent events
882 are handled even while we're in the menu or on a scrollbar */
883 CFRunLoopSourceContext event_posted_context
= {0};
884 event_posted_context
.perform
= macPostedEventCallback
;
885 m_macEventPosted
= CFRunLoopSourceCreate(NULL
,0,&event_posted_context
);
886 CFRunLoopAddSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
887 // run loop takes ownership
888 CFRelease(m_macEventPosted
);
891 UMAShowArrowCursor() ;
896 AEEventHandlerUPP sODocHandler
= NULL
;
897 AEEventHandlerUPP sGURLHandler
= NULL
;
898 AEEventHandlerUPP sOAppHandler
= NULL
;
899 AEEventHandlerUPP sPDocHandler
= NULL
;
900 AEEventHandlerUPP sRAppHandler
= NULL
;
901 AEEventHandlerUPP sQuitHandler
= NULL
;
903 bool wxApp::OnInitGui()
905 if ( !wxAppBase::OnInitGui() )
908 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
912 InstallApplicationEventHandler(
913 GetwxMacAppEventHandlerUPP(),
914 GetEventTypeCount(eventList
), eventList
, wxTheApp
, (EventHandlerRef
*)&(wxTheApp
->m_macEventHandler
));
919 sODocHandler
= NewAEEventHandlerUPP(AEHandleODoc
) ;
920 sGURLHandler
= NewAEEventHandlerUPP(AEHandleGURL
) ;
921 sOAppHandler
= NewAEEventHandlerUPP(AEHandleOApp
) ;
922 sPDocHandler
= NewAEEventHandlerUPP(AEHandlePDoc
) ;
923 sRAppHandler
= NewAEEventHandlerUPP(AEHandleRApp
) ;
924 sQuitHandler
= NewAEEventHandlerUPP(AEHandleQuit
) ;
926 AEInstallEventHandler( kCoreEventClass
, kAEOpenDocuments
,
927 sODocHandler
, 0 , FALSE
) ;
928 AEInstallEventHandler( kInternetEventClass
, kAEGetURL
,
929 sGURLHandler
, 0 , FALSE
) ;
930 AEInstallEventHandler( kCoreEventClass
, kAEOpenApplication
,
931 sOAppHandler
, 0 , FALSE
) ;
932 AEInstallEventHandler( kCoreEventClass
, kAEPrintDocuments
,
933 sPDocHandler
, 0 , FALSE
) ;
934 AEInstallEventHandler( kCoreEventClass
, kAEReopenApplication
,
935 sRAppHandler
, 0 , FALSE
) ;
936 AEInstallEventHandler( kCoreEventClass
, kAEQuitApplication
,
937 sQuitHandler
, 0 , FALSE
) ;
943 void wxApp::CleanUp()
946 wxToolTip::RemoveToolTips() ;
950 if (m_macEventPosted
)
952 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
953 m_macEventPosted
= NULL
;
957 // One last chance for pending objects to be cleaned up
958 wxTheApp
->DeletePendingObjects();
960 wxMacDestroyNotifierTable() ;
963 # if __option(profile)
964 ProfilerDump( (StringPtr
)"\papp.prof" ) ;
969 UMACleanupToolbox() ;
972 RemoveEventHandler( (EventHandlerRef
)(wxTheApp
->m_macEventHandler
) );
976 AERemoveEventHandler( kCoreEventClass
, kAEOpenDocuments
,
977 sODocHandler
, FALSE
) ;
978 AERemoveEventHandler( kInternetEventClass
, kAEGetURL
,
979 sGURLHandler
, FALSE
) ;
980 AERemoveEventHandler( kCoreEventClass
, kAEOpenApplication
,
981 sOAppHandler
, FALSE
) ;
982 AERemoveEventHandler( kCoreEventClass
, kAEPrintDocuments
,
983 sPDocHandler
, FALSE
) ;
984 AERemoveEventHandler( kCoreEventClass
, kAEReopenApplication
,
985 sRAppHandler
, FALSE
) ;
986 AERemoveEventHandler( kCoreEventClass
, kAEQuitApplication
,
987 sQuitHandler
, FALSE
) ;
989 DisposeAEEventHandlerUPP( sODocHandler
) ;
990 DisposeAEEventHandlerUPP( sGURLHandler
) ;
991 DisposeAEEventHandlerUPP( sOAppHandler
) ;
992 DisposeAEEventHandlerUPP( sPDocHandler
) ;
993 DisposeAEEventHandlerUPP( sRAppHandler
) ;
994 DisposeAEEventHandlerUPP( sQuitHandler
) ;
997 wxAppBase::CleanUp();
1000 //----------------------------------------------------------------------
1001 // misc initialization stuff
1002 //----------------------------------------------------------------------
1004 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
1006 // for shared libraries we have to manually get the correct resource
1007 // ref num upon initializing and releasing when terminating, therefore
1008 // the __wxinitialize and __wxterminate must be used
1012 void __sinit(void); // (generated by linker)
1013 pascal OSErr
__initialize(const CFragInitBlock
*theInitBlock
);
1014 pascal void __terminate(void);
1017 pascal OSErr
__wxinitialize(const CFragInitBlock
*theInitBlock
)
1019 return __initialize( theInitBlock
) ;
1022 pascal void __wxterminate(void)
1027 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
1029 bool wxMacConvertEventToRecord( EventRef event
, EventRecord
*rec
)
1031 OSStatus err
= noErr
;
1032 bool converted
= ConvertEventRefToEventRecord( event
, rec
) ;
1036 switch ( GetEventClass( event
) )
1038 case kEventClassKeyboard
:
1041 switch ( GetEventKind(event
) )
1043 case kEventRawKeyDown
:
1044 rec
->what
= keyDown
;
1047 case kEventRawKeyRepeat
:
1048 rec
->what
= autoKey
;
1051 case kEventRawKeyUp
:
1055 case kEventRawKeyModifiersChanged
:
1056 rec
->what
= nullEvent
;
1067 unsigned char charCode
;
1070 GetMouse( &rec
->where
) ;
1072 err
= GetEventParameter(event
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1073 err
= GetEventParameter(event
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1074 err
= GetEventParameter(event
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1075 rec
->modifiers
= modifiers
;
1076 rec
->message
= (keyCode
<< 8 ) + charCode
;
1081 case kEventClassTextInput
:
1083 switch ( GetEventKind( event
) )
1085 case kEventTextInputUnicodeForKeyEvent
:
1088 err
= GetEventParameter(
1089 event
, kEventParamTextInputSendKeyboardEvent
, typeEventRef
, NULL
,
1090 sizeof(rawEvent
), NULL
, &rawEvent
) ;
1094 UInt32 keyCode
, modifiers
;
1095 unsigned char charCode
;
1098 GetMouse( &rec
->where
) ;
1100 rec
->what
= keyDown
;
1101 err
= GetEventParameter(rawEvent
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1102 err
= GetEventParameter(rawEvent
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1103 err
= GetEventParameter(rawEvent
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1104 rec
->modifiers
= modifiers
;
1105 rec
->message
= (keyCode
<< 8 ) + charCode
;
1126 m_printMode
= wxPRINT_WINDOWS
;
1128 m_macCurrentEvent
= NULL
;
1129 m_macCurrentEventHandlerCallRef
= NULL
;
1131 #ifdef __WXMAC_OSX__
1132 m_macEventPosted
= NULL
;
1136 void wxApp::OnIdle(wxIdleEvent
& event
)
1138 wxAppBase::OnIdle(event
);
1140 // If they are pending events, we must process them: pending events are
1141 // either events to the threads other than main or events posted with
1142 // wxPostEvent() functions
1143 wxMacProcessNotifierAndPendingEvents();
1145 if (!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1146 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1149 void wxApp::WakeUpIdle()
1151 #ifdef __WXMAC_OSX__
1152 if (m_macEventPosted
)
1154 CFRunLoopSourceSignal(m_macEventPosted
);
1161 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1164 GetTopWindow()->Close(true);
1167 // Default behaviour: close the application with prompts. The
1168 // user can veto the close, and therefore the end session.
1169 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1173 if (!GetTopWindow()->Close(!event
.CanVeto()))
1178 extern "C" void wxCYield() ;
1184 // Yield to other processes
1186 bool wxApp::Yield(bool onlyIfNeeded
)
1190 if ( !onlyIfNeeded
)
1192 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1200 // by definition yield should handle all non-processed events
1204 OSStatus status
= noErr
;
1206 while ( status
== noErr
)
1208 s_inReceiveEvent
= true ;
1209 status
= ReceiveNextEvent(0, NULL
,kEventDurationNoWait
,true,&theEvent
) ;
1210 s_inReceiveEvent
= false ;
1212 if ( status
== eventLoopTimedOutErr
)
1214 // make sure next time the event loop will trigger idle events
1215 sleepTime
= kEventDurationNoWait
;
1217 else if ( status
== eventLoopQuitErr
)
1219 // according to QA1061 this may also occur when a WakeUp Process
1224 MacHandleOneEvent( theEvent
) ;
1225 ReleaseEvent(theEvent
);
1229 wxMacProcessNotifierAndPendingEvents() ;
1235 void wxApp::MacDoOneEvent()
1239 s_inReceiveEvent
= true ;
1240 OSStatus status
= ReceiveNextEvent(0, NULL
, sleepTime
, true, &theEvent
) ;
1241 s_inReceiveEvent
= false ;
1245 case eventLoopTimedOutErr
:
1246 if ( wxTheApp
->ProcessIdle() )
1247 sleepTime
= kEventDurationNoWait
;
1249 sleepTime
= kEventDurationSecond
;
1252 case eventLoopQuitErr
:
1253 // according to QA1061 this may also occur
1254 // when a WakeUp Process is executed
1258 MacHandleOneEvent( theEvent
) ;
1259 ReleaseEvent( theEvent
);
1260 sleepTime
= kEventDurationNoWait
;
1265 DeletePendingObjects() ;
1266 wxMacProcessNotifierAndPendingEvents() ;
1270 void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr
)
1272 // Override to process unhandled events as you please
1275 CFMutableArrayRef
GetAutoReleaseArray()
1277 static CFMutableArrayRef array
= 0;
1279 array
= CFArrayCreateMutable(kCFAllocatorDefault
,0,&kCFTypeArrayCallBacks
);
1283 void wxApp::MacHandleOneEvent( WXEVENTREF evr
)
1285 EventTargetRef theTarget
;
1286 theTarget
= GetEventDispatcherTarget();
1287 m_macCurrentEvent
= evr
;
1289 OSStatus status
= SendEventToEventTarget((EventRef
) evr
, theTarget
);
1290 if (status
== eventNotHandledErr
)
1291 MacHandleUnhandledEvent(evr
);
1293 wxMacProcessNotifierAndPendingEvents() ;
1296 wxMutexGuiLeaveOrEnter();
1297 #endif // wxUSE_THREADS
1299 CFArrayRemoveAllValues( GetAutoReleaseArray() );
1302 void wxApp::MacAddToAutorelease( void* cfrefobj
)
1304 CFArrayAppendValue( GetAutoReleaseArray(), cfrefobj
);
1307 long wxMacTranslateKey(unsigned char key
, unsigned char code
)
1312 case kHomeCharCode
:
1316 case kEnterCharCode
:
1317 retval
= WXK_RETURN
;
1323 case kHelpCharCode
:
1327 case kBackspaceCharCode
:
1335 case kPageUpCharCode
:
1336 retval
= WXK_PAGEUP
;
1339 case kPageDownCharCode
:
1340 retval
= WXK_PAGEDOWN
;
1343 case kReturnCharCode
:
1344 retval
= WXK_RETURN
;
1347 case kFunctionKeyCharCode
:
1417 case kEscapeCharCode
:
1418 retval
= WXK_ESCAPE
;
1421 case kLeftArrowCharCode
:
1425 case kRightArrowCharCode
:
1426 retval
= WXK_RIGHT
;
1429 case kUpArrowCharCode
:
1433 case kDownArrowCharCode
:
1437 case kDeleteCharCode
:
1438 retval
= WXK_DELETE
;
1448 int wxMacKeyCodeToModifier(wxKeyCode key
)
1474 bool wxGetKeyState(wxKeyCode key
) //virtual key code if < 10.2.x, else see below
1476 wxASSERT_MSG(key
!= WXK_LBUTTON
&& key
!= WXK_RBUTTON
&& key
!=
1477 WXK_MBUTTON
, wxT("can't use wxGetKeyState() for mouse buttons"));
1479 //if OS X > 10.2 (i.e. 10.2.x)
1480 //a known apple bug prevents the system from determining led
1481 //states with GetKeys... can only determine caps lock led
1482 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key
));
1484 // KeyMapByteArray keymap;
1485 // GetKeys((BigEndianLong*)keymap);
1486 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1491 wxMouseState
wxGetMouseState()
1495 wxPoint pt
= wxGetMousePosition();
1499 #if TARGET_API_MAC_OSX
1500 UInt32 buttons
= GetCurrentButtonState();
1501 ms
.SetLeftDown( (buttons
& 0x01) != 0 );
1502 ms
.SetMiddleDown( (buttons
& 0x04) != 0 );
1503 ms
.SetRightDown( (buttons
& 0x02) != 0 );
1505 ms
.SetLeftDown( Button() );
1506 ms
.SetMiddleDown( 0 );
1507 ms
.SetRightDown( 0 );
1510 UInt32 modifiers
= GetCurrentKeyModifiers();
1511 ms
.SetControlDown(modifiers
& controlKey
);
1512 ms
.SetShiftDown(modifiers
& shiftKey
);
1513 ms
.SetAltDown(modifiers
& optionKey
);
1514 ms
.SetMetaDown(modifiers
& cmdKey
);
1519 // TODO : once the new key/char handling is tested, move all the code to wxWindow
1521 bool wxApp::MacSendKeyDownEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1527 wxKeyEvent
event(wxEVT_KEY_DOWN
) ;
1528 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1530 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1531 if ( handled
&& event
.GetSkipped() )
1537 wxWindow
*ancestor
= focus
;
1540 int command
= ancestor
->GetAcceleratorTable()->GetCommand( event
);
1543 wxEvtHandler
* const handler
= ancestor
->GetEventHandler();
1545 wxCommandEvent
command_event( wxEVT_COMMAND_MENU_SELECTED
, command
);
1546 handled
= handler
->ProcessEvent( command_event
);
1550 // accelerators can also be used with buttons, try them too
1551 command_event
.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED
);
1552 handled
= handler
->ProcessEvent( command_event
);
1558 if (ancestor
->IsTopLevel())
1561 ancestor
= ancestor
->GetParent();
1564 #endif // wxUSE_ACCEL
1569 bool wxApp::MacSendKeyUpEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1575 wxKeyEvent
event( wxEVT_KEY_UP
) ;
1576 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1577 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1582 bool wxApp::MacSendCharEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1587 wxKeyEvent
event(wxEVT_CHAR
) ;
1588 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1589 long keyval
= event
.m_keyCode
;
1591 bool handled
= false ;
1593 wxTopLevelWindowMac
*tlw
= focus
->MacGetTopLevelWindow() ;
1597 event
.SetEventType( wxEVT_CHAR_HOOK
);
1598 handled
= tlw
->GetEventHandler()->ProcessEvent( event
);
1599 if ( handled
&& event
.GetSkipped() )
1605 event
.SetEventType( wxEVT_CHAR
);
1606 event
.Skip( false ) ;
1607 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1610 if ( !handled
&& (keyval
== WXK_TAB
) )
1612 wxWindow
* iter
= focus
->GetParent() ;
1613 while ( iter
&& !handled
)
1615 if ( iter
->HasFlag( wxTAB_TRAVERSAL
) )
1617 wxNavigationKeyEvent new_event
;
1618 new_event
.SetEventObject( focus
);
1619 new_event
.SetDirection( !event
.ShiftDown() );
1620 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1621 new_event
.SetWindowChange( event
.ControlDown() );
1622 new_event
.SetCurrentFocus( focus
);
1623 handled
= focus
->GetParent()->GetEventHandler()->ProcessEvent( new_event
);
1624 if ( handled
&& new_event
.GetSkipped() )
1628 iter
= iter
->GetParent() ;
1632 // backdoor handler for default return and command escape
1633 if ( !handled
&& (!focus
->IsKindOf(CLASSINFO(wxControl
) ) || !focus
->MacCanFocus() ) )
1635 // if window is not having a focus still testing for default enter or cancel
1636 // TODO: add the UMA version for ActiveNonFloatingWindow
1637 wxWindow
* focus
= wxFindWinFromMacWindow( FrontWindow() ) ;
1640 if ( keyval
== WXK_RETURN
|| keyval
== WXK_NUMPAD_ENTER
)
1642 wxTopLevelWindow
*tlw
= wxDynamicCast(wxGetTopLevelParent(focus
), wxTopLevelWindow
);
1643 if ( tlw
&& tlw
->GetDefaultItem() )
1645 wxButton
*def
= wxDynamicCast(tlw
->GetDefaultItem(), wxButton
);
1646 if ( def
&& def
->IsEnabled() )
1648 wxCommandEvent
event(wxEVT_COMMAND_BUTTON_CLICKED
, def
->GetId() );
1649 event
.SetEventObject(def
);
1650 def
->Command(event
);
1656 else if (keyval
== WXK_ESCAPE
|| (keyval
== '.' && modifiers
& cmdKey
) )
1658 // generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs)
1659 wxCommandEvent
new_event(wxEVT_COMMAND_BUTTON_CLICKED
,wxID_CANCEL
);
1660 new_event
.SetEventObject( focus
);
1661 handled
= focus
->GetEventHandler()->ProcessEvent( new_event
);
1668 // This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
1669 void wxApp::MacCreateKeyEvent( wxKeyEvent
& event
, wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1671 short keycode
, keychar
;
1673 keychar
= short(keymessage
& charCodeMask
);
1674 keycode
= short(keymessage
& keyCodeMask
) >> 8 ;
1675 if ( !(event
.GetEventType() == wxEVT_CHAR
) && (modifiers
& (controlKey
| shiftKey
| optionKey
) ) )
1677 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1678 // and look at the character after
1680 UInt32 keyInfo
= KeyTranslate((Ptr
)GetScriptManagerVariable(smKCHRCache
), ( modifiers
& (~(controlKey
| shiftKey
| optionKey
))) | keycode
, &state
);
1681 keychar
= short(keyInfo
& charCodeMask
);
1684 long keyval
= wxMacTranslateKey(keychar
, keycode
) ;
1685 if ( keyval
== keychar
&& ( event
.GetEventType() == wxEVT_KEY_UP
|| event
.GetEventType() == wxEVT_KEY_DOWN
) )
1686 keyval
= wxToupper( keyval
) ;
1688 // Check for NUMPAD keys
1689 if (keyval
>= '0' && keyval
<= '9' && keycode
>= 82 && keycode
<= 92)
1691 keyval
= (keyval
- '0') + WXK_NUMPAD0
;
1693 else if (keycode
>= 67 && keycode
<= 81)
1698 keyval
= WXK_NUMPAD_ENTER
;
1702 keyval
= WXK_NUMPAD_EQUAL
;
1706 keyval
= WXK_NUMPAD_MULTIPLY
;
1710 keyval
= WXK_NUMPAD_DIVIDE
;
1714 keyval
= WXK_NUMPAD_SUBTRACT
;
1718 keyval
= WXK_NUMPAD_ADD
;
1722 keyval
= WXK_NUMPAD_DECIMAL
;
1730 event
.m_shiftDown
= modifiers
& shiftKey
;
1731 event
.m_controlDown
= modifiers
& controlKey
;
1732 event
.m_altDown
= modifiers
& optionKey
;
1733 event
.m_metaDown
= modifiers
& cmdKey
;
1734 event
.m_keyCode
= keyval
;
1736 event
.m_uniChar
= uniChar
;
1739 event
.m_rawCode
= keymessage
;
1740 event
.m_rawFlags
= modifiers
;
1743 event
.SetTimestamp(when
);
1744 event
.SetEventObject(focus
);