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/osx/uma.h"
50 #include "wx/osx/private.h"
53 #if defined(WXMAKINGDLL_CORE)
54 # 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 #if wxOSX_USE_COCOA_OR_CARBON
64 static EventTime sleepTime
= kEventDurationNoWait
;
67 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
68 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
69 EVT_IDLE(wxApp::OnIdle
)
70 EVT_END_SESSION(wxApp::OnEndSession
)
71 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
75 // platform specific static variables
76 static const short kwxMacAppleMenuId
= 1 ;
78 wxWindow
* wxApp::s_captureWindow
= NULL
;
79 long wxApp::s_lastModifiers
= 0 ;
81 long wxApp::s_macAboutMenuItemId
= wxID_ABOUT
;
82 long wxApp::s_macPreferencesMenuItemId
= wxID_PREFERENCES
;
83 long wxApp::s_macExitMenuItemId
= wxID_EXIT
;
84 wxString
wxApp::s_macHelpMenuTitleName
= wxT("&Help") ;
86 bool wxApp::sm_isEmbedded
= false; // Normally we're not a plugin
88 #if wxOSX_USE_COCOA_OR_CARBON
90 //----------------------------------------------------------------------
91 // Core Apple Event Support
92 //----------------------------------------------------------------------
94 AEEventHandlerUPP sODocHandler
= NULL
;
95 AEEventHandlerUPP sGURLHandler
= NULL
;
96 AEEventHandlerUPP sOAppHandler
= NULL
;
97 AEEventHandlerUPP sPDocHandler
= NULL
;
98 AEEventHandlerUPP sRAppHandler
= NULL
;
99 AEEventHandlerUPP sQuitHandler
= NULL
;
101 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
102 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
103 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
104 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
105 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
106 pascal OSErr
AEHandleGURL( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
108 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
110 return wxTheApp
->MacHandleAEODoc( (AppleEvent
*) event
, reply
) ;
113 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
115 return wxTheApp
->MacHandleAEOApp( (AppleEvent
*) event
, reply
) ;
118 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
120 return wxTheApp
->MacHandleAEPDoc( (AppleEvent
*) event
, reply
) ;
123 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
125 return wxTheApp
->MacHandleAEQuit( (AppleEvent
*) event
, reply
) ;
128 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
130 return wxTheApp
->MacHandleAERApp( (AppleEvent
*) event
, reply
) ;
133 pascal OSErr
AEHandleGURL( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
135 return wxTheApp
->MacHandleAEGURL((WXEVENTREF
*)event
, reply
) ;
139 // AEODoc Calls MacOpenFile on each of the files passed
141 short wxApp::MacHandleAEODoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
145 DescType returnedType
;
151 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
155 err
= AECountItems(&docList
, &itemsInList
);
159 ProcessSerialNumber PSN
;
160 PSN
.highLongOfPSN
= 0 ;
161 PSN
.lowLongOfPSN
= kCurrentProcess
;
162 SetFrontProcess( &PSN
) ;
167 for (i
= 1; i
<= itemsInList
; i
++)
170 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
171 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
172 fName
= wxMacFSRefToPath( &theRef
) ;
180 // AEODoc Calls MacOpenURL on the url passed
182 short wxApp::MacHandleAEGURL(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
184 DescType returnedType
;
187 OSErr err
= AEGetParamPtr((AppleEvent
*)event
, keyDirectObject
, typeChar
,
188 &returnedType
, url
, sizeof(url
)-1,
193 url
[actualSize
] = '\0'; // Terminate the C string
195 ProcessSerialNumber PSN
;
196 PSN
.highLongOfPSN
= 0 ;
197 PSN
.lowLongOfPSN
= kCurrentProcess
;
198 SetFrontProcess( &PSN
) ;
200 MacOpenURL(wxString(url
, wxConvUTF8
));
205 // AEPDoc Calls MacPrintFile on each of the files passed
207 short wxApp::MacHandleAEPDoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
211 DescType returnedType
;
217 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
221 err
= AECountItems(&docList
, &itemsInList
);
225 ProcessSerialNumber PSN
;
226 PSN
.highLongOfPSN
= 0 ;
227 PSN
.lowLongOfPSN
= kCurrentProcess
;
228 SetFrontProcess( &PSN
) ;
233 for (i
= 1; i
<= itemsInList
; i
++)
236 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
237 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
238 fName
= wxMacFSRefToPath( &theRef
) ;
246 // AEOApp calls MacNewFile
248 short wxApp::MacHandleAEOApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
254 // AEQuit attempts to quit the application
256 short wxApp::MacHandleAEQuit(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
258 wxWindow
* win
= GetTopWindow() ;
261 wxCommandEvent
exitEvent(wxEVT_COMMAND_MENU_SELECTED
, s_macExitMenuItemId
);
262 if (!win
->ProcessEvent(exitEvent
))
273 // AEROApp calls MacReopenApp
275 short wxApp::MacHandleAERApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
284 //----------------------------------------------------------------------
285 // Support Routines linking the Mac...File Calls to the Document Manager
286 //----------------------------------------------------------------------
288 void wxApp::MacOpenFile(const wxString
& fileName
)
290 #if wxUSE_DOC_VIEW_ARCHITECTURE
291 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
293 dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
297 void wxApp::MacOpenURL(const wxString
& WXUNUSED(url
) )
301 void wxApp::MacPrintFile(const wxString
& fileName
)
303 #if wxUSE_DOC_VIEW_ARCHITECTURE
305 #if wxUSE_PRINTING_ARCHITECTURE
306 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
309 wxDocument
*doc
= dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
312 wxView
* view
= doc
->GetFirstView() ;
315 wxPrintout
*printout
= view
->OnCreatePrintout();
319 printer
.Print(view
->GetFrame(), printout
, true);
326 doc
->DeleteAllViews();
327 dm
->RemoveDocument(doc
) ;
338 void wxApp::MacNewFile()
342 void wxApp::MacReopenApp()
345 // if there is no open window -> create a new one
346 // if all windows are hidden -> show the first
347 // if some windows are not hidden -> do nothing
349 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetFirst();
356 wxTopLevelWindow
* firstIconized
= NULL
;
357 wxTopLevelWindow
* firstHidden
= NULL
;
360 wxTopLevelWindow
* win
= (wxTopLevelWindow
*) node
->GetData();
361 if ( !win
->IsShown() )
363 // make sure we don't show 'virtual toplevel windows' like wxTaskBarIconWindow
364 if ( firstHidden
== NULL
&& ( wxDynamicCast( win
, wxFrame
) || wxDynamicCast( win
, wxDialog
) ) )
367 else if ( win
->IsIconized() )
369 if ( firstIconized
== NULL
)
370 firstIconized
= win
;
374 // we do have a visible, non-iconized toplevelwindow -> do nothing
378 node
= node
->GetNext();
382 firstIconized
->Iconize( false ) ;
383 else if ( firstHidden
)
384 firstHidden
->Show( true );
388 //----------------------------------------------------------------------
389 // Macintosh CommandID support - converting between native and wx IDs
390 //----------------------------------------------------------------------
392 // if no native match they just return the passed-in id
402 IdPair gCommandIds
[] =
404 { kHICommandCut
, wxID_CUT
} ,
405 { kHICommandCopy
, wxID_COPY
} ,
406 { kHICommandPaste
, wxID_PASTE
} ,
407 { kHICommandSelectAll
, wxID_SELECTALL
} ,
408 { kHICommandClear
, wxID_CLEAR
} ,
409 { kHICommandUndo
, wxID_UNDO
} ,
410 { kHICommandRedo
, wxID_REDO
} ,
413 int wxMacCommandToId( UInt32 macCommandId
)
417 switch ( macCommandId
)
419 case kHICommandPreferences
:
420 wxid
= wxApp::s_macPreferencesMenuItemId
;
423 case kHICommandQuit
:
424 wxid
= wxApp::s_macExitMenuItemId
;
427 case kHICommandAbout
:
428 wxid
= wxApp::s_macAboutMenuItemId
;
433 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
435 if ( gCommandIds
[i
].macId
== macCommandId
)
437 wxid
= gCommandIds
[i
].wxId
;
446 wxid
= (int) macCommandId
;
451 UInt32
wxIdToMacCommand( int wxId
)
455 if ( wxId
== wxApp::s_macPreferencesMenuItemId
)
456 macId
= kHICommandPreferences
;
457 else if (wxId
== wxApp::s_macExitMenuItemId
)
458 macId
= kHICommandQuit
;
459 else if (wxId
== wxApp::s_macAboutMenuItemId
)
460 macId
= kHICommandAbout
;
463 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
465 if ( gCommandIds
[i
].wxId
== wxId
)
467 macId
= gCommandIds
[i
].macId
;
479 wxMenu
* wxFindMenuFromMacCommand( const HICommand
&command
, wxMenuItem
* &item
)
481 wxMenu
* itemMenu
= NULL
;
482 #ifndef __WXUNIVERSAL__
485 // for 'standard' commands which don't have a wx-menu
486 if ( command
.commandID
== kHICommandPreferences
|| command
.commandID
== kHICommandQuit
|| command
.commandID
== kHICommandAbout
)
488 id
= wxMacCommandToId( command
.commandID
) ;
490 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
492 item
= mbar
->FindItem( id
, &itemMenu
) ;
494 else if ( command
.commandID
!= 0 && command
.menu
.menuRef
!= 0 && command
.menu
.menuItemIndex
!= 0 )
496 id
= wxMacCommandToId( command
.commandID
) ;
497 // make sure it is one of our own menus, or of the 'synthetic' apple and help menus , otherwise don't touch
498 MenuItemIndex firstUserHelpMenuItem
;
499 static MenuHandle helpMenuHandle
= NULL
;
500 if ( helpMenuHandle
== NULL
)
502 if ( UMAGetHelpMenuDontCreate( &helpMenuHandle
, &firstUserHelpMenuItem
) != noErr
)
503 helpMenuHandle
= NULL
;
506 // is it part of the application or the Help menu, then look for the id directly
507 if ( ( GetMenuHandle( kwxMacAppleMenuId
) != NULL
&& command
.menu
.menuRef
== GetMenuHandle( kwxMacAppleMenuId
) ) ||
508 ( helpMenuHandle
!= NULL
&& command
.menu
.menuRef
== helpMenuHandle
) ||
509 wxMenuBar::MacGetWindowMenuHMenu() != NULL
&& command
.menu
.menuRef
== wxMenuBar::MacGetWindowMenuHMenu() )
511 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
513 item
= mbar
->FindItem( id
, &itemMenu
) ;
519 GetMenuItemRefCon( command
.menu
.menuRef
, command
.menu
.menuItemIndex
, &refCon
) ;
520 itemMenu
= wxFindMenuFromMacMenu( command
.menu
.menuRef
) ;
521 if ( itemMenu
!= NULL
)
522 item
= (wxMenuItem
*) refCon
;
531 //----------------------------------------------------------------------
532 // Carbon Event Handler
533 //----------------------------------------------------------------------
537 static const EventTypeSpec eventList
[] =
539 { kEventClassCommand
, kEventProcessCommand
} ,
540 { kEventClassCommand
, kEventCommandUpdateStatus
} ,
542 { kEventClassMenu
, kEventMenuOpening
},
543 { kEventClassMenu
, kEventMenuClosed
},
544 { kEventClassMenu
, kEventMenuTargetItem
},
546 { kEventClassApplication
, kEventAppActivated
} ,
547 { kEventClassApplication
, kEventAppDeactivated
} ,
548 // handling the quit event is not recommended by apple
549 // rather using the quit apple event - which we do
551 { kEventClassAppleEvent
, kEventAppleEvent
} ,
553 { kEventClassMouse
, kEventMouseDown
} ,
554 { kEventClassMouse
, kEventMouseMoved
} ,
555 { kEventClassMouse
, kEventMouseUp
} ,
556 { kEventClassMouse
, kEventMouseDragged
} ,
560 static pascal OSStatus
561 wxMacAppMenuEventHandler( EventHandlerCallRef
WXUNUSED(handler
),
563 void *WXUNUSED(data
) )
565 wxMacCarbonEvent
cEvent( event
) ;
566 MenuRef menuRef
= cEvent
.GetParameter
<MenuRef
>(kEventParamDirectObject
) ;
567 #ifndef __WXUNIVERSAL__
568 wxMenu
* menu
= wxFindMenuFromMacMenu( menuRef
) ;
574 switch (GetEventKind(event
))
576 case kEventMenuOpening
:
577 type
= wxEVT_MENU_OPEN
;
580 case kEventMenuClosed
:
581 type
= wxEVT_MENU_CLOSE
;
584 case kEventMenuTargetItem
:
585 cmd
= cEvent
.GetParameter
<MenuCommand
>(kEventParamMenuCommand
,typeMenuCommand
) ;
587 type
= wxEVT_MENU_HIGHLIGHT
;
591 wxFAIL_MSG(wxT("Unexpected menu event kind"));
597 wxMenuEvent
wxevent(type
, cmd
, menu
);
598 wxevent
.SetEventObject(menu
);
600 wxEvtHandler
* handler
= menu
->GetEventHandler();
601 if (handler
&& handler
->ProcessEvent(wxevent
))
607 wxWindow
*win
= menu
->GetInvokingWindow();
609 win
->HandleWindowEvent(wxevent
);
614 return eventNotHandledErr
;
617 static pascal OSStatus
618 wxMacAppCommandEventHandler( EventHandlerCallRef
WXUNUSED(handler
) ,
620 void *WXUNUSED(data
) )
622 OSStatus result
= eventNotHandledErr
;
626 wxMacCarbonEvent
cEvent( event
) ;
627 cEvent
.GetParameter
<HICommand
>(kEventParamDirectObject
,typeHICommand
,&command
) ;
629 wxMenuItem
* item
= NULL
;
630 wxMenu
* itemMenu
= wxFindMenuFromMacCommand( command
, item
) ;
631 int id
= wxMacCommandToId( command
.commandID
) ;
635 wxASSERT( itemMenu
!= NULL
) ;
637 switch ( cEvent
.GetKind() )
639 case kEventProcessCommand
:
640 result
= itemMenu
->MacHandleCommandProcess( item
, id
);
643 case kEventCommandUpdateStatus
:
644 result
= itemMenu
->MacHandleCommandUpdateStatus( item
, id
);
654 static pascal OSStatus
655 wxMacAppApplicationEventHandler( EventHandlerCallRef
WXUNUSED(handler
) ,
657 void *WXUNUSED(data
) )
659 OSStatus result
= eventNotHandledErr
;
660 switch ( GetEventKind( event
) )
662 case kEventAppActivated
:
664 wxTheApp
->SetActive( true , NULL
) ;
668 case kEventAppDeactivated
:
670 wxTheApp
->SetActive( false , NULL
) ;
681 pascal OSStatus
wxMacAppEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
683 EventRef formerEvent
= (EventRef
) wxTheApp
->MacGetCurrentEvent() ;
684 EventHandlerCallRef formerEventHandlerCallRef
= (EventHandlerCallRef
) wxTheApp
->MacGetCurrentEventHandlerCallRef() ;
685 wxTheApp
->MacSetCurrentEvent( event
, handler
) ;
687 OSStatus result
= eventNotHandledErr
;
688 switch ( GetEventClass( event
) )
691 case kEventClassCommand
:
692 result
= wxMacAppCommandEventHandler( handler
, event
, data
) ;
695 case kEventClassApplication
:
696 result
= wxMacAppApplicationEventHandler( handler
, event
, data
) ;
699 case kEventClassMenu
:
700 result
= wxMacAppMenuEventHandler( handler
, event
, data
) ;
703 case kEventClassMouse
:
705 wxMacCarbonEvent
cEvent( event
) ;
708 Point screenMouseLocation
= cEvent
.GetParameter
<Point
>(kEventParamMouseLocation
) ;
709 ::FindWindow(screenMouseLocation
, &window
);
710 // only send this event in case it had not already been sent to a tlw, as we get
711 // double events otherwise (in case event.skip) was called
712 if ( window
== NULL
)
713 result
= wxMacTopLevelMouseEventHandler( handler
, event
, NULL
) ;
717 case kEventClassAppleEvent
:
719 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
720 if ( AEProcessEvent
!= NULL
)
722 result
= AEProcessEvent(event
);
725 #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
729 wxMacConvertEventToRecord( event
, &rec
) ;
730 result
= AEProcessAppleEvent( &rec
) ;
740 wxTheApp
->MacSetCurrentEvent( formerEvent
, formerEventHandlerCallRef
) ;
745 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler
)
748 #if defined( __WXDEBUG__ ) && wxOSX_USE_COCOA_OR_CARBON
751 wxMacAssertOutputHandler(OSType
WXUNUSED(componentSignature
),
752 UInt32
WXUNUSED(options
),
753 const char *assertionString
,
754 const char *exceptionLabelString
,
755 const char *errorString
,
756 const char *fileName
,
759 ConstStr255Param
WXUNUSED(outputMsg
))
761 // flow into assert handling
762 wxString fileNameStr
;
763 wxString assertionStr
;
764 wxString exceptionStr
;
768 fileNameStr
= wxString(fileName
, wxConvLocal
);
769 assertionStr
= wxString(assertionString
, wxConvLocal
);
770 exceptionStr
= wxString((exceptionLabelString
!=0) ? exceptionLabelString
: "", wxConvLocal
) ;
771 errorStr
= wxString((errorString
!=0) ? errorString
: "", wxConvLocal
) ;
773 fileNameStr
= fileName
;
774 assertionStr
= assertionString
;
775 exceptionStr
= (exceptionLabelString
!=0) ? exceptionLabelString
: "" ;
776 errorStr
= (errorString
!=0) ? errorString
: "" ;
781 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
782 assertionStr
.c_str() ,
783 exceptionStr
.c_str() ,
785 fileNameStr
.c_str(), lineNumber
,
789 wxOnAssert(fileNameStr
, lineNumber
, assertionStr
,
790 wxString::Format( wxT("%s %s value (%p)") , exceptionStr
, errorStr
, value
) ) ;
796 extern "C" void macPostedEventCallback(void *WXUNUSED(unused
))
798 wxTheApp
->ProcessPendingEvents();
801 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
805 #if defined( __WXDEBUG__ ) && wxOSX_USE_COCOA_OR_CARBON
806 InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler
) );
809 // Mac OS X passes a process serial number command line argument when
810 // the application is launched from the Finder. This argument must be
811 // removed from the command line arguments before being handled by the
812 // application (otherwise applications would need to handle it)
815 static const wxChar
*ARG_PSN
= _T("-psn_");
816 if ( wxStrncmp(argv
[1], ARG_PSN
, wxStrlen(ARG_PSN
)) == 0 )
818 // remove this argument
820 memmove(argv
+ 1, argv
+ 2, argc
* sizeof(char *));
824 if ( !wxAppBase::Initialize(argc
, argv
) )
828 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
831 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
832 wxString startupCwd
= wxGetCwd() ;
833 if ( startupCwd
== wxT("/") || startupCwd
.Right(15) == wxT("/Contents/MacOS") )
835 CFURLRef url
= CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
836 CFURLRef urlParent
= CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault
, url
) ;
838 CFStringRef path
= CFURLCopyFileSystemPath ( urlParent
, kCFURLPOSIXPathStyle
) ;
839 CFRelease( urlParent
) ;
840 wxString cwd
= wxCFStringRef(path
).AsString(wxLocale::GetSystemEncoding());
841 wxSetWorkingDirectory( cwd
) ;
844 /* connect posted events to common-mode run loop so that wxPostEvent events
845 are handled even while we're in the menu or on a scrollbar */
846 CFRunLoopSourceContext event_posted_context
= {0};
847 event_posted_context
.perform
= macPostedEventCallback
;
848 m_macEventPosted
= CFRunLoopSourceCreate(NULL
,0,&event_posted_context
);
849 CFRunLoopAddSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
850 // run loop takes ownership
851 CFRelease(m_macEventPosted
);
856 bool wxApp::OnInitGui()
858 if ( !wxAppBase::OnInitGui() )
861 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
864 InstallApplicationEventHandler(
865 GetwxMacAppEventHandlerUPP(),
866 GetEventTypeCount(eventList
), eventList
, wxTheApp
, (EventHandlerRef
*)&(wxTheApp
->m_macEventHandler
));
870 #if wxOSX_USE_COCOA_OR_CARBON
873 sODocHandler
= NewAEEventHandlerUPP(AEHandleODoc
) ;
874 sGURLHandler
= NewAEEventHandlerUPP(AEHandleGURL
) ;
875 sOAppHandler
= NewAEEventHandlerUPP(AEHandleOApp
) ;
876 sPDocHandler
= NewAEEventHandlerUPP(AEHandlePDoc
) ;
877 sRAppHandler
= NewAEEventHandlerUPP(AEHandleRApp
) ;
878 sQuitHandler
= NewAEEventHandlerUPP(AEHandleQuit
) ;
880 AEInstallEventHandler( kCoreEventClass
, kAEOpenDocuments
,
881 sODocHandler
, 0 , FALSE
) ;
882 AEInstallEventHandler( kInternetEventClass
, kAEGetURL
,
883 sGURLHandler
, 0 , FALSE
) ;
884 AEInstallEventHandler( kCoreEventClass
, kAEOpenApplication
,
885 sOAppHandler
, 0 , FALSE
) ;
886 AEInstallEventHandler( kCoreEventClass
, kAEPrintDocuments
,
887 sPDocHandler
, 0 , FALSE
) ;
888 AEInstallEventHandler( kCoreEventClass
, kAEReopenApplication
,
889 sRAppHandler
, 0 , FALSE
) ;
890 AEInstallEventHandler( kCoreEventClass
, kAEQuitApplication
,
891 sQuitHandler
, 0 , FALSE
) ;
895 if ( !wxMacInitCocoa() )
902 void wxApp::CleanUp()
905 wxToolTip::RemoveToolTips() ;
908 if (m_macEventPosted
)
910 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
911 m_macEventPosted
= NULL
;
914 // One last chance for pending objects to be cleaned up
915 wxTheApp
->DeletePendingObjects();
917 #if wxOSX_USE_COCOA_OR_CARBON
920 RemoveEventHandler( (EventHandlerRef
)(wxTheApp
->m_macEventHandler
) );
924 AERemoveEventHandler( kCoreEventClass
, kAEOpenDocuments
,
925 sODocHandler
, FALSE
) ;
926 AERemoveEventHandler( kInternetEventClass
, kAEGetURL
,
927 sGURLHandler
, FALSE
) ;
928 AERemoveEventHandler( kCoreEventClass
, kAEOpenApplication
,
929 sOAppHandler
, FALSE
) ;
930 AERemoveEventHandler( kCoreEventClass
, kAEPrintDocuments
,
931 sPDocHandler
, FALSE
) ;
932 AERemoveEventHandler( kCoreEventClass
, kAEReopenApplication
,
933 sRAppHandler
, FALSE
) ;
934 AERemoveEventHandler( kCoreEventClass
, kAEQuitApplication
,
935 sQuitHandler
, FALSE
) ;
937 DisposeAEEventHandlerUPP( sODocHandler
) ;
938 DisposeAEEventHandlerUPP( sGURLHandler
) ;
939 DisposeAEEventHandlerUPP( sOAppHandler
) ;
940 DisposeAEEventHandlerUPP( sPDocHandler
) ;
941 DisposeAEEventHandlerUPP( sRAppHandler
) ;
942 DisposeAEEventHandlerUPP( sQuitHandler
) ;
947 wxAppBase::CleanUp();
950 //----------------------------------------------------------------------
951 // misc initialization stuff
952 //----------------------------------------------------------------------
954 #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
955 bool wxMacConvertEventToRecord( EventRef event
, EventRecord
*rec
)
957 OSStatus err
= noErr
;
958 bool converted
= ConvertEventRefToEventRecord( event
, rec
) ;
962 switch ( GetEventClass( event
) )
964 case kEventClassKeyboard
:
967 switch ( GetEventKind(event
) )
969 case kEventRawKeyDown
:
970 rec
->what
= keyDown
;
973 case kEventRawKeyRepeat
:
974 rec
->what
= autoKey
;
977 case kEventRawKeyUp
:
981 case kEventRawKeyModifiersChanged
:
982 rec
->what
= nullEvent
;
993 unsigned char charCode
;
995 GetMouse( &rec
->where
) ;
996 err
= GetEventParameter(event
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
997 err
= GetEventParameter(event
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
998 err
= GetEventParameter(event
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
999 rec
->modifiers
= modifiers
;
1000 rec
->message
= (keyCode
<< 8 ) + charCode
;
1005 case kEventClassTextInput
:
1007 switch ( GetEventKind( event
) )
1009 case kEventTextInputUnicodeForKeyEvent
:
1012 err
= GetEventParameter(
1013 event
, kEventParamTextInputSendKeyboardEvent
, typeEventRef
, NULL
,
1014 sizeof(rawEvent
), NULL
, &rawEvent
) ;
1018 UInt32 keyCode
, modifiers
;
1019 unsigned char charCode
;
1020 GetMouse( &rec
->where
) ;
1021 rec
->what
= keyDown
;
1022 err
= GetEventParameter(rawEvent
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1023 err
= GetEventParameter(rawEvent
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1024 err
= GetEventParameter(rawEvent
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1025 rec
->modifiers
= modifiers
;
1026 rec
->message
= (keyCode
<< 8 ) + charCode
;
1048 m_printMode
= wxPRINT_WINDOWS
;
1050 m_macCurrentEvent
= NULL
;
1051 m_macCurrentEventHandlerCallRef
= NULL
;
1052 m_macEventPosted
= NULL
;
1055 void wxApp::OnIdle(wxIdleEvent
& WXUNUSED(event
))
1057 // If they are pending events, we must process them: pending events are
1058 // either events to the threads other than main or events posted with
1059 // wxPostEvent() functions
1060 #ifndef __WXUNIVERSAL__
1061 if (!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1062 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1066 void wxApp::WakeUpIdle()
1068 if (m_macEventPosted
)
1070 CFRunLoopSourceSignal(m_macEventPosted
);
1076 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1079 GetTopWindow()->Close(true);
1082 // Default behaviour: close the application with prompts. The
1083 // user can veto the close, and therefore the end session.
1084 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1088 if (!GetTopWindow()->Close(!event
.CanVeto()))
1093 extern "C" void wxCYield() ;
1099 // Yield to other processes
1101 bool wxApp::Yield(bool onlyIfNeeded
)
1105 if ( !onlyIfNeeded
)
1107 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1114 // Yielding from a non-gui thread needs to bail out, otherwise we end up
1115 // possibly sending events in the thread too.
1116 if ( !wxThread::IsMain() )
1120 #endif // wxUSE_THREADS
1124 // by definition yield should handle all non-processed events
1126 #if wxOSX_USE_COCOA_OR_CARBON
1130 OSStatus status
= noErr
;
1132 while ( status
== noErr
)
1134 s_inReceiveEvent
= true ;
1135 status
= ReceiveNextEvent(0, NULL
,kEventDurationNoWait
,true,&theEvent
) ;
1136 s_inReceiveEvent
= false ;
1138 if ( status
== eventLoopTimedOutErr
)
1140 // make sure next time the event loop will trigger idle events
1141 sleepTime
= kEventDurationNoWait
;
1143 else if ( status
== eventLoopQuitErr
)
1145 // according to QA1061 this may also occur when a WakeUp Process
1150 MacHandleOneEvent( theEvent
) ;
1151 ReleaseEvent(theEvent
);
1164 void wxApp::MacDoOneEvent()
1166 #if wxOSX_USE_COCOA_OR_CARBON
1167 wxMacAutoreleasePool autoreleasepool
;
1170 s_inReceiveEvent
= true ;
1171 OSStatus status
= ReceiveNextEvent(0, NULL
, sleepTime
, true, &theEvent
) ;
1172 s_inReceiveEvent
= false ;
1176 case eventLoopTimedOutErr
:
1177 if ( wxTheApp
->ProcessIdle() )
1178 sleepTime
= kEventDurationNoWait
;
1180 sleepTime
= kEventDurationSecond
;
1183 case eventLoopQuitErr
:
1184 // according to QA1061 this may also occur
1185 // when a WakeUp Process is executed
1189 MacHandleOneEvent( theEvent
) ;
1190 ReleaseEvent( theEvent
);
1191 sleepTime
= kEventDurationNoWait
;
1197 DeletePendingObjects() ;
1201 void wxApp::MacHandleUnhandledEvent( WXEVENTREF
WXUNUSED(evr
) )
1203 // Override to process unhandled events as you please
1206 CFMutableArrayRef
GetAutoReleaseArray()
1208 static CFMutableArrayRef array
= 0;
1210 array
= CFArrayCreateMutable(kCFAllocatorDefault
,0,&kCFTypeArrayCallBacks
);
1223 void wxApp::MacHandleOneEvent( WXEVENTREF evr
)
1225 #if wxOSX_USE_COCOA_OR_CARBON
1226 EventTargetRef theTarget
;
1227 theTarget
= GetEventDispatcherTarget();
1228 m_macCurrentEvent
= evr
;
1230 OSStatus status
= SendEventToEventTarget((EventRef
) evr
, theTarget
);
1231 if (status
== eventNotHandledErr
)
1232 MacHandleUnhandledEvent(evr
);
1235 wxMutexGuiLeaveOrEnter();
1236 #endif // wxUSE_THREADS
1243 CFArrayRemoveAllValues( GetAutoReleaseArray() );
1246 void wxApp::MacAddToAutorelease( void* cfrefobj
)
1248 CFArrayAppendValue( GetAutoReleaseArray(), cfrefobj
);
1251 #if wxOSX_USE_COCOA_OR_CARBON
1253 long wxMacTranslateKey(unsigned char key
, unsigned char code
)
1258 case kHomeCharCode
:
1262 case kEnterCharCode
:
1263 retval
= WXK_RETURN
;
1269 case kHelpCharCode
:
1273 case kBackspaceCharCode
:
1281 case kPageUpCharCode
:
1282 retval
= WXK_PAGEUP
;
1285 case kPageDownCharCode
:
1286 retval
= WXK_PAGEDOWN
;
1289 case kReturnCharCode
:
1290 retval
= WXK_RETURN
;
1293 case kFunctionKeyCharCode
:
1363 case kEscapeCharCode
:
1364 retval
= WXK_ESCAPE
;
1367 case kLeftArrowCharCode
:
1371 case kRightArrowCharCode
:
1372 retval
= WXK_RIGHT
;
1375 case kUpArrowCharCode
:
1379 case kDownArrowCharCode
:
1383 case kDeleteCharCode
:
1384 retval
= WXK_DELETE
;
1394 int wxMacKeyCodeToModifier(wxKeyCode key
)
1420 wxMouseState
wxGetMouseState()
1423 #if wxOSX_USE_COCOA_OR_CARBON
1425 wxPoint pt
= wxGetMousePosition();
1429 UInt32 buttons
= GetCurrentButtonState();
1430 ms
.SetLeftDown( (buttons
& 0x01) != 0 );
1431 ms
.SetMiddleDown( (buttons
& 0x04) != 0 );
1432 ms
.SetRightDown( (buttons
& 0x02) != 0 );
1434 UInt32 modifiers
= GetCurrentKeyModifiers();
1435 ms
.SetControlDown(modifiers
& controlKey
);
1436 ms
.SetShiftDown(modifiers
& shiftKey
);
1437 ms
.SetAltDown(modifiers
& optionKey
);
1438 ms
.SetMetaDown(modifiers
& cmdKey
);
1444 // TODO : once the new key/char handling is tested, move all the code to wxWindow
1446 bool wxApp::MacSendKeyDownEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1452 wxKeyEvent
event(wxEVT_KEY_DOWN
) ;
1453 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1455 handled
= focus
->HandleWindowEvent( event
) ;
1456 if ( handled
&& event
.GetSkipped() )
1462 wxWindow
*ancestor
= focus
;
1465 int command
= ancestor
->GetAcceleratorTable()->GetCommand( event
);
1468 wxEvtHandler
* const handler
= ancestor
->GetEventHandler();
1470 wxCommandEvent
command_event( wxEVT_COMMAND_MENU_SELECTED
, command
);
1471 handled
= handler
->ProcessEvent( command_event
);
1475 // accelerators can also be used with buttons, try them too
1476 command_event
.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED
);
1477 handled
= handler
->ProcessEvent( command_event
);
1483 if (ancestor
->IsTopLevel())
1486 ancestor
= ancestor
->GetParent();
1489 #endif // wxUSE_ACCEL
1494 bool wxApp::MacSendKeyUpEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1500 wxKeyEvent
event( wxEVT_KEY_UP
) ;
1501 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1502 handled
= focus
->HandleWindowEvent( event
) ;
1507 bool wxApp::MacSendCharEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1511 wxKeyEvent
event(wxEVT_CHAR
) ;
1512 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1513 long keyval
= event
.m_keyCode
;
1515 bool handled
= false ;
1517 #if wxOSX_USE_CARBON
1518 wxNonOwnedWindow
*tlw
= focus
->MacGetTopLevelWindow() ;
1522 event
.SetEventType( wxEVT_CHAR_HOOK
);
1523 handled
= tlw
->HandleWindowEvent( event
);
1524 if ( handled
&& event
.GetSkipped() )
1530 event
.SetEventType( wxEVT_CHAR
);
1531 event
.Skip( false ) ;
1532 handled
= focus
->HandleWindowEvent( event
) ;
1535 if ( !handled
&& (keyval
== WXK_TAB
) )
1537 wxWindow
* iter
= focus
->GetParent() ;
1538 while ( iter
&& !handled
)
1540 if ( iter
->HasFlag( wxTAB_TRAVERSAL
) )
1542 wxNavigationKeyEvent new_event
;
1543 new_event
.SetEventObject( focus
);
1544 new_event
.SetDirection( !event
.ShiftDown() );
1545 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1546 new_event
.SetWindowChange( event
.ControlDown() );
1547 new_event
.SetCurrentFocus( focus
);
1548 handled
= focus
->GetParent()->HandleWindowEvent( new_event
);
1549 if ( handled
&& new_event
.GetSkipped() )
1553 iter
= iter
->GetParent() ;
1557 // backdoor handler for default return and command escape
1558 if ( !handled
&& (!focus
->IsKindOf(CLASSINFO(wxControl
) ) || !focus
->AcceptsFocus() ) )
1560 // if window is not having a focus still testing for default enter or cancel
1561 // TODO: add the UMA version for ActiveNonFloatingWindow
1563 wxWindow
* focus
= wxNonOwnedWindow::GetFromWXWindow( (WXWindow
) FrontWindow() ) ;
1566 if ( keyval
== WXK_RETURN
|| keyval
== WXK_NUMPAD_ENTER
)
1568 wxTopLevelWindow
*tlw
= wxDynamicCast(wxGetTopLevelParent(focus
), wxTopLevelWindow
);
1569 if ( tlw
&& tlw
->GetDefaultItem() )
1571 wxButton
*def
= wxDynamicCast(tlw
->GetDefaultItem(), wxButton
);
1572 if ( def
&& def
->IsEnabled() )
1574 wxCommandEvent
event(wxEVT_COMMAND_BUTTON_CLICKED
, def
->GetId() );
1575 event
.SetEventObject(def
);
1576 def
->Command(event
);
1582 else if (keyval
== WXK_ESCAPE
|| (keyval
== '.' && modifiers
& cmdKey
) )
1584 // generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs)
1585 wxCommandEvent
new_event(wxEVT_COMMAND_BUTTON_CLICKED
,wxID_CANCEL
);
1586 new_event
.SetEventObject( focus
);
1587 handled
= focus
->HandleWindowEvent( new_event
);
1596 // This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
1597 void wxApp::MacCreateKeyEvent( wxKeyEvent
& event
, wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1599 #if wxOSX_USE_COCOA_OR_CARBON
1600 short keycode
, keychar
;
1602 keychar
= short(keymessage
& charCodeMask
);
1603 keycode
= short(keymessage
& keyCodeMask
) >> 8 ;
1604 if ( !(event
.GetEventType() == wxEVT_CHAR
) && (modifiers
& (controlKey
| shiftKey
| optionKey
) ) )
1606 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1607 // and look at the character after
1609 // TODO new implementation using TextInputSources
1612 UInt32 keyInfo
= KeyTranslate((Ptr
)GetScriptManagerVariable(smKCHRCache
), ( modifiers
& (~(controlKey
| shiftKey
| optionKey
))) | keycode
, &state
);
1613 keychar
= short(keyInfo
& charCodeMask
);
1617 long keyval
= wxMacTranslateKey(keychar
, keycode
) ;
1618 if ( keyval
== keychar
&& ( event
.GetEventType() == wxEVT_KEY_UP
|| event
.GetEventType() == wxEVT_KEY_DOWN
) )
1619 keyval
= wxToupper( keyval
) ;
1621 // Check for NUMPAD keys. For KEY_UP/DOWN events we need to use the
1622 // WXK_NUMPAD constants, but for the CHAR event we want to use the
1623 // standard ascii values
1624 if ( event
.GetEventType() != wxEVT_CHAR
)
1626 if (keyval
>= '0' && keyval
<= '9' && keycode
>= 82 && keycode
<= 92)
1628 keyval
= (keyval
- '0') + WXK_NUMPAD0
;
1630 else if (keycode
>= 65 && keycode
<= 81)
1635 keyval
= WXK_NUMPAD_ENTER
;
1639 keyval
= WXK_NUMPAD_EQUAL
;
1643 keyval
= WXK_NUMPAD_MULTIPLY
;
1647 keyval
= WXK_NUMPAD_DIVIDE
;
1651 keyval
= WXK_NUMPAD_SUBTRACT
;
1655 keyval
= WXK_NUMPAD_ADD
;
1659 keyval
= WXK_NUMPAD_DECIMAL
;
1667 event
.m_shiftDown
= modifiers
& shiftKey
;
1668 event
.m_controlDown
= modifiers
& controlKey
;
1669 event
.m_altDown
= modifiers
& optionKey
;
1670 event
.m_metaDown
= modifiers
& cmdKey
;
1671 event
.m_keyCode
= keyval
;
1673 event
.m_uniChar
= uniChar
;
1676 event
.m_rawCode
= keymessage
;
1677 event
.m_rawFlags
= modifiers
;
1680 event
.SetTimestamp(when
);
1681 event
.SetEventObject(focus
);
1686 void wxApp::MacHideApp()
1688 #if wxOSX_USE_CARBON
1689 wxMacCarbonEvent
event( kEventClassCommand
, kEventCommandProcess
);
1691 memset( &command
, 0 , sizeof(command
) );
1692 command
.commandID
= kHICommandHide
;
1693 event
.SetParameter
<HICommand
>(kEventParamDirectObject
, command
);
1694 SendEventToApplication( event
);