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"
25 #include "wx/button.h"
26 #include "wx/gdicmn.h"
29 #include "wx/cursor.h"
31 #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
)
736 pascal static void wxMacAssertOutputHandler(OSType componentSignature
, UInt32 options
,
737 const char *assertionString
, const char *exceptionLabelString
,
738 const char *errorString
, const char *fileName
, long lineNumber
, void *value
, ConstStr255Param outputMsg
)
740 // flow into assert handling
741 wxString fileNameStr
;
742 wxString assertionStr
;
743 wxString exceptionStr
;
747 fileNameStr
= wxString(fileName
, wxConvLocal
);
748 assertionStr
= wxString(assertionString
, wxConvLocal
);
749 exceptionStr
= wxString((exceptionLabelString
!=0) ? exceptionLabelString
: "", wxConvLocal
) ;
750 errorStr
= wxString((errorString
!=0) ? errorString
: "", wxConvLocal
) ;
752 fileNameStr
= fileName
;
753 assertionStr
= assertionString
;
754 exceptionStr
= (exceptionLabelString
!=0) ? exceptionLabelString
: "" ;
755 errorStr
= (errorString
!=0) ? errorString
: "" ;
760 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
761 assertionStr
.c_str() ,
762 exceptionStr
.c_str() ,
764 fileNameStr
.c_str(), lineNumber
,
768 wxOnAssert(fileNameStr
, lineNumber
, assertionStr
,
769 wxString::Format( wxT("%s %s value (%p)") , exceptionStr
, errorStr
, value
) ) ;
778 // m_macEventPosted run loop source callback:
779 void macPostedEventCallback(void *unused
);
782 void macPostedEventCallback(void *unused
)
784 wxTheApp
->ProcessPendingEvents();
788 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
793 InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler
) );
796 UMAInitToolbox( 4, sm_isEmbedded
) ;
797 SetEventMask( everyEvent
) ;
798 UMAShowWatchCursor() ;
801 # if __option(profile)
802 ProfilerInit( collectDetailed
, bestTimeBase
, 40000 , 50 ) ;
807 // now avoid exceptions thrown for new (bad_alloc)
808 // FIXME CS for some changes outside wxMac does not compile anymore
810 std::__throws_bad_alloc
= 0 ;
815 s_macCursorRgn
= ::NewRgn() ;
817 // Mac OS X passes a process serial number command line argument when
818 // the application is launched from the Finder. This argument must be
819 // removed from the command line arguments before being handled by the
820 // application (otherwise applications would need to handle it)
823 static const wxChar
*ARG_PSN
= _T("-psn_");
824 if ( wxStrncmp(argv
[1], ARG_PSN
, wxStrlen(ARG_PSN
)) == 0 )
826 // remove this argument
828 memmove(argv
+ 1, argv
+ 2, argc
* sizeof(char *));
832 if ( !wxAppBase::Initialize(argc
, argv
) )
836 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
839 #if TARGET_API_MAC_OSX
840 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
841 wxString startupCwd
= wxGetCwd() ;
842 if ( startupCwd
== wxT("/") || startupCwd
.Right(15) == wxT("/Contents/MacOS") )
844 CFURLRef url
= CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
845 CFURLRef urlParent
= CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault
, url
) ;
847 CFStringRef path
= CFURLCopyFileSystemPath ( urlParent
, kCFURLPOSIXPathStyle
) ;
848 CFRelease( urlParent
) ;
849 wxString cwd
= wxMacCFStringHolder(path
).AsString(wxLocale::GetSystemEncoding());
850 wxSetWorkingDirectory( cwd
) ;
854 wxMacCreateNotifierTable() ;
857 /* connect posted events to common-mode run loop so that wxPostEvent events
858 are handled even while we're in the menu or on a scrollbar */
859 CFRunLoopSourceContext event_posted_context
= {0};
860 event_posted_context
.perform
= macPostedEventCallback
;
861 m_macEventPosted
= CFRunLoopSourceCreate(NULL
,0,&event_posted_context
);
862 CFRunLoopAddSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
865 UMAShowArrowCursor() ;
870 AEEventHandlerUPP sODocHandler
= NULL
;
871 AEEventHandlerUPP sOAppHandler
= NULL
;
872 AEEventHandlerUPP sPDocHandler
= NULL
;
873 AEEventHandlerUPP sRAppHandler
= NULL
;
874 AEEventHandlerUPP sQuitHandler
= NULL
;
876 bool wxApp::OnInitGui()
878 if ( !wxAppBase::OnInitGui() )
881 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
885 InstallApplicationEventHandler(
886 GetwxMacAppEventHandlerUPP(),
887 GetEventTypeCount(eventList
), eventList
, wxTheApp
, (EventHandlerRef
*)&(wxTheApp
->m_macEventHandler
));
892 sODocHandler
= NewAEEventHandlerUPP(AEHandleODoc
) ;
893 sOAppHandler
= NewAEEventHandlerUPP(AEHandleOApp
) ;
894 sPDocHandler
= NewAEEventHandlerUPP(AEHandlePDoc
) ;
895 sRAppHandler
= NewAEEventHandlerUPP(AEHandleRApp
) ;
896 sQuitHandler
= NewAEEventHandlerUPP(AEHandleQuit
) ;
898 AEInstallEventHandler( kCoreEventClass
, kAEOpenDocuments
,
899 sODocHandler
, 0 , FALSE
) ;
900 AEInstallEventHandler( kCoreEventClass
, kAEOpenApplication
,
901 sOAppHandler
, 0 , FALSE
) ;
902 AEInstallEventHandler( kCoreEventClass
, kAEPrintDocuments
,
903 sPDocHandler
, 0 , FALSE
) ;
904 AEInstallEventHandler( kCoreEventClass
, kAEReopenApplication
,
905 sRAppHandler
, 0 , FALSE
) ;
906 AEInstallEventHandler( kCoreEventClass
, kAEQuitApplication
,
907 sQuitHandler
, 0 , FALSE
) ;
913 void wxApp::CleanUp()
916 wxToolTip::RemoveToolTips() ;
920 if (m_macEventPosted
)
921 CFRelease(m_macEventPosted
);
922 m_macEventPosted
= NULL
;
925 // One last chance for pending objects to be cleaned up
926 wxTheApp
->DeletePendingObjects();
928 wxMacDestroyNotifierTable() ;
931 # if __option(profile)
932 ProfilerDump( (StringPtr
)"\papp.prof" ) ;
937 UMACleanupToolbox() ;
939 ::DisposeRgn((RgnHandle
)s_macCursorRgn
);
942 RemoveEventHandler( (EventHandlerRef
)(wxTheApp
->m_macEventHandler
) );
946 AERemoveEventHandler( kCoreEventClass
, kAEOpenDocuments
,
947 sODocHandler
, FALSE
) ;
948 AERemoveEventHandler( kCoreEventClass
, kAEOpenApplication
,
949 sOAppHandler
, FALSE
) ;
950 AERemoveEventHandler( kCoreEventClass
, kAEPrintDocuments
,
951 sPDocHandler
, FALSE
) ;
952 AERemoveEventHandler( kCoreEventClass
, kAEReopenApplication
,
953 sRAppHandler
, FALSE
) ;
954 AERemoveEventHandler( kCoreEventClass
, kAEQuitApplication
,
955 sQuitHandler
, FALSE
) ;
957 DisposeAEEventHandlerUPP( sODocHandler
) ;
958 DisposeAEEventHandlerUPP( sOAppHandler
) ;
959 DisposeAEEventHandlerUPP( sPDocHandler
) ;
960 DisposeAEEventHandlerUPP( sRAppHandler
) ;
961 DisposeAEEventHandlerUPP( sQuitHandler
) ;
964 wxAppBase::CleanUp();
967 //----------------------------------------------------------------------
968 // misc initialization stuff
969 //----------------------------------------------------------------------
971 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
973 // for shared libraries we have to manually get the correct resource
974 // ref num upon initializing and releasing when terminating, therefore
975 // the __wxinitialize and __wxterminate must be used
979 void __sinit(void); // (generated by linker)
980 pascal OSErr
__initialize(const CFragInitBlock
*theInitBlock
);
981 pascal void __terminate(void);
984 pascal OSErr
__wxinitialize(const CFragInitBlock
*theInitBlock
)
986 return __initialize( theInitBlock
) ;
989 pascal void __wxterminate(void)
994 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
996 bool wxMacConvertEventToRecord( EventRef event
, EventRecord
*rec
)
998 OSStatus err
= noErr
;
999 bool converted
= ConvertEventRefToEventRecord( event
, rec
) ;
1003 switch ( GetEventClass( event
) )
1005 case kEventClassKeyboard
:
1008 switch ( GetEventKind(event
) )
1010 case kEventRawKeyDown
:
1011 rec
->what
= keyDown
;
1014 case kEventRawKeyRepeat
:
1015 rec
->what
= autoKey
;
1018 case kEventRawKeyUp
:
1022 case kEventRawKeyModifiersChanged
:
1023 rec
->what
= nullEvent
;
1034 unsigned char charCode
;
1036 GetMouse( &rec
->where
) ;
1038 err
= GetEventParameter(event
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1039 err
= GetEventParameter(event
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1040 err
= GetEventParameter(event
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1041 rec
->modifiers
= modifiers
;
1042 rec
->message
= (keyCode
<< 8 ) + charCode
;
1047 case kEventClassTextInput
:
1049 switch ( GetEventKind( event
) )
1051 case kEventTextInputUnicodeForKeyEvent
:
1054 err
= GetEventParameter(
1055 event
, kEventParamTextInputSendKeyboardEvent
, typeEventRef
, NULL
,
1056 sizeof(rawEvent
), NULL
, &rawEvent
) ;
1060 UInt32 keyCode
, modifiers
;
1061 unsigned char charCode
;
1063 GetMouse( &rec
->where
) ;
1064 rec
->what
= keyDown
;
1065 err
= GetEventParameter(rawEvent
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1066 err
= GetEventParameter(rawEvent
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1067 err
= GetEventParameter(rawEvent
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1068 rec
->modifiers
= modifiers
;
1069 rec
->message
= (keyCode
<< 8 ) + charCode
;
1090 m_printMode
= wxPRINT_WINDOWS
;
1092 m_macCurrentEvent
= NULL
;
1093 m_macCurrentEventHandlerCallRef
= NULL
;
1095 #ifdef __WXMAC_OSX__
1096 m_macEventPosted
= NULL
;
1100 void wxApp::OnIdle(wxIdleEvent
& event
)
1102 wxAppBase::OnIdle(event
);
1104 // If they are pending events, we must process them: pending events are
1105 // either events to the threads other than main or events posted with
1106 // wxPostEvent() functions
1107 wxMacProcessNotifierAndPendingEvents();
1109 if (!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1110 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1113 void wxApp::WakeUpIdle()
1115 #ifdef __WXMAC_OSX__
1116 if (m_macEventPosted
)
1118 CFRunLoopSourceSignal(m_macEventPosted
);
1125 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1128 GetTopWindow()->Close(true);
1131 // Default behaviour: close the application with prompts. The
1132 // user can veto the close, and therefore the end session.
1133 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1137 if (!GetTopWindow()->Close(!event
.CanVeto()))
1142 extern "C" void wxCYield() ;
1148 // Yield to other processes
1150 bool wxApp::Yield(bool onlyIfNeeded
)
1154 if ( !onlyIfNeeded
)
1156 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1164 // by definition yield should handle all non-processed events
1168 OSStatus status
= noErr
;
1170 while ( status
== noErr
)
1172 s_inReceiveEvent
= true ;
1173 status
= ReceiveNextEvent(0, NULL
,kEventDurationNoWait
,true,&theEvent
) ;
1174 s_inReceiveEvent
= false ;
1176 if ( status
== eventLoopTimedOutErr
)
1178 // make sure next time the event loop will trigger idle events
1179 sleepTime
= kEventDurationNoWait
;
1181 else if ( status
== eventLoopQuitErr
)
1183 // according to QA1061 this may also occur when a WakeUp Process
1188 MacHandleOneEvent( theEvent
) ;
1189 ReleaseEvent(theEvent
);
1193 wxMacProcessNotifierAndPendingEvents() ;
1199 void wxApp::MacDoOneEvent()
1203 s_inReceiveEvent
= true ;
1204 OSStatus status
= ReceiveNextEvent(0, NULL
, sleepTime
, true, &theEvent
) ;
1205 s_inReceiveEvent
= false ;
1209 case eventLoopTimedOutErr
:
1210 if ( wxTheApp
->ProcessIdle() )
1211 sleepTime
= kEventDurationNoWait
;
1213 sleepTime
= kEventDurationSecond
;
1216 case eventLoopQuitErr
:
1217 // according to QA1061 this may also occur
1218 // when a WakeUp Process is executed
1222 MacHandleOneEvent( theEvent
) ;
1223 ReleaseEvent( theEvent
);
1224 sleepTime
= kEventDurationNoWait
;
1229 DeletePendingObjects() ;
1230 wxMacProcessNotifierAndPendingEvents() ;
1234 void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr
)
1236 // Override to process unhandled events as you please
1239 void wxApp::MacHandleOneEvent( WXEVENTREF evr
)
1241 EventTargetRef theTarget
;
1242 theTarget
= GetEventDispatcherTarget();
1243 m_macCurrentEvent
= evr
;
1245 OSStatus status
= SendEventToEventTarget((EventRef
) evr
, theTarget
);
1246 if (status
== eventNotHandledErr
)
1247 MacHandleUnhandledEvent(evr
);
1249 wxMacProcessNotifierAndPendingEvents() ;
1252 wxMutexGuiLeaveOrEnter();
1253 #endif // wxUSE_THREADS
1256 long wxMacTranslateKey(unsigned char key
, unsigned char code
)
1261 case kHomeCharCode
:
1265 case kEnterCharCode
:
1266 retval
= WXK_RETURN
;
1272 case kHelpCharCode
:
1276 case kBackspaceCharCode
:
1284 case kPageUpCharCode
:
1285 retval
= WXK_PAGEUP
;
1288 case kPageDownCharCode
:
1289 retval
= WXK_PAGEDOWN
;
1292 case kReturnCharCode
:
1293 retval
= WXK_RETURN
;
1296 case kFunctionKeyCharCode
:
1366 case kEscapeCharCode
:
1367 retval
= WXK_ESCAPE
;
1370 case kLeftArrowCharCode
:
1374 case kRightArrowCharCode
:
1375 retval
= WXK_RIGHT
;
1378 case kUpArrowCharCode
:
1382 case kDownArrowCharCode
:
1386 case kDeleteCharCode
:
1387 retval
= WXK_DELETE
;
1397 int wxMacKeyCodeToModifier(wxKeyCode key
)
1423 bool wxGetKeyState(wxKeyCode key
) //virtual key code if < 10.2.x, else see below
1425 wxASSERT_MSG(key
!= WXK_LBUTTON
&& key
!= WXK_RBUTTON
&& key
!=
1426 WXK_MBUTTON
, wxT("can't use wxGetKeyState() for mouse buttons"));
1428 //if OS X > 10.2 (i.e. 10.2.x)
1429 //a known apple bug prevents the system from determining led
1430 //states with GetKeys... can only determine caps lock led
1431 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key
));
1433 // KeyMapByteArray keymap;
1434 // GetKeys((BigEndianLong*)keymap);
1435 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1440 wxMouseState
wxGetMouseState()
1444 wxPoint pt
= wxGetMousePosition();
1448 #if TARGET_API_MAC_OSX
1449 UInt32 buttons
= GetCurrentButtonState();
1450 ms
.SetLeftDown( (buttons
& 0x01) != 0 );
1451 ms
.SetMiddleDown( (buttons
& 0x04) != 0 );
1452 ms
.SetRightDown( (buttons
& 0x02) != 0 );
1454 ms
.SetLeftDown( Button() );
1455 ms
.SetMiddleDown( 0 );
1456 ms
.SetRightDown( 0 );
1459 UInt32 modifiers
= GetCurrentKeyModifiers();
1460 ms
.SetControlDown(modifiers
& controlKey
);
1461 ms
.SetShiftDown(modifiers
& shiftKey
);
1462 ms
.SetAltDown(modifiers
& optionKey
);
1463 ms
.SetMetaDown(modifiers
& cmdKey
);
1468 // TODO : once the new key/char handling is tested, move all the code to wxWindow
1470 bool wxApp::MacSendKeyDownEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1476 wxKeyEvent
event(wxEVT_KEY_DOWN
) ;
1477 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1479 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1480 if ( handled
&& event
.GetSkipped() )
1486 wxWindow
*ancestor
= focus
;
1489 int command
= ancestor
->GetAcceleratorTable()->GetCommand( event
);
1492 wxCommandEvent
command_event( wxEVT_COMMAND_MENU_SELECTED
, command
);
1493 handled
= ancestor
->GetEventHandler()->ProcessEvent( command_event
);
1497 if (ancestor
->IsTopLevel())
1500 ancestor
= ancestor
->GetParent();
1503 #endif // wxUSE_ACCEL
1508 bool wxApp::MacSendKeyUpEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1514 wxKeyEvent
event( wxEVT_KEY_UP
) ;
1515 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1516 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1521 bool wxApp::MacSendCharEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1526 wxKeyEvent
event(wxEVT_CHAR
) ;
1527 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1528 long keyval
= event
.m_keyCode
;
1530 bool handled
= false ;
1532 wxTopLevelWindowMac
*tlw
= focus
->MacGetTopLevelWindow() ;
1536 event
.SetEventType( wxEVT_CHAR_HOOK
);
1537 handled
= tlw
->GetEventHandler()->ProcessEvent( event
);
1538 if ( handled
&& event
.GetSkipped() )
1544 event
.SetEventType( wxEVT_CHAR
);
1545 event
.Skip( false ) ;
1546 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1549 if ( !handled
&& (keyval
== WXK_TAB
) )
1551 wxWindow
* iter
= focus
->GetParent() ;
1552 while ( iter
&& !handled
)
1554 if ( iter
->HasFlag( wxTAB_TRAVERSAL
) )
1556 wxNavigationKeyEvent new_event
;
1557 new_event
.SetEventObject( focus
);
1558 new_event
.SetDirection( !event
.ShiftDown() );
1559 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1560 new_event
.SetWindowChange( event
.ControlDown() );
1561 new_event
.SetCurrentFocus( focus
);
1562 handled
= focus
->GetParent()->GetEventHandler()->ProcessEvent( new_event
);
1563 if ( handled
&& new_event
.GetSkipped() )
1567 iter
= iter
->GetParent() ;
1571 // backdoor handler for default return and command escape
1572 if ( !handled
&& (!focus
->IsKindOf(CLASSINFO(wxControl
) ) || !focus
->MacCanFocus() ) )
1574 // if window is not having a focus still testing for default enter or cancel
1575 // TODO: add the UMA version for ActiveNonFloatingWindow
1576 wxWindow
* focus
= wxFindWinFromMacWindow( FrontWindow() ) ;
1579 if ( keyval
== WXK_RETURN
)
1581 wxButton
*def
= wxDynamicCast(focus
->GetDefaultItem(), wxButton
);
1582 if ( def
&& def
->IsEnabled() )
1584 wxCommandEvent
event(wxEVT_COMMAND_BUTTON_CLICKED
, def
->GetId() );
1585 event
.SetEventObject(def
);
1586 def
->Command(event
);
1591 else if (keyval
== WXK_ESCAPE
|| (keyval
== '.' && modifiers
& cmdKey
) )
1593 // generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs)
1594 wxCommandEvent
new_event(wxEVT_COMMAND_BUTTON_CLICKED
,wxID_CANCEL
);
1595 new_event
.SetEventObject( focus
);
1596 handled
= focus
->GetEventHandler()->ProcessEvent( new_event
);
1603 // This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
1604 void wxApp::MacCreateKeyEvent( wxKeyEvent
& event
, wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1606 short keycode
, keychar
;
1608 keychar
= short(keymessage
& charCodeMask
);
1609 keycode
= short(keymessage
& keyCodeMask
) >> 8 ;
1610 if ( !(event
.GetEventType() == wxEVT_CHAR
) && (modifiers
& (controlKey
| shiftKey
| optionKey
) ) )
1612 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1613 // and look at the character after
1615 UInt32 keyInfo
= KeyTranslate((Ptr
)GetScriptManagerVariable(smKCHRCache
), ( modifiers
& (~(controlKey
| shiftKey
| optionKey
))) | keycode
, &state
);
1616 keychar
= short(keyInfo
& charCodeMask
);
1619 long keyval
= wxMacTranslateKey(keychar
, keycode
) ;
1620 if ( keyval
== keychar
&& ( event
.GetEventType() == wxEVT_KEY_UP
|| event
.GetEventType() == wxEVT_KEY_DOWN
) )
1621 keyval
= wxToupper( keyval
) ;
1623 // Check for NUMPAD keys
1624 if (keyval
>= '0' && keyval
<= '9' && keycode
>= 82 && keycode
<= 92)
1626 keyval
= (keyval
- '0') + WXK_NUMPAD0
;
1628 else if (keycode
>= 67 && keycode
<= 81)
1633 keyval
= WXK_NUMPAD_ENTER
;
1637 keyval
= WXK_NUMPAD_EQUAL
;
1641 keyval
= WXK_NUMPAD_MULTIPLY
;
1645 keyval
= WXK_NUMPAD_DIVIDE
;
1649 keyval
= WXK_NUMPAD_SUBTRACT
;
1653 keyval
= WXK_NUMPAD_ADD
;
1657 keyval
= WXK_NUMPAD_DECIMAL
;
1665 event
.m_shiftDown
= modifiers
& shiftKey
;
1666 event
.m_controlDown
= modifiers
& controlKey
;
1667 event
.m_altDown
= modifiers
& optionKey
;
1668 event
.m_metaDown
= modifiers
& cmdKey
;
1669 event
.m_keyCode
= keyval
;
1671 event
.m_uniChar
= uniChar
;
1674 event
.m_rawCode
= keymessage
;
1675 event
.m_rawFlags
= modifiers
;
1678 event
.SetTimestamp(when
);
1679 event
.SetEventObject(focus
);