1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/mac/carbon/app.cpp
4 // Author: Stefan Csomor
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
20 #include "wx/window.h"
23 #include "wx/button.h"
27 #include "wx/palette.h"
29 #include "wx/cursor.h"
30 #include "wx/dialog.h"
31 #include "wx/msgdlg.h"
32 #include "wx/textctrl.h"
33 #include "wx/memory.h"
34 #include "wx/gdicmn.h"
35 #include "wx/module.h"
38 #include "wx/tooltip.h"
39 #include "wx/docview.h"
40 #include "wx/filename.h"
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
)
74 // statics for implementation
75 static bool s_inYield
= false;
76 static bool s_inReceiveEvent
= false ;
77 static EventTime sleepTime
= kEventDurationNoWait
;
80 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
81 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
82 EVT_IDLE(wxApp::OnIdle
)
83 EVT_END_SESSION(wxApp::OnEndSession
)
84 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
88 // platform specific static variables
89 static const short kwxMacAppleMenuId
= 1 ;
91 wxWindow
* wxApp::s_captureWindow
= NULL
;
92 long wxApp::s_lastModifiers
= 0 ;
94 long wxApp::s_macAboutMenuItemId
= wxID_ABOUT
;
95 long wxApp::s_macPreferencesMenuItemId
= wxID_PREFERENCES
;
96 long wxApp::s_macExitMenuItemId
= wxID_EXIT
;
97 wxString
wxApp::s_macHelpMenuTitleName
= wxT("&Help") ;
99 bool wxApp::sm_isEmbedded
= false; // Normally we're not a plugin
101 //----------------------------------------------------------------------
102 // Core Apple Event Support
103 //----------------------------------------------------------------------
105 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
106 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
107 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
108 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
109 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon refcon
) ;
111 pascal OSErr
AEHandleODoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
113 return wxTheApp
->MacHandleAEODoc( (AppleEvent
*) event
, reply
) ;
116 pascal OSErr
AEHandleOApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
118 return wxTheApp
->MacHandleAEOApp( (AppleEvent
*) event
, reply
) ;
121 pascal OSErr
AEHandlePDoc( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
123 return wxTheApp
->MacHandleAEPDoc( (AppleEvent
*) event
, reply
) ;
126 pascal OSErr
AEHandleQuit( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
128 return wxTheApp
->MacHandleAEQuit( (AppleEvent
*) event
, reply
) ;
131 pascal OSErr
AEHandleRApp( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
133 return wxTheApp
->MacHandleAERApp( (AppleEvent
*) event
, reply
) ;
136 pascal OSErr
AEHandleGURL( const AppleEvent
*event
, AppleEvent
*reply
, SRefCon
WXUNUSED(refcon
) )
138 return wxTheApp
->MacHandleAEGURL((WXEVENTREF
*)event
, reply
) ;
142 // AEODoc Calls MacOpenFile on each of the files passed
144 short wxApp::MacHandleAEODoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
148 DescType returnedType
;
154 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
158 err
= AECountItems(&docList
, &itemsInList
);
162 ProcessSerialNumber PSN
;
163 PSN
.highLongOfPSN
= 0 ;
164 PSN
.lowLongOfPSN
= kCurrentProcess
;
165 SetFrontProcess( &PSN
) ;
170 for (i
= 1; i
<= itemsInList
; i
++)
173 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
174 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
175 fName
= wxMacFSRefToPath( &theRef
) ;
183 // AEODoc Calls MacOpenURL on the url passed
185 short wxApp::MacHandleAEGURL(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
187 DescType returnedType
;
190 OSErr err
= AEGetParamPtr((AppleEvent
*)event
, keyDirectObject
, typeChar
,
191 &returnedType
, url
, sizeof(url
)-1,
196 url
[actualSize
] = '\0'; // Terminate the C string
198 ProcessSerialNumber PSN
;
199 PSN
.highLongOfPSN
= 0 ;
200 PSN
.lowLongOfPSN
= kCurrentProcess
;
201 SetFrontProcess( &PSN
) ;
203 MacOpenURL(wxString(url
, wxConvUTF8
));
208 // AEPDoc Calls MacPrintFile on each of the files passed
210 short wxApp::MacHandleAEPDoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
214 DescType returnedType
;
220 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
224 err
= AECountItems(&docList
, &itemsInList
);
228 ProcessSerialNumber PSN
;
229 PSN
.highLongOfPSN
= 0 ;
230 PSN
.lowLongOfPSN
= kCurrentProcess
;
231 SetFrontProcess( &PSN
) ;
236 for (i
= 1; i
<= itemsInList
; i
++)
239 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
240 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
241 fName
= wxMacFSRefToPath( &theRef
) ;
249 // AEOApp calls MacNewFile
251 short wxApp::MacHandleAEOApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
257 // AEQuit attempts to quit the application
259 short wxApp::MacHandleAEQuit(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
261 wxWindow
* win
= GetTopWindow() ;
264 wxCommandEvent
exitEvent(wxEVT_COMMAND_MENU_SELECTED
, s_macExitMenuItemId
);
265 if (!win
->ProcessEvent(exitEvent
))
276 // AEROApp calls MacReopenApp
278 short wxApp::MacHandleAERApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
285 //----------------------------------------------------------------------
286 // Support Routines linking the Mac...File Calls to the Document Manager
287 //----------------------------------------------------------------------
289 void wxApp::MacOpenFile(const wxString
& fileName
)
291 #if wxUSE_DOC_VIEW_ARCHITECTURE
292 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
294 dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
298 void wxApp::MacOpenURL(const wxString
& WXUNUSED(url
) )
302 void wxApp::MacPrintFile(const wxString
& fileName
)
304 #if wxUSE_DOC_VIEW_ARCHITECTURE
306 #if wxUSE_PRINTING_ARCHITECTURE
307 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
310 wxDocument
*doc
= dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
313 wxView
* view
= doc
->GetFirstView() ;
316 wxPrintout
*printout
= view
->OnCreatePrintout();
320 printer
.Print(view
->GetFrame(), printout
, true);
327 doc
->DeleteAllViews();
328 dm
->RemoveDocument(doc
) ;
339 void wxApp::MacNewFile()
343 void wxApp::MacReopenApp()
346 // if there is no open window -> create a new one
347 // if all windows are hidden -> show the first
348 // if some windows are not hidden -> do nothing
350 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetFirst();
357 wxTopLevelWindow
* firstIconized
= NULL
;
360 wxTopLevelWindow
* win
= (wxTopLevelWindow
*) node
->GetData();
361 if ( !win
->IsIconized() )
363 firstIconized
= NULL
;
368 if ( firstIconized
== NULL
)
369 firstIconized
= win
;
372 node
= node
->GetNext();
376 firstIconized
->Iconize( false ) ;
380 //----------------------------------------------------------------------
381 // Macintosh CommandID support - converting between native and wx IDs
382 //----------------------------------------------------------------------
384 // if no native match they just return the passed-in id
392 IdPair gCommandIds
[] =
394 { kHICommandCut
, wxID_CUT
} ,
395 { kHICommandCopy
, wxID_COPY
} ,
396 { kHICommandPaste
, wxID_PASTE
} ,
397 { kHICommandSelectAll
, wxID_SELECTALL
} ,
398 { kHICommandClear
, wxID_CLEAR
} ,
399 { kHICommandUndo
, wxID_UNDO
} ,
400 { kHICommandRedo
, wxID_REDO
} ,
403 int wxMacCommandToId( UInt32 macCommandId
)
407 switch ( macCommandId
)
409 case kHICommandPreferences
:
410 wxid
= wxApp::s_macPreferencesMenuItemId
;
413 case kHICommandQuit
:
414 wxid
= wxApp::s_macExitMenuItemId
;
417 case kHICommandAbout
:
418 wxid
= wxApp::s_macAboutMenuItemId
;
423 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
425 if ( gCommandIds
[i
].macId
== macCommandId
)
427 wxid
= gCommandIds
[i
].wxId
;
436 wxid
= (int) macCommandId
;
441 UInt32
wxIdToMacCommand( int wxId
)
445 if ( wxId
== wxApp::s_macPreferencesMenuItemId
)
446 macId
= kHICommandPreferences
;
447 else if (wxId
== wxApp::s_macExitMenuItemId
)
448 macId
= kHICommandQuit
;
449 else if (wxId
== wxApp::s_macAboutMenuItemId
)
450 macId
= kHICommandAbout
;
453 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
455 if ( gCommandIds
[i
].wxId
== wxId
)
457 macId
= gCommandIds
[i
].macId
;
469 wxMenu
* wxFindMenuFromMacCommand( const HICommand
&command
, wxMenuItem
* &item
)
471 wxMenu
* itemMenu
= NULL
;
474 // for 'standard' commands which don't have a wx-menu
475 if ( command
.commandID
== kHICommandPreferences
|| command
.commandID
== kHICommandQuit
|| command
.commandID
== kHICommandAbout
)
477 id
= wxMacCommandToId( command
.commandID
) ;
479 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
481 item
= mbar
->FindItem( id
, &itemMenu
) ;
483 else if ( command
.commandID
!= 0 && command
.menu
.menuRef
!= 0 && command
.menu
.menuItemIndex
!= 0 )
485 id
= wxMacCommandToId( command
.commandID
) ;
486 // make sure it is one of our own menus, or of the 'synthetic' apple and help menus , otherwise don't touch
487 MenuItemIndex firstUserHelpMenuItem
;
488 static MenuHandle helpMenuHandle
= NULL
;
489 if ( helpMenuHandle
== NULL
)
491 if ( UMAGetHelpMenuDontCreate( &helpMenuHandle
, &firstUserHelpMenuItem
) != noErr
)
492 helpMenuHandle
= NULL
;
495 // is it part of the application or the Help menu, then look for the id directly
496 if ( ( GetMenuHandle( kwxMacAppleMenuId
) != NULL
&& command
.menu
.menuRef
== GetMenuHandle( kwxMacAppleMenuId
) ) ||
497 ( helpMenuHandle
!= NULL
&& command
.menu
.menuRef
== helpMenuHandle
) ||
498 wxMenuBar::MacGetWindowMenuHMenu() != NULL
&& command
.menu
.menuRef
== wxMenuBar::MacGetWindowMenuHMenu() )
500 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
502 item
= mbar
->FindItem( id
, &itemMenu
) ;
508 GetMenuItemRefCon( command
.menu
.menuRef
, command
.menu
.menuItemIndex
, &refCon
) ;
509 itemMenu
= wxFindMenuFromMacMenu( command
.menu
.menuRef
) ;
510 if ( itemMenu
!= NULL
)
511 item
= (wxMenuItem
*) refCon
;
518 //----------------------------------------------------------------------
519 // Carbon Event Handler
520 //----------------------------------------------------------------------
522 static const EventTypeSpec eventList
[] =
524 { kEventClassCommand
, kEventProcessCommand
} ,
525 { kEventClassCommand
, kEventCommandUpdateStatus
} ,
527 { kEventClassMenu
, kEventMenuOpening
},
528 { kEventClassMenu
, kEventMenuClosed
},
529 { kEventClassMenu
, kEventMenuTargetItem
},
531 { kEventClassApplication
, kEventAppActivated
} ,
532 { kEventClassApplication
, kEventAppDeactivated
} ,
533 // handling the quit event is not recommended by apple
534 // rather using the quit apple event - which we do
536 { kEventClassAppleEvent
, kEventAppleEvent
} ,
538 { kEventClassMouse
, kEventMouseDown
} ,
539 { kEventClassMouse
, kEventMouseMoved
} ,
540 { kEventClassMouse
, kEventMouseUp
} ,
541 { kEventClassMouse
, kEventMouseDragged
} ,
545 static pascal OSStatus
546 wxMacAppMenuEventHandler( EventHandlerCallRef
WXUNUSED(handler
),
548 void *WXUNUSED(data
) )
550 wxMacCarbonEvent
cEvent( event
) ;
551 MenuRef menuRef
= cEvent
.GetParameter
<MenuRef
>(kEventParamDirectObject
) ;
552 wxMenu
* menu
= wxFindMenuFromMacMenu( menuRef
) ;
558 switch (GetEventKind(event
))
560 case kEventMenuOpening
:
561 type
= wxEVT_MENU_OPEN
;
564 case kEventMenuClosed
:
565 type
= wxEVT_MENU_CLOSE
;
568 case kEventMenuTargetItem
:
569 cmd
= cEvent
.GetParameter
<MenuCommand
>(kEventParamMenuCommand
,typeMenuCommand
) ;
571 type
= wxEVT_MENU_HIGHLIGHT
;
575 wxFAIL_MSG(wxT("Unexpected menu event kind"));
581 wxMenuEvent
wxevent(type
, cmd
, menu
);
582 wxevent
.SetEventObject(menu
);
584 wxEvtHandler
* handler
= menu
->GetEventHandler();
585 if (handler
&& handler
->ProcessEvent(wxevent
))
591 wxWindow
*win
= menu
->GetInvokingWindow();
593 win
->GetEventHandler()->ProcessEvent(wxevent
);
598 return eventNotHandledErr
;
601 static pascal OSStatus
602 wxMacAppCommandEventHandler( EventHandlerCallRef
WXUNUSED(handler
) ,
604 void *WXUNUSED(data
) )
606 OSStatus result
= eventNotHandledErr
;
610 wxMacCarbonEvent
cEvent( event
) ;
611 cEvent
.GetParameter
<HICommand
>(kEventParamDirectObject
,typeHICommand
,&command
) ;
613 wxMenuItem
* item
= NULL
;
614 wxMenu
* itemMenu
= wxFindMenuFromMacCommand( command
, item
) ;
615 int id
= wxMacCommandToId( command
.commandID
) ;
619 wxASSERT( itemMenu
!= NULL
) ;
621 switch ( cEvent
.GetKind() )
623 case kEventProcessCommand
:
625 if (item
->IsCheckable())
626 item
->Check( !item
->IsChecked() ) ;
628 if ( itemMenu
->SendEvent( id
, item
->IsCheckable() ? item
->IsChecked() : -1 ) )
633 case kEventCommandUpdateStatus
:
635 wxUpdateUIEvent
event(id
);
636 event
.SetEventObject( itemMenu
);
638 bool processed
= false;
640 // Try the menu's event handler
642 wxEvtHandler
*handler
= itemMenu
->GetEventHandler();
644 processed
= handler
->ProcessEvent(event
);
647 // Try the window the menu was popped up from
648 // (and up through the hierarchy)
651 const wxMenuBase
*menu
= itemMenu
;
654 wxWindow
*win
= menu
->GetInvokingWindow();
657 processed
= win
->GetEventHandler()->ProcessEvent(event
);
661 menu
= menu
->GetParent();
667 // if anything changed, update the changed attribute
668 if (event
.GetSetText())
669 itemMenu
->SetLabel(id
, event
.GetText());
670 if (event
.GetSetChecked())
671 itemMenu
->Check(id
, event
.GetChecked());
672 if (event
.GetSetEnabled())
673 itemMenu
->Enable(id
, event
.GetEnabled());
687 static pascal OSStatus
688 wxMacAppApplicationEventHandler( EventHandlerCallRef
WXUNUSED(handler
) ,
690 void *WXUNUSED(data
) )
692 OSStatus result
= eventNotHandledErr
;
693 switch ( GetEventKind( event
) )
695 case kEventAppActivated
:
697 wxTheApp
->SetActive( true , NULL
) ;
701 case kEventAppDeactivated
:
703 wxTheApp
->SetActive( false , NULL
) ;
714 pascal OSStatus
wxMacAppEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
716 EventRef formerEvent
= (EventRef
) wxTheApp
->MacGetCurrentEvent() ;
717 EventHandlerCallRef formerEventHandlerCallRef
= (EventHandlerCallRef
) wxTheApp
->MacGetCurrentEventHandlerCallRef() ;
718 wxTheApp
->MacSetCurrentEvent( event
, handler
) ;
720 OSStatus result
= eventNotHandledErr
;
721 switch ( GetEventClass( event
) )
723 case kEventClassCommand
:
724 result
= wxMacAppCommandEventHandler( handler
, event
, data
) ;
727 case kEventClassApplication
:
728 result
= wxMacAppApplicationEventHandler( handler
, event
, data
) ;
731 case kEventClassMenu
:
732 result
= wxMacAppMenuEventHandler( handler
, event
, data
) ;
735 case kEventClassMouse
:
737 wxMacCarbonEvent
cEvent( event
) ;
740 Point screenMouseLocation
= cEvent
.GetParameter
<Point
>(kEventParamMouseLocation
) ;
741 ::FindWindow(screenMouseLocation
, &window
);
742 // only send this event in case it had not already been sent to a tlw, as we get
743 // double events otherwise (in case event.skip) was called
744 if ( window
== NULL
)
745 result
= wxMacTopLevelMouseEventHandler( handler
, event
, NULL
) ;
749 case kEventClassAppleEvent
:
753 wxMacConvertEventToRecord( event
, &rec
) ;
754 result
= AEProcessAppleEvent( &rec
) ;
762 wxTheApp
->MacSetCurrentEvent( formerEvent
, formerEventHandlerCallRef
) ;
767 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler
)
772 wxMacAssertOutputHandler(OSType
WXUNUSED(componentSignature
),
773 UInt32
WXUNUSED(options
),
774 const char *assertionString
,
775 const char *exceptionLabelString
,
776 const char *errorString
,
777 const char *fileName
,
780 ConstStr255Param
WXUNUSED(outputMsg
))
782 // flow into assert handling
783 wxString fileNameStr
;
784 wxString assertionStr
;
785 wxString exceptionStr
;
789 fileNameStr
= wxString(fileName
, wxConvLocal
);
790 assertionStr
= wxString(assertionString
, wxConvLocal
);
791 exceptionStr
= wxString((exceptionLabelString
!=0) ? exceptionLabelString
: "", wxConvLocal
) ;
792 errorStr
= wxString((errorString
!=0) ? errorString
: "", wxConvLocal
) ;
794 fileNameStr
= fileName
;
795 assertionStr
= assertionString
;
796 exceptionStr
= (exceptionLabelString
!=0) ? exceptionLabelString
: "" ;
797 errorStr
= (errorString
!=0) ? errorString
: "" ;
802 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
803 assertionStr
.c_str() ,
804 exceptionStr
.c_str() ,
806 fileNameStr
.c_str(), lineNumber
,
810 wxOnAssert(fileNameStr
, lineNumber
, assertionStr
,
811 wxString::Format( wxT("%s %s value (%p)") , exceptionStr
, errorStr
, value
) ) ;
818 extern "C" void macPostedEventCallback(void *WXUNUSED(unused
))
820 wxTheApp
->ProcessPendingEvents();
824 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
829 InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler
) );
832 UMAInitToolbox( 4, sm_isEmbedded
) ;
833 SetEventMask( everyEvent
) ;
834 UMAShowWatchCursor() ;
837 # if __option(profile)
838 ProfilerInit( collectDetailed
, bestTimeBase
, 40000 , 50 ) ;
843 // now avoid exceptions thrown for new (bad_alloc)
844 // FIXME CS for some changes outside wxMac does not compile anymore
846 std::__throws_bad_alloc
= 0 ;
851 // Mac OS X passes a process serial number command line argument when
852 // the application is launched from the Finder. This argument must be
853 // removed from the command line arguments before being handled by the
854 // application (otherwise applications would need to handle it)
857 static const wxChar
*ARG_PSN
= _T("-psn_");
858 if ( wxStrncmp(argv
[1], ARG_PSN
, wxStrlen(ARG_PSN
)) == 0 )
860 // remove this argument
862 memmove(argv
+ 1, argv
+ 2, argc
* sizeof(char *));
866 if ( !wxAppBase::Initialize(argc
, argv
) )
870 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
873 #if TARGET_API_MAC_OSX
874 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
875 wxString startupCwd
= wxGetCwd() ;
876 if ( startupCwd
== wxT("/") || startupCwd
.Right(15) == wxT("/Contents/MacOS") )
878 CFURLRef url
= CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
879 CFURLRef urlParent
= CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault
, url
) ;
881 CFStringRef path
= CFURLCopyFileSystemPath ( urlParent
, kCFURLPOSIXPathStyle
) ;
882 CFRelease( urlParent
) ;
883 wxString cwd
= wxMacCFStringHolder(path
).AsString(wxLocale::GetSystemEncoding());
884 wxSetWorkingDirectory( cwd
) ;
888 wxMacCreateNotifierTable() ;
891 /* connect posted events to common-mode run loop so that wxPostEvent events
892 are handled even while we're in the menu or on a scrollbar */
893 CFRunLoopSourceContext event_posted_context
= {0};
894 event_posted_context
.perform
= macPostedEventCallback
;
895 m_macEventPosted
= CFRunLoopSourceCreate(NULL
,0,&event_posted_context
);
896 CFRunLoopAddSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
897 // run loop takes ownership
898 CFRelease(m_macEventPosted
);
901 UMAShowArrowCursor() ;
906 AEEventHandlerUPP sODocHandler
= NULL
;
907 AEEventHandlerUPP sGURLHandler
= NULL
;
908 AEEventHandlerUPP sOAppHandler
= NULL
;
909 AEEventHandlerUPP sPDocHandler
= NULL
;
910 AEEventHandlerUPP sRAppHandler
= NULL
;
911 AEEventHandlerUPP sQuitHandler
= NULL
;
913 bool wxApp::OnInitGui()
915 if ( !wxAppBase::OnInitGui() )
918 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
922 InstallApplicationEventHandler(
923 GetwxMacAppEventHandlerUPP(),
924 GetEventTypeCount(eventList
), eventList
, wxTheApp
, (EventHandlerRef
*)&(wxTheApp
->m_macEventHandler
));
929 sODocHandler
= NewAEEventHandlerUPP(AEHandleODoc
) ;
930 sGURLHandler
= NewAEEventHandlerUPP(AEHandleGURL
) ;
931 sOAppHandler
= NewAEEventHandlerUPP(AEHandleOApp
) ;
932 sPDocHandler
= NewAEEventHandlerUPP(AEHandlePDoc
) ;
933 sRAppHandler
= NewAEEventHandlerUPP(AEHandleRApp
) ;
934 sQuitHandler
= NewAEEventHandlerUPP(AEHandleQuit
) ;
936 AEInstallEventHandler( kCoreEventClass
, kAEOpenDocuments
,
937 sODocHandler
, 0 , FALSE
) ;
938 AEInstallEventHandler( kInternetEventClass
, kAEGetURL
,
939 sGURLHandler
, 0 , FALSE
) ;
940 AEInstallEventHandler( kCoreEventClass
, kAEOpenApplication
,
941 sOAppHandler
, 0 , FALSE
) ;
942 AEInstallEventHandler( kCoreEventClass
, kAEPrintDocuments
,
943 sPDocHandler
, 0 , FALSE
) ;
944 AEInstallEventHandler( kCoreEventClass
, kAEReopenApplication
,
945 sRAppHandler
, 0 , FALSE
) ;
946 AEInstallEventHandler( kCoreEventClass
, kAEQuitApplication
,
947 sQuitHandler
, 0 , FALSE
) ;
953 void wxApp::CleanUp()
956 wxToolTip::RemoveToolTips() ;
960 if (m_macEventPosted
)
962 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
963 m_macEventPosted
= NULL
;
967 // One last chance for pending objects to be cleaned up
968 wxTheApp
->DeletePendingObjects();
970 wxMacDestroyNotifierTable() ;
973 # if __option(profile)
974 ProfilerDump( (StringPtr
)"\papp.prof" ) ;
979 UMACleanupToolbox() ;
982 RemoveEventHandler( (EventHandlerRef
)(wxTheApp
->m_macEventHandler
) );
986 AERemoveEventHandler( kCoreEventClass
, kAEOpenDocuments
,
987 sODocHandler
, FALSE
) ;
988 AERemoveEventHandler( kInternetEventClass
, kAEGetURL
,
989 sGURLHandler
, FALSE
) ;
990 AERemoveEventHandler( kCoreEventClass
, kAEOpenApplication
,
991 sOAppHandler
, FALSE
) ;
992 AERemoveEventHandler( kCoreEventClass
, kAEPrintDocuments
,
993 sPDocHandler
, FALSE
) ;
994 AERemoveEventHandler( kCoreEventClass
, kAEReopenApplication
,
995 sRAppHandler
, FALSE
) ;
996 AERemoveEventHandler( kCoreEventClass
, kAEQuitApplication
,
997 sQuitHandler
, FALSE
) ;
999 DisposeAEEventHandlerUPP( sODocHandler
) ;
1000 DisposeAEEventHandlerUPP( sGURLHandler
) ;
1001 DisposeAEEventHandlerUPP( sOAppHandler
) ;
1002 DisposeAEEventHandlerUPP( sPDocHandler
) ;
1003 DisposeAEEventHandlerUPP( sRAppHandler
) ;
1004 DisposeAEEventHandlerUPP( sQuitHandler
) ;
1007 wxAppBase::CleanUp();
1010 //----------------------------------------------------------------------
1011 // misc initialization stuff
1012 //----------------------------------------------------------------------
1014 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
1016 // for shared libraries we have to manually get the correct resource
1017 // ref num upon initializing and releasing when terminating, therefore
1018 // the __wxinitialize and __wxterminate must be used
1022 void __sinit(void); // (generated by linker)
1023 pascal OSErr
__initialize(const CFragInitBlock
*theInitBlock
);
1024 pascal void __terminate(void);
1027 pascal OSErr
__wxinitialize(const CFragInitBlock
*theInitBlock
)
1029 return __initialize( theInitBlock
) ;
1032 pascal void __wxterminate(void)
1037 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
1039 bool wxMacConvertEventToRecord( EventRef event
, EventRecord
*rec
)
1041 OSStatus err
= noErr
;
1042 bool converted
= ConvertEventRefToEventRecord( event
, rec
) ;
1046 switch ( GetEventClass( event
) )
1048 case kEventClassKeyboard
:
1051 switch ( GetEventKind(event
) )
1053 case kEventRawKeyDown
:
1054 rec
->what
= keyDown
;
1057 case kEventRawKeyRepeat
:
1058 rec
->what
= autoKey
;
1061 case kEventRawKeyUp
:
1065 case kEventRawKeyModifiersChanged
:
1066 rec
->what
= nullEvent
;
1077 unsigned char charCode
;
1080 GetMouse( &rec
->where
) ;
1082 err
= GetEventParameter(event
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1083 err
= GetEventParameter(event
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1084 err
= GetEventParameter(event
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1085 rec
->modifiers
= modifiers
;
1086 rec
->message
= (keyCode
<< 8 ) + charCode
;
1091 case kEventClassTextInput
:
1093 switch ( GetEventKind( event
) )
1095 case kEventTextInputUnicodeForKeyEvent
:
1098 err
= GetEventParameter(
1099 event
, kEventParamTextInputSendKeyboardEvent
, typeEventRef
, NULL
,
1100 sizeof(rawEvent
), NULL
, &rawEvent
) ;
1104 UInt32 keyCode
, modifiers
;
1105 unsigned char charCode
;
1108 GetMouse( &rec
->where
) ;
1110 rec
->what
= keyDown
;
1111 err
= GetEventParameter(rawEvent
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1112 err
= GetEventParameter(rawEvent
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1113 err
= GetEventParameter(rawEvent
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1114 rec
->modifiers
= modifiers
;
1115 rec
->message
= (keyCode
<< 8 ) + charCode
;
1136 m_printMode
= wxPRINT_WINDOWS
;
1138 m_macCurrentEvent
= NULL
;
1139 m_macCurrentEventHandlerCallRef
= NULL
;
1141 #ifdef __WXMAC_OSX__
1142 m_macEventPosted
= NULL
;
1146 void wxApp::OnIdle(wxIdleEvent
& WXUNUSED(event
))
1148 wxMacProcessNotifierEvents();
1150 if (!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1151 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1154 void wxApp::WakeUpIdle()
1156 #ifdef __WXMAC_OSX__
1157 if (m_macEventPosted
)
1159 CFRunLoopSourceSignal(m_macEventPosted
);
1166 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1169 GetTopWindow()->Close(true);
1172 // Default behaviour: close the application with prompts. The
1173 // user can veto the close, and therefore the end session.
1174 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1178 if (!GetTopWindow()->Close(!event
.CanVeto()))
1183 extern "C" void wxCYield() ;
1189 // Yield to other processes
1191 bool wxApp::Yield(bool onlyIfNeeded
)
1195 if ( !onlyIfNeeded
)
1197 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1204 // Yielding from a non-gui thread needs to bail out, otherwise we end up
1205 // possibly sending events in the thread too.
1206 if ( !wxThread::IsMain() )
1210 #endif // wxUSE_THREADS
1214 // by definition yield should handle all non-processed events
1218 OSStatus status
= noErr
;
1220 while ( status
== noErr
)
1222 s_inReceiveEvent
= true ;
1223 status
= ReceiveNextEvent(0, NULL
,kEventDurationNoWait
,true,&theEvent
) ;
1224 s_inReceiveEvent
= false ;
1226 if ( status
== eventLoopTimedOutErr
)
1228 // make sure next time the event loop will trigger idle events
1229 sleepTime
= kEventDurationNoWait
;
1231 else if ( status
== eventLoopQuitErr
)
1233 // according to QA1061 this may also occur when a WakeUp Process
1238 MacHandleOneEvent( theEvent
) ;
1239 ReleaseEvent(theEvent
);
1243 wxMacProcessNotifierAndPendingEvents() ;
1249 void wxApp::MacDoOneEvent()
1253 s_inReceiveEvent
= true ;
1254 OSStatus status
= ReceiveNextEvent(0, NULL
, sleepTime
, true, &theEvent
) ;
1255 s_inReceiveEvent
= false ;
1259 case eventLoopTimedOutErr
:
1260 if ( wxTheApp
->ProcessIdle() )
1261 sleepTime
= kEventDurationNoWait
;
1263 sleepTime
= kEventDurationSecond
;
1266 case eventLoopQuitErr
:
1267 // according to QA1061 this may also occur
1268 // when a WakeUp Process is executed
1272 MacHandleOneEvent( theEvent
) ;
1273 ReleaseEvent( theEvent
);
1274 sleepTime
= kEventDurationNoWait
;
1279 DeletePendingObjects() ;
1280 wxMacProcessNotifierAndPendingEvents() ;
1284 void wxApp::MacHandleUnhandledEvent( WXEVENTREF
WXUNUSED(evr
) )
1286 // Override to process unhandled events as you please
1289 CFMutableArrayRef
GetAutoReleaseArray()
1291 static CFMutableArrayRef array
= 0;
1293 array
= CFArrayCreateMutable(kCFAllocatorDefault
,0,&kCFTypeArrayCallBacks
);
1297 void wxApp::MacHandleOneEvent( WXEVENTREF evr
)
1299 EventTargetRef theTarget
;
1300 theTarget
= GetEventDispatcherTarget();
1301 m_macCurrentEvent
= evr
;
1303 OSStatus status
= SendEventToEventTarget((EventRef
) evr
, theTarget
);
1304 if (status
== eventNotHandledErr
)
1305 MacHandleUnhandledEvent(evr
);
1307 wxMacProcessNotifierAndPendingEvents() ;
1310 wxMutexGuiLeaveOrEnter();
1311 #endif // wxUSE_THREADS
1313 CFArrayRemoveAllValues( GetAutoReleaseArray() );
1316 void wxApp::MacAddToAutorelease( void* cfrefobj
)
1318 CFArrayAppendValue( GetAutoReleaseArray(), cfrefobj
);
1321 long wxMacTranslateKey(unsigned char key
, unsigned char code
)
1326 case kHomeCharCode
:
1330 case kEnterCharCode
:
1331 retval
= WXK_RETURN
;
1337 case kHelpCharCode
:
1341 case kBackspaceCharCode
:
1349 case kPageUpCharCode
:
1350 retval
= WXK_PAGEUP
;
1353 case kPageDownCharCode
:
1354 retval
= WXK_PAGEDOWN
;
1357 case kReturnCharCode
:
1358 retval
= WXK_RETURN
;
1361 case kFunctionKeyCharCode
:
1431 case kEscapeCharCode
:
1432 retval
= WXK_ESCAPE
;
1435 case kLeftArrowCharCode
:
1439 case kRightArrowCharCode
:
1440 retval
= WXK_RIGHT
;
1443 case kUpArrowCharCode
:
1447 case kDownArrowCharCode
:
1451 case kDeleteCharCode
:
1452 retval
= WXK_DELETE
;
1462 int wxMacKeyCodeToModifier(wxKeyCode key
)
1488 bool wxGetKeyState(wxKeyCode key
) //virtual key code if < 10.2.x, else see below
1490 wxASSERT_MSG(key
!= WXK_LBUTTON
&& key
!= WXK_RBUTTON
&& key
!=
1491 WXK_MBUTTON
, wxT("can't use wxGetKeyState() for mouse buttons"));
1493 //if OS X > 10.2 (i.e. 10.2.x)
1494 //a known apple bug prevents the system from determining led
1495 //states with GetKeys... can only determine caps lock led
1496 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key
));
1498 // KeyMapByteArray keymap;
1499 // GetKeys((BigEndianLong*)keymap);
1500 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1505 wxMouseState
wxGetMouseState()
1509 wxPoint pt
= wxGetMousePosition();
1513 #if TARGET_API_MAC_OSX
1514 UInt32 buttons
= GetCurrentButtonState();
1515 ms
.SetLeftDown( (buttons
& 0x01) != 0 );
1516 ms
.SetMiddleDown( (buttons
& 0x04) != 0 );
1517 ms
.SetRightDown( (buttons
& 0x02) != 0 );
1519 ms
.SetLeftDown( Button() );
1520 ms
.SetMiddleDown( 0 );
1521 ms
.SetRightDown( 0 );
1524 UInt32 modifiers
= GetCurrentKeyModifiers();
1525 ms
.SetControlDown(modifiers
& controlKey
);
1526 ms
.SetShiftDown(modifiers
& shiftKey
);
1527 ms
.SetAltDown(modifiers
& optionKey
);
1528 ms
.SetMetaDown(modifiers
& cmdKey
);
1533 // TODO : once the new key/char handling is tested, move all the code to wxWindow
1535 bool wxApp::MacSendKeyDownEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1541 wxKeyEvent
event(wxEVT_KEY_DOWN
) ;
1542 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1544 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1545 if ( handled
&& event
.GetSkipped() )
1551 wxWindow
*ancestor
= focus
;
1554 int command
= ancestor
->GetAcceleratorTable()->GetCommand( event
);
1557 wxEvtHandler
* const handler
= ancestor
->GetEventHandler();
1559 wxCommandEvent
command_event( wxEVT_COMMAND_MENU_SELECTED
, command
);
1560 handled
= handler
->ProcessEvent( command_event
);
1564 // accelerators can also be used with buttons, try them too
1565 command_event
.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED
);
1566 handled
= handler
->ProcessEvent( command_event
);
1572 if (ancestor
->IsTopLevel())
1575 ancestor
= ancestor
->GetParent();
1578 #endif // wxUSE_ACCEL
1583 bool wxApp::MacSendKeyUpEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1589 wxKeyEvent
event( wxEVT_KEY_UP
) ;
1590 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1591 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1596 bool wxApp::MacSendCharEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1601 wxKeyEvent
event(wxEVT_CHAR
) ;
1602 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1603 long keyval
= event
.m_keyCode
;
1605 bool handled
= false ;
1607 wxTopLevelWindowMac
*tlw
= focus
->MacGetTopLevelWindow() ;
1611 event
.SetEventType( wxEVT_CHAR_HOOK
);
1612 handled
= tlw
->GetEventHandler()->ProcessEvent( event
);
1613 if ( handled
&& event
.GetSkipped() )
1619 event
.SetEventType( wxEVT_CHAR
);
1620 event
.Skip( false ) ;
1621 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1624 if ( !handled
&& (keyval
== WXK_TAB
) )
1626 wxWindow
* iter
= focus
->GetParent() ;
1627 while ( iter
&& !handled
)
1629 if ( iter
->HasFlag( wxTAB_TRAVERSAL
) )
1631 wxNavigationKeyEvent new_event
;
1632 new_event
.SetEventObject( focus
);
1633 new_event
.SetDirection( !event
.ShiftDown() );
1634 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1635 new_event
.SetWindowChange( event
.ControlDown() );
1636 new_event
.SetCurrentFocus( focus
);
1637 handled
= focus
->GetParent()->GetEventHandler()->ProcessEvent( new_event
);
1638 if ( handled
&& new_event
.GetSkipped() )
1642 iter
= iter
->GetParent() ;
1646 // backdoor handler for default return and command escape
1647 if ( !handled
&& (!focus
->IsKindOf(CLASSINFO(wxControl
) ) || !focus
->MacCanFocus() ) )
1649 // if window is not having a focus still testing for default enter or cancel
1650 // TODO: add the UMA version for ActiveNonFloatingWindow
1651 wxWindow
* focus
= wxFindWinFromMacWindow( FrontWindow() ) ;
1654 if ( keyval
== WXK_RETURN
|| keyval
== WXK_NUMPAD_ENTER
)
1656 wxTopLevelWindow
*tlw
= wxDynamicCast(wxGetTopLevelParent(focus
), wxTopLevelWindow
);
1657 if ( tlw
&& tlw
->GetDefaultItem() )
1659 wxButton
*def
= wxDynamicCast(tlw
->GetDefaultItem(), wxButton
);
1660 if ( def
&& def
->IsEnabled() )
1662 wxCommandEvent
event(wxEVT_COMMAND_BUTTON_CLICKED
, def
->GetId() );
1663 event
.SetEventObject(def
);
1664 def
->Command(event
);
1670 else if (keyval
== WXK_ESCAPE
|| (keyval
== '.' && modifiers
& cmdKey
) )
1672 // generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs)
1673 wxCommandEvent
new_event(wxEVT_COMMAND_BUTTON_CLICKED
,wxID_CANCEL
);
1674 new_event
.SetEventObject( focus
);
1675 handled
= focus
->GetEventHandler()->ProcessEvent( new_event
);
1682 // This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
1683 void wxApp::MacCreateKeyEvent( wxKeyEvent
& event
, wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1685 short keycode
, keychar
;
1687 keychar
= short(keymessage
& charCodeMask
);
1688 keycode
= short(keymessage
& keyCodeMask
) >> 8 ;
1689 if ( !(event
.GetEventType() == wxEVT_CHAR
) && (modifiers
& (controlKey
| shiftKey
| optionKey
) ) )
1691 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1692 // and look at the character after
1694 UInt32 keyInfo
= KeyTranslate((Ptr
)GetScriptManagerVariable(smKCHRCache
), ( modifiers
& (~(controlKey
| shiftKey
| optionKey
))) | keycode
, &state
);
1695 keychar
= short(keyInfo
& charCodeMask
);
1698 long keyval
= wxMacTranslateKey(keychar
, keycode
) ;
1699 if ( keyval
== keychar
&& ( event
.GetEventType() == wxEVT_KEY_UP
|| event
.GetEventType() == wxEVT_KEY_DOWN
) )
1700 keyval
= wxToupper( keyval
) ;
1702 // Check for NUMPAD keys
1703 if (keyval
>= '0' && keyval
<= '9' && keycode
>= 82 && keycode
<= 92)
1705 keyval
= (keyval
- '0') + WXK_NUMPAD0
;
1707 else if (keycode
>= 67 && keycode
<= 81)
1712 keyval
= WXK_NUMPAD_ENTER
;
1716 keyval
= WXK_NUMPAD_EQUAL
;
1720 keyval
= WXK_NUMPAD_MULTIPLY
;
1724 keyval
= WXK_NUMPAD_DIVIDE
;
1728 keyval
= WXK_NUMPAD_SUBTRACT
;
1732 keyval
= WXK_NUMPAD_ADD
;
1736 keyval
= WXK_NUMPAD_DECIMAL
;
1744 event
.m_shiftDown
= modifiers
& shiftKey
;
1745 event
.m_controlDown
= modifiers
& controlKey
;
1746 event
.m_altDown
= modifiers
& optionKey
;
1747 event
.m_metaDown
= modifiers
& cmdKey
;
1748 event
.m_keyCode
= keyval
;
1750 event
.m_uniChar
= uniChar
;
1753 event
.m_rawCode
= keymessage
;
1754 event
.m_rawFlags
= modifiers
;
1757 event
.SetTimestamp(when
);
1758 event
.SetEventObject(focus
);