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"
42 #include "wx/thread.h"
48 #include "wx/mac/uma.h"
51 # include <CoreServices/CoreServices.h>
52 # if defined(WXMAKINGDLL_CORE)
53 # include <mach-o/dyld.h>
57 // Keep linker from discarding wxStockGDIMac
58 wxFORCE_LINK_MODULE(gdiobj
)
60 // statics for implementation
61 static bool s_inYield
= false;
62 static bool s_inReceiveEvent
= false ;
63 static EventTime sleepTime
= kEventDurationNoWait
;
66 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
67 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
68 EVT_IDLE(wxApp::OnIdle
)
69 EVT_END_SESSION(wxApp::OnEndSession
)
70 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
74 // platform specific static variables
75 static const short kwxMacAppleMenuId
= 1 ;
77 wxWindow
* wxApp::s_captureWindow
= NULL
;
78 long wxApp::s_lastModifiers
= 0 ;
80 long wxApp::s_macAboutMenuItemId
= wxID_ABOUT
;
81 long wxApp::s_macPreferencesMenuItemId
= wxID_PREFERENCES
;
82 long wxApp::s_macExitMenuItemId
= wxID_EXIT
;
83 wxString
wxApp::s_macHelpMenuTitleName
= wxT("&Help") ;
85 bool wxApp::sm_isEmbedded
= false; // Normally we're not a plugin
87 //----------------------------------------------------------------------
88 // Core Apple Event Support
89 //----------------------------------------------------------------------
91 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
92 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
93 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
94 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
95 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
97 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
99 return wxTheApp
->MacHandleAEODoc( (AppleEvent
*) event
, reply
) ;
102 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
104 return wxTheApp
->MacHandleAEOApp( (AppleEvent
*) event
, reply
) ;
107 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
109 return wxTheApp
->MacHandleAEPDoc( (AppleEvent
*) event
, reply
) ;
112 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
114 return wxTheApp
->MacHandleAEQuit( (AppleEvent
*) event
, reply
) ;
117 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
119 return wxTheApp
->MacHandleAERApp( (AppleEvent
*) event
, reply
) ;
122 pascal OSErr
AEHandleGURL( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
124 return wxTheApp
->MacHandleAEGURL((WXEVENTREF
*)event
, reply
) ;
128 // AEODoc Calls MacOpenFile on each of the files passed
130 short wxApp::MacHandleAEODoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
134 DescType returnedType
;
140 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
144 err
= AECountItems(&docList
, &itemsInList
);
148 ProcessSerialNumber PSN
;
149 PSN
.highLongOfPSN
= 0 ;
150 PSN
.lowLongOfPSN
= kCurrentProcess
;
151 SetFrontProcess( &PSN
) ;
156 for (i
= 1; i
<= itemsInList
; i
++)
159 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
160 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
161 fName
= wxMacFSRefToPath( &theRef
) ;
169 // AEODoc Calls MacOpenURL on the url passed
171 short wxApp::MacHandleAEGURL(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
173 DescType returnedType
;
176 OSErr err
= AEGetParamPtr((AppleEvent
*)event
, keyDirectObject
, typeChar
,
177 &returnedType
, url
, sizeof(url
)-1,
182 url
[actualSize
] = '\0'; // Terminate the C string
184 ProcessSerialNumber PSN
;
185 PSN
.highLongOfPSN
= 0 ;
186 PSN
.lowLongOfPSN
= kCurrentProcess
;
187 SetFrontProcess( &PSN
) ;
189 MacOpenURL(wxString(url
, wxConvUTF8
));
194 // AEPDoc Calls MacPrintFile on each of the files passed
196 short wxApp::MacHandleAEPDoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
200 DescType returnedType
;
206 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
210 err
= AECountItems(&docList
, &itemsInList
);
214 ProcessSerialNumber PSN
;
215 PSN
.highLongOfPSN
= 0 ;
216 PSN
.lowLongOfPSN
= kCurrentProcess
;
217 SetFrontProcess( &PSN
) ;
222 for (i
= 1; i
<= itemsInList
; i
++)
225 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
226 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
227 fName
= wxMacFSRefToPath( &theRef
) ;
235 // AEOApp calls MacNewFile
237 short wxApp::MacHandleAEOApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
243 // AEQuit attempts to quit the application
245 short wxApp::MacHandleAEQuit(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
247 wxWindow
* win
= GetTopWindow() ;
250 wxCommandEvent
exitEvent(wxEVT_COMMAND_MENU_SELECTED
, s_macExitMenuItemId
);
251 if (!win
->ProcessEvent(exitEvent
))
262 // AEROApp calls MacReopenApp
264 short wxApp::MacHandleAERApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
271 //----------------------------------------------------------------------
272 // Support Routines linking the Mac...File Calls to the Document Manager
273 //----------------------------------------------------------------------
275 void wxApp::MacOpenFile(const wxString
& fileName
)
277 #if wxUSE_DOC_VIEW_ARCHITECTURE
278 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
280 dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
284 void wxApp::MacOpenURL(const wxString
& WXUNUSED(url
) )
288 void wxApp::MacPrintFile(const wxString
& fileName
)
290 #if wxUSE_DOC_VIEW_ARCHITECTURE
292 #if wxUSE_PRINTING_ARCHITECTURE
293 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
296 wxDocument
*doc
= dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
299 wxView
* view
= doc
->GetFirstView() ;
302 wxPrintout
*printout
= view
->OnCreatePrintout();
306 printer
.Print(view
->GetFrame(), printout
, true);
313 doc
->DeleteAllViews();
314 dm
->RemoveDocument(doc
) ;
325 void wxApp::MacNewFile()
329 void wxApp::MacReopenApp()
332 // if there is no open window -> create a new one
333 // if all windows are hidden -> show the first
334 // if some windows are not hidden -> do nothing
336 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetFirst();
343 wxTopLevelWindow
* firstIconized
= NULL
;
344 wxTopLevelWindow
* firstHidden
= NULL
;
347 wxTopLevelWindow
* win
= (wxTopLevelWindow
*) node
->GetData();
348 if ( !win
->IsShown() )
350 // make sure we don't show 'virtual toplevel windows' like wxTaskBarIconWindow
351 if ( firstHidden
== NULL
&& ( wxDynamicCast( win
, wxFrame
) || wxDynamicCast( win
, wxDialog
) ) )
354 else if ( win
->IsIconized() )
356 if ( firstIconized
== NULL
)
357 firstIconized
= win
;
361 // we do have a visible, non-iconized toplevelwindow -> do nothing
365 node
= node
->GetNext();
369 firstIconized
->Iconize( false ) ;
370 else if ( firstHidden
)
371 firstHidden
->Show( true );
375 //----------------------------------------------------------------------
376 // Macintosh CommandID support - converting between native and wx IDs
377 //----------------------------------------------------------------------
379 // if no native match they just return the passed-in id
387 IdPair gCommandIds
[] =
389 { kHICommandCut
, wxID_CUT
} ,
390 { kHICommandCopy
, wxID_COPY
} ,
391 { kHICommandPaste
, wxID_PASTE
} ,
392 { kHICommandSelectAll
, wxID_SELECTALL
} ,
393 { kHICommandClear
, wxID_CLEAR
} ,
394 { kHICommandUndo
, wxID_UNDO
} ,
395 { kHICommandRedo
, wxID_REDO
} ,
398 int wxMacCommandToId( UInt32 macCommandId
)
402 switch ( macCommandId
)
404 case kHICommandPreferences
:
405 wxid
= wxApp::s_macPreferencesMenuItemId
;
408 case kHICommandQuit
:
409 wxid
= wxApp::s_macExitMenuItemId
;
412 case kHICommandAbout
:
413 wxid
= wxApp::s_macAboutMenuItemId
;
418 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
420 if ( gCommandIds
[i
].macId
== macCommandId
)
422 wxid
= gCommandIds
[i
].wxId
;
431 wxid
= (int) macCommandId
;
436 UInt32
wxIdToMacCommand( int wxId
)
440 if ( wxId
== wxApp::s_macPreferencesMenuItemId
)
441 macId
= kHICommandPreferences
;
442 else if (wxId
== wxApp::s_macExitMenuItemId
)
443 macId
= kHICommandQuit
;
444 else if (wxId
== wxApp::s_macAboutMenuItemId
)
445 macId
= kHICommandAbout
;
448 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
450 if ( gCommandIds
[i
].wxId
== wxId
)
452 macId
= gCommandIds
[i
].macId
;
464 wxMenu
* wxFindMenuFromMacCommand( const HICommand
&command
, wxMenuItem
* &item
)
466 wxMenu
* itemMenu
= NULL
;
467 #ifndef __WXUNIVERSAL__
470 // for 'standard' commands which don't have a wx-menu
471 if ( command
.commandID
== kHICommandPreferences
|| command
.commandID
== kHICommandQuit
|| command
.commandID
== kHICommandAbout
)
473 id
= wxMacCommandToId( command
.commandID
) ;
475 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
477 item
= mbar
->FindItem( id
, &itemMenu
) ;
479 else if ( command
.commandID
!= 0 && command
.menu
.menuRef
!= 0 && command
.menu
.menuItemIndex
!= 0 )
481 id
= wxMacCommandToId( command
.commandID
) ;
482 // make sure it is one of our own menus, or of the 'synthetic' apple and help menus , otherwise don't touch
483 MenuItemIndex firstUserHelpMenuItem
;
484 static MenuHandle helpMenuHandle
= NULL
;
485 if ( helpMenuHandle
== NULL
)
487 if ( UMAGetHelpMenuDontCreate( &helpMenuHandle
, &firstUserHelpMenuItem
) != noErr
)
488 helpMenuHandle
= NULL
;
491 // is it part of the application or the Help menu, then look for the id directly
492 if ( ( GetMenuHandle( kwxMacAppleMenuId
) != NULL
&& command
.menu
.menuRef
== GetMenuHandle( kwxMacAppleMenuId
) ) ||
493 ( helpMenuHandle
!= NULL
&& command
.menu
.menuRef
== helpMenuHandle
) ||
494 wxMenuBar::MacGetWindowMenuHMenu() != NULL
&& command
.menu
.menuRef
== wxMenuBar::MacGetWindowMenuHMenu() )
496 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
498 item
= mbar
->FindItem( id
, &itemMenu
) ;
504 GetMenuItemRefCon( command
.menu
.menuRef
, command
.menu
.menuItemIndex
, &refCon
) ;
505 itemMenu
= wxFindMenuFromMacMenu( command
.menu
.menuRef
) ;
506 if ( itemMenu
!= NULL
)
507 item
= (wxMenuItem
*) refCon
;
514 //----------------------------------------------------------------------
515 // Carbon Event Handler
516 //----------------------------------------------------------------------
518 static const EventTypeSpec eventList
[] =
520 { kEventClassCommand
, kEventProcessCommand
} ,
521 { kEventClassCommand
, kEventCommandUpdateStatus
} ,
523 { kEventClassMenu
, kEventMenuOpening
},
524 { kEventClassMenu
, kEventMenuClosed
},
525 { kEventClassMenu
, kEventMenuTargetItem
},
527 { kEventClassApplication
, kEventAppActivated
} ,
528 { kEventClassApplication
, kEventAppDeactivated
} ,
529 // handling the quit event is not recommended by apple
530 // rather using the quit apple event - which we do
532 { kEventClassAppleEvent
, kEventAppleEvent
} ,
534 { kEventClassMouse
, kEventMouseDown
} ,
535 { kEventClassMouse
, kEventMouseMoved
} ,
536 { kEventClassMouse
, kEventMouseUp
} ,
537 { kEventClassMouse
, kEventMouseDragged
} ,
541 static pascal OSStatus
542 wxMacAppMenuEventHandler( EventHandlerCallRef
WXUNUSED(handler
),
544 void *WXUNUSED(data
) )
546 wxMacCarbonEvent
cEvent( event
) ;
547 MenuRef menuRef
= cEvent
.GetParameter
<MenuRef
>(kEventParamDirectObject
) ;
548 #ifndef __WXUNIVERSAL__
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
->HandleWindowEvent(wxevent
);
595 return eventNotHandledErr
;
599 static pascal OSStatus
600 wxMacAppCommandEventHandler( EventHandlerCallRef
WXUNUSED(handler
) ,
602 void *WXUNUSED(data
) )
604 OSStatus result
= eventNotHandledErr
;
608 wxMacCarbonEvent
cEvent( event
) ;
609 cEvent
.GetParameter
<HICommand
>(kEventParamDirectObject
,typeHICommand
,&command
) ;
611 wxMenuItem
* item
= NULL
;
612 wxMenu
* itemMenu
= wxFindMenuFromMacCommand( command
, item
) ;
613 int id
= wxMacCommandToId( command
.commandID
) ;
617 wxASSERT( itemMenu
!= NULL
) ;
619 switch ( cEvent
.GetKind() )
621 case kEventProcessCommand
:
622 result
= itemMenu
->MacHandleCommandProcess( item
, id
);
625 case kEventCommandUpdateStatus
:
626 result
= itemMenu
->MacHandleCommandUpdateStatus( item
, id
);
637 static pascal OSStatus
638 wxMacAppApplicationEventHandler( EventHandlerCallRef
WXUNUSED(handler
) ,
640 void *WXUNUSED(data
) )
642 OSStatus result
= eventNotHandledErr
;
643 switch ( GetEventKind( event
) )
645 case kEventAppActivated
:
647 wxTheApp
->SetActive( true , NULL
) ;
651 case kEventAppDeactivated
:
653 wxTheApp
->SetActive( false , NULL
) ;
664 pascal OSStatus
wxMacAppEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
666 EventRef formerEvent
= (EventRef
) wxTheApp
->MacGetCurrentEvent() ;
667 EventHandlerCallRef formerEventHandlerCallRef
= (EventHandlerCallRef
) wxTheApp
->MacGetCurrentEventHandlerCallRef() ;
668 wxTheApp
->MacSetCurrentEvent( event
, handler
) ;
670 OSStatus result
= eventNotHandledErr
;
671 switch ( GetEventClass( event
) )
674 case kEventClassCommand
:
675 result
= wxMacAppCommandEventHandler( handler
, event
, data
) ;
678 case kEventClassApplication
:
679 result
= wxMacAppApplicationEventHandler( handler
, event
, data
) ;
682 case kEventClassMenu
:
683 result
= wxMacAppMenuEventHandler( handler
, event
, data
) ;
686 case kEventClassMouse
:
688 wxMacCarbonEvent
cEvent( event
) ;
691 Point screenMouseLocation
= cEvent
.GetParameter
<Point
>(kEventParamMouseLocation
) ;
692 ::FindWindow(screenMouseLocation
, &window
);
693 // only send this event in case it had not already been sent to a tlw, as we get
694 // double events otherwise (in case event.skip) was called
695 if ( window
== NULL
)
696 result
= wxMacTopLevelMouseEventHandler( handler
, event
, NULL
) ;
700 case kEventClassAppleEvent
:
702 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
703 if ( AEProcessEvent
!= NULL
)
705 result
= AEProcessEvent(event
);
708 #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
712 wxMacConvertEventToRecord( event
, &rec
) ;
713 result
= AEProcessAppleEvent( &rec
) ;
723 wxTheApp
->MacSetCurrentEvent( formerEvent
, formerEventHandlerCallRef
) ;
728 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler
)
733 wxMacAssertOutputHandler(OSType
WXUNUSED(componentSignature
),
734 UInt32
WXUNUSED(options
),
735 const char *assertionString
,
736 const char *exceptionLabelString
,
737 const char *errorString
,
738 const char *fileName
,
741 ConstStr255Param
WXUNUSED(outputMsg
))
743 // flow into assert handling
744 wxString fileNameStr
;
745 wxString assertionStr
;
746 wxString exceptionStr
;
750 fileNameStr
= wxString(fileName
, wxConvLocal
);
751 assertionStr
= wxString(assertionString
, wxConvLocal
);
752 exceptionStr
= wxString((exceptionLabelString
!=0) ? exceptionLabelString
: "", wxConvLocal
) ;
753 errorStr
= wxString((errorString
!=0) ? errorString
: "", wxConvLocal
) ;
755 fileNameStr
= fileName
;
756 assertionStr
= assertionString
;
757 exceptionStr
= (exceptionLabelString
!=0) ? exceptionLabelString
: "" ;
758 errorStr
= (errorString
!=0) ? errorString
: "" ;
763 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
764 assertionStr
.c_str() ,
765 exceptionStr
.c_str() ,
767 fileNameStr
.c_str(), lineNumber
,
771 wxOnAssert(fileNameStr
, lineNumber
, assertionStr
,
772 wxString::Format( wxT("%s %s value (%p)") , exceptionStr
, errorStr
, value
) ) ;
778 extern "C" void macPostedEventCallback(void *WXUNUSED(unused
))
780 wxTheApp
->ProcessPendingEvents();
783 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
788 InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler
) );
791 UMAInitToolbox( 4, sm_isEmbedded
) ;
792 // TODO CHECK Can Be Removed SetEventMask( everyEvent ) ;
794 // Mac OS X passes a process serial number command line argument when
795 // the application is launched from the Finder. This argument must be
796 // removed from the command line arguments before being handled by the
797 // application (otherwise applications would need to handle it)
800 static const wxChar
*ARG_PSN
= _T("-psn_");
801 if ( wxStrncmp(argv
[1], ARG_PSN
, wxStrlen(ARG_PSN
)) == 0 )
803 // remove this argument
805 memmove(argv
+ 1, argv
+ 2, argc
* sizeof(char *));
809 if ( !wxAppBase::Initialize(argc
, argv
) )
813 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
816 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
817 wxString startupCwd
= wxGetCwd() ;
818 if ( startupCwd
== wxT("/") || startupCwd
.Right(15) == wxT("/Contents/MacOS") )
820 CFURLRef url
= CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
821 CFURLRef urlParent
= CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault
, url
) ;
823 CFStringRef path
= CFURLCopyFileSystemPath ( urlParent
, kCFURLPOSIXPathStyle
) ;
824 CFRelease( urlParent
) ;
825 wxString cwd
= wxCFStringRef(path
).AsString(wxLocale::GetSystemEncoding());
826 wxSetWorkingDirectory( cwd
) ;
829 /* connect posted events to common-mode run loop so that wxPostEvent events
830 are handled even while we're in the menu or on a scrollbar */
831 CFRunLoopSourceContext event_posted_context
= {0};
832 event_posted_context
.perform
= macPostedEventCallback
;
833 m_macEventPosted
= CFRunLoopSourceCreate(NULL
,0,&event_posted_context
);
834 CFRunLoopAddSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
835 // run loop takes ownership
836 CFRelease(m_macEventPosted
);
841 AEEventHandlerUPP sODocHandler
= NULL
;
842 AEEventHandlerUPP sGURLHandler
= NULL
;
843 AEEventHandlerUPP sOAppHandler
= NULL
;
844 AEEventHandlerUPP sPDocHandler
= NULL
;
845 AEEventHandlerUPP sRAppHandler
= NULL
;
846 AEEventHandlerUPP sQuitHandler
= NULL
;
848 bool wxApp::OnInitGui()
850 if ( !wxAppBase::OnInitGui() )
853 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
856 InstallApplicationEventHandler(
857 GetwxMacAppEventHandlerUPP(),
858 GetEventTypeCount(eventList
), eventList
, wxTheApp
, (EventHandlerRef
*)&(wxTheApp
->m_macEventHandler
));
864 sODocHandler
= NewAEEventHandlerUPP(AEHandleODoc
) ;
865 sGURLHandler
= NewAEEventHandlerUPP(AEHandleGURL
) ;
866 sOAppHandler
= NewAEEventHandlerUPP(AEHandleOApp
) ;
867 sPDocHandler
= NewAEEventHandlerUPP(AEHandlePDoc
) ;
868 sRAppHandler
= NewAEEventHandlerUPP(AEHandleRApp
) ;
869 sQuitHandler
= NewAEEventHandlerUPP(AEHandleQuit
) ;
871 AEInstallEventHandler( kCoreEventClass
, kAEOpenDocuments
,
872 sODocHandler
, 0 , FALSE
) ;
873 AEInstallEventHandler( kInternetEventClass
, kAEGetURL
,
874 sGURLHandler
, 0 , FALSE
) ;
875 AEInstallEventHandler( kCoreEventClass
, kAEOpenApplication
,
876 sOAppHandler
, 0 , FALSE
) ;
877 AEInstallEventHandler( kCoreEventClass
, kAEPrintDocuments
,
878 sPDocHandler
, 0 , FALSE
) ;
879 AEInstallEventHandler( kCoreEventClass
, kAEReopenApplication
,
880 sRAppHandler
, 0 , FALSE
) ;
881 AEInstallEventHandler( kCoreEventClass
, kAEQuitApplication
,
882 sQuitHandler
, 0 , FALSE
) ;
885 if ( !wxMacInitCocoa() )
891 void wxApp::CleanUp()
894 wxToolTip::RemoveToolTips() ;
897 if (m_macEventPosted
)
899 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
900 m_macEventPosted
= NULL
;
903 // One last chance for pending objects to be cleaned up
904 wxTheApp
->DeletePendingObjects();
907 RemoveEventHandler( (EventHandlerRef
)(wxTheApp
->m_macEventHandler
) );
911 AERemoveEventHandler( kCoreEventClass
, kAEOpenDocuments
,
912 sODocHandler
, FALSE
) ;
913 AERemoveEventHandler( kInternetEventClass
, kAEGetURL
,
914 sGURLHandler
, FALSE
) ;
915 AERemoveEventHandler( kCoreEventClass
, kAEOpenApplication
,
916 sOAppHandler
, FALSE
) ;
917 AERemoveEventHandler( kCoreEventClass
, kAEPrintDocuments
,
918 sPDocHandler
, FALSE
) ;
919 AERemoveEventHandler( kCoreEventClass
, kAEReopenApplication
,
920 sRAppHandler
, FALSE
) ;
921 AERemoveEventHandler( kCoreEventClass
, kAEQuitApplication
,
922 sQuitHandler
, FALSE
) ;
924 DisposeAEEventHandlerUPP( sODocHandler
) ;
925 DisposeAEEventHandlerUPP( sGURLHandler
) ;
926 DisposeAEEventHandlerUPP( sOAppHandler
) ;
927 DisposeAEEventHandlerUPP( sPDocHandler
) ;
928 DisposeAEEventHandlerUPP( sRAppHandler
) ;
929 DisposeAEEventHandlerUPP( sQuitHandler
) ;
932 wxAppBase::CleanUp();
935 //----------------------------------------------------------------------
936 // misc initialization stuff
937 //----------------------------------------------------------------------
939 #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
940 bool wxMacConvertEventToRecord( EventRef event
, EventRecord
*rec
)
942 OSStatus err
= noErr
;
943 bool converted
= ConvertEventRefToEventRecord( event
, rec
) ;
947 switch ( GetEventClass( event
) )
949 case kEventClassKeyboard
:
952 switch ( GetEventKind(event
) )
954 case kEventRawKeyDown
:
955 rec
->what
= keyDown
;
958 case kEventRawKeyRepeat
:
959 rec
->what
= autoKey
;
962 case kEventRawKeyUp
:
966 case kEventRawKeyModifiersChanged
:
967 rec
->what
= nullEvent
;
978 unsigned char charCode
;
980 GetMouse( &rec
->where
) ;
981 err
= GetEventParameter(event
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
982 err
= GetEventParameter(event
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
983 err
= GetEventParameter(event
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
984 rec
->modifiers
= modifiers
;
985 rec
->message
= (keyCode
<< 8 ) + charCode
;
990 case kEventClassTextInput
:
992 switch ( GetEventKind( event
) )
994 case kEventTextInputUnicodeForKeyEvent
:
997 err
= GetEventParameter(
998 event
, kEventParamTextInputSendKeyboardEvent
, typeEventRef
, NULL
,
999 sizeof(rawEvent
), NULL
, &rawEvent
) ;
1003 UInt32 keyCode
, modifiers
;
1004 unsigned char charCode
;
1005 GetMouse( &rec
->where
) ;
1006 rec
->what
= keyDown
;
1007 err
= GetEventParameter(rawEvent
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1008 err
= GetEventParameter(rawEvent
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1009 err
= GetEventParameter(rawEvent
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1010 rec
->modifiers
= modifiers
;
1011 rec
->message
= (keyCode
<< 8 ) + charCode
;
1033 m_printMode
= wxPRINT_WINDOWS
;
1035 m_macCurrentEvent
= NULL
;
1036 m_macCurrentEventHandlerCallRef
= NULL
;
1037 m_macEventPosted
= NULL
;
1040 void wxApp::OnIdle(wxIdleEvent
& WXUNUSED(event
))
1042 // If they are pending events, we must process them: pending events are
1043 // either events to the threads other than main or events posted with
1044 // wxPostEvent() functions
1045 #ifndef __WXUNIVERSAL__
1046 if (!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1047 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1051 void wxApp::WakeUpIdle()
1053 if (m_macEventPosted
)
1055 CFRunLoopSourceSignal(m_macEventPosted
);
1061 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1064 GetTopWindow()->Close(true);
1067 // Default behaviour: close the application with prompts. The
1068 // user can veto the close, and therefore the end session.
1069 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1073 if (!GetTopWindow()->Close(!event
.CanVeto()))
1078 extern "C" void wxCYield() ;
1084 // Yield to other processes
1086 bool wxApp::Yield(bool onlyIfNeeded
)
1090 if ( !onlyIfNeeded
)
1092 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1099 // Yielding from a non-gui thread needs to bail out, otherwise we end up
1100 // possibly sending events in the thread too.
1101 if ( !wxThread::IsMain() )
1105 #endif // wxUSE_THREADS
1109 // by definition yield should handle all non-processed events
1113 OSStatus status
= noErr
;
1115 while ( status
== noErr
)
1117 s_inReceiveEvent
= true ;
1118 status
= ReceiveNextEvent(0, NULL
,kEventDurationNoWait
,true,&theEvent
) ;
1119 s_inReceiveEvent
= false ;
1121 if ( status
== eventLoopTimedOutErr
)
1123 // make sure next time the event loop will trigger idle events
1124 sleepTime
= kEventDurationNoWait
;
1126 else if ( status
== eventLoopQuitErr
)
1128 // according to QA1061 this may also occur when a WakeUp Process
1133 MacHandleOneEvent( theEvent
) ;
1134 ReleaseEvent(theEvent
);
1143 void wxApp::MacDoOneEvent()
1145 wxMacAutoreleasePool autoreleasepool
;
1148 s_inReceiveEvent
= true ;
1149 OSStatus status
= ReceiveNextEvent(0, NULL
, sleepTime
, true, &theEvent
) ;
1150 s_inReceiveEvent
= false ;
1154 case eventLoopTimedOutErr
:
1155 if ( wxTheApp
->ProcessIdle() )
1156 sleepTime
= kEventDurationNoWait
;
1158 sleepTime
= kEventDurationSecond
;
1161 case eventLoopQuitErr
:
1162 // according to QA1061 this may also occur
1163 // when a WakeUp Process is executed
1167 MacHandleOneEvent( theEvent
) ;
1168 ReleaseEvent( theEvent
);
1169 sleepTime
= kEventDurationNoWait
;
1174 DeletePendingObjects() ;
1178 void wxApp::MacHandleUnhandledEvent( WXEVENTREF
WXUNUSED(evr
) )
1180 // Override to process unhandled events as you please
1183 CFMutableArrayRef
GetAutoReleaseArray()
1185 static CFMutableArrayRef array
= 0;
1187 array
= CFArrayCreateMutable(kCFAllocatorDefault
,0,&kCFTypeArrayCallBacks
);
1191 void wxApp::MacHandleOneEvent( WXEVENTREF evr
)
1193 EventTargetRef theTarget
;
1194 theTarget
= GetEventDispatcherTarget();
1195 m_macCurrentEvent
= evr
;
1197 OSStatus status
= SendEventToEventTarget((EventRef
) evr
, theTarget
);
1198 if (status
== eventNotHandledErr
)
1199 MacHandleUnhandledEvent(evr
);
1202 wxMutexGuiLeaveOrEnter();
1203 #endif // wxUSE_THREADS
1205 CFArrayRemoveAllValues( GetAutoReleaseArray() );
1208 void wxApp::MacAddToAutorelease( void* cfrefobj
)
1210 CFArrayAppendValue( GetAutoReleaseArray(), cfrefobj
);
1213 long wxMacTranslateKey(unsigned char key
, unsigned char code
)
1218 case kHomeCharCode
:
1222 case kEnterCharCode
:
1223 retval
= WXK_RETURN
;
1229 case kHelpCharCode
:
1233 case kBackspaceCharCode
:
1241 case kPageUpCharCode
:
1242 retval
= WXK_PAGEUP
;
1245 case kPageDownCharCode
:
1246 retval
= WXK_PAGEDOWN
;
1249 case kReturnCharCode
:
1250 retval
= WXK_RETURN
;
1253 case kFunctionKeyCharCode
:
1323 case kEscapeCharCode
:
1324 retval
= WXK_ESCAPE
;
1327 case kLeftArrowCharCode
:
1331 case kRightArrowCharCode
:
1332 retval
= WXK_RIGHT
;
1335 case kUpArrowCharCode
:
1339 case kDownArrowCharCode
:
1343 case kDeleteCharCode
:
1344 retval
= WXK_DELETE
;
1354 int wxMacKeyCodeToModifier(wxKeyCode key
)
1379 wxMouseState
wxGetMouseState()
1383 wxPoint pt
= wxGetMousePosition();
1387 UInt32 buttons
= GetCurrentButtonState();
1388 ms
.SetLeftDown( (buttons
& 0x01) != 0 );
1389 ms
.SetMiddleDown( (buttons
& 0x04) != 0 );
1390 ms
.SetRightDown( (buttons
& 0x02) != 0 );
1392 UInt32 modifiers
= GetCurrentKeyModifiers();
1393 ms
.SetControlDown(modifiers
& controlKey
);
1394 ms
.SetShiftDown(modifiers
& shiftKey
);
1395 ms
.SetAltDown(modifiers
& optionKey
);
1396 ms
.SetMetaDown(modifiers
& cmdKey
);
1401 // TODO : once the new key/char handling is tested, move all the code to wxWindow
1403 bool wxApp::MacSendKeyDownEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1409 wxKeyEvent
event(wxEVT_KEY_DOWN
) ;
1410 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1412 handled
= focus
->HandleWindowEvent( event
) ;
1413 if ( handled
&& event
.GetSkipped() )
1419 wxWindow
*ancestor
= focus
;
1422 int command
= ancestor
->GetAcceleratorTable()->GetCommand( event
);
1425 wxEvtHandler
* const handler
= ancestor
->GetEventHandler();
1427 wxCommandEvent
command_event( wxEVT_COMMAND_MENU_SELECTED
, command
);
1428 handled
= handler
->ProcessEvent( command_event
);
1432 // accelerators can also be used with buttons, try them too
1433 command_event
.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED
);
1434 handled
= handler
->ProcessEvent( command_event
);
1440 if (ancestor
->IsTopLevel())
1443 ancestor
= ancestor
->GetParent();
1446 #endif // wxUSE_ACCEL
1451 bool wxApp::MacSendKeyUpEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1457 wxKeyEvent
event( wxEVT_KEY_UP
) ;
1458 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1459 handled
= focus
->HandleWindowEvent( event
) ;
1464 bool wxApp::MacSendCharEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1469 wxKeyEvent
event(wxEVT_CHAR
) ;
1470 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1471 long keyval
= event
.m_keyCode
;
1473 bool handled
= false ;
1475 wxNonOwnedWindow
*tlw
= focus
->MacGetTopLevelWindow() ;
1479 event
.SetEventType( wxEVT_CHAR_HOOK
);
1480 handled
= tlw
->HandleWindowEvent( event
);
1481 if ( handled
&& event
.GetSkipped() )
1487 event
.SetEventType( wxEVT_CHAR
);
1488 event
.Skip( false ) ;
1489 handled
= focus
->HandleWindowEvent( event
) ;
1492 if ( !handled
&& (keyval
== WXK_TAB
) )
1494 wxWindow
* iter
= focus
->GetParent() ;
1495 while ( iter
&& !handled
)
1497 if ( iter
->HasFlag( wxTAB_TRAVERSAL
) )
1499 wxNavigationKeyEvent new_event
;
1500 new_event
.SetEventObject( focus
);
1501 new_event
.SetDirection( !event
.ShiftDown() );
1502 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1503 new_event
.SetWindowChange( event
.ControlDown() );
1504 new_event
.SetCurrentFocus( focus
);
1505 handled
= focus
->GetParent()->HandleWindowEvent( new_event
);
1506 if ( handled
&& new_event
.GetSkipped() )
1510 iter
= iter
->GetParent() ;
1514 // backdoor handler for default return and command escape
1515 if ( !handled
&& (!focus
->IsKindOf(CLASSINFO(wxControl
) ) || !focus
->MacCanFocus() ) )
1517 // if window is not having a focus still testing for default enter or cancel
1518 // TODO: add the UMA version for ActiveNonFloatingWindow
1520 wxWindow
* focus
= wxFindWinFromMacWindow( FrontWindow() ) ;
1523 if ( keyval
== WXK_RETURN
|| keyval
== WXK_NUMPAD_ENTER
)
1525 wxTopLevelWindow
*tlw
= wxDynamicCast(wxGetTopLevelParent(focus
), wxTopLevelWindow
);
1526 if ( tlw
&& tlw
->GetDefaultItem() )
1528 wxButton
*def
= wxDynamicCast(tlw
->GetDefaultItem(), wxButton
);
1529 if ( def
&& def
->IsEnabled() )
1531 wxCommandEvent
event(wxEVT_COMMAND_BUTTON_CLICKED
, def
->GetId() );
1532 event
.SetEventObject(def
);
1533 def
->Command(event
);
1539 else if (keyval
== WXK_ESCAPE
|| (keyval
== '.' && modifiers
& cmdKey
) )
1541 // generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs)
1542 wxCommandEvent
new_event(wxEVT_COMMAND_BUTTON_CLICKED
,wxID_CANCEL
);
1543 new_event
.SetEventObject( focus
);
1544 handled
= focus
->HandleWindowEvent( new_event
);
1552 // This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
1553 void wxApp::MacCreateKeyEvent( wxKeyEvent
& event
, wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1555 short keycode
, keychar
;
1557 keychar
= short(keymessage
& charCodeMask
);
1558 keycode
= short(keymessage
& keyCodeMask
) >> 8 ;
1559 if ( !(event
.GetEventType() == wxEVT_CHAR
) && (modifiers
& (controlKey
| shiftKey
| optionKey
) ) )
1561 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1562 // and look at the character after
1564 // TODO new implementation using TextInputSources
1567 UInt32 keyInfo
= KeyTranslate((Ptr
)GetScriptManagerVariable(smKCHRCache
), ( modifiers
& (~(controlKey
| shiftKey
| optionKey
))) | keycode
, &state
);
1568 keychar
= short(keyInfo
& charCodeMask
);
1572 long keyval
= wxMacTranslateKey(keychar
, keycode
) ;
1573 if ( keyval
== keychar
&& ( event
.GetEventType() == wxEVT_KEY_UP
|| event
.GetEventType() == wxEVT_KEY_DOWN
) )
1574 keyval
= wxToupper( keyval
) ;
1576 // Check for NUMPAD keys. For KEY_UP/DOWN events we need to use the
1577 // WXK_NUMPAD constants, but for the CHAR event we want to use the
1578 // standard ascii values
1579 if ( event
.GetEventType() != wxEVT_CHAR
)
1581 if (keyval
>= '0' && keyval
<= '9' && keycode
>= 82 && keycode
<= 92)
1583 keyval
= (keyval
- '0') + WXK_NUMPAD0
;
1585 else if (keycode
>= 65 && keycode
<= 81)
1590 keyval
= WXK_NUMPAD_ENTER
;
1594 keyval
= WXK_NUMPAD_EQUAL
;
1598 keyval
= WXK_NUMPAD_MULTIPLY
;
1602 keyval
= WXK_NUMPAD_DIVIDE
;
1606 keyval
= WXK_NUMPAD_SUBTRACT
;
1610 keyval
= WXK_NUMPAD_ADD
;
1614 keyval
= WXK_NUMPAD_DECIMAL
;
1622 event
.m_shiftDown
= modifiers
& shiftKey
;
1623 event
.m_controlDown
= modifiers
& controlKey
;
1624 event
.m_altDown
= modifiers
& optionKey
;
1625 event
.m_metaDown
= modifiers
& cmdKey
;
1626 event
.m_keyCode
= keyval
;
1628 event
.m_uniChar
= uniChar
;
1631 event
.m_rawCode
= keymessage
;
1632 event
.m_rawFlags
= modifiers
;
1635 event
.SetTimestamp(when
);
1636 event
.SetEventObject(focus
);
1640 void wxApp::MacHideApp()
1642 wxMacCarbonEvent
event( kEventClassCommand
, kEventCommandProcess
);
1644 memset( &command
, 0 , sizeof(command
) );
1645 command
.commandID
= kHICommandHide
;
1646 event
.SetParameter
<HICommand
>(kEventParamDirectObject
, command
);
1647 SendEventToApplication( event
);