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 // AEODoc Calls MacOpenFile on each of the files passed
138 short wxApp::MacHandleAEODoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
142 DescType returnedType
;
148 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
152 err
= AECountItems(&docList
, &itemsInList
);
156 ProcessSerialNumber PSN
;
157 PSN
.highLongOfPSN
= 0 ;
158 PSN
.lowLongOfPSN
= kCurrentProcess
;
159 SetFrontProcess( &PSN
) ;
164 for (i
= 1; i
<= itemsInList
; i
++)
167 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
168 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
169 fName
= wxMacFSRefToPath( &theRef
) ;
177 // AEPDoc Calls MacPrintFile on each of the files passed
179 short wxApp::MacHandleAEPDoc(const WXEVENTREF event
, WXEVENTREF
WXUNUSED(reply
))
183 DescType returnedType
;
189 err
= AEGetParamDesc((AppleEvent
*)event
, keyDirectObject
, typeAEList
,&docList
);
193 err
= AECountItems(&docList
, &itemsInList
);
197 ProcessSerialNumber PSN
;
198 PSN
.highLongOfPSN
= 0 ;
199 PSN
.lowLongOfPSN
= kCurrentProcess
;
200 SetFrontProcess( &PSN
) ;
205 for (i
= 1; i
<= itemsInList
; i
++)
208 &docList
, i
, typeFSRef
, &keywd
, &returnedType
,
209 (Ptr
)&theRef
, sizeof(theRef
), &actualSize
);
210 fName
= wxMacFSRefToPath( &theRef
) ;
218 // AEOApp calls MacNewFile
220 short wxApp::MacHandleAEOApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
226 // AEQuit attempts to quit the application
228 short wxApp::MacHandleAEQuit(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
230 wxWindow
* win
= GetTopWindow() ;
233 wxCommandEvent
exitEvent(wxEVT_COMMAND_MENU_SELECTED
, s_macExitMenuItemId
);
234 if (!win
->ProcessEvent(exitEvent
))
245 // AEROApp calls MacReopenApp
247 short wxApp::MacHandleAERApp(const WXEVENTREF
WXUNUSED(event
) , WXEVENTREF
WXUNUSED(reply
))
254 //----------------------------------------------------------------------
255 // Support Routines linking the Mac...File Calls to the Document Manager
256 //----------------------------------------------------------------------
258 void wxApp::MacOpenFile(const wxString
& fileName
)
260 #if wxUSE_DOC_VIEW_ARCHITECTURE
261 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
263 dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
268 void wxApp::MacPrintFile(const wxString
& fileName
)
270 #if wxUSE_DOC_VIEW_ARCHITECTURE
272 #if wxUSE_PRINTING_ARCHITECTURE
273 wxDocManager
* dm
= wxDocManager::GetDocumentManager() ;
276 wxDocument
*doc
= dm
->CreateDocument(fileName
, wxDOC_SILENT
) ;
279 wxView
* view
= doc
->GetFirstView() ;
282 wxPrintout
*printout
= view
->OnCreatePrintout();
286 printer
.Print(view
->GetFrame(), printout
, true);
293 doc
->DeleteAllViews();
294 dm
->RemoveDocument(doc
) ;
305 void wxApp::MacNewFile()
309 void wxApp::MacReopenApp()
312 // if there is no open window -> create a new one
313 // if all windows are hidden -> show the first
314 // if some windows are not hidden -> do nothing
316 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetFirst();
323 wxTopLevelWindow
* firstIconized
= NULL
;
326 wxTopLevelWindow
* win
= (wxTopLevelWindow
*) node
->GetData();
327 if ( !win
->IsIconized() )
329 firstIconized
= NULL
;
334 if ( firstIconized
== NULL
)
335 firstIconized
= win
;
338 node
= node
->GetNext();
342 firstIconized
->Iconize( false ) ;
346 //----------------------------------------------------------------------
347 // Macintosh CommandID support - converting between native and wx IDs
348 //----------------------------------------------------------------------
350 // if no native match they just return the passed-in id
358 IdPair gCommandIds
[] =
360 { kHICommandCut
, wxID_CUT
} ,
361 { kHICommandCopy
, wxID_COPY
} ,
362 { kHICommandPaste
, wxID_PASTE
} ,
363 { kHICommandSelectAll
, wxID_SELECTALL
} ,
364 { kHICommandClear
, wxID_CLEAR
} ,
365 { kHICommandUndo
, wxID_UNDO
} ,
366 { kHICommandRedo
, wxID_REDO
} ,
369 int wxMacCommandToId( UInt32 macCommandId
)
373 switch ( macCommandId
)
375 case kHICommandPreferences
:
376 wxid
= wxApp::s_macPreferencesMenuItemId
;
379 case kHICommandQuit
:
380 wxid
= wxApp::s_macExitMenuItemId
;
383 case kHICommandAbout
:
384 wxid
= wxApp::s_macAboutMenuItemId
;
389 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
391 if ( gCommandIds
[i
].macId
== macCommandId
)
393 wxid
= gCommandIds
[i
].wxId
;
402 wxid
= (int) macCommandId
;
407 UInt32
wxIdToMacCommand( int wxId
)
411 if ( wxId
== wxApp::s_macPreferencesMenuItemId
)
412 macId
= kHICommandPreferences
;
413 else if (wxId
== wxApp::s_macExitMenuItemId
)
414 macId
= kHICommandQuit
;
415 else if (wxId
== wxApp::s_macAboutMenuItemId
)
416 macId
= kHICommandAbout
;
419 for ( size_t i
= 0 ; i
< WXSIZEOF(gCommandIds
) ; ++i
)
421 if ( gCommandIds
[i
].wxId
== wxId
)
423 macId
= gCommandIds
[i
].macId
;
435 wxMenu
* wxFindMenuFromMacCommand( const HICommand
&command
, wxMenuItem
* &item
)
437 wxMenu
* itemMenu
= NULL
;
440 // for 'standard' commands which don't have a wx-menu
441 if ( command
.commandID
== kHICommandPreferences
|| command
.commandID
== kHICommandQuit
|| command
.commandID
== kHICommandAbout
)
443 id
= wxMacCommandToId( command
.commandID
) ;
445 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
447 item
= mbar
->FindItem( id
, &itemMenu
) ;
449 else if ( command
.commandID
!= 0 && command
.menu
.menuRef
!= 0 && command
.menu
.menuItemIndex
!= 0 )
451 id
= wxMacCommandToId( command
.commandID
) ;
452 // make sure it is one of our own menus, or of the 'synthetic' apple and help menus , otherwise don't touch
453 MenuItemIndex firstUserHelpMenuItem
;
454 static MenuHandle helpMenuHandle
= NULL
;
455 if ( helpMenuHandle
== NULL
)
457 if ( UMAGetHelpMenuDontCreate( &helpMenuHandle
, &firstUserHelpMenuItem
) != noErr
)
458 helpMenuHandle
= NULL
;
461 // is it part of the application or the Help menu, then look for the id directly
462 if ( ( GetMenuHandle( kwxMacAppleMenuId
) != NULL
&& command
.menu
.menuRef
== GetMenuHandle( kwxMacAppleMenuId
) ) ||
463 ( helpMenuHandle
!= NULL
&& command
.menu
.menuRef
== helpMenuHandle
) )
465 wxMenuBar
* mbar
= wxMenuBar::MacGetInstalledMenuBar() ;
467 item
= mbar
->FindItem( id
, &itemMenu
) ;
473 GetMenuItemRefCon( command
.menu
.menuRef
, command
.menu
.menuItemIndex
, &refCon
) ;
474 itemMenu
= wxFindMenuFromMacMenu( command
.menu
.menuRef
) ;
475 if ( itemMenu
!= NULL
)
476 item
= (wxMenuItem
*) refCon
;
483 //----------------------------------------------------------------------
484 // Carbon Event Handler
485 //----------------------------------------------------------------------
487 static const EventTypeSpec eventList
[] =
489 { kEventClassCommand
, kEventProcessCommand
} ,
490 { kEventClassCommand
, kEventCommandUpdateStatus
} ,
492 { kEventClassMenu
, kEventMenuOpening
},
493 { kEventClassMenu
, kEventMenuClosed
},
494 { kEventClassMenu
, kEventMenuTargetItem
},
496 { kEventClassApplication
, kEventAppActivated
} ,
497 { kEventClassApplication
, kEventAppDeactivated
} ,
498 // handling the quit event is not recommended by apple
499 // rather using the quit apple event - which we do
501 { kEventClassAppleEvent
, kEventAppleEvent
} ,
503 { kEventClassMouse
, kEventMouseDown
} ,
504 { kEventClassMouse
, kEventMouseMoved
} ,
505 { kEventClassMouse
, kEventMouseUp
} ,
506 { kEventClassMouse
, kEventMouseDragged
} ,
510 static pascal OSStatus
511 wxMacAppMenuEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
513 wxMacCarbonEvent
cEvent( event
) ;
514 MenuRef menuRef
= cEvent
.GetParameter
<MenuRef
>(kEventParamDirectObject
) ;
515 wxMenu
* menu
= wxFindMenuFromMacMenu( menuRef
) ;
521 switch (GetEventKind(event
))
523 case kEventMenuOpening
:
524 type
= wxEVT_MENU_OPEN
;
527 case kEventMenuClosed
:
528 type
= wxEVT_MENU_CLOSE
;
531 case kEventMenuTargetItem
:
532 cmd
= cEvent
.GetParameter
<MenuCommand
>(kEventParamMenuCommand
,typeMenuCommand
) ;
534 type
= wxEVT_MENU_HIGHLIGHT
;
538 wxFAIL_MSG(wxT("Unexpected menu event kind"));
544 wxMenuEvent
wxevent(type
, cmd
, menu
);
545 wxevent
.SetEventObject(menu
);
547 wxEvtHandler
* handler
= menu
->GetEventHandler();
548 if (handler
&& handler
->ProcessEvent(wxevent
))
554 wxWindow
*win
= menu
->GetInvokingWindow();
556 win
->GetEventHandler()->ProcessEvent(wxevent
);
561 return eventNotHandledErr
;
564 static pascal OSStatus
wxMacAppCommandEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
566 OSStatus result
= eventNotHandledErr
;
570 wxMacCarbonEvent
cEvent( event
) ;
571 cEvent
.GetParameter
<HICommand
>(kEventParamDirectObject
,typeHICommand
,&command
) ;
573 wxMenuItem
* item
= NULL
;
574 wxMenu
* itemMenu
= wxFindMenuFromMacCommand( command
, item
) ;
575 int id
= wxMacCommandToId( command
.commandID
) ;
579 wxASSERT( itemMenu
!= NULL
) ;
581 switch ( cEvent
.GetKind() )
583 case kEventProcessCommand
:
585 if (item
->IsCheckable())
586 item
->Check( !item
->IsChecked() ) ;
588 if ( itemMenu
->SendEvent( id
, item
->IsCheckable() ? item
->IsChecked() : -1 ) )
593 case kEventCommandUpdateStatus
:
595 wxUpdateUIEvent
event(id
);
596 event
.SetEventObject( itemMenu
);
598 bool processed
= false;
600 // Try the menu's event handler
602 wxEvtHandler
*handler
= itemMenu
->GetEventHandler();
604 processed
= handler
->ProcessEvent(event
);
607 // Try the window the menu was popped up from
608 // (and up through the hierarchy)
611 const wxMenuBase
*menu
= itemMenu
;
614 wxWindow
*win
= menu
->GetInvokingWindow();
617 processed
= win
->GetEventHandler()->ProcessEvent(event
);
621 menu
= menu
->GetParent();
627 // if anything changed, update the changed attribute
628 if (event
.GetSetText())
629 itemMenu
->SetLabel(id
, event
.GetText());
630 if (event
.GetSetChecked())
631 itemMenu
->Check(id
, event
.GetChecked());
632 if (event
.GetSetEnabled())
633 itemMenu
->Enable(id
, event
.GetEnabled());
647 static pascal OSStatus
wxMacAppApplicationEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
649 OSStatus result
= eventNotHandledErr
;
650 switch ( GetEventKind( event
) )
652 case kEventAppActivated
:
654 wxTheApp
->SetActive( true , NULL
) ;
658 case kEventAppDeactivated
:
660 wxTheApp
->SetActive( false , NULL
) ;
671 pascal OSStatus
wxMacAppEventHandler( EventHandlerCallRef handler
, EventRef event
, void *data
)
673 EventRef formerEvent
= (EventRef
) wxTheApp
->MacGetCurrentEvent() ;
674 EventHandlerCallRef formerEventHandlerCallRef
= (EventHandlerCallRef
) wxTheApp
->MacGetCurrentEventHandlerCallRef() ;
675 wxTheApp
->MacSetCurrentEvent( event
, handler
) ;
677 OSStatus result
= eventNotHandledErr
;
678 switch ( GetEventClass( event
) )
680 case kEventClassCommand
:
681 result
= wxMacAppCommandEventHandler( handler
, event
, data
) ;
684 case kEventClassApplication
:
685 result
= wxMacAppApplicationEventHandler( handler
, event
, data
) ;
688 case kEventClassMenu
:
689 result
= wxMacAppMenuEventHandler( handler
, event
, data
) ;
692 case kEventClassMouse
:
694 wxMacCarbonEvent
cEvent( event
) ;
697 Point screenMouseLocation
= cEvent
.GetParameter
<Point
>(kEventParamMouseLocation
) ;
698 ::FindWindow(screenMouseLocation
, &window
);
699 // only send this event in case it had not already been sent to a tlw, as we get
700 // double events otherwise (in case event.skip) was called
701 if ( window
== NULL
)
702 result
= wxMacTopLevelMouseEventHandler( handler
, event
, NULL
) ;
706 case kEventClassAppleEvent
:
710 wxMacConvertEventToRecord( event
, &rec
) ;
711 result
= AEProcessAppleEvent( &rec
) ;
719 wxTheApp
->MacSetCurrentEvent( formerEvent
, formerEventHandlerCallRef
) ;
724 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler
)
728 pascal static void wxMacAssertOutputHandler(OSType componentSignature
, UInt32 options
,
729 const char *assertionString
, const char *exceptionLabelString
,
730 const char *errorString
, const char *fileName
, long lineNumber
, void *value
, ConstStr255Param outputMsg
)
732 // flow into assert handling
733 wxString fileNameStr
;
734 wxString assertionStr
;
735 wxString exceptionStr
;
739 fileNameStr
= wxString(fileName
, wxConvLocal
);
740 assertionStr
= wxString(assertionString
, wxConvLocal
);
741 exceptionStr
= wxString((exceptionLabelString
!=0) ? exceptionLabelString
: "", wxConvLocal
) ;
742 errorStr
= wxString((errorString
!=0) ? errorString
: "", wxConvLocal
) ;
744 fileNameStr
= fileName
;
745 assertionStr
= assertionString
;
746 exceptionStr
= (exceptionLabelString
!=0) ? exceptionLabelString
: "" ;
747 errorStr
= (errorString
!=0) ? errorString
: "" ;
752 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
753 assertionStr
.c_str() ,
754 exceptionStr
.c_str() ,
756 fileNameStr
.c_str(), lineNumber
,
760 wxOnAssert(fileNameStr
, lineNumber
, assertionStr
,
761 wxString::Format( wxT("%s %s value (%p)") , exceptionStr
, errorStr
, value
) ) ;
770 // m_macEventPosted run loop source callback:
771 void macPostedEventCallback(void *unused
);
774 void macPostedEventCallback(void *unused
)
776 wxTheApp
->ProcessPendingEvents();
780 bool wxApp::Initialize(int& argc
, wxChar
**argv
)
785 InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler
) );
788 UMAInitToolbox( 4, sm_isEmbedded
) ;
789 SetEventMask( everyEvent
) ;
790 UMAShowWatchCursor() ;
793 # if __option(profile)
794 ProfilerInit( collectDetailed
, bestTimeBase
, 40000 , 50 ) ;
799 // now avoid exceptions thrown for new (bad_alloc)
800 // FIXME CS for some changes outside wxMac does not compile anymore
802 std::__throws_bad_alloc
= 0 ;
807 // Mac OS X passes a process serial number command line argument when
808 // the application is launched from the Finder. This argument must be
809 // removed from the command line arguments before being handled by the
810 // application (otherwise applications would need to handle it)
813 static const wxChar
*ARG_PSN
= _T("-psn_");
814 if ( wxStrncmp(argv
[1], ARG_PSN
, wxStrlen(ARG_PSN
)) == 0 )
816 // remove this argument
818 memmove(argv
+ 1, argv
+ 2, argc
* sizeof(char *));
822 if ( !wxAppBase::Initialize(argc
, argv
) )
826 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
829 #if TARGET_API_MAC_OSX
830 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
831 wxString startupCwd
= wxGetCwd() ;
832 if ( startupCwd
== wxT("/") || startupCwd
.Right(15) == wxT("/Contents/MacOS") )
834 CFURLRef url
= CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
835 CFURLRef urlParent
= CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault
, url
) ;
837 CFStringRef path
= CFURLCopyFileSystemPath ( urlParent
, kCFURLPOSIXPathStyle
) ;
838 CFRelease( urlParent
) ;
839 wxString cwd
= wxMacCFStringHolder(path
).AsString(wxLocale::GetSystemEncoding());
840 wxSetWorkingDirectory( cwd
) ;
844 wxMacCreateNotifierTable() ;
847 /* connect posted events to common-mode run loop so that wxPostEvent events
848 are handled even while we're in the menu or on a scrollbar */
849 CFRunLoopSourceContext event_posted_context
= {0};
850 event_posted_context
.perform
= macPostedEventCallback
;
851 m_macEventPosted
= CFRunLoopSourceCreate(NULL
,0,&event_posted_context
);
852 CFRunLoopAddSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
853 // run loop takes ownership
854 CFRelease(m_macEventPosted
);
857 UMAShowArrowCursor() ;
862 AEEventHandlerUPP sODocHandler
= NULL
;
863 AEEventHandlerUPP sOAppHandler
= NULL
;
864 AEEventHandlerUPP sPDocHandler
= NULL
;
865 AEEventHandlerUPP sRAppHandler
= NULL
;
866 AEEventHandlerUPP sQuitHandler
= NULL
;
868 bool wxApp::OnInitGui()
870 if ( !wxAppBase::OnInitGui() )
873 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
877 InstallApplicationEventHandler(
878 GetwxMacAppEventHandlerUPP(),
879 GetEventTypeCount(eventList
), eventList
, wxTheApp
, (EventHandlerRef
*)&(wxTheApp
->m_macEventHandler
));
884 sODocHandler
= NewAEEventHandlerUPP(AEHandleODoc
) ;
885 sOAppHandler
= NewAEEventHandlerUPP(AEHandleOApp
) ;
886 sPDocHandler
= NewAEEventHandlerUPP(AEHandlePDoc
) ;
887 sRAppHandler
= NewAEEventHandlerUPP(AEHandleRApp
) ;
888 sQuitHandler
= NewAEEventHandlerUPP(AEHandleQuit
) ;
890 AEInstallEventHandler( kCoreEventClass
, kAEOpenDocuments
,
891 sODocHandler
, 0 , FALSE
) ;
892 AEInstallEventHandler( kCoreEventClass
, kAEOpenApplication
,
893 sOAppHandler
, 0 , FALSE
) ;
894 AEInstallEventHandler( kCoreEventClass
, kAEPrintDocuments
,
895 sPDocHandler
, 0 , FALSE
) ;
896 AEInstallEventHandler( kCoreEventClass
, kAEReopenApplication
,
897 sRAppHandler
, 0 , FALSE
) ;
898 AEInstallEventHandler( kCoreEventClass
, kAEQuitApplication
,
899 sQuitHandler
, 0 , FALSE
) ;
905 void wxApp::CleanUp()
908 wxToolTip::RemoveToolTips() ;
912 if (m_macEventPosted
)
914 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m_macEventPosted
, kCFRunLoopCommonModes
);
915 m_macEventPosted
= NULL
;
919 // One last chance for pending objects to be cleaned up
920 wxTheApp
->DeletePendingObjects();
922 wxMacDestroyNotifierTable() ;
925 # if __option(profile)
926 ProfilerDump( (StringPtr
)"\papp.prof" ) ;
931 UMACleanupToolbox() ;
934 RemoveEventHandler( (EventHandlerRef
)(wxTheApp
->m_macEventHandler
) );
938 AERemoveEventHandler( kCoreEventClass
, kAEOpenDocuments
,
939 sODocHandler
, FALSE
) ;
940 AERemoveEventHandler( kCoreEventClass
, kAEOpenApplication
,
941 sOAppHandler
, FALSE
) ;
942 AERemoveEventHandler( kCoreEventClass
, kAEPrintDocuments
,
943 sPDocHandler
, FALSE
) ;
944 AERemoveEventHandler( kCoreEventClass
, kAEReopenApplication
,
945 sRAppHandler
, FALSE
) ;
946 AERemoveEventHandler( kCoreEventClass
, kAEQuitApplication
,
947 sQuitHandler
, FALSE
) ;
949 DisposeAEEventHandlerUPP( sODocHandler
) ;
950 DisposeAEEventHandlerUPP( sOAppHandler
) ;
951 DisposeAEEventHandlerUPP( sPDocHandler
) ;
952 DisposeAEEventHandlerUPP( sRAppHandler
) ;
953 DisposeAEEventHandlerUPP( sQuitHandler
) ;
956 wxAppBase::CleanUp();
959 //----------------------------------------------------------------------
960 // misc initialization stuff
961 //----------------------------------------------------------------------
963 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
965 // for shared libraries we have to manually get the correct resource
966 // ref num upon initializing and releasing when terminating, therefore
967 // the __wxinitialize and __wxterminate must be used
971 void __sinit(void); // (generated by linker)
972 pascal OSErr
__initialize(const CFragInitBlock
*theInitBlock
);
973 pascal void __terminate(void);
976 pascal OSErr
__wxinitialize(const CFragInitBlock
*theInitBlock
)
978 return __initialize( theInitBlock
) ;
981 pascal void __wxterminate(void)
986 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
988 bool wxMacConvertEventToRecord( EventRef event
, EventRecord
*rec
)
990 OSStatus err
= noErr
;
991 bool converted
= ConvertEventRefToEventRecord( event
, rec
) ;
995 switch ( GetEventClass( event
) )
997 case kEventClassKeyboard
:
1000 switch ( GetEventKind(event
) )
1002 case kEventRawKeyDown
:
1003 rec
->what
= keyDown
;
1006 case kEventRawKeyRepeat
:
1007 rec
->what
= autoKey
;
1010 case kEventRawKeyUp
:
1014 case kEventRawKeyModifiersChanged
:
1015 rec
->what
= nullEvent
;
1026 unsigned char charCode
;
1029 GetMouse( &rec
->where
) ;
1031 err
= GetEventParameter(event
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1032 err
= GetEventParameter(event
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1033 err
= GetEventParameter(event
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1034 rec
->modifiers
= modifiers
;
1035 rec
->message
= (keyCode
<< 8 ) + charCode
;
1040 case kEventClassTextInput
:
1042 switch ( GetEventKind( event
) )
1044 case kEventTextInputUnicodeForKeyEvent
:
1047 err
= GetEventParameter(
1048 event
, kEventParamTextInputSendKeyboardEvent
, typeEventRef
, NULL
,
1049 sizeof(rawEvent
), NULL
, &rawEvent
) ;
1053 UInt32 keyCode
, modifiers
;
1054 unsigned char charCode
;
1057 GetMouse( &rec
->where
) ;
1059 rec
->what
= keyDown
;
1060 err
= GetEventParameter(rawEvent
, kEventParamKeyModifiers
, typeUInt32
, NULL
, 4, NULL
, &modifiers
);
1061 err
= GetEventParameter(rawEvent
, kEventParamKeyCode
, typeUInt32
, NULL
, 4, NULL
, &keyCode
);
1062 err
= GetEventParameter(rawEvent
, kEventParamKeyMacCharCodes
, typeChar
, NULL
, 1, NULL
, &charCode
);
1063 rec
->modifiers
= modifiers
;
1064 rec
->message
= (keyCode
<< 8 ) + charCode
;
1085 m_printMode
= wxPRINT_WINDOWS
;
1087 m_macCurrentEvent
= NULL
;
1088 m_macCurrentEventHandlerCallRef
= NULL
;
1090 #ifdef __WXMAC_OSX__
1091 m_macEventPosted
= NULL
;
1095 void wxApp::OnIdle(wxIdleEvent
& event
)
1097 wxAppBase::OnIdle(event
);
1099 // If they are pending events, we must process them: pending events are
1100 // either events to the threads other than main or events posted with
1101 // wxPostEvent() functions
1102 wxMacProcessNotifierAndPendingEvents();
1104 if (!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1105 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1108 void wxApp::WakeUpIdle()
1110 #ifdef __WXMAC_OSX__
1111 if (m_macEventPosted
)
1113 CFRunLoopSourceSignal(m_macEventPosted
);
1120 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1123 GetTopWindow()->Close(true);
1126 // Default behaviour: close the application with prompts. The
1127 // user can veto the close, and therefore the end session.
1128 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1132 if (!GetTopWindow()->Close(!event
.CanVeto()))
1137 extern "C" void wxCYield() ;
1143 // Yield to other processes
1145 bool wxApp::Yield(bool onlyIfNeeded
)
1149 if ( !onlyIfNeeded
)
1151 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1159 // by definition yield should handle all non-processed events
1163 OSStatus status
= noErr
;
1165 while ( status
== noErr
)
1167 s_inReceiveEvent
= true ;
1168 status
= ReceiveNextEvent(0, NULL
,kEventDurationNoWait
,true,&theEvent
) ;
1169 s_inReceiveEvent
= false ;
1171 if ( status
== eventLoopTimedOutErr
)
1173 // make sure next time the event loop will trigger idle events
1174 sleepTime
= kEventDurationNoWait
;
1176 else if ( status
== eventLoopQuitErr
)
1178 // according to QA1061 this may also occur when a WakeUp Process
1183 MacHandleOneEvent( theEvent
) ;
1184 ReleaseEvent(theEvent
);
1188 wxMacProcessNotifierAndPendingEvents() ;
1194 void wxApp::MacDoOneEvent()
1198 s_inReceiveEvent
= true ;
1199 OSStatus status
= ReceiveNextEvent(0, NULL
, sleepTime
, true, &theEvent
) ;
1200 s_inReceiveEvent
= false ;
1204 case eventLoopTimedOutErr
:
1205 if ( wxTheApp
->ProcessIdle() )
1206 sleepTime
= kEventDurationNoWait
;
1208 sleepTime
= kEventDurationSecond
;
1211 case eventLoopQuitErr
:
1212 // according to QA1061 this may also occur
1213 // when a WakeUp Process is executed
1217 MacHandleOneEvent( theEvent
) ;
1218 ReleaseEvent( theEvent
);
1219 sleepTime
= kEventDurationNoWait
;
1224 DeletePendingObjects() ;
1225 wxMacProcessNotifierAndPendingEvents() ;
1229 void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr
)
1231 // Override to process unhandled events as you please
1234 CFMutableArrayRef
GetAutoReleaseArray()
1236 static CFMutableArrayRef array
= 0;
1238 array
= CFArrayCreateMutable(kCFAllocatorDefault
,0,&kCFTypeArrayCallBacks
);
1242 void wxApp::MacHandleOneEvent( WXEVENTREF evr
)
1244 EventTargetRef theTarget
;
1245 theTarget
= GetEventDispatcherTarget();
1246 m_macCurrentEvent
= evr
;
1248 OSStatus status
= SendEventToEventTarget((EventRef
) evr
, theTarget
);
1249 if (status
== eventNotHandledErr
)
1250 MacHandleUnhandledEvent(evr
);
1252 wxMacProcessNotifierAndPendingEvents() ;
1255 wxMutexGuiLeaveOrEnter();
1256 #endif // wxUSE_THREADS
1258 CFArrayRemoveAllValues( GetAutoReleaseArray() );
1261 void wxApp::MacAddToAutorelease( void* cfrefobj
)
1263 CFArrayAppendValue( GetAutoReleaseArray(), cfrefobj
);
1266 long wxMacTranslateKey(unsigned char key
, unsigned char code
)
1271 case kHomeCharCode
:
1275 case kEnterCharCode
:
1276 retval
= WXK_RETURN
;
1282 case kHelpCharCode
:
1286 case kBackspaceCharCode
:
1294 case kPageUpCharCode
:
1295 retval
= WXK_PAGEUP
;
1298 case kPageDownCharCode
:
1299 retval
= WXK_PAGEDOWN
;
1302 case kReturnCharCode
:
1303 retval
= WXK_RETURN
;
1306 case kFunctionKeyCharCode
:
1376 case kEscapeCharCode
:
1377 retval
= WXK_ESCAPE
;
1380 case kLeftArrowCharCode
:
1384 case kRightArrowCharCode
:
1385 retval
= WXK_RIGHT
;
1388 case kUpArrowCharCode
:
1392 case kDownArrowCharCode
:
1396 case kDeleteCharCode
:
1397 retval
= WXK_DELETE
;
1407 int wxMacKeyCodeToModifier(wxKeyCode key
)
1433 bool wxGetKeyState(wxKeyCode key
) //virtual key code if < 10.2.x, else see below
1435 wxASSERT_MSG(key
!= WXK_LBUTTON
&& key
!= WXK_RBUTTON
&& key
!=
1436 WXK_MBUTTON
, wxT("can't use wxGetKeyState() for mouse buttons"));
1438 //if OS X > 10.2 (i.e. 10.2.x)
1439 //a known apple bug prevents the system from determining led
1440 //states with GetKeys... can only determine caps lock led
1441 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key
));
1443 // KeyMapByteArray keymap;
1444 // GetKeys((BigEndianLong*)keymap);
1445 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1450 wxMouseState
wxGetMouseState()
1454 wxPoint pt
= wxGetMousePosition();
1458 #if TARGET_API_MAC_OSX
1459 UInt32 buttons
= GetCurrentButtonState();
1460 ms
.SetLeftDown( (buttons
& 0x01) != 0 );
1461 ms
.SetMiddleDown( (buttons
& 0x04) != 0 );
1462 ms
.SetRightDown( (buttons
& 0x02) != 0 );
1464 ms
.SetLeftDown( Button() );
1465 ms
.SetMiddleDown( 0 );
1466 ms
.SetRightDown( 0 );
1469 UInt32 modifiers
= GetCurrentKeyModifiers();
1470 ms
.SetControlDown(modifiers
& controlKey
);
1471 ms
.SetShiftDown(modifiers
& shiftKey
);
1472 ms
.SetAltDown(modifiers
& optionKey
);
1473 ms
.SetMetaDown(modifiers
& cmdKey
);
1478 // TODO : once the new key/char handling is tested, move all the code to wxWindow
1480 bool wxApp::MacSendKeyDownEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1486 wxKeyEvent
event(wxEVT_KEY_DOWN
) ;
1487 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1489 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1490 if ( handled
&& event
.GetSkipped() )
1496 wxWindow
*ancestor
= focus
;
1499 int command
= ancestor
->GetAcceleratorTable()->GetCommand( event
);
1502 wxCommandEvent
command_event( wxEVT_COMMAND_MENU_SELECTED
, command
);
1503 handled
= ancestor
->GetEventHandler()->ProcessEvent( command_event
);
1507 if (ancestor
->IsTopLevel())
1510 ancestor
= ancestor
->GetParent();
1513 #endif // wxUSE_ACCEL
1518 bool wxApp::MacSendKeyUpEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1524 wxKeyEvent
event( wxEVT_KEY_UP
) ;
1525 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1526 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1531 bool wxApp::MacSendCharEvent( wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1536 wxKeyEvent
event(wxEVT_CHAR
) ;
1537 MacCreateKeyEvent( event
, focus
, keymessage
, modifiers
, when
, wherex
, wherey
, uniChar
) ;
1538 long keyval
= event
.m_keyCode
;
1540 bool handled
= false ;
1542 wxTopLevelWindowMac
*tlw
= focus
->MacGetTopLevelWindow() ;
1546 event
.SetEventType( wxEVT_CHAR_HOOK
);
1547 handled
= tlw
->GetEventHandler()->ProcessEvent( event
);
1548 if ( handled
&& event
.GetSkipped() )
1554 event
.SetEventType( wxEVT_CHAR
);
1555 event
.Skip( false ) ;
1556 handled
= focus
->GetEventHandler()->ProcessEvent( event
) ;
1559 if ( !handled
&& (keyval
== WXK_TAB
) )
1561 wxWindow
* iter
= focus
->GetParent() ;
1562 while ( iter
&& !handled
)
1564 if ( iter
->HasFlag( wxTAB_TRAVERSAL
) )
1566 wxNavigationKeyEvent new_event
;
1567 new_event
.SetEventObject( focus
);
1568 new_event
.SetDirection( !event
.ShiftDown() );
1569 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1570 new_event
.SetWindowChange( event
.ControlDown() );
1571 new_event
.SetCurrentFocus( focus
);
1572 handled
= focus
->GetParent()->GetEventHandler()->ProcessEvent( new_event
);
1573 if ( handled
&& new_event
.GetSkipped() )
1577 iter
= iter
->GetParent() ;
1581 // backdoor handler for default return and command escape
1582 if ( !handled
&& (!focus
->IsKindOf(CLASSINFO(wxControl
) ) || !focus
->MacCanFocus() ) )
1584 // if window is not having a focus still testing for default enter or cancel
1585 // TODO: add the UMA version for ActiveNonFloatingWindow
1586 wxWindow
* focus
= wxFindWinFromMacWindow( FrontWindow() ) ;
1589 if ( keyval
== WXK_RETURN
|| keyval
== WXK_NUMPAD_ENTER
)
1591 wxTopLevelWindow
*tlw
= wxDynamicCast(wxGetTopLevelParent(focus
), wxTopLevelWindow
);
1592 if ( tlw
&& tlw
->GetDefaultItem() )
1594 wxButton
*def
= wxDynamicCast(tlw
->GetDefaultItem(), wxButton
);
1595 if ( def
&& def
->IsEnabled() )
1597 wxCommandEvent
event(wxEVT_COMMAND_BUTTON_CLICKED
, def
->GetId() );
1598 event
.SetEventObject(def
);
1599 def
->Command(event
);
1605 else if (keyval
== WXK_ESCAPE
|| (keyval
== '.' && modifiers
& cmdKey
) )
1607 // generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs)
1608 wxCommandEvent
new_event(wxEVT_COMMAND_BUTTON_CLICKED
,wxID_CANCEL
);
1609 new_event
.SetEventObject( focus
);
1610 handled
= focus
->GetEventHandler()->ProcessEvent( new_event
);
1617 // This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
1618 void wxApp::MacCreateKeyEvent( wxKeyEvent
& event
, wxWindow
* focus
, long keymessage
, long modifiers
, long when
, short wherex
, short wherey
, wxChar uniChar
)
1620 short keycode
, keychar
;
1622 keychar
= short(keymessage
& charCodeMask
);
1623 keycode
= short(keymessage
& keyCodeMask
) >> 8 ;
1624 if ( !(event
.GetEventType() == wxEVT_CHAR
) && (modifiers
& (controlKey
| shiftKey
| optionKey
) ) )
1626 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1627 // and look at the character after
1629 UInt32 keyInfo
= KeyTranslate((Ptr
)GetScriptManagerVariable(smKCHRCache
), ( modifiers
& (~(controlKey
| shiftKey
| optionKey
))) | keycode
, &state
);
1630 keychar
= short(keyInfo
& charCodeMask
);
1633 long keyval
= wxMacTranslateKey(keychar
, keycode
) ;
1634 if ( keyval
== keychar
&& ( event
.GetEventType() == wxEVT_KEY_UP
|| event
.GetEventType() == wxEVT_KEY_DOWN
) )
1635 keyval
= wxToupper( keyval
) ;
1637 // Check for NUMPAD keys
1638 if (keyval
>= '0' && keyval
<= '9' && keycode
>= 82 && keycode
<= 92)
1640 keyval
= (keyval
- '0') + WXK_NUMPAD0
;
1642 else if (keycode
>= 67 && keycode
<= 81)
1647 keyval
= WXK_NUMPAD_ENTER
;
1651 keyval
= WXK_NUMPAD_EQUAL
;
1655 keyval
= WXK_NUMPAD_MULTIPLY
;
1659 keyval
= WXK_NUMPAD_DIVIDE
;
1663 keyval
= WXK_NUMPAD_SUBTRACT
;
1667 keyval
= WXK_NUMPAD_ADD
;
1671 keyval
= WXK_NUMPAD_DECIMAL
;
1679 event
.m_shiftDown
= modifiers
& shiftKey
;
1680 event
.m_controlDown
= modifiers
& controlKey
;
1681 event
.m_altDown
= modifiers
& optionKey
;
1682 event
.m_metaDown
= modifiers
& cmdKey
;
1683 event
.m_keyCode
= keyval
;
1685 event
.m_uniChar
= uniChar
;
1688 event
.m_rawCode
= keymessage
;
1689 event
.m_rawFlags
= modifiers
;
1692 event
.SetTimestamp(when
);
1693 event
.SetEventObject(focus
);