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"
21 #include "wx/window.h"
23 #include "wx/button.h"
25 #include "wx/gdicmn.h"
28 #include "wx/cursor.h"
30 #include "wx/palette.h"
32 #include "wx/dialog.h"
33 #include "wx/msgdlg.h"
34 #include "wx/module.h"
35 #include "wx/memory.h"
36 #include "wx/tooltip.h"
37 #include "wx/textctrl.h"
39 #include "wx/docview.h"
40 #include "wx/filename.h"
52 // #include "apprsrc.h"
54 #include "wx/mac/uma.h"
55 #include "wx/mac/macnotfy.h"
58 # include <CoreServices/CoreServices.h>
59 # if defined(WXMAKINGDLL_CORE)
60 # include <mach-o/dyld.h>
65 # include <ToolUtils.h>
66 # include <DiskInit.h>
70 extern wxList wxPendingDelete
;
73 extern size_t g_numberOfThreads
;
76 // statics for implementation
77 static bool s_inYield
= false;
78 static bool s_inReceiveEvent
= false ;
79 static EventTime sleepTime
= kEventDurationNoWait
;
82 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
83 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
84 EVT_IDLE(wxApp::OnIdle
)
85 EVT_END_SESSION(wxApp::OnEndSession
)
86 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
90 // platform specific static variables
91 const short kMacMinHeap
= (29 * 1024) ;
92 const short kwxMacMenuBarResource
= 1 ;
93 const short kwxMacAppleMenuId
= 1 ;
95 WXHRGN
wxApp::s_macCursorRgn
= NULL
;
96 wxWindow
* wxApp::s_captureWindow
= NULL
;
97 int wxApp::s_lastMouseDown
= 0 ;
98 long wxApp::sm_lastMessageTime
= 0;
99 long wxApp::s_lastModifiers
= 0 ;
101 bool wxApp::s_macSupportPCMenuShortcuts
= true ;
102 long wxApp::s_macAboutMenuItemId
= wxID_ABOUT
;
103 long wxApp::s_macPreferencesMenuItemId
= wxID_PREFERENCES
;
104 long wxApp::s_macExitMenuItemId
= wxID_EXIT
;
105 wxString
wxApp::s_macHelpMenuTitleName
= wxT("&Help") ;
107 bool wxApp::sm_isEmbedded
= false; // Normally we're not a plugin
109 //----------------------------------------------------------------------
110 // Core Apple Event Support
111 //----------------------------------------------------------------------
113 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
114 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
115 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
116 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
117 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
119 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
121 return wxTheApp
->MacHandleAEODoc( (AppleEvent
*) event
, reply
) ;
124 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
126 return wxTheApp
->MacHandleAEOApp( (AppleEvent
*) event
, reply
) ;
129 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
131 return wxTheApp
->MacHandleAEPDoc( (AppleEvent
*) event
, reply
) ;
134 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
136 return wxTheApp
->MacHandleAEQuit( (AppleEvent
*) event
, reply
) ;
139 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
141 return wxTheApp
->MacHandleAERApp( (AppleEvent
*) event
, reply
) ;
144 // AEODoc Calls MacOpenFile on each of the files passed
146 short wxApp::MacHandleAEODoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
150 DescType returnedType
;
156 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
160 err
= AECountItems(&docList
, &itemsInList
);
164 ProcessSerialNumber PSN
;
165 PSN
.highLongOfPSN
= 0 ;
166 PSN
.lowLongOfPSN
= kCurrentProcess
;
167 SetFrontProcess( &PSN
) ;
172 for (i
= 1; i
<= itemsInList
; i
++)
175 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
176 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
177 fName
= wxMacFSRefToPath( &theRef
) ;
185 // AEPDoc Calls MacPrintFile on each of the files passed
187 short wxApp::MacHandleAEPDoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
191 DescType returnedType
;
197 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
201 err
= AECountItems(&docList
, &itemsInList
);
205 ProcessSerialNumber PSN
;
206 PSN
.highLongOfPSN
= 0 ;
207 PSN
.lowLongOfPSN
= kCurrentProcess
;
208 SetFrontProcess( &PSN
) ;
213 for (i
= 1; i
<= itemsInList
; i
++)
216 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
217 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
218 fName
= wxMacFSRefToPath( &theRef
) ;
226 // AEOApp calls MacNewFile
228 short wxApp::MacHandleAEOApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
234 // AEQuit attempts to quit the application
236 short wxApp::MacHandleAEQuit(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
238 wxWindow
* win
= GetTopWindow() ;
241 wxCommandEvent
exitEvent(wxEVT_COMMAND_MENU_SELECTED
, s_macExitMenuItemId
);
242 if (!win
->ProcessEvent(exitEvent
))
253 // AEROApp calls MacReopenApp
255 short wxApp::MacHandleAERApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
262 //----------------------------------------------------------------------
263 // Support Routines linking the Mac...File Calls to the Document Manager
264 //----------------------------------------------------------------------
266 void wxApp::MacOpenFile(const wxString
& fileName
)
268 #if wxUSE_DOC_VIEW_ARCHITECTURE
269 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
271 dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
276 void wxApp::MacPrintFile(const wxString
& fileName
)
278 #if wxUSE_DOC_VIEW_ARCHITECTURE
280 #if wxUSE_PRINTING_ARCHITECTURE
281 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
284 wxDocument
*doc
= dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
287 wxView
* view
= doc
->GetFirstView() ;
290 wxPrintout
*printout
= view
->OnCreatePrintout();
294 printer
.Print(view
->GetFrame(), printout
, true);
301 doc
->DeleteAllViews();
302 dm
->RemoveDocument(doc
) ;
313 void wxApp::MacNewFile()
317 void wxApp::MacReopenApp()
320 // if there is no open window -> create a new one
321 // if all windows are hidden -> show the first
322 // if some windows are not hidden -> do nothing
324 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetFirst();
331 wxTopLevelWindow
* firstIconized
= NULL
;
334 wxTopLevelWindow
* win
= (wxTopLevelWindow
*) node
->GetData();
335 if ( !win
->IsIconized() )
337 firstIconized
= NULL
;
342 if ( firstIconized
== NULL
)
343 firstIconized
= win
;
346 node
= node
->GetNext();
350 firstIconized
->Iconize( false ) ;
354 //----------------------------------------------------------------------
355 // Macintosh CommandID support - converting between native and wx IDs
356 //----------------------------------------------------------------------
358 // if no native match they just return the passed-in id
366 IdPair gCommandIds
[] =
368 { kHICommandCut
, wxID_CUT
} ,
369 { kHICommandCopy
, wxID_COPY
} ,
370 { kHICommandPaste
, wxID_PASTE
} ,
371 { kHICommandSelectAll
, wxID_SELECTALL
} ,
372 { kHICommandClear
, wxID_CLEAR
} ,
373 { kHICommandUndo
, wxID_UNDO
} ,
374 { kHICommandRedo
, wxID_REDO
} ,
377 int wxMacCommandToId( UInt32 macCommandId
)
381 switch ( macCommandId
)
383 case kHICommandPreferences
:
384 wxid
= wxApp::s_macPreferencesMenuItemId
;
387 case kHICommandQuit
:
388 wxid
= wxApp::s_macExitMenuItemId
;
391 case kHICommandAbout
:
392 wxid
= wxApp::s_macAboutMenuItemId
;
397 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
399 if ( gCommandIds
[i
].macId
== macCommandId
)
401 wxid
= gCommandIds
[i
].wxId
;
410 wxid
= (int) macCommandId
;
415 UInt32
wxIdToMacCommand( int wxId
)
419 if ( wxId
== wxApp::s_macPreferencesMenuItemId
)
420 macId
= kHICommandPreferences
;
421 else if (wxId
== wxApp::s_macExitMenuItemId
)
422 macId
= kHICommandQuit
;
423 else if (wxId
== wxApp::s_macAboutMenuItemId
)
424 macId
= kHICommandAbout
;
427 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
429 if ( gCommandIds
[i
].wxId
== wxId
)
431 macId
= gCommandIds
[i
].macId
;
443 wxMenu
* wxFindMenuFromMacCommand( const HICommand
&command
, wxMenuItem
* &item
)
445 wxMenu
* itemMenu
= NULL
;
448 // for 'standard' commands which don't have a wx-menu
449 if ( command
.commandID
== kHICommandPreferences
|| command
.commandID
== kHICommandQuit
|| command
.commandID
== kHICommandAbout
)
451 id
= wxMacCommandToId( command
.commandID
) ;
453 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
455 item
= mbar
->FindItem( id
, &itemMenu
) ;
457 else if ( command
.commandID
!= 0 && command
.menu
.menuRef
!= 0 && command
.menu
.menuItemIndex
!= 0 )
459 id
= wxMacCommandToId( command
.commandID
) ;
460 // make sure it is one of our own menus, or of the 'synthetic' apple and help menus , otherwise don't touch
461 MenuItemIndex firstUserHelpMenuItem
;
462 static MenuHandle mh
= NULL
;
465 if ( UMAGetHelpMenu( &mh
, &firstUserHelpMenuItem
) != noErr
)
469 // is it part of the application or the Help menu, then look for the id directly
470 if ( ( GetMenuHandle( kwxMacAppleMenuId
) != NULL
&& command
.menu
.menuRef
== GetMenuHandle( kwxMacAppleMenuId
) ) ||
471 ( mh
!= NULL
&& command
.menu
.menuRef
== mh
) )
473 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
475 item
= mbar
->FindItem( id
, &itemMenu
) ;
481 GetMenuItemRefCon( command
.menu
.menuRef
, command
.menu
.menuItemIndex
, &refCon
) ;
482 itemMenu
= wxFindMenuFromMacMenu( command
.menu
.menuRef
) ;
483 if ( itemMenu
!= NULL
)
484 item
= (wxMenuItem
*) refCon
;
491 //----------------------------------------------------------------------
492 // Carbon Event Handler
493 //----------------------------------------------------------------------
495 static const EventTypeSpec eventList
[] =
497 { kEventClassCommand
, kEventProcessCommand
} ,
498 { kEventClassCommand
, kEventCommandUpdateStatus
} ,
500 { kEventClassMenu
, kEventMenuOpening
},
501 { kEventClassMenu
, kEventMenuClosed
},
502 { kEventClassMenu
, kEventMenuTargetItem
},
504 { kEventClassApplication
, kEventAppActivated
} ,
505 { kEventClassApplication
, kEventAppDeactivated
} ,
506 // handling the quit event is not recommended by apple
507 // rather using the quit apple event - which we do
509 { kEventClassAppleEvent
, kEventAppleEvent
} ,
511 { kEventClassMouse
, kEventMouseDown
} ,
512 { kEventClassMouse
, kEventMouseMoved
} ,
513 { kEventClassMouse
, kEventMouseUp
} ,
514 { kEventClassMouse
, kEventMouseDragged
} ,
518 static pascal OSStatus
519 wxMacAppMenuEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
521 wxMacCarbonEvent
cEvent( event
) ;
522 MenuRef menuRef
= cEvent
.GetParameter
<MenuRef
>(kEventParamDirectObject
) ;
523 wxMenu
* menu
= wxFindMenuFromMacMenu( menuRef
) ;
529 switch (GetEventKind(event
))
531 case kEventMenuOpening
:
532 type
= wxEVT_MENU_OPEN
;
535 case kEventMenuClosed
:
536 type
= wxEVT_MENU_CLOSE
;
539 case kEventMenuTargetItem
:
540 cmd
= cEvent
.GetParameter
<MenuCommand
>(kEventParamMenuCommand
,typeMenuCommand
) ;
542 type
= wxEVT_MENU_HIGHLIGHT
;
546 wxFAIL_MSG(wxT("Unexpected menu event kind"));
552 wxMenuEvent
wxevent(type
, cmd
, menu
);
553 wxevent
.SetEventObject(menu
);
555 wxEvtHandler
* handler
= menu
->GetEventHandler();
556 if (handler
&& handler
->ProcessEvent(wxevent
))
562 wxWindow
*win
= menu
->GetInvokingWindow();
564 win
->GetEventHandler()->ProcessEvent(wxevent
);
569 return eventNotHandledErr
;
572 static pascal OSStatus
wxMacAppCommandEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
574 OSStatus result
= eventNotHandledErr
;
578 wxMacCarbonEvent
cEvent( event
) ;
579 cEvent
.GetParameter
<HICommand
>(kEventParamDirectObject
,typeHICommand
,&command
) ;
581 wxMenuItem
* item
= NULL
;
582 wxMenu
* itemMenu
= wxFindMenuFromMacCommand( command
, item
) ;
583 int id
= wxMacCommandToId( command
.commandID
) ;
587 wxASSERT( itemMenu
!= NULL
) ;
589 switch ( cEvent
.GetKind() )
591 case kEventProcessCommand
:
593 if (item
->IsCheckable())
594 item
->Check( !item
->IsChecked() ) ;
596 if ( itemMenu
->SendEvent( id
, item
->IsCheckable() ? item
->IsChecked() : -1 ) )
601 case kEventCommandUpdateStatus
:
603 wxUpdateUIEvent
event(id
);
604 event
.SetEventObject( itemMenu
);
606 bool processed
= false;
608 // Try the menu's event handler
610 wxEvtHandler
*handler
= itemMenu
->GetEventHandler();
612 processed
= handler
->ProcessEvent(event
);
615 // Try the window the menu was popped up from
616 // (and up through the hierarchy)
619 const wxMenuBase
*menu
= itemMenu
;
622 wxWindow
*win
= menu
->GetInvokingWindow();
625 processed
= win
->GetEventHandler()->ProcessEvent(event
);
629 menu
= menu
->GetParent();
635 // if anything changed, update the changed attribute
636 if (event
.GetSetText())
637 itemMenu
->SetLabel(id
, event
.GetText());
638 if (event
.GetSetChecked())
639 itemMenu
->Check(id
, event
.GetChecked());
640 if (event
.GetSetEnabled())
641 itemMenu
->Enable(id
, event
.GetEnabled());
655 static pascal OSStatus
wxMacAppApplicationEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
657 OSStatus result
= eventNotHandledErr
;
658 switch ( GetEventKind( event
) )
660 case kEventAppActivated
:
662 wxTheApp
->SetActive( true , NULL
) ;
666 case kEventAppDeactivated
:
668 wxTheApp
->SetActive( false , NULL
) ;
679 pascal OSStatus
wxMacAppEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
681 EventRef formerEvent
= (EventRef
) wxTheApp
->MacGetCurrentEvent() ;
682 EventHandlerCallRef formerEventHandlerCallRef
= (EventHandlerCallRef
) wxTheApp
->MacGetCurrentEventHandlerCallRef() ;
683 wxTheApp
->MacSetCurrentEvent( event
, handler
) ;
685 OSStatus result
= eventNotHandledErr
;
686 switch ( GetEventClass( event
) )
688 case kEventClassCommand
:
689 result
= wxMacAppCommandEventHandler( handler
, event
, data
) ;
692 case kEventClassApplication
:
693 result
= wxMacAppApplicationEventHandler( handler
, event
, data
) ;
696 case kEventClassMenu
:
697 result
= wxMacAppMenuEventHandler( handler
, event
, data
) ;
700 case kEventClassMouse
:
702 wxMacCarbonEvent
cEvent( event
) ;
705 Point screenMouseLocation
= cEvent
.GetParameter
<Point
>(kEventParamMouseLocation
) ;
706 ::FindWindow(screenMouseLocation
, &window
);
707 // only send this event in case it had not already been sent to a tlw, as we get
708 // double events otherwise (in case event.skip) was called
709 if ( window
== NULL
)
710 result
= wxMacTopLevelMouseEventHandler( handler
, event
, NULL
) ;
714 case kEventClassAppleEvent
:
718 wxMacConvertEventToRecord( event
, &rec
) ;
719 result
= AEProcessAppleEvent( &rec
) ;
727 wxTheApp
->MacSetCurrentEvent( formerEvent
, formerEventHandlerCallRef
) ;
732 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler
)
734 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
735 // we know it's there ;-)
736 WXIMPORT
char std::__throws_bad_alloc
;
741 pascal static void wxMacAssertOutputHandler(OSType componentSignature
, UInt32 options
,
742 const char *assertionString
, const char *exceptionLabelString
,
743 const char *errorString
, const char *fileName
, long lineNumber
, void *value
, ConstStr255Param outputMsg
)
745 // flow into assert handling
746 wxString fileNameStr
;
747 wxString assertionStr
;
748 wxString exceptionStr
;
752 fileNameStr
= wxString(fileName
, wxConvLocal
);
753 assertionStr
= wxString(assertionString
, wxConvLocal
);
754 exceptionStr
= wxString((exceptionLabelString
!=0) ? exceptionLabelString
: "", wxConvLocal
) ;
755 errorStr
= wxString((errorString
!=0) ? errorString
: "", wxConvLocal
) ;
757 fileNameStr
= fileName
;
758 assertionStr
= assertionString
;
759 exceptionStr
= (exceptionLabelString
!=0) ? exceptionLabelString
: "" ;
760 errorStr
= (errorString
!=0) ? errorString
: "" ;
765 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
766 assertionStr
.c_str() ,
767 exceptionStr
.c_str() ,
769 fileNameStr
.c_str(), lineNumber
,
773 wxOnAssert(fileNameStr
, lineNumber
, assertionStr
,
774 wxString::Format( wxT("%s %s value (%p)") , exceptionStr
, errorStr
, value
) ) ;
783 // m_macEventPosted run loop source callback:
784 void macPostedEventCallback(void *unused
);
787 void macPostedEventCallback(void *unused
)
789 wxTheApp
->ProcessPendingEvents();
793 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
798 InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler
) );
801 UMAInitToolbox( 4, sm_isEmbedded
) ;
802 SetEventMask( everyEvent
) ;
803 UMAShowWatchCursor() ;
806 # if __option(profile)
807 ProfilerInit( collectDetailed
, bestTimeBase
, 40000 , 50 ) ;
812 // now avoid exceptions thrown for new (bad_alloc)
813 // FIXME CS for some changes outside wxMac does not compile anymore
815 std::__throws_bad_alloc
= 0 ;
820 s_macCursorRgn
= ::NewRgn() ;
822 // Mac OS X passes a process serial number command line argument when
823 // the application is launched from the Finder. This argument must be
824 // removed from the command line arguments before being handled by the
825 // application (otherwise applications would need to handle it)
828 static const wxChar
*ARG_PSN
= _T("-psn_");
829 if ( wxStrncmp(argv
[1], ARG_PSN
, wxStrlen(ARG_PSN
)) == 0 )
831 // remove this argument
833 memmove(argv
+ 1, argv
+ 2, argc
* sizeof(char *));
837 if ( !wxAppBase::Initialize(argc
, argv
) )
841 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
844 #if TARGET_API_MAC_OSX
845 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
846 wxString startupCwd
= wxGetCwd() ;
847 if ( startupCwd
== wxT("/") || startupCwd
.Right(15) == wxT("/Contents/MacOS") )
849 CFURLRef url
= CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
850 CFURLRef urlParent
= CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault
, url
) ;
852 CFStringRef path
= CFURLCopyFileSystemPath ( urlParent
, kCFURLPOSIXPathStyle
) ;
853 CFRelease( urlParent
) ;
854 wxString cwd
= wxMacCFStringHolder(path
).AsString(wxLocale::GetSystemEncoding());
855 wxSetWorkingDirectory( cwd
) ;
859 wxMacCreateNotifierTable() ;
862 /* connect posted events to common-mode run loop so that wxPostEvent events
863 are handled even while we're in the menu or on a scrollbar */
864 CFRunLoopSourceContext event_posted_context
= {0};
865 event_posted_context
.perform
= macPostedEventCallback
;
866 m_macEventPosted
= CFRunLoopSourceCreate(NULL
,0,&event_posted_context
);
867 CFRunLoopAddSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
870 UMAShowArrowCursor() ;
875 AEEventHandlerUPP sODocHandler
= NULL
;
876 AEEventHandlerUPP sOAppHandler
= NULL
;
877 AEEventHandlerUPP sPDocHandler
= NULL
;
878 AEEventHandlerUPP sRAppHandler
= NULL
;
879 AEEventHandlerUPP sQuitHandler
= NULL
;
881 bool wxApp::OnInitGui()
883 if ( !wxAppBase::OnInitGui() )
886 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
890 InstallApplicationEventHandler(
891 GetwxMacAppEventHandlerUPP(),
892 GetEventTypeCount(eventList
), eventList
, wxTheApp
, (EventHandlerRef
*)&(wxTheApp
->m_macEventHandler
));
897 sODocHandler
= NewAEEventHandlerUPP(AEHandleODoc
) ;
898 sOAppHandler
= NewAEEventHandlerUPP(AEHandleOApp
) ;
899 sPDocHandler
= NewAEEventHandlerUPP(AEHandlePDoc
) ;
900 sRAppHandler
= NewAEEventHandlerUPP(AEHandleRApp
) ;
901 sQuitHandler
= NewAEEventHandlerUPP(AEHandleQuit
) ;
903 AEInstallEventHandler( kCoreEventClass
, kAEOpenDocuments
,
904 sODocHandler
, 0 , FALSE
) ;
905 AEInstallEventHandler( kCoreEventClass
, kAEOpenApplication
,
906 sOAppHandler
, 0 , FALSE
) ;
907 AEInstallEventHandler( kCoreEventClass
, kAEPrintDocuments
,
908 sPDocHandler
, 0 , FALSE
) ;
909 AEInstallEventHandler( kCoreEventClass
, kAEReopenApplication
,
910 sRAppHandler
, 0 , FALSE
) ;
911 AEInstallEventHandler( kCoreEventClass
, kAEQuitApplication
,
912 sQuitHandler
, 0 , FALSE
) ;
918 void wxApp::CleanUp()
921 wxToolTip::RemoveToolTips() ;
925 if (m_macEventPosted
)
926 CFRelease(m_macEventPosted
);
927 m_macEventPosted
= NULL
;
930 // One last chance for pending objects to be cleaned up
931 wxTheApp
->DeletePendingObjects();
933 wxMacDestroyNotifierTable() ;
936 # if __option(profile)
937 ProfilerDump( (StringPtr
)"\papp.prof" ) ;
942 UMACleanupToolbox() ;
944 ::DisposeRgn((RgnHandle
)s_macCursorRgn
);
947 RemoveEventHandler( (EventHandlerRef
)(wxTheApp
->m_macEventHandler
) );
951 AERemoveEventHandler( kCoreEventClass
, kAEOpenDocuments
,
952 sODocHandler
, FALSE
) ;
953 AERemoveEventHandler( kCoreEventClass
, kAEOpenApplication
,
954 sOAppHandler
, FALSE
) ;
955 AERemoveEventHandler( kCoreEventClass
, kAEPrintDocuments
,
956 sPDocHandler
, FALSE
) ;
957 AERemoveEventHandler( kCoreEventClass
, kAEReopenApplication
,
958 sRAppHandler
, FALSE
) ;
959 AERemoveEventHandler( kCoreEventClass
, kAEQuitApplication
,
960 sQuitHandler
, FALSE
) ;
962 DisposeAEEventHandlerUPP( sODocHandler
) ;
963 DisposeAEEventHandlerUPP( sOAppHandler
) ;
964 DisposeAEEventHandlerUPP( sPDocHandler
) ;
965 DisposeAEEventHandlerUPP( sRAppHandler
) ;
966 DisposeAEEventHandlerUPP( sQuitHandler
) ;
969 wxAppBase::CleanUp();
972 //----------------------------------------------------------------------
973 // misc initialization stuff
974 //----------------------------------------------------------------------
976 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
978 // for shared libraries we have to manually get the correct resource
979 // ref num upon initializing and releasing when terminating, therefore
980 // the __wxinitialize and __wxterminate must be used
984 void __sinit(void); // (generated by linker)
985 pascal OSErr
__initialize(const CFragInitBlock
*theInitBlock
);
986 pascal void __terminate(void);
989 pascal OSErr
__wxinitialize(const CFragInitBlock
*theInitBlock
)
991 return __initialize( theInitBlock
) ;
994 pascal void __wxterminate(void)
999 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
1001 bool wxMacConvertEventToRecord( EventRef event
, EventRecord
*rec
)
1003 OSStatus err
= noErr
;
1004 bool converted
= ConvertEventRefToEventRecord( event
, rec
) ;
1008 switch ( GetEventClass( event
) )
1010 case kEventClassKeyboard
:
1013 switch ( GetEventKind(event
) )
1015 case kEventRawKeyDown
:
1016 rec
->what
= keyDown
;
1019 case kEventRawKeyRepeat
:
1020 rec
->what
= autoKey
;
1023 case kEventRawKeyUp
:
1027 case kEventRawKeyModifiersChanged
:
1028 rec
->what
= nullEvent
;
1039 unsigned char charCode
;
1041 GetMouse( &rec
->where
) ;
1043 err
= GetEventParameter(event
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1044 err
= GetEventParameter(event
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1045 err
= GetEventParameter(event
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1046 rec
->modifiers
= modifiers
;
1047 rec
->message
= (keyCode
<< 8 ) + charCode
;
1052 case kEventClassTextInput
:
1054 switch ( GetEventKind( event
) )
1056 case kEventTextInputUnicodeForKeyEvent
:
1059 err
= GetEventParameter(
1060 event
, kEventParamTextInputSendKeyboardEvent
, typeEventRef
, NULL
,
1061 sizeof(rawEvent
), NULL
, &rawEvent
) ;
1065 UInt32 keyCode
, modifiers
;
1066 unsigned char charCode
;
1068 GetMouse( &rec
->where
) ;
1069 rec
->what
= keyDown
;
1070 err
= GetEventParameter(rawEvent
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1071 err
= GetEventParameter(rawEvent
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1072 err
= GetEventParameter(rawEvent
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1073 rec
->modifiers
= modifiers
;
1074 rec
->message
= (keyCode
<< 8 ) + charCode
;
1095 m_printMode
= wxPRINT_WINDOWS
;
1097 m_macCurrentEvent
= NULL
;
1098 m_macCurrentEventHandlerCallRef
= NULL
;
1100 #ifdef __WXMAC_OSX__
1101 m_macEventPosted
= NULL
;
1105 void wxApp::OnIdle(wxIdleEvent
& event
)
1107 wxAppBase::OnIdle(event
);
1109 // If they are pending events, we must process them: pending events are
1110 // either events to the threads other than main or events posted with
1111 // wxPostEvent() functions
1112 wxMacProcessNotifierAndPendingEvents();
1114 if (!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1115 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1118 void wxApp::WakeUpIdle()
1120 #ifdef __WXMAC_OSX__
1121 if (m_macEventPosted
)
1123 CFRunLoopSourceSignal(m_macEventPosted
);
1130 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1133 GetTopWindow()->Close(true);
1136 // Default behaviour: close the application with prompts. The
1137 // user can veto the close, and therefore the end session.
1138 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1142 if (!GetTopWindow()->Close(!event
.CanVeto()))
1147 extern "C" void wxCYield() ;
1153 // Yield to other processes
1155 bool wxApp::Yield(bool onlyIfNeeded
)
1159 if ( !onlyIfNeeded
)
1161 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1169 // by definition yield should handle all non-processed events
1173 OSStatus status
= noErr
;
1175 while ( status
== noErr
)
1177 s_inReceiveEvent
= true ;
1178 status
= ReceiveNextEvent(0, NULL
,kEventDurationNoWait
,true,&theEvent
) ;
1179 s_inReceiveEvent
= false ;
1181 if ( status
== eventLoopTimedOutErr
)
1183 // make sure next time the event loop will trigger idle events
1184 sleepTime
= kEventDurationNoWait
;
1186 else if ( status
== eventLoopQuitErr
)
1188 // according to QA1061 this may also occur when a WakeUp Process
1193 MacHandleOneEvent( theEvent
) ;
1194 ReleaseEvent(theEvent
);
1198 wxMacProcessNotifierAndPendingEvents() ;
1204 void wxApp::MacDoOneEvent()
1208 s_inReceiveEvent
= true ;
1209 OSStatus status
= ReceiveNextEvent(0, NULL
, sleepTime
, true, &theEvent
) ;
1210 s_inReceiveEvent
= false ;
1214 case eventLoopTimedOutErr
:
1215 if ( wxTheApp
->ProcessIdle() )
1216 sleepTime
= kEventDurationNoWait
;
1218 sleepTime
= kEventDurationSecond
;
1221 case eventLoopQuitErr
:
1222 // according to QA1061 this may also occur
1223 // when a WakeUp Process is executed
1227 MacHandleOneEvent( theEvent
) ;
1228 ReleaseEvent( theEvent
);
1229 sleepTime
= kEventDurationNoWait
;
1234 DeletePendingObjects() ;
1235 wxMacProcessNotifierAndPendingEvents() ;
1239 void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr
)
1241 // Override to process unhandled events as you please
1244 void wxApp::MacHandleOneEvent( WXEVENTREF evr
)
1246 EventTargetRef theTarget
;
1247 theTarget
= GetEventDispatcherTarget();
1248 m_macCurrentEvent
= evr
;
1250 OSStatus status
= SendEventToEventTarget((EventRef
) evr
, theTarget
);
1251 if (status
== eventNotHandledErr
)
1252 MacHandleUnhandledEvent(evr
);
1254 wxMacProcessNotifierAndPendingEvents() ;
1257 wxMutexGuiLeaveOrEnter();
1258 #endif // wxUSE_THREADS
1261 long wxMacTranslateKey(unsigned char key
, unsigned char code
)
1266 case kHomeCharCode
:
1270 case kEnterCharCode
:
1271 retval
= WXK_RETURN
;
1277 case kHelpCharCode
:
1281 case kBackspaceCharCode
:
1289 case kPageUpCharCode
:
1290 retval
= WXK_PAGEUP
;
1293 case kPageDownCharCode
:
1294 retval
= WXK_PAGEDOWN
;
1297 case kReturnCharCode
:
1298 retval
= WXK_RETURN
;
1301 case kFunctionKeyCharCode
:
1371 case kEscapeCharCode
:
1372 retval
= WXK_ESCAPE
;
1375 case kLeftArrowCharCode
:
1379 case kRightArrowCharCode
:
1380 retval
= WXK_RIGHT
;
1383 case kUpArrowCharCode
:
1387 case kDownArrowCharCode
:
1391 case kDeleteCharCode
:
1392 retval
= WXK_DELETE
;
1402 int wxMacKeyCodeToModifier(wxKeyCode key
)
1428 bool wxGetKeyState(wxKeyCode key
) //virtual key code if < 10.2.x, else see below
1430 wxASSERT_MSG(key
!= WXK_LBUTTON
&& key
!= WXK_RBUTTON
&& key
!=
1431 WXK_MBUTTON
, wxT("can't use wxGetKeyState() for mouse buttons"));
1433 //if OS X > 10.2 (i.e. 10.2.x)
1434 //a known apple bug prevents the system from determining led
1435 //states with GetKeys... can only determine caps lock led
1436 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key
));
1438 // KeyMapByteArray keymap;
1439 // GetKeys((BigEndianLong*)keymap);
1440 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1445 wxMouseState
wxGetMouseState()
1449 wxPoint pt
= wxGetMousePosition();
1453 #if TARGET_API_MAC_OSX
1454 UInt32 buttons
= GetCurrentButtonState();
1455 ms
.SetLeftDown( (buttons
& 0x01) != 0 );
1456 ms
.SetMiddleDown( (buttons
& 0x04) != 0 );
1457 ms
.SetRightDown( (buttons
& 0x02) != 0 );
1459 ms
.SetLeftDown( Button() );
1460 ms
.SetMiddleDown( 0 );
1461 ms
.SetRightDown( 0 );
1464 UInt32 modifiers
= GetCurrentKeyModifiers();
1465 ms
.SetControlDown(modifiers
& controlKey
);
1466 ms
.SetShiftDown(modifiers
& shiftKey
);
1467 ms
.SetAltDown(modifiers
& optionKey
);
1468 ms
.SetMetaDown(modifiers
& cmdKey
);
1473 // TODO : once the new key/char handling is tested, move all the code to wxWindow
1475 bool wxApp::MacSendKeyDownEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1481 wxKeyEvent
event(wxEVT_KEY_DOWN
) ;
1482 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1484 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1485 if ( handled
&& event
.GetSkipped() )
1491 wxWindow
*ancestor
= focus
;
1494 int command
= ancestor
->GetAcceleratorTable()->GetCommand( event
);
1497 wxCommandEvent
command_event( wxEVT_COMMAND_MENU_SELECTED
, command
);
1498 handled
= ancestor
->GetEventHandler()->ProcessEvent( command_event
);
1502 if (ancestor
->IsTopLevel())
1505 ancestor
= ancestor
->GetParent();
1508 #endif // wxUSE_ACCEL
1513 bool wxApp::MacSendKeyUpEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1519 wxKeyEvent
event( wxEVT_KEY_UP
) ;
1520 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1521 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1526 bool wxApp::MacSendCharEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1531 wxKeyEvent
event(wxEVT_CHAR
) ;
1532 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1533 long keyval
= event
.m_keyCode
;
1535 bool handled
= false ;
1537 wxTopLevelWindowMac
*tlw
= focus
->MacGetTopLevelWindow() ;
1541 event
.SetEventType( wxEVT_CHAR_HOOK
);
1542 handled
= tlw
->GetEventHandler()->ProcessEvent( event
);
1543 if ( handled
&& event
.GetSkipped() )
1549 event
.SetEventType( wxEVT_CHAR
);
1550 event
.Skip( false ) ;
1551 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1554 if ( !handled
&& (keyval
== WXK_TAB
) )
1556 wxWindow
* iter
= focus
->GetParent() ;
1557 while ( iter
&& !handled
)
1559 if ( iter
->HasFlag( wxTAB_TRAVERSAL
) )
1561 wxNavigationKeyEvent new_event
;
1562 new_event
.SetEventObject( focus
);
1563 new_event
.SetDirection( !event
.ShiftDown() );
1564 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1565 new_event
.SetWindowChange( event
.ControlDown() );
1566 new_event
.SetCurrentFocus( focus
);
1567 handled
= focus
->GetParent()->GetEventHandler()->ProcessEvent( new_event
);
1568 if ( handled
&& new_event
.GetSkipped() )
1572 iter
= iter
->GetParent() ;
1576 // backdoor handler for default return and command escape
1577 if ( !handled
&& (!focus
->IsKindOf(CLASSINFO(wxControl
) ) || !focus
->MacCanFocus() ) )
1579 // if window is not having a focus still testing for default enter or cancel
1580 // TODO: add the UMA version for ActiveNonFloatingWindow
1581 wxWindow
* focus
= wxFindWinFromMacWindow( FrontWindow() ) ;
1584 if ( keyval
== WXK_RETURN
)
1586 wxButton
*def
= wxDynamicCast(focus
->GetDefaultItem(), wxButton
);
1587 if ( def
&& def
->IsEnabled() )
1589 wxCommandEvent
event(wxEVT_COMMAND_BUTTON_CLICKED
, def
->GetId() );
1590 event
.SetEventObject(def
);
1591 def
->Command(event
);
1596 else if (keyval
== WXK_ESCAPE
|| (keyval
== '.' && modifiers
& cmdKey
) )
1598 // generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs)
1599 wxCommandEvent
new_event(wxEVT_COMMAND_BUTTON_CLICKED
,wxID_CANCEL
);
1600 new_event
.SetEventObject( focus
);
1601 handled
= focus
->GetEventHandler()->ProcessEvent( new_event
);
1608 // This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
1609 void wxApp::MacCreateKeyEvent( wxKeyEvent
& event
, wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1611 short keycode
, keychar
;
1613 keychar
= short(keymessage
& charCodeMask
);
1614 keycode
= short(keymessage
& keyCodeMask
) >> 8 ;
1615 if ( !(event
.GetEventType() == wxEVT_CHAR
) && (modifiers
& (controlKey
| shiftKey
| optionKey
) ) )
1617 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1618 // and look at the character after
1620 UInt32 keyInfo
= KeyTranslate((Ptr
)GetScriptManagerVariable(smKCHRCache
), ( modifiers
& (~(controlKey
| shiftKey
| optionKey
))) | keycode
, &state
);
1621 keychar
= short(keyInfo
& charCodeMask
);
1624 long keyval
= wxMacTranslateKey(keychar
, keycode
) ;
1625 if ( keyval
== keychar
&& ( event
.GetEventType() == wxEVT_KEY_UP
|| event
.GetEventType() == wxEVT_KEY_DOWN
) )
1626 keyval
= wxToupper( keyval
) ;
1628 // Check for NUMPAD keys
1629 if (keyval
>= '0' && keyval
<= '9' && keycode
>= 82 && keycode
<= 92)
1631 keyval
= (keyval
- '0') + WXK_NUMPAD0
;
1633 else if (keycode
>= 67 && keycode
<= 81)
1638 keyval
= WXK_NUMPAD_ENTER
;
1642 keyval
= WXK_NUMPAD_EQUAL
;
1646 keyval
= WXK_NUMPAD_MULTIPLY
;
1650 keyval
= WXK_NUMPAD_DIVIDE
;
1654 keyval
= WXK_NUMPAD_SUBTRACT
;
1658 keyval
= WXK_NUMPAD_ADD
;
1662 keyval
= WXK_NUMPAD_DECIMAL
;
1670 event
.m_shiftDown
= modifiers
& shiftKey
;
1671 event
.m_controlDown
= modifiers
& controlKey
;
1672 event
.m_altDown
= modifiers
& optionKey
;
1673 event
.m_metaDown
= modifiers
& cmdKey
;
1674 event
.m_keyCode
= keyval
;
1676 event
.m_uniChar
= uniChar
;
1679 event
.m_rawCode
= keymessage
;
1680 event
.m_rawFlags
= modifiers
;
1683 event
.SetTimestamp(when
);
1684 event
.SetEventObject(focus
);