1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/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"
43 #include "wx/evtloop.h"
49 #include "wx/osx/uma.h"
51 #include "wx/osx/private.h"
54 #if defined(WXMAKINGDLL_CORE)
55 # include <mach-o/dyld.h>
58 // Keep linker from discarding wxStockGDIMac
59 wxFORCE_LINK_MODULE(gdiobj
)
61 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
62 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
63 EVT_IDLE(wxApp::OnIdle
)
64 EVT_END_SESSION(wxApp::OnEndSession
)
65 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
69 // platform specific static variables
70 static const short kwxMacAppleMenuId
= 1 ;
72 wxWindow
* wxApp::s_captureWindow
= NULL
;
73 long wxApp::s_lastModifiers
= 0 ;
75 long wxApp::s_macAboutMenuItemId
= wxID_ABOUT
;
76 long wxApp::s_macPreferencesMenuItemId
= wxID_PREFERENCES
;
77 long wxApp::s_macExitMenuItemId
= wxID_EXIT
;
78 wxString
wxApp::s_macHelpMenuTitleName
= wxT("&Help") ;
80 bool wxApp::sm_isEmbedded
= false; // Normally we're not a plugin
84 //----------------------------------------------------------------------
85 // Core Apple Event Support
86 //----------------------------------------------------------------------
88 AEEventHandlerUPP sODocHandler
= NULL
;
89 AEEventHandlerUPP sGURLHandler
= NULL
;
90 AEEventHandlerUPP sOAppHandler
= NULL
;
91 AEEventHandlerUPP sPDocHandler
= NULL
;
92 AEEventHandlerUPP sRAppHandler
= NULL
;
93 AEEventHandlerUPP sQuitHandler
= NULL
;
95 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
96 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
97 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
98 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
99 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
100 pascal OSErr
AEHandleGURL( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
102 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
104 return wxTheApp
->MacHandleAEODoc( (AppleEvent
*) event
, reply
) ;
107 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
109 return wxTheApp
->MacHandleAEOApp( (AppleEvent
*) event
, reply
) ;
112 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
114 return wxTheApp
->MacHandleAEPDoc( (AppleEvent
*) event
, reply
) ;
117 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
119 return wxTheApp
->MacHandleAEQuit( (AppleEvent
*) event
, reply
) ;
122 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
124 return wxTheApp
->MacHandleAERApp( (AppleEvent
*) event
, reply
) ;
127 pascal OSErr
AEHandleGURL( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
129 return wxTheApp
->MacHandleAEGURL((WXEVENTREF
*)event
, reply
) ;
133 // AEODoc Calls MacOpenFile on each of the files passed
135 short wxApp::MacHandleAEODoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
139 DescType returnedType
;
145 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
149 err
= AECountItems(&docList
, &itemsInList
);
153 ProcessSerialNumber PSN
;
154 PSN
.highLongOfPSN
= 0 ;
155 PSN
.lowLongOfPSN
= kCurrentProcess
;
156 SetFrontProcess( &PSN
) ;
161 for (i
= 1; i
<= itemsInList
; i
++)
164 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
165 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
166 fName
= wxMacFSRefToPath( &theRef
) ;
174 // AEODoc Calls MacOpenURL on the url passed
176 short wxApp::MacHandleAEGURL(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
178 DescType returnedType
;
181 OSErr err
= AEGetParamPtr((AppleEvent
*)event
, keyDirectObject
, typeChar
,
182 &returnedType
, url
, sizeof(url
)-1,
187 url
[actualSize
] = '\0'; // Terminate the C string
189 ProcessSerialNumber PSN
;
190 PSN
.highLongOfPSN
= 0 ;
191 PSN
.lowLongOfPSN
= kCurrentProcess
;
192 SetFrontProcess( &PSN
) ;
194 MacOpenURL(wxString(url
, wxConvUTF8
));
199 // AEPDoc Calls MacPrintFile on each of the files passed
201 short wxApp::MacHandleAEPDoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
205 DescType returnedType
;
211 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
215 err
= AECountItems(&docList
, &itemsInList
);
219 ProcessSerialNumber PSN
;
220 PSN
.highLongOfPSN
= 0 ;
221 PSN
.lowLongOfPSN
= kCurrentProcess
;
222 SetFrontProcess( &PSN
) ;
227 for (i
= 1; i
<= itemsInList
; i
++)
230 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
231 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
232 fName
= wxMacFSRefToPath( &theRef
) ;
240 // AEOApp calls MacNewFile
242 short wxApp::MacHandleAEOApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
248 // AEQuit attempts to quit the application
250 short wxApp::MacHandleAEQuit(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
252 wxWindow
* win
= GetTopWindow() ;
255 wxCommandEvent
exitEvent(wxEVT_COMMAND_MENU_SELECTED
, s_macExitMenuItemId
);
256 if (!win
->ProcessEvent(exitEvent
))
267 // AEROApp calls MacReopenApp
269 short wxApp::MacHandleAERApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
278 //----------------------------------------------------------------------
279 // Support Routines linking the Mac...File Calls to the Document Manager
280 //----------------------------------------------------------------------
282 void wxApp::MacOpenFile(const wxString
& fileName
)
284 #if wxUSE_DOC_VIEW_ARCHITECTURE
285 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
287 dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
291 void wxApp::MacOpenURL(const wxString
& WXUNUSED(url
) )
295 void wxApp::MacPrintFile(const wxString
& fileName
)
297 #if wxUSE_DOC_VIEW_ARCHITECTURE
299 #if wxUSE_PRINTING_ARCHITECTURE
300 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
303 wxDocument
*doc
= dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
306 wxView
* view
= doc
->GetFirstView() ;
309 wxPrintout
*printout
= view
->OnCreatePrintout();
313 printer
.Print(view
->GetFrame(), printout
, true);
320 doc
->DeleteAllViews();
321 dm
->RemoveDocument(doc
) ;
332 void wxApp::MacNewFile()
336 void wxApp::MacReopenApp()
339 // if there is no open window -> create a new one
340 // if all windows are hidden -> show the first
341 // if some windows are not hidden -> do nothing
343 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetFirst();
350 wxTopLevelWindow
* firstIconized
= NULL
;
351 wxTopLevelWindow
* firstHidden
= NULL
;
354 wxTopLevelWindow
* win
= (wxTopLevelWindow
*) node
->GetData();
355 if ( !win
->IsShown() )
357 // make sure we don't show 'virtual toplevel windows' like wxTaskBarIconWindow
358 if ( firstHidden
== NULL
&& ( wxDynamicCast( win
, wxFrame
) || wxDynamicCast( win
, wxDialog
) ) )
361 else if ( win
->IsIconized() )
363 if ( firstIconized
== NULL
)
364 firstIconized
= win
;
368 // we do have a visible, non-iconized toplevelwindow -> do nothing
372 node
= node
->GetNext();
376 firstIconized
->Iconize( false ) ;
377 else if ( firstHidden
)
378 firstHidden
->Show( true );
382 //----------------------------------------------------------------------
383 // Macintosh CommandID support - converting between native and wx IDs
384 //----------------------------------------------------------------------
386 // if no native match they just return the passed-in id
396 IdPair gCommandIds
[] =
398 { kHICommandCut
, wxID_CUT
} ,
399 { kHICommandCopy
, wxID_COPY
} ,
400 { kHICommandPaste
, wxID_PASTE
} ,
401 { kHICommandSelectAll
, wxID_SELECTALL
} ,
402 { kHICommandClear
, wxID_CLEAR
} ,
403 { kHICommandUndo
, wxID_UNDO
} ,
404 { kHICommandRedo
, wxID_REDO
} ,
407 int wxMacCommandToId( UInt32 macCommandId
)
411 switch ( macCommandId
)
413 case kHICommandPreferences
:
414 wxid
= wxApp::s_macPreferencesMenuItemId
;
417 case kHICommandQuit
:
418 wxid
= wxApp::s_macExitMenuItemId
;
421 case kHICommandAbout
:
422 wxid
= wxApp::s_macAboutMenuItemId
;
427 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
429 if ( gCommandIds
[i
].macId
== macCommandId
)
431 wxid
= gCommandIds
[i
].wxId
;
440 wxid
= (int) macCommandId
;
445 UInt32
wxIdToMacCommand( int wxId
)
449 if ( wxId
== wxApp::s_macPreferencesMenuItemId
)
450 macId
= kHICommandPreferences
;
451 else if (wxId
== wxApp::s_macExitMenuItemId
)
452 macId
= kHICommandQuit
;
453 else if (wxId
== wxApp::s_macAboutMenuItemId
)
454 macId
= kHICommandAbout
;
457 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
459 if ( gCommandIds
[i
].wxId
== wxId
)
461 macId
= gCommandIds
[i
].macId
;
473 wxMenu
* wxFindMenuFromMacCommand( const HICommand
&command
, wxMenuItem
* &item
)
475 wxMenu
* itemMenu
= NULL
;
476 #ifndef __WXUNIVERSAL__
479 // for 'standard' commands which don't have a wx-menu
480 if ( command
.commandID
== kHICommandPreferences
|| command
.commandID
== kHICommandQuit
|| command
.commandID
== kHICommandAbout
)
482 id
= wxMacCommandToId( command
.commandID
) ;
484 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
486 item
= mbar
->FindItem( id
, &itemMenu
) ;
488 else if ( command
.commandID
!= 0 && command
.menu
.menuRef
!= 0 && command
.menu
.menuItemIndex
!= 0 )
490 id
= wxMacCommandToId( command
.commandID
) ;
491 // make sure it is one of our own menus, or of the 'synthetic' apple and help menus , otherwise don't touch
492 MenuItemIndex firstUserHelpMenuItem
;
493 static MenuHandle helpMenuHandle
= NULL
;
494 if ( helpMenuHandle
== NULL
)
496 if ( UMAGetHelpMenuDontCreate( &helpMenuHandle
, &firstUserHelpMenuItem
) != noErr
)
497 helpMenuHandle
= NULL
;
500 // is it part of the application or the Help menu, then look for the id directly
501 if ( ( GetMenuHandle( kwxMacAppleMenuId
) != NULL
&& command
.menu
.menuRef
== GetMenuHandle( kwxMacAppleMenuId
) ) ||
502 ( helpMenuHandle
!= NULL
&& command
.menu
.menuRef
== helpMenuHandle
) ||
503 wxMenuBar::MacGetWindowMenuHMenu() != NULL
&& command
.menu
.menuRef
== wxMenuBar::MacGetWindowMenuHMenu() )
505 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
507 item
= mbar
->FindItem( id
, &itemMenu
) ;
511 URefCon refCon
= NULL
;
513 GetMenuItemRefCon( command
.menu
.menuRef
, command
.menu
.menuItemIndex
, &refCon
) ;
514 itemMenu
= wxFindMenuFromMacMenu( command
.menu
.menuRef
) ;
515 if ( itemMenu
!= NULL
&& refCon
!= 0)
516 item
= ((wxMenuItemImpl
*) refCon
)->GetWXPeer() ;
525 //----------------------------------------------------------------------
526 // Carbon Event Handler
527 //----------------------------------------------------------------------
531 static const EventTypeSpec eventList
[] =
533 { kEventClassCommand
, kEventProcessCommand
} ,
534 { kEventClassCommand
, kEventCommandUpdateStatus
} ,
536 { kEventClassMenu
, kEventMenuOpening
},
537 { kEventClassMenu
, kEventMenuClosed
},
538 { kEventClassMenu
, kEventMenuTargetItem
},
540 { kEventClassApplication
, kEventAppActivated
} ,
541 { kEventClassApplication
, kEventAppDeactivated
} ,
542 // handling the quit event is not recommended by apple
543 // rather using the quit apple event - which we do
545 { kEventClassAppleEvent
, kEventAppleEvent
} ,
547 { kEventClassMouse
, kEventMouseDown
} ,
548 { kEventClassMouse
, kEventMouseMoved
} ,
549 { kEventClassMouse
, kEventMouseUp
} ,
550 { kEventClassMouse
, kEventMouseDragged
} ,
554 static pascal OSStatus
555 wxMacAppMenuEventHandler( EventHandlerCallRef
WXUNUSED(handler
),
557 void *WXUNUSED(data
) )
559 wxMacCarbonEvent
cEvent( event
) ;
560 MenuRef menuRef
= cEvent
.GetParameter
<MenuRef
>(kEventParamDirectObject
) ;
561 #ifndef __WXUNIVERSAL__
562 wxMenu
* menu
= wxFindMenuFromMacMenu( menuRef
) ;
566 switch (GetEventKind(event
))
568 case kEventMenuOpening
:
569 menu
->HandleMenuOpened();
572 case kEventMenuClosed
:
573 menu
->HandleMenuClosed();
576 case kEventMenuTargetItem
:
580 command
.menu
.menuRef
= menuRef
;
581 command
.menu
.menuItemIndex
= cEvent
.GetParameter
<MenuItemIndex
>(kEventParamMenuItemIndex
,typeMenuItemIndex
) ;
582 command
.commandID
= cEvent
.GetParameter
<MenuCommand
>(kEventParamMenuCommand
,typeMenuCommand
) ;
583 if (command
.commandID
!= 0)
585 wxMenuItem
* item
= NULL
;
586 wxMenu
* itemMenu
= wxFindMenuFromMacCommand( command
, item
) ;
587 if ( itemMenu
&& item
)
588 itemMenu
->HandleMenuItemHighlighted( item
);
594 wxFAIL_MSG(wxT("Unexpected menu event kind"));
600 return eventNotHandledErr
;
603 static pascal OSStatus
604 wxMacAppCommandEventHandler( EventHandlerCallRef
WXUNUSED(handler
) ,
606 void *WXUNUSED(data
) )
608 OSStatus result
= eventNotHandledErr
;
612 wxMacCarbonEvent
cEvent( event
) ;
613 cEvent
.GetParameter
<HICommand
>(kEventParamDirectObject
,typeHICommand
,&command
) ;
615 wxMenuItem
* item
= NULL
;
616 wxMenu
* itemMenu
= wxFindMenuFromMacCommand( command
, item
) ;
620 wxASSERT( itemMenu
!= NULL
) ;
622 switch ( cEvent
.GetKind() )
624 case kEventProcessCommand
:
625 if ( itemMenu
->HandleCommandProcess( item
) )
629 case kEventCommandUpdateStatus
:
630 if ( itemMenu
->HandleCommandUpdateStatus( item
) )
641 static pascal OSStatus
642 wxMacAppApplicationEventHandler( EventHandlerCallRef
WXUNUSED(handler
) ,
644 void *WXUNUSED(data
) )
646 OSStatus result
= eventNotHandledErr
;
647 switch ( GetEventKind( event
) )
649 case kEventAppActivated
:
651 wxTheApp
->SetActive( true , NULL
) ;
655 case kEventAppDeactivated
:
657 wxTheApp
->SetActive( false , NULL
) ;
668 pascal OSStatus
wxMacAppEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
670 EventRef formerEvent
= (EventRef
) wxTheApp
->MacGetCurrentEvent() ;
671 EventHandlerCallRef formerEventHandlerCallRef
= (EventHandlerCallRef
) wxTheApp
->MacGetCurrentEventHandlerCallRef() ;
672 wxTheApp
->MacSetCurrentEvent( event
, handler
) ;
674 OSStatus result
= eventNotHandledErr
;
675 switch ( GetEventClass( event
) )
678 case kEventClassCommand
:
679 result
= wxMacAppCommandEventHandler( handler
, event
, data
) ;
682 case kEventClassApplication
:
683 result
= wxMacAppApplicationEventHandler( handler
, event
, data
) ;
686 case kEventClassMenu
:
687 result
= wxMacAppMenuEventHandler( handler
, event
, data
) ;
690 case kEventClassMouse
:
692 wxMacCarbonEvent
cEvent( event
) ;
695 Point screenMouseLocation
= cEvent
.GetParameter
<Point
>(kEventParamMouseLocation
) ;
696 ::FindWindow(screenMouseLocation
, &window
);
697 // only send this event in case it had not already been sent to a tlw, as we get
698 // double events otherwise (in case event.skip) was called
699 if ( window
== NULL
)
700 result
= wxMacTopLevelMouseEventHandler( handler
, event
, NULL
) ;
704 case kEventClassAppleEvent
:
706 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
707 if ( AEProcessEvent
!= NULL
)
709 result
= AEProcessEvent(event
);
712 #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
716 wxMacConvertEventToRecord( event
, &rec
) ;
717 result
= AEProcessAppleEvent( &rec
) ;
727 wxTheApp
->MacSetCurrentEvent( formerEvent
, formerEventHandlerCallRef
) ;
732 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler
)
735 #if defined( __WXDEBUG__ ) && wxOSX_USE_COCOA_OR_CARBON
738 wxMacAssertOutputHandler(OSType
WXUNUSED(componentSignature
),
739 UInt32
WXUNUSED(options
),
740 const char *assertionString
,
741 const char *exceptionLabelString
,
742 const char *errorString
,
743 const char *fileName
,
746 ConstStr255Param
WXUNUSED(outputMsg
))
748 // flow into assert handling
749 wxString fileNameStr
;
750 wxString assertionStr
;
751 wxString exceptionStr
;
755 fileNameStr
= wxString(fileName
, wxConvLocal
);
756 assertionStr
= wxString(assertionString
, wxConvLocal
);
757 exceptionStr
= wxString((exceptionLabelString
!=0) ? exceptionLabelString
: "", wxConvLocal
) ;
758 errorStr
= wxString((errorString
!=0) ? errorString
: "", wxConvLocal
) ;
760 fileNameStr
= fileName
;
761 assertionStr
= assertionString
;
762 exceptionStr
= (exceptionLabelString
!=0) ? exceptionLabelString
: "" ;
763 errorStr
= (errorString
!=0) ? errorString
: "" ;
768 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
769 assertionStr
.c_str() ,
770 exceptionStr
.c_str() ,
772 fileNameStr
.c_str(), lineNumber
,
776 wxOnAssert(fileNameStr
, lineNumber
, assertionStr
,
777 wxString::Format( wxT("%s %s value (%p)") , exceptionStr
, errorStr
, value
) ) ;
783 extern "C" void macPostedEventCallback(void *WXUNUSED(unused
))
785 wxTheApp
->ProcessPendingEvents();
788 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
792 #if defined( __WXDEBUG__ ) && wxOSX_USE_COCOA_OR_CARBON
793 InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler
) );
796 // Mac OS X passes a process serial number command line argument when
797 // the application is launched from the Finder. This argument must be
798 // removed from the command line arguments before being handled by the
799 // application (otherwise applications would need to handle it)
802 static const wxChar
*ARG_PSN
= _T("-psn_");
803 if ( wxStrncmp(argv
[1], ARG_PSN
, wxStrlen(ARG_PSN
)) == 0 )
805 // remove this argument
807 memmove(argv
+ 1, argv
+ 2, argc
* sizeof(char *));
811 if ( !wxAppBase::Initialize(argc
, argv
) )
815 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
818 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
819 wxString startupCwd
= wxGetCwd() ;
820 if ( startupCwd
== wxT("/") || startupCwd
.Right(15) == wxT("/Contents/MacOS") )
822 CFURLRef url
= CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
823 CFURLRef urlParent
= CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault
, url
) ;
825 CFStringRef path
= CFURLCopyFileSystemPath ( urlParent
, kCFURLPOSIXPathStyle
) ;
826 CFRelease( urlParent
) ;
827 wxString cwd
= wxCFStringRef(path
).AsString(wxLocale::GetSystemEncoding());
828 wxSetWorkingDirectory( cwd
) ;
831 /* connect posted events to common-mode run loop so that wxPostEvent events
832 are handled even while we're in the menu or on a scrollbar */
834 CFRunLoopSourceContext event_posted_context = {0};
835 event_posted_context.perform = macPostedEventCallback;
836 m_macEventPosted = CFRunLoopSourceCreate(NULL,0,&event_posted_context);
837 CFRunLoopAddSource(CFRunLoopGetCurrent(), m_macEventPosted, kCFRunLoopCommonModes);
838 // run loop takes ownership
839 CFRelease(m_macEventPosted);
844 bool wxApp::CallOnInit()
846 wxMacAutoreleasePool autoreleasepool
;
850 bool wxApp::OnInitGui()
852 if ( !wxAppBase::OnInitGui() )
861 bool wxApp::ProcessIdle()
863 wxMacAutoreleasePool autoreleasepool
;
864 return wxAppBase::ProcessIdle();
868 bool wxApp::DoInitGui()
870 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
873 InstallApplicationEventHandler(
874 GetwxMacAppEventHandlerUPP(),
875 GetEventTypeCount(eventList
), eventList
, wxTheApp
, (EventHandlerRef
*)&(wxTheApp
->m_macEventHandler
));
880 sODocHandler
= NewAEEventHandlerUPP(AEHandleODoc
) ;
881 sGURLHandler
= NewAEEventHandlerUPP(AEHandleGURL
) ;
882 sOAppHandler
= NewAEEventHandlerUPP(AEHandleOApp
) ;
883 sPDocHandler
= NewAEEventHandlerUPP(AEHandlePDoc
) ;
884 sRAppHandler
= NewAEEventHandlerUPP(AEHandleRApp
) ;
885 sQuitHandler
= NewAEEventHandlerUPP(AEHandleQuit
) ;
887 AEInstallEventHandler( kCoreEventClass
, kAEOpenDocuments
,
888 sODocHandler
, 0 , FALSE
) ;
889 AEInstallEventHandler( kInternetEventClass
, kAEGetURL
,
890 sGURLHandler
, 0 , FALSE
) ;
891 AEInstallEventHandler( kCoreEventClass
, kAEOpenApplication
,
892 sOAppHandler
, 0 , FALSE
) ;
893 AEInstallEventHandler( kCoreEventClass
, kAEPrintDocuments
,
894 sPDocHandler
, 0 , FALSE
) ;
895 AEInstallEventHandler( kCoreEventClass
, kAEReopenApplication
,
896 sRAppHandler
, 0 , FALSE
) ;
897 AEInstallEventHandler( kCoreEventClass
, kAEQuitApplication
,
898 sQuitHandler
, 0 , FALSE
) ;
901 if ( !wxMacInitCocoa() )
907 void wxApp::DoCleanUp()
910 RemoveEventHandler( (EventHandlerRef
)(wxTheApp
->m_macEventHandler
) );
914 AERemoveEventHandler( kCoreEventClass
, kAEOpenDocuments
,
915 sODocHandler
, FALSE
) ;
916 AERemoveEventHandler( kInternetEventClass
, kAEGetURL
,
917 sGURLHandler
, FALSE
) ;
918 AERemoveEventHandler( kCoreEventClass
, kAEOpenApplication
,
919 sOAppHandler
, FALSE
) ;
920 AERemoveEventHandler( kCoreEventClass
, kAEPrintDocuments
,
921 sPDocHandler
, FALSE
) ;
922 AERemoveEventHandler( kCoreEventClass
, kAEReopenApplication
,
923 sRAppHandler
, FALSE
) ;
924 AERemoveEventHandler( kCoreEventClass
, kAEQuitApplication
,
925 sQuitHandler
, FALSE
) ;
927 DisposeAEEventHandlerUPP( sODocHandler
) ;
928 DisposeAEEventHandlerUPP( sGURLHandler
) ;
929 DisposeAEEventHandlerUPP( sOAppHandler
) ;
930 DisposeAEEventHandlerUPP( sPDocHandler
) ;
931 DisposeAEEventHandlerUPP( sRAppHandler
) ;
932 DisposeAEEventHandlerUPP( sQuitHandler
) ;
938 void wxApp::CleanUp()
941 wxToolTip::RemoveToolTips() ;
944 if (m_macEventPosted
)
946 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
947 m_macEventPosted
= NULL
;
952 wxAppBase::CleanUp();
955 //----------------------------------------------------------------------
956 // misc initialization stuff
957 //----------------------------------------------------------------------
959 #if wxOSX_USE_CARBON && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
960 bool wxMacConvertEventToRecord( EventRef event
, EventRecord
*rec
)
962 OSStatus err
= noErr
;
963 bool converted
= ConvertEventRefToEventRecord( event
, rec
) ;
967 switch ( GetEventClass( event
) )
969 case kEventClassKeyboard
:
972 switch ( GetEventKind(event
) )
974 case kEventRawKeyDown
:
975 rec
->what
= keyDown
;
978 case kEventRawKeyRepeat
:
979 rec
->what
= autoKey
;
982 case kEventRawKeyUp
:
986 case kEventRawKeyModifiersChanged
:
987 rec
->what
= nullEvent
;
998 unsigned char charCode
;
1000 GetMouse( &rec
->where
) ;
1001 err
= GetEventParameter(event
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1002 err
= GetEventParameter(event
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1003 err
= GetEventParameter(event
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1004 rec
->modifiers
= modifiers
;
1005 rec
->message
= (keyCode
<< 8 ) + charCode
;
1010 case kEventClassTextInput
:
1012 switch ( GetEventKind( event
) )
1014 case kEventTextInputUnicodeForKeyEvent
:
1017 err
= GetEventParameter(
1018 event
, kEventParamTextInputSendKeyboardEvent
, typeEventRef
, NULL
,
1019 sizeof(rawEvent
), NULL
, &rawEvent
) ;
1023 UInt32 keyCode
, modifiers
;
1024 unsigned char charCode
;
1025 GetMouse( &rec
->where
) ;
1026 rec
->what
= keyDown
;
1027 err
= GetEventParameter(rawEvent
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1028 err
= GetEventParameter(rawEvent
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1029 err
= GetEventParameter(rawEvent
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1030 rec
->modifiers
= modifiers
;
1031 rec
->message
= (keyCode
<< 8 ) + charCode
;
1053 m_printMode
= wxPRINT_WINDOWS
;
1055 m_macCurrentEvent
= NULL
;
1056 m_macCurrentEventHandlerCallRef
= NULL
;
1057 m_macEventPosted
= NULL
;
1060 CFMutableArrayRef
GetAutoReleaseArray()
1062 static CFMutableArrayRef array
= 0;
1064 array
= CFArrayCreateMutable(kCFAllocatorDefault
,0,&kCFTypeArrayCallBacks
);
1068 void wxApp::MacAddToAutorelease( void* cfrefobj
)
1070 CFArrayAppendValue( GetAutoReleaseArray(), cfrefobj
);
1073 void wxApp::OnIdle(wxIdleEvent
& WXUNUSED(event
))
1075 // If they are pending events, we must process them: pending events are
1076 // either events to the threads other than main or events posted with
1077 // wxPostEvent() functions
1078 #ifndef __WXUNIVERSAL__
1080 if (!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1081 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1084 CFArrayRemoveAllValues( GetAutoReleaseArray() );
1087 void wxApp::WakeUpIdle()
1089 if (m_macEventPosted
)
1091 CFRunLoopSourceSignal(m_macEventPosted
);
1097 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1100 GetTopWindow()->Close(true);
1103 // Default behaviour: close the application with prompts. The
1104 // user can veto the close, and therefore the end session.
1105 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1109 if (!GetTopWindow()->Close(!event
.CanVeto()))
1114 extern "C" void wxCYield() ;
1120 // Yield to other processes
1122 bool wxApp::Yield(bool onlyIfNeeded
)
1125 // Yielding from a non-gui thread needs to bail out, otherwise we end up
1126 // possibly sending events in the thread too.
1127 if ( !wxThread::IsMain() )
1131 #endif // wxUSE_THREADS
1133 if (m_isInsideYield
)
1135 if ( !onlyIfNeeded
)
1137 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1143 m_isInsideYield
= true;
1146 // disable log flushing from here because a call to wxYield() shouldn't
1147 // normally result in message boxes popping up &c
1152 loop
= static_cast<wxEventLoop
*>(wxEventLoop::GetActive());
1155 // process all pending events:
1156 while ( loop
->Pending() )
1160 // it's necessary to call ProcessIdle() to update the frames sizes which
1161 // might have been changed (it also will update other things set from
1162 // OnUpdateUI() which is a nice (and desired) side effect)
1163 while ( ProcessIdle() ) {}
1168 m_isInsideYield
= false;
1174 void wxApp::MacHandleUnhandledEvent( WXEVENTREF
WXUNUSED(evr
) )
1176 // Override to process unhandled events as you please
1179 #if wxOSX_USE_CARBON
1181 long wxMacTranslateKey(unsigned char key
, unsigned char code
)
1186 case kHomeCharCode
:
1190 case kEnterCharCode
:
1191 retval
= WXK_RETURN
;
1197 case kHelpCharCode
:
1201 case kBackspaceCharCode
:
1209 case kPageUpCharCode
:
1210 retval
= WXK_PAGEUP
;
1213 case kPageDownCharCode
:
1214 retval
= WXK_PAGEDOWN
;
1217 case kReturnCharCode
:
1218 retval
= WXK_RETURN
;
1221 case kFunctionKeyCharCode
:
1291 case kEscapeCharCode
:
1292 retval
= WXK_ESCAPE
;
1295 case kLeftArrowCharCode
:
1299 case kRightArrowCharCode
:
1300 retval
= WXK_RIGHT
;
1303 case kUpArrowCharCode
:
1307 case kDownArrowCharCode
:
1311 case kDeleteCharCode
:
1312 retval
= WXK_DELETE
;
1322 int wxMacKeyCodeToModifier(wxKeyCode key
)
1348 wxMouseState
wxGetMouseState()
1352 wxPoint pt
= wxGetMousePosition();
1356 #if wxOSX_USE_CARBON
1357 UInt32 buttons
= GetCurrentButtonState();
1358 ms
.SetLeftDown( (buttons
& 0x01) != 0 );
1359 ms
.SetMiddleDown( (buttons
& 0x04) != 0 );
1360 ms
.SetRightDown( (buttons
& 0x02) != 0 );
1362 UInt32 modifiers
= GetCurrentKeyModifiers();
1363 ms
.SetControlDown(modifiers
& controlKey
);
1364 ms
.SetShiftDown(modifiers
& shiftKey
);
1365 ms
.SetAltDown(modifiers
& optionKey
);
1366 ms
.SetMetaDown(modifiers
& cmdKey
);
1373 // TODO : once the new key/char handling is tested, move all the code to wxWindow
1375 bool wxApp::MacSendKeyDownEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1381 wxKeyEvent
event(wxEVT_KEY_DOWN
) ;
1382 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1384 handled
= focus
->HandleWindowEvent( event
) ;
1385 if ( handled
&& event
.GetSkipped() )
1391 wxWindow
*ancestor
= focus
;
1394 int command
= ancestor
->GetAcceleratorTable()->GetCommand( event
);
1397 wxEvtHandler
* const handler
= ancestor
->GetEventHandler();
1399 wxCommandEvent
command_event( wxEVT_COMMAND_MENU_SELECTED
, command
);
1400 handled
= handler
->ProcessEvent( command_event
);
1404 // accelerators can also be used with buttons, try them too
1405 command_event
.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED
);
1406 handled
= handler
->ProcessEvent( command_event
);
1412 if (ancestor
->IsTopLevel())
1415 ancestor
= ancestor
->GetParent();
1418 #endif // wxUSE_ACCEL
1423 bool wxApp::MacSendKeyUpEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1429 wxKeyEvent
event( wxEVT_KEY_UP
) ;
1430 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1431 handled
= focus
->HandleWindowEvent( event
) ;
1436 bool wxApp::MacSendCharEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1440 wxKeyEvent
event(wxEVT_CHAR
) ;
1441 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1443 bool handled
= false ;
1445 #if wxOSX_USE_CARBON
1446 long keyval
= event
.m_keyCode
;
1447 wxNonOwnedWindow
*tlw
= focus
->MacGetTopLevelWindow() ;
1451 event
.SetEventType( wxEVT_CHAR_HOOK
);
1452 handled
= tlw
->HandleWindowEvent( event
);
1453 if ( handled
&& event
.GetSkipped() )
1459 event
.SetEventType( wxEVT_CHAR
);
1460 event
.Skip( false ) ;
1461 handled
= focus
->HandleWindowEvent( event
) ;
1464 if ( !handled
&& (keyval
== WXK_TAB
) )
1466 wxWindow
* iter
= focus
->GetParent() ;
1467 while ( iter
&& !handled
)
1469 if ( iter
->HasFlag( wxTAB_TRAVERSAL
) )
1471 wxNavigationKeyEvent new_event
;
1472 new_event
.SetEventObject( focus
);
1473 new_event
.SetDirection( !event
.ShiftDown() );
1474 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1475 new_event
.SetWindowChange( event
.ControlDown() );
1476 new_event
.SetCurrentFocus( focus
);
1477 handled
= focus
->GetParent()->HandleWindowEvent( new_event
);
1478 if ( handled
&& new_event
.GetSkipped() )
1482 iter
= iter
->GetParent() ;
1486 // backdoor handler for default return and command escape
1487 if ( !handled
&& (!focus
->IsKindOf(CLASSINFO(wxControl
) ) || !focus
->AcceptsFocus() ) )
1489 // if window is not having a focus still testing for default enter or cancel
1490 // TODO: add the UMA version for ActiveNonFloatingWindow
1492 wxWindow
* focus
= wxNonOwnedWindow::GetFromWXWindow( (WXWindow
) FrontWindow() ) ;
1495 if ( keyval
== WXK_RETURN
|| keyval
== WXK_NUMPAD_ENTER
)
1497 wxTopLevelWindow
*tlw
= wxDynamicCast(wxGetTopLevelParent(focus
), wxTopLevelWindow
);
1498 if ( tlw
&& tlw
->GetDefaultItem() )
1500 wxButton
*def
= wxDynamicCast(tlw
->GetDefaultItem(), wxButton
);
1501 if ( def
&& def
->IsEnabled() )
1503 wxCommandEvent
event(wxEVT_COMMAND_BUTTON_CLICKED
, def
->GetId() );
1504 event
.SetEventObject(def
);
1505 def
->Command(event
);
1511 else if (keyval
== WXK_ESCAPE
|| (keyval
== '.' && modifiers
& cmdKey
) )
1513 // generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs)
1514 wxCommandEvent
new_event(wxEVT_COMMAND_BUTTON_CLICKED
,wxID_CANCEL
);
1515 new_event
.SetEventObject( focus
);
1516 handled
= focus
->HandleWindowEvent( new_event
);
1525 // This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
1526 void wxApp::MacCreateKeyEvent( wxKeyEvent
& event
, wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1528 #if wxOSX_USE_CARBON
1529 short keycode
, keychar
;
1531 keychar
= short(keymessage
& charCodeMask
);
1532 keycode
= short(keymessage
& keyCodeMask
) >> 8 ;
1533 if ( !(event
.GetEventType() == wxEVT_CHAR
) && (modifiers
& (controlKey
| shiftKey
| optionKey
) ) )
1535 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1536 // and look at the character after
1538 // TODO new implementation using TextInputSources
1541 UInt32 keyInfo
= KeyTranslate((Ptr
)GetScriptManagerVariable(smKCHRCache
), ( modifiers
& (~(controlKey
| shiftKey
| optionKey
))) | keycode
, &state
);
1542 keychar
= short(keyInfo
& charCodeMask
);
1546 long keyval
= wxMacTranslateKey(keychar
, keycode
) ;
1547 if ( keyval
== keychar
&& ( event
.GetEventType() == wxEVT_KEY_UP
|| event
.GetEventType() == wxEVT_KEY_DOWN
) )
1548 keyval
= wxToupper( keyval
) ;
1550 // Check for NUMPAD keys. For KEY_UP/DOWN events we need to use the
1551 // WXK_NUMPAD constants, but for the CHAR event we want to use the
1552 // standard ascii values
1553 if ( event
.GetEventType() != wxEVT_CHAR
)
1555 if (keyval
>= '0' && keyval
<= '9' && keycode
>= 82 && keycode
<= 92)
1557 keyval
= (keyval
- '0') + WXK_NUMPAD0
;
1559 else if (keycode
>= 65 && keycode
<= 81)
1564 keyval
= WXK_NUMPAD_ENTER
;
1568 keyval
= WXK_NUMPAD_EQUAL
;
1572 keyval
= WXK_NUMPAD_MULTIPLY
;
1576 keyval
= WXK_NUMPAD_DIVIDE
;
1580 keyval
= WXK_NUMPAD_SUBTRACT
;
1584 keyval
= WXK_NUMPAD_ADD
;
1588 keyval
= WXK_NUMPAD_DECIMAL
;
1596 event
.m_shiftDown
= modifiers
& shiftKey
;
1597 event
.m_controlDown
= modifiers
& controlKey
;
1598 event
.m_altDown
= modifiers
& optionKey
;
1599 event
.m_metaDown
= modifiers
& cmdKey
;
1600 event
.m_keyCode
= keyval
;
1602 event
.m_uniChar
= uniChar
;
1605 event
.m_rawCode
= keymessage
;
1606 event
.m_rawFlags
= modifiers
;
1609 event
.SetTimestamp(when
);
1610 event
.SetEventObject(focus
);
1615 void wxApp::MacHideApp()
1617 #if wxOSX_USE_CARBON
1618 wxMacCarbonEvent
event( kEventClassCommand
, kEventCommandProcess
);
1620 memset( &command
, 0 , sizeof(command
) );
1621 command
.commandID
= kHICommandHide
;
1622 event
.SetParameter
<HICommand
>(kEventParamDirectObject
, command
);
1623 SendEventToApplication( event
);