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"
37 #include "wx/module.h"
38 #include "wx/tooltip.h"
39 #include "wx/docview.h"
40 #include "wx/filename.h"
53 // #include "apprsrc.h"
55 #include "wx/mac/uma.h"
56 #include "wx/mac/macnotfy.h"
59 # include <CoreServices/CoreServices.h>
60 # if defined(WXMAKINGDLL_CORE)
61 # include <mach-o/dyld.h>
66 # include <ToolUtils.h>
67 # include <DiskInit.h>
71 // Keep linker from discarding wxStockGDIMac
72 wxFORCE_LINK_MODULE(gdiobj
)
75 extern size_t g_numberOfThreads
;
78 // statics for implementation
79 static bool s_inYield
= false;
80 static bool s_inReceiveEvent
= false ;
81 static EventTime sleepTime
= kEventDurationNoWait
;
84 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
85 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
86 EVT_IDLE(wxApp::OnIdle
)
87 EVT_END_SESSION(wxApp::OnEndSession
)
88 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
92 // platform specific static variables
93 const short kMacMinHeap
= (29 * 1024) ;
94 const short kwxMacMenuBarResource
= 1 ;
95 const short kwxMacAppleMenuId
= 1 ;
97 WXHRGN
wxApp::s_macCursorRgn
= NULL
;
98 wxWindow
* wxApp::s_captureWindow
= NULL
;
99 int wxApp::s_lastMouseDown
= 0 ;
100 long wxApp::sm_lastMessageTime
= 0;
101 long wxApp::s_lastModifiers
= 0 ;
103 bool wxApp::s_macSupportPCMenuShortcuts
= true ;
104 long wxApp::s_macAboutMenuItemId
= wxID_ABOUT
;
105 long wxApp::s_macPreferencesMenuItemId
= wxID_PREFERENCES
;
106 long wxApp::s_macExitMenuItemId
= wxID_EXIT
;
107 wxString
wxApp::s_macHelpMenuTitleName
= wxT("&Help") ;
109 bool wxApp::sm_isEmbedded
= false; // Normally we're not a plugin
111 //----------------------------------------------------------------------
112 // Core Apple Event Support
113 //----------------------------------------------------------------------
115 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
116 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
117 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
118 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
119 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, long refcon
) ;
121 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
123 return wxTheApp
->MacHandleAEODoc( (AppleEvent
*) event
, reply
) ;
126 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
128 return wxTheApp
->MacHandleAEOApp( (AppleEvent
*) event
, reply
) ;
131 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
133 return wxTheApp
->MacHandleAEPDoc( (AppleEvent
*) event
, reply
) ;
136 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
138 return wxTheApp
->MacHandleAEQuit( (AppleEvent
*) event
, reply
) ;
141 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, long WXUNUSED(refcon
) )
143 return wxTheApp
->MacHandleAERApp( (AppleEvent
*) event
, reply
) ;
146 // AEODoc Calls MacOpenFile on each of the files passed
148 short wxApp::MacHandleAEODoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
152 DescType returnedType
;
158 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
162 err
= AECountItems(&docList
, &itemsInList
);
166 ProcessSerialNumber PSN
;
167 PSN
.highLongOfPSN
= 0 ;
168 PSN
.lowLongOfPSN
= kCurrentProcess
;
169 SetFrontProcess( &PSN
) ;
174 for (i
= 1; i
<= itemsInList
; i
++)
177 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
178 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
179 fName
= wxMacFSRefToPath( &theRef
) ;
187 // AEPDoc Calls MacPrintFile on each of the files passed
189 short wxApp::MacHandleAEPDoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
193 DescType returnedType
;
199 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
203 err
= AECountItems(&docList
, &itemsInList
);
207 ProcessSerialNumber PSN
;
208 PSN
.highLongOfPSN
= 0 ;
209 PSN
.lowLongOfPSN
= kCurrentProcess
;
210 SetFrontProcess( &PSN
) ;
215 for (i
= 1; i
<= itemsInList
; i
++)
218 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
219 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
220 fName
= wxMacFSRefToPath( &theRef
) ;
228 // AEOApp calls MacNewFile
230 short wxApp::MacHandleAEOApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
236 // AEQuit attempts to quit the application
238 short wxApp::MacHandleAEQuit(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
240 wxWindow
* win
= GetTopWindow() ;
243 wxCommandEvent
exitEvent(wxEVT_COMMAND_MENU_SELECTED
, s_macExitMenuItemId
);
244 if (!win
->ProcessEvent(exitEvent
))
255 // AEROApp calls MacReopenApp
257 short wxApp::MacHandleAERApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
264 //----------------------------------------------------------------------
265 // Support Routines linking the Mac...File Calls to the Document Manager
266 //----------------------------------------------------------------------
268 void wxApp::MacOpenFile(const wxString
& fileName
)
270 #if wxUSE_DOC_VIEW_ARCHITECTURE
271 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
273 dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
278 void wxApp::MacPrintFile(const wxString
& fileName
)
280 #if wxUSE_DOC_VIEW_ARCHITECTURE
282 #if wxUSE_PRINTING_ARCHITECTURE
283 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
286 wxDocument
*doc
= dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
289 wxView
* view
= doc
->GetFirstView() ;
292 wxPrintout
*printout
= view
->OnCreatePrintout();
296 printer
.Print(view
->GetFrame(), printout
, true);
303 doc
->DeleteAllViews();
304 dm
->RemoveDocument(doc
) ;
315 void wxApp::MacNewFile()
319 void wxApp::MacReopenApp()
322 // if there is no open window -> create a new one
323 // if all windows are hidden -> show the first
324 // if some windows are not hidden -> do nothing
326 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetFirst();
333 wxTopLevelWindow
* firstIconized
= NULL
;
336 wxTopLevelWindow
* win
= (wxTopLevelWindow
*) node
->GetData();
337 if ( !win
->IsIconized() )
339 firstIconized
= NULL
;
344 if ( firstIconized
== NULL
)
345 firstIconized
= win
;
348 node
= node
->GetNext();
352 firstIconized
->Iconize( false ) ;
356 //----------------------------------------------------------------------
357 // Macintosh CommandID support - converting between native and wx IDs
358 //----------------------------------------------------------------------
360 // if no native match they just return the passed-in id
368 IdPair gCommandIds
[] =
370 { kHICommandCut
, wxID_CUT
} ,
371 { kHICommandCopy
, wxID_COPY
} ,
372 { kHICommandPaste
, wxID_PASTE
} ,
373 { kHICommandSelectAll
, wxID_SELECTALL
} ,
374 { kHICommandClear
, wxID_CLEAR
} ,
375 { kHICommandUndo
, wxID_UNDO
} ,
376 { kHICommandRedo
, wxID_REDO
} ,
379 int wxMacCommandToId( UInt32 macCommandId
)
383 switch ( macCommandId
)
385 case kHICommandPreferences
:
386 wxid
= wxApp::s_macPreferencesMenuItemId
;
389 case kHICommandQuit
:
390 wxid
= wxApp::s_macExitMenuItemId
;
393 case kHICommandAbout
:
394 wxid
= wxApp::s_macAboutMenuItemId
;
399 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
401 if ( gCommandIds
[i
].macId
== macCommandId
)
403 wxid
= gCommandIds
[i
].wxId
;
412 wxid
= (int) macCommandId
;
417 UInt32
wxIdToMacCommand( int wxId
)
421 if ( wxId
== wxApp::s_macPreferencesMenuItemId
)
422 macId
= kHICommandPreferences
;
423 else if (wxId
== wxApp::s_macExitMenuItemId
)
424 macId
= kHICommandQuit
;
425 else if (wxId
== wxApp::s_macAboutMenuItemId
)
426 macId
= kHICommandAbout
;
429 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
431 if ( gCommandIds
[i
].wxId
== wxId
)
433 macId
= gCommandIds
[i
].macId
;
445 wxMenu
* wxFindMenuFromMacCommand( const HICommand
&command
, wxMenuItem
* &item
)
447 wxMenu
* itemMenu
= NULL
;
450 // for 'standard' commands which don't have a wx-menu
451 if ( command
.commandID
== kHICommandPreferences
|| command
.commandID
== kHICommandQuit
|| command
.commandID
== kHICommandAbout
)
453 id
= wxMacCommandToId( command
.commandID
) ;
455 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
457 item
= mbar
->FindItem( id
, &itemMenu
) ;
459 else if ( command
.commandID
!= 0 && command
.menu
.menuRef
!= 0 && command
.menu
.menuItemIndex
!= 0 )
461 id
= wxMacCommandToId( command
.commandID
) ;
462 // make sure it is one of our own menus, or of the 'synthetic' apple and help menus , otherwise don't touch
463 MenuItemIndex firstUserHelpMenuItem
;
464 static MenuHandle mh
= NULL
;
467 if ( UMAGetHelpMenu( &mh
, &firstUserHelpMenuItem
) != noErr
)
471 // is it part of the application or the Help menu, then look for the id directly
472 if ( ( GetMenuHandle( kwxMacAppleMenuId
) != NULL
&& command
.menu
.menuRef
== GetMenuHandle( kwxMacAppleMenuId
) ) ||
473 ( mh
!= NULL
&& command
.menu
.menuRef
== mh
) )
475 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
477 item
= mbar
->FindItem( id
, &itemMenu
) ;
483 GetMenuItemRefCon( command
.menu
.menuRef
, command
.menu
.menuItemIndex
, &refCon
) ;
484 itemMenu
= wxFindMenuFromMacMenu( command
.menu
.menuRef
) ;
485 if ( itemMenu
!= NULL
)
486 item
= (wxMenuItem
*) refCon
;
493 //----------------------------------------------------------------------
494 // Carbon Event Handler
495 //----------------------------------------------------------------------
497 static const EventTypeSpec eventList
[] =
499 { kEventClassCommand
, kEventProcessCommand
} ,
500 { kEventClassCommand
, kEventCommandUpdateStatus
} ,
502 { kEventClassMenu
, kEventMenuOpening
},
503 { kEventClassMenu
, kEventMenuClosed
},
504 { kEventClassMenu
, kEventMenuTargetItem
},
506 { kEventClassApplication
, kEventAppActivated
} ,
507 { kEventClassApplication
, kEventAppDeactivated
} ,
508 // handling the quit event is not recommended by apple
509 // rather using the quit apple event - which we do
511 { kEventClassAppleEvent
, kEventAppleEvent
} ,
513 { kEventClassMouse
, kEventMouseDown
} ,
514 { kEventClassMouse
, kEventMouseMoved
} ,
515 { kEventClassMouse
, kEventMouseUp
} ,
516 { kEventClassMouse
, kEventMouseDragged
} ,
520 static pascal OSStatus
521 wxMacAppMenuEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
523 wxMacCarbonEvent
cEvent( event
) ;
524 MenuRef menuRef
= cEvent
.GetParameter
<MenuRef
>(kEventParamDirectObject
) ;
525 wxMenu
* menu
= wxFindMenuFromMacMenu( menuRef
) ;
531 switch (GetEventKind(event
))
533 case kEventMenuOpening
:
534 type
= wxEVT_MENU_OPEN
;
537 case kEventMenuClosed
:
538 type
= wxEVT_MENU_CLOSE
;
541 case kEventMenuTargetItem
:
542 cmd
= cEvent
.GetParameter
<MenuCommand
>(kEventParamMenuCommand
,typeMenuCommand
) ;
544 type
= wxEVT_MENU_HIGHLIGHT
;
548 wxFAIL_MSG(wxT("Unexpected menu event kind"));
554 wxMenuEvent
wxevent(type
, cmd
, menu
);
555 wxevent
.SetEventObject(menu
);
557 wxEvtHandler
* handler
= menu
->GetEventHandler();
558 if (handler
&& handler
->ProcessEvent(wxevent
))
564 wxWindow
*win
= menu
->GetInvokingWindow();
566 win
->GetEventHandler()->ProcessEvent(wxevent
);
571 return eventNotHandledErr
;
574 static pascal OSStatus
wxMacAppCommandEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
576 OSStatus result
= eventNotHandledErr
;
580 wxMacCarbonEvent
cEvent( event
) ;
581 cEvent
.GetParameter
<HICommand
>(kEventParamDirectObject
,typeHICommand
,&command
) ;
583 wxMenuItem
* item
= NULL
;
584 wxMenu
* itemMenu
= wxFindMenuFromMacCommand( command
, item
) ;
585 int id
= wxMacCommandToId( command
.commandID
) ;
589 wxASSERT( itemMenu
!= NULL
) ;
591 switch ( cEvent
.GetKind() )
593 case kEventProcessCommand
:
595 if (item
->IsCheckable())
596 item
->Check( !item
->IsChecked() ) ;
598 if ( itemMenu
->SendEvent( id
, item
->IsCheckable() ? item
->IsChecked() : -1 ) )
603 case kEventCommandUpdateStatus
:
605 wxUpdateUIEvent
event(id
);
606 event
.SetEventObject( itemMenu
);
608 bool processed
= false;
610 // Try the menu's event handler
612 wxEvtHandler
*handler
= itemMenu
->GetEventHandler();
614 processed
= handler
->ProcessEvent(event
);
617 // Try the window the menu was popped up from
618 // (and up through the hierarchy)
621 const wxMenuBase
*menu
= itemMenu
;
624 wxWindow
*win
= menu
->GetInvokingWindow();
627 processed
= win
->GetEventHandler()->ProcessEvent(event
);
631 menu
= menu
->GetParent();
637 // if anything changed, update the changed attribute
638 if (event
.GetSetText())
639 itemMenu
->SetLabel(id
, event
.GetText());
640 if (event
.GetSetChecked())
641 itemMenu
->Check(id
, event
.GetChecked());
642 if (event
.GetSetEnabled())
643 itemMenu
->Enable(id
, event
.GetEnabled());
657 static pascal OSStatus
wxMacAppApplicationEventHandler( EventHandlerCallRef handler
, EventRef event
, void *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
) )
690 case kEventClassCommand
:
691 result
= wxMacAppCommandEventHandler( handler
, event
, data
) ;
694 case kEventClassApplication
:
695 result
= wxMacAppApplicationEventHandler( handler
, event
, data
) ;
698 case kEventClassMenu
:
699 result
= wxMacAppMenuEventHandler( handler
, event
, data
) ;
702 case kEventClassMouse
:
704 wxMacCarbonEvent
cEvent( event
) ;
707 Point screenMouseLocation
= cEvent
.GetParameter
<Point
>(kEventParamMouseLocation
) ;
708 ::FindWindow(screenMouseLocation
, &window
);
709 // only send this event in case it had not already been sent to a tlw, as we get
710 // double events otherwise (in case event.skip) was called
711 if ( window
== NULL
)
712 result
= wxMacTopLevelMouseEventHandler( handler
, event
, NULL
) ;
716 case kEventClassAppleEvent
:
720 wxMacConvertEventToRecord( event
, &rec
) ;
721 result
= AEProcessAppleEvent( &rec
) ;
729 wxTheApp
->MacSetCurrentEvent( formerEvent
, formerEventHandlerCallRef
) ;
734 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler
)
738 pascal static void wxMacAssertOutputHandler(OSType componentSignature
, UInt32 options
,
739 const char *assertionString
, const char *exceptionLabelString
,
740 const char *errorString
, const char *fileName
, long lineNumber
, void *value
, ConstStr255Param outputMsg
)
742 // flow into assert handling
743 wxString fileNameStr
;
744 wxString assertionStr
;
745 wxString exceptionStr
;
749 fileNameStr
= wxString(fileName
, wxConvLocal
);
750 assertionStr
= wxString(assertionString
, wxConvLocal
);
751 exceptionStr
= wxString((exceptionLabelString
!=0) ? exceptionLabelString
: "", wxConvLocal
) ;
752 errorStr
= wxString((errorString
!=0) ? errorString
: "", wxConvLocal
) ;
754 fileNameStr
= fileName
;
755 assertionStr
= assertionString
;
756 exceptionStr
= (exceptionLabelString
!=0) ? exceptionLabelString
: "" ;
757 errorStr
= (errorString
!=0) ? errorString
: "" ;
762 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
763 assertionStr
.c_str() ,
764 exceptionStr
.c_str() ,
766 fileNameStr
.c_str(), lineNumber
,
770 wxOnAssert(fileNameStr
, lineNumber
, assertionStr
,
771 wxString::Format( wxT("%s %s value (%p)") , exceptionStr
, errorStr
, value
) ) ;
780 // m_macEventPosted run loop source callback:
781 void macPostedEventCallback(void *unused
);
784 void macPostedEventCallback(void *unused
)
786 wxTheApp
->ProcessPendingEvents();
790 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
795 InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler
) );
798 UMAInitToolbox( 4, sm_isEmbedded
) ;
799 SetEventMask( everyEvent
) ;
800 UMAShowWatchCursor() ;
803 # if __option(profile)
804 ProfilerInit( collectDetailed
, bestTimeBase
, 40000 , 50 ) ;
809 // now avoid exceptions thrown for new (bad_alloc)
810 // FIXME CS for some changes outside wxMac does not compile anymore
812 std::__throws_bad_alloc
= 0 ;
817 s_macCursorRgn
= ::NewRgn() ;
819 // Mac OS X passes a process serial number command line argument when
820 // the application is launched from the Finder. This argument must be
821 // removed from the command line arguments before being handled by the
822 // application (otherwise applications would need to handle it)
825 static const wxChar
*ARG_PSN
= _T("-psn_");
826 if ( wxStrncmp(argv
[1], ARG_PSN
, wxStrlen(ARG_PSN
)) == 0 )
828 // remove this argument
830 memmove(argv
+ 1, argv
+ 2, argc
* sizeof(char *));
834 if ( !wxAppBase::Initialize(argc
, argv
) )
838 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
841 #if TARGET_API_MAC_OSX
842 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
843 wxString startupCwd
= wxGetCwd() ;
844 if ( startupCwd
== wxT("/") || startupCwd
.Right(15) == wxT("/Contents/MacOS") )
846 CFURLRef url
= CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
847 CFURLRef urlParent
= CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault
, url
) ;
849 CFStringRef path
= CFURLCopyFileSystemPath ( urlParent
, kCFURLPOSIXPathStyle
) ;
850 CFRelease( urlParent
) ;
851 wxString cwd
= wxMacCFStringHolder(path
).AsString(wxLocale::GetSystemEncoding());
852 wxSetWorkingDirectory( cwd
) ;
856 wxMacCreateNotifierTable() ;
859 /* connect posted events to common-mode run loop so that wxPostEvent events
860 are handled even while we're in the menu or on a scrollbar */
861 CFRunLoopSourceContext event_posted_context
= {0};
862 event_posted_context
.perform
= macPostedEventCallback
;
863 m_macEventPosted
= CFRunLoopSourceCreate(NULL
,0,&event_posted_context
);
864 CFRunLoopAddSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
867 UMAShowArrowCursor() ;
872 AEEventHandlerUPP sODocHandler
= NULL
;
873 AEEventHandlerUPP sOAppHandler
= NULL
;
874 AEEventHandlerUPP sPDocHandler
= NULL
;
875 AEEventHandlerUPP sRAppHandler
= NULL
;
876 AEEventHandlerUPP sQuitHandler
= NULL
;
878 bool wxApp::OnInitGui()
880 if ( !wxAppBase::OnInitGui() )
883 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
887 InstallApplicationEventHandler(
888 GetwxMacAppEventHandlerUPP(),
889 GetEventTypeCount(eventList
), eventList
, wxTheApp
, (EventHandlerRef
*)&(wxTheApp
->m_macEventHandler
));
894 sODocHandler
= NewAEEventHandlerUPP(AEHandleODoc
) ;
895 sOAppHandler
= NewAEEventHandlerUPP(AEHandleOApp
) ;
896 sPDocHandler
= NewAEEventHandlerUPP(AEHandlePDoc
) ;
897 sRAppHandler
= NewAEEventHandlerUPP(AEHandleRApp
) ;
898 sQuitHandler
= NewAEEventHandlerUPP(AEHandleQuit
) ;
900 AEInstallEventHandler( kCoreEventClass
, kAEOpenDocuments
,
901 sODocHandler
, 0 , FALSE
) ;
902 AEInstallEventHandler( kCoreEventClass
, kAEOpenApplication
,
903 sOAppHandler
, 0 , FALSE
) ;
904 AEInstallEventHandler( kCoreEventClass
, kAEPrintDocuments
,
905 sPDocHandler
, 0 , FALSE
) ;
906 AEInstallEventHandler( kCoreEventClass
, kAEReopenApplication
,
907 sRAppHandler
, 0 , FALSE
) ;
908 AEInstallEventHandler( kCoreEventClass
, kAEQuitApplication
,
909 sQuitHandler
, 0 , FALSE
) ;
915 void wxApp::CleanUp()
918 wxToolTip::RemoveToolTips() ;
922 if (m_macEventPosted
)
923 CFRelease(m_macEventPosted
);
924 m_macEventPosted
= NULL
;
927 // One last chance for pending objects to be cleaned up
928 wxTheApp
->DeletePendingObjects();
930 wxMacDestroyNotifierTable() ;
933 # if __option(profile)
934 ProfilerDump( (StringPtr
)"\papp.prof" ) ;
939 UMACleanupToolbox() ;
941 ::DisposeRgn((RgnHandle
)s_macCursorRgn
);
944 RemoveEventHandler( (EventHandlerRef
)(wxTheApp
->m_macEventHandler
) );
948 AERemoveEventHandler( kCoreEventClass
, kAEOpenDocuments
,
949 sODocHandler
, FALSE
) ;
950 AERemoveEventHandler( kCoreEventClass
, kAEOpenApplication
,
951 sOAppHandler
, FALSE
) ;
952 AERemoveEventHandler( kCoreEventClass
, kAEPrintDocuments
,
953 sPDocHandler
, FALSE
) ;
954 AERemoveEventHandler( kCoreEventClass
, kAEReopenApplication
,
955 sRAppHandler
, FALSE
) ;
956 AERemoveEventHandler( kCoreEventClass
, kAEQuitApplication
,
957 sQuitHandler
, FALSE
) ;
959 DisposeAEEventHandlerUPP( sODocHandler
) ;
960 DisposeAEEventHandlerUPP( sOAppHandler
) ;
961 DisposeAEEventHandlerUPP( sPDocHandler
) ;
962 DisposeAEEventHandlerUPP( sRAppHandler
) ;
963 DisposeAEEventHandlerUPP( sQuitHandler
) ;
966 wxAppBase::CleanUp();
969 //----------------------------------------------------------------------
970 // misc initialization stuff
971 //----------------------------------------------------------------------
973 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
975 // for shared libraries we have to manually get the correct resource
976 // ref num upon initializing and releasing when terminating, therefore
977 // the __wxinitialize and __wxterminate must be used
981 void __sinit(void); // (generated by linker)
982 pascal OSErr
__initialize(const CFragInitBlock
*theInitBlock
);
983 pascal void __terminate(void);
986 pascal OSErr
__wxinitialize(const CFragInitBlock
*theInitBlock
)
988 return __initialize( theInitBlock
) ;
991 pascal void __wxterminate(void)
996 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
998 bool wxMacConvertEventToRecord( EventRef event
, EventRecord
*rec
)
1000 OSStatus err
= noErr
;
1001 bool converted
= ConvertEventRefToEventRecord( event
, rec
) ;
1005 switch ( GetEventClass( event
) )
1007 case kEventClassKeyboard
:
1010 switch ( GetEventKind(event
) )
1012 case kEventRawKeyDown
:
1013 rec
->what
= keyDown
;
1016 case kEventRawKeyRepeat
:
1017 rec
->what
= autoKey
;
1020 case kEventRawKeyUp
:
1024 case kEventRawKeyModifiersChanged
:
1025 rec
->what
= nullEvent
;
1036 unsigned char charCode
;
1038 GetMouse( &rec
->where
) ;
1040 err
= GetEventParameter(event
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1041 err
= GetEventParameter(event
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1042 err
= GetEventParameter(event
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1043 rec
->modifiers
= modifiers
;
1044 rec
->message
= (keyCode
<< 8 ) + charCode
;
1049 case kEventClassTextInput
:
1051 switch ( GetEventKind( event
) )
1053 case kEventTextInputUnicodeForKeyEvent
:
1056 err
= GetEventParameter(
1057 event
, kEventParamTextInputSendKeyboardEvent
, typeEventRef
, NULL
,
1058 sizeof(rawEvent
), NULL
, &rawEvent
) ;
1062 UInt32 keyCode
, modifiers
;
1063 unsigned char charCode
;
1065 GetMouse( &rec
->where
) ;
1066 rec
->what
= keyDown
;
1067 err
= GetEventParameter(rawEvent
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1068 err
= GetEventParameter(rawEvent
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1069 err
= GetEventParameter(rawEvent
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1070 rec
->modifiers
= modifiers
;
1071 rec
->message
= (keyCode
<< 8 ) + charCode
;
1092 m_printMode
= wxPRINT_WINDOWS
;
1094 m_macCurrentEvent
= NULL
;
1095 m_macCurrentEventHandlerCallRef
= NULL
;
1097 #ifdef __WXMAC_OSX__
1098 m_macEventPosted
= NULL
;
1102 void wxApp::OnIdle(wxIdleEvent
& event
)
1104 wxAppBase::OnIdle(event
);
1106 // If they are pending events, we must process them: pending events are
1107 // either events to the threads other than main or events posted with
1108 // wxPostEvent() functions
1109 wxMacProcessNotifierAndPendingEvents();
1111 if (!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1112 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1115 void wxApp::WakeUpIdle()
1117 #ifdef __WXMAC_OSX__
1118 if (m_macEventPosted
)
1120 CFRunLoopSourceSignal(m_macEventPosted
);
1127 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1130 GetTopWindow()->Close(true);
1133 // Default behaviour: close the application with prompts. The
1134 // user can veto the close, and therefore the end session.
1135 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1139 if (!GetTopWindow()->Close(!event
.CanVeto()))
1144 extern "C" void wxCYield() ;
1150 // Yield to other processes
1152 bool wxApp::Yield(bool onlyIfNeeded
)
1156 if ( !onlyIfNeeded
)
1158 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1166 // by definition yield should handle all non-processed events
1170 OSStatus status
= noErr
;
1172 while ( status
== noErr
)
1174 s_inReceiveEvent
= true ;
1175 status
= ReceiveNextEvent(0, NULL
,kEventDurationNoWait
,true,&theEvent
) ;
1176 s_inReceiveEvent
= false ;
1178 if ( status
== eventLoopTimedOutErr
)
1180 // make sure next time the event loop will trigger idle events
1181 sleepTime
= kEventDurationNoWait
;
1183 else if ( status
== eventLoopQuitErr
)
1185 // according to QA1061 this may also occur when a WakeUp Process
1190 MacHandleOneEvent( theEvent
) ;
1191 ReleaseEvent(theEvent
);
1195 wxMacProcessNotifierAndPendingEvents() ;
1201 void wxApp::MacDoOneEvent()
1205 s_inReceiveEvent
= true ;
1206 OSStatus status
= ReceiveNextEvent(0, NULL
, sleepTime
, true, &theEvent
) ;
1207 s_inReceiveEvent
= false ;
1211 case eventLoopTimedOutErr
:
1212 if ( wxTheApp
->ProcessIdle() )
1213 sleepTime
= kEventDurationNoWait
;
1215 sleepTime
= kEventDurationSecond
;
1218 case eventLoopQuitErr
:
1219 // according to QA1061 this may also occur
1220 // when a WakeUp Process is executed
1224 MacHandleOneEvent( theEvent
) ;
1225 ReleaseEvent( theEvent
);
1226 sleepTime
= kEventDurationNoWait
;
1231 DeletePendingObjects() ;
1232 wxMacProcessNotifierAndPendingEvents() ;
1236 void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr
)
1238 // Override to process unhandled events as you please
1241 void wxApp::MacHandleOneEvent( WXEVENTREF evr
)
1243 EventTargetRef theTarget
;
1244 theTarget
= GetEventDispatcherTarget();
1245 m_macCurrentEvent
= evr
;
1247 OSStatus status
= SendEventToEventTarget((EventRef
) evr
, theTarget
);
1248 if (status
== eventNotHandledErr
)
1249 MacHandleUnhandledEvent(evr
);
1251 wxMacProcessNotifierAndPendingEvents() ;
1254 wxMutexGuiLeaveOrEnter();
1255 #endif // wxUSE_THREADS
1258 long wxMacTranslateKey(unsigned char key
, unsigned char code
)
1263 case kHomeCharCode
:
1267 case kEnterCharCode
:
1268 retval
= WXK_RETURN
;
1274 case kHelpCharCode
:
1278 case kBackspaceCharCode
:
1286 case kPageUpCharCode
:
1287 retval
= WXK_PAGEUP
;
1290 case kPageDownCharCode
:
1291 retval
= WXK_PAGEDOWN
;
1294 case kReturnCharCode
:
1295 retval
= WXK_RETURN
;
1298 case kFunctionKeyCharCode
:
1368 case kEscapeCharCode
:
1369 retval
= WXK_ESCAPE
;
1372 case kLeftArrowCharCode
:
1376 case kRightArrowCharCode
:
1377 retval
= WXK_RIGHT
;
1380 case kUpArrowCharCode
:
1384 case kDownArrowCharCode
:
1388 case kDeleteCharCode
:
1389 retval
= WXK_DELETE
;
1399 int wxMacKeyCodeToModifier(wxKeyCode key
)
1425 bool wxGetKeyState(wxKeyCode key
) //virtual key code if < 10.2.x, else see below
1427 wxASSERT_MSG(key
!= WXK_LBUTTON
&& key
!= WXK_RBUTTON
&& key
!=
1428 WXK_MBUTTON
, wxT("can't use wxGetKeyState() for mouse buttons"));
1430 //if OS X > 10.2 (i.e. 10.2.x)
1431 //a known apple bug prevents the system from determining led
1432 //states with GetKeys... can only determine caps lock led
1433 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key
));
1435 // KeyMapByteArray keymap;
1436 // GetKeys((BigEndianLong*)keymap);
1437 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1442 wxMouseState
wxGetMouseState()
1446 wxPoint pt
= wxGetMousePosition();
1450 #if TARGET_API_MAC_OSX
1451 UInt32 buttons
= GetCurrentButtonState();
1452 ms
.SetLeftDown( (buttons
& 0x01) != 0 );
1453 ms
.SetMiddleDown( (buttons
& 0x04) != 0 );
1454 ms
.SetRightDown( (buttons
& 0x02) != 0 );
1456 ms
.SetLeftDown( Button() );
1457 ms
.SetMiddleDown( 0 );
1458 ms
.SetRightDown( 0 );
1461 UInt32 modifiers
= GetCurrentKeyModifiers();
1462 ms
.SetControlDown(modifiers
& controlKey
);
1463 ms
.SetShiftDown(modifiers
& shiftKey
);
1464 ms
.SetAltDown(modifiers
& optionKey
);
1465 ms
.SetMetaDown(modifiers
& cmdKey
);
1470 // TODO : once the new key/char handling is tested, move all the code to wxWindow
1472 bool wxApp::MacSendKeyDownEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1478 wxKeyEvent
event(wxEVT_KEY_DOWN
) ;
1479 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1481 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1482 if ( handled
&& event
.GetSkipped() )
1488 wxWindow
*ancestor
= focus
;
1491 int command
= ancestor
->GetAcceleratorTable()->GetCommand( event
);
1494 wxCommandEvent
command_event( wxEVT_COMMAND_MENU_SELECTED
, command
);
1495 handled
= ancestor
->GetEventHandler()->ProcessEvent( command_event
);
1499 if (ancestor
->IsTopLevel())
1502 ancestor
= ancestor
->GetParent();
1505 #endif // wxUSE_ACCEL
1510 bool wxApp::MacSendKeyUpEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1516 wxKeyEvent
event( wxEVT_KEY_UP
) ;
1517 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1518 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1523 bool wxApp::MacSendCharEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1528 wxKeyEvent
event(wxEVT_CHAR
) ;
1529 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1530 long keyval
= event
.m_keyCode
;
1532 bool handled
= false ;
1534 wxTopLevelWindowMac
*tlw
= focus
->MacGetTopLevelWindow() ;
1538 event
.SetEventType( wxEVT_CHAR_HOOK
);
1539 handled
= tlw
->GetEventHandler()->ProcessEvent( event
);
1540 if ( handled
&& event
.GetSkipped() )
1546 event
.SetEventType( wxEVT_CHAR
);
1547 event
.Skip( false ) ;
1548 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1551 if ( !handled
&& (keyval
== WXK_TAB
) )
1553 wxWindow
* iter
= focus
->GetParent() ;
1554 while ( iter
&& !handled
)
1556 if ( iter
->HasFlag( wxTAB_TRAVERSAL
) )
1558 wxNavigationKeyEvent new_event
;
1559 new_event
.SetEventObject( focus
);
1560 new_event
.SetDirection( !event
.ShiftDown() );
1561 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1562 new_event
.SetWindowChange( event
.ControlDown() );
1563 new_event
.SetCurrentFocus( focus
);
1564 handled
= focus
->GetParent()->GetEventHandler()->ProcessEvent( new_event
);
1565 if ( handled
&& new_event
.GetSkipped() )
1569 iter
= iter
->GetParent() ;
1573 // backdoor handler for default return and command escape
1574 if ( !handled
&& (!focus
->IsKindOf(CLASSINFO(wxControl
) ) || !focus
->MacCanFocus() ) )
1576 // if window is not having a focus still testing for default enter or cancel
1577 // TODO: add the UMA version for ActiveNonFloatingWindow
1578 wxWindow
* focus
= wxFindWinFromMacWindow( FrontWindow() ) ;
1581 if ( keyval
== WXK_RETURN
)
1583 wxTopLevelWindow
*tlw
= wxDynamicCast(wxGetTopLevelParent(focus
), wxTopLevelWindow
);
1584 if ( tlw
&& tlw
->GetDefaultItem() )
1586 wxButton
*def
= wxDynamicCast(tlw
->GetDefaultItem(), wxButton
);
1587 if ( def
&& def
->IsEnabled() )
1589 wxCommandEvent
event(wxEVT_COMMAND_BUTTON_CLICKED
, def
->GetId() );
1590 event
.SetEventObject(def
);
1591 def
->Command(event
);
1597 else if (keyval
== WXK_ESCAPE
|| (keyval
== '.' && modifiers
& cmdKey
) )
1599 // generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs)
1600 wxCommandEvent
new_event(wxEVT_COMMAND_BUTTON_CLICKED
,wxID_CANCEL
);
1601 new_event
.SetEventObject( focus
);
1602 handled
= focus
->GetEventHandler()->ProcessEvent( new_event
);
1609 // This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
1610 void wxApp::MacCreateKeyEvent( wxKeyEvent
& event
, wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1612 short keycode
, keychar
;
1614 keychar
= short(keymessage
& charCodeMask
);
1615 keycode
= short(keymessage
& keyCodeMask
) >> 8 ;
1616 if ( !(event
.GetEventType() == wxEVT_CHAR
) && (modifiers
& (controlKey
| shiftKey
| optionKey
) ) )
1618 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1619 // and look at the character after
1621 UInt32 keyInfo
= KeyTranslate((Ptr
)GetScriptManagerVariable(smKCHRCache
), ( modifiers
& (~(controlKey
| shiftKey
| optionKey
))) | keycode
, &state
);
1622 keychar
= short(keyInfo
& charCodeMask
);
1625 long keyval
= wxMacTranslateKey(keychar
, keycode
) ;
1626 if ( keyval
== keychar
&& ( event
.GetEventType() == wxEVT_KEY_UP
|| event
.GetEventType() == wxEVT_KEY_DOWN
) )
1627 keyval
= wxToupper( keyval
) ;
1629 // Check for NUMPAD keys
1630 if (keyval
>= '0' && keyval
<= '9' && keycode
>= 82 && keycode
<= 92)
1632 keyval
= (keyval
- '0') + WXK_NUMPAD0
;
1634 else if (keycode
>= 67 && keycode
<= 81)
1639 keyval
= WXK_NUMPAD_ENTER
;
1643 keyval
= WXK_NUMPAD_EQUAL
;
1647 keyval
= WXK_NUMPAD_MULTIPLY
;
1651 keyval
= WXK_NUMPAD_DIVIDE
;
1655 keyval
= WXK_NUMPAD_SUBTRACT
;
1659 keyval
= WXK_NUMPAD_ADD
;
1663 keyval
= WXK_NUMPAD_DECIMAL
;
1671 event
.m_shiftDown
= modifiers
& shiftKey
;
1672 event
.m_controlDown
= modifiers
& controlKey
;
1673 event
.m_altDown
= modifiers
& optionKey
;
1674 event
.m_metaDown
= modifiers
& cmdKey
;
1675 event
.m_keyCode
= keyval
;
1677 event
.m_uniChar
= uniChar
;
1680 event
.m_rawCode
= keymessage
;
1681 event
.m_rawFlags
= modifiers
;
1684 event
.SetTimestamp(when
);
1685 event
.SetEventObject(focus
);