]> git.saurik.com Git - wxWidgets.git/blame - src/mac/carbon/app.cpp
switching to correct name as Tiger doesn't have the workaround anymore
[wxWidgets.git] / src / mac / carbon / app.cpp
CommitLineData
e9576ca5
SC
1/////////////////////////////////////////////////////////////////////////////
2// Name: app.cpp
3// Purpose: wxApp
a31a5f85 4// Author: Stefan Csomor
e9576ca5 5// Modified by:
a31a5f85 6// Created: 1998-01-01
e9576ca5 7// RCS-ID: $Id$
a31a5f85 8// Copyright: (c) Stefan Csomor
65571936 9// Licence: wxWindows licence
e9576ca5
SC
10/////////////////////////////////////////////////////////////////////////////
11
12#ifdef __GNUG__
13#pragma implementation "app.h"
14#endif
15
df06d1a4
GD
16#include "wx/defs.h"
17
03e11df5 18#include "wx/window.h"
e9576ca5 19#include "wx/frame.h"
e8566d35 20#include "wx/button.h"
e9576ca5
SC
21#include "wx/app.h"
22#include "wx/utils.h"
23#include "wx/gdicmn.h"
24#include "wx/pen.h"
25#include "wx/brush.h"
26#include "wx/cursor.h"
ed5b9811 27#include "wx/intl.h"
e9576ca5
SC
28#include "wx/icon.h"
29#include "wx/palette.h"
30#include "wx/dc.h"
31#include "wx/dialog.h"
32#include "wx/msgdlg.h"
33#include "wx/log.h"
34#include "wx/module.h"
35#include "wx/memory.h"
2f1ae414 36#include "wx/tooltip.h"
b3c406a5 37#include "wx/textctrl.h"
03e11df5 38#include "wx/menu.h"
738a6daa 39#include "wx/docview.h"
1c32ded3 40#include "wx/filename.h"
738a6daa 41
e9576ca5
SC
42#include <string.h>
43
8be97d65
SC
44// mac
45
f5c6eb5c 46#ifndef __DARWIN__
03e11df5 47 #if __option(profile)
8461e4c2 48 #include <profiler.h>
03e11df5 49 #endif
9779893b 50#endif
519cb848 51
9d331599 52// #include "apprsrc.h"
8be97d65 53
03e11df5
GD
54#include "wx/mac/uma.h"
55#include "wx/mac/macnotfy.h"
2f1ae414 56
df06d1a4
GD
57#ifdef __DARWIN__
58# include <CoreServices/CoreServices.h>
21870a5d 59# if defined(WXMAKINGDLL_CORE)
ed581ee2
GD
60# include <mach-o/dyld.h>
61# endif
df06d1a4
GD
62#else
63# include <Sound.h>
64# include <Threads.h>
65# include <ToolUtils.h>
66# include <DiskInit.h>
67# include <Devices.h>
2f1ae414 68#endif
519cb848 69
e9576ca5 70extern wxList wxPendingDelete;
facd6764 71
3fbf8e7f
SC
72// set wxMAC_USE_RAEL to 1 if RunApplicationEventLoop should be used
73// if 0 the lower level CarbonEventLoop will be used
74// on the long run RAEL should replace the low level event loop
75// we will have to clean up event handling to make sure we don't
76// miss handling of things like pending events etc
77// perhaps we will also have to pipe events through an ueber-event-handler
78// to make sure we have one place to do all these house-keeping functions
79
80#define wxMAC_USE_RAEL 0
81
c944ce35 82#if wxUSE_THREADS
e64313ba 83extern size_t g_numberOfThreads;
c944ce35 84#endif // wxUSE_THREADS
e9576ca5 85
c5c9378c
SC
86// statics for implementation
87
738a6daa 88static bool s_inYield = FALSE;
c5c9378c 89
c5c9378c
SC
90static bool s_inReceiveEvent = FALSE ;
91static EventTime sleepTime = kEventDurationNoWait ;
738a6daa 92
2f1ae414 93#if !USE_SHARED_LIBRARY
e9576ca5
SC
94IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
95BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
96 EVT_IDLE(wxApp::OnIdle)
15b41e90
SC
97 EVT_END_SESSION(wxApp::OnEndSession)
98 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
e9576ca5 99END_EVENT_TABLE()
2f1ae414 100#endif
e9576ca5 101
169935ad 102
8461e4c2 103const short kMacMinHeap = (29 * 1024) ;
8be97d65 104// platform specific static variables
169935ad 105
519cb848
SC
106const short kwxMacMenuBarResource = 1 ;
107const short kwxMacAppleMenuId = 1 ;
108
fbbdb7cd
GD
109WXHRGN wxApp::s_macCursorRgn = NULL;
110wxWindow* wxApp::s_captureWindow = NULL ;
111int wxApp::s_lastMouseDown = 0 ;
112long wxApp::sm_lastMessageTime = 0;
41d368a4
SC
113long wxApp::s_lastModifiers = 0 ;
114
519cb848 115
fbbdb7cd
GD
116bool wxApp::s_macSupportPCMenuShortcuts = true ;
117long wxApp::s_macAboutMenuItemId = wxID_ABOUT ;
882b0479 118long wxApp::s_macPreferencesMenuItemId = wxID_PREFERENCES ;
2b5f62a0 119long wxApp::s_macExitMenuItemId = wxID_EXIT ;
427ff662 120wxString wxApp::s_macHelpMenuTitleName = wxT("&Help") ;
519cb848 121
e128397f
DS
122// Normally we're not a plugin
123bool wxApp::sm_isEmbedded = false;
15b41e90
SC
124//----------------------------------------------------------------------
125// Core Apple Event Support
126//----------------------------------------------------------------------
127
72055702
SC
128pascal OSErr AEHandleODoc( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
129pascal OSErr AEHandleOApp( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
130pascal OSErr AEHandlePDoc( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
131pascal OSErr AEHandleQuit( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
1c32ded3 132pascal OSErr AEHandleRApp( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
72055702 133
2a294857 134pascal OSErr AEHandleODoc( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
519cb848 135{
8461e4c2 136 return wxTheApp->MacHandleAEODoc( (AppleEvent*) event , reply) ;
519cb848
SC
137}
138
2a294857 139pascal OSErr AEHandleOApp( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
519cb848 140{
8461e4c2 141 return wxTheApp->MacHandleAEOApp( (AppleEvent*) event , reply ) ;
519cb848
SC
142}
143
2a294857 144pascal OSErr AEHandlePDoc( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
519cb848 145{
8461e4c2 146 return wxTheApp->MacHandleAEPDoc( (AppleEvent*) event , reply ) ;
519cb848
SC
147}
148
2a294857 149pascal OSErr AEHandleQuit( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
519cb848 150{
8461e4c2 151 return wxTheApp->MacHandleAEQuit( (AppleEvent*) event , reply) ;
519cb848
SC
152}
153
1c32ded3
SC
154pascal OSErr AEHandleRApp( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
155{
156 return wxTheApp->MacHandleAERApp( (AppleEvent*) event , reply) ;
157}
158
15b41e90 159// AEODoc Calls MacOpenFile on each of the files passed
5ab6aab8 160
2072fbbb
SC
161short wxApp::MacHandleAEODoc(const WXEVENTREF event, WXEVENTREF WXUNUSED(reply))
162{
163 AEDescList docList;
164 AEKeyword keywd;
165 DescType returnedType;
166 Size actualSize;
167 long itemsInList;
168 FSSpec theSpec;
169 OSErr err;
170 short i;
171 err = AEGetParamDesc((AppleEvent *)event, keyDirectObject, typeAEList,&docList);
172 if (err != noErr)
173 return err;
7c9955d1 174
2072fbbb
SC
175 err = AECountItems(&docList, &itemsInList);
176 if (err != noErr)
177 return err;
7c9955d1 178
8461e4c2
VZ
179 ProcessSerialNumber PSN ;
180 PSN.highLongOfPSN = 0 ;
181 PSN.lowLongOfPSN = kCurrentProcess ;
182 SetFrontProcess( &PSN ) ;
7c9955d1 183
2072fbbb
SC
184 for (i = 1; i <= itemsInList; i++) {
185 AEGetNthPtr(&docList, i, typeFSS, &keywd, &returnedType,
186 (Ptr) & theSpec, sizeof(theSpec), &actualSize);
187 wxString fName = wxMacFSSpec2MacFilename(&theSpec);
188 MacOpenFile(fName);
189 }
190 return noErr;
519cb848
SC
191}
192
15b41e90
SC
193// AEPDoc Calls MacPrintFile on each of the files passed
194
2072fbbb 195short wxApp::MacHandleAEPDoc(const WXEVENTREF event , WXEVENTREF WXUNUSED(reply))
519cb848 196{
2072fbbb
SC
197 AEDescList docList;
198 AEKeyword keywd;
199 DescType returnedType;
200 Size actualSize;
201 long itemsInList;
202 FSSpec theSpec;
203 OSErr err;
204 short i;
205 err = AEGetParamDesc((AppleEvent *)event, keyDirectObject, typeAEList,&docList);
206 if (err != noErr)
207 return err;
7c9955d1 208
2072fbbb
SC
209 err = AECountItems(&docList, &itemsInList);
210 if (err != noErr)
211 return err;
7c9955d1 212
2072fbbb
SC
213 ProcessSerialNumber PSN ;
214 PSN.highLongOfPSN = 0 ;
215 PSN.lowLongOfPSN = kCurrentProcess ;
216 SetFrontProcess( &PSN ) ;
7c9955d1 217
2072fbbb
SC
218 for (i = 1; i <= itemsInList; i++) {
219 AEGetNthPtr(&docList, i, typeFSS, &keywd, &returnedType,
220 (Ptr) & theSpec, sizeof(theSpec), &actualSize);
221 wxString fName = wxMacFSSpec2MacFilename(&theSpec);
222 MacPrintFile(fName);
223 }
224 return noErr;
519cb848
SC
225}
226
15b41e90
SC
227// AEOApp calls MacNewFile
228
2a294857 229short wxApp::MacHandleAEOApp(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
519cb848 230{
2072fbbb 231 MacNewFile() ;
8461e4c2 232 return noErr ;
519cb848
SC
233}
234
76a60a81 235// AEQuit attempts to quit the application
15b41e90 236
2a294857 237short wxApp::MacHandleAEQuit(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
519cb848 238{
38106243 239 wxWindow* win = GetTopWindow() ;
8461e4c2
VZ
240 if ( win )
241 {
38106243
JS
242 wxCommandEvent exitEvent(wxEVT_COMMAND_MENU_SELECTED, s_macExitMenuItemId);
243 if (!win->ProcessEvent(exitEvent))
244 win->Close(TRUE ) ;
8461e4c2 245 }
38106243 246 else
8461e4c2
VZ
247 {
248 ExitMainLoop() ;
249 }
250 return noErr ;
519cb848
SC
251}
252
1c32ded3
SC
253// AEROApp calls MacReopenApp
254
255short wxApp::MacHandleAERApp(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
256{
257 MacReopenApp() ;
258 return noErr ;
259}
260
261
15b41e90
SC
262//----------------------------------------------------------------------
263// Support Routines linking the Mac...File Calls to the Document Manager
264//----------------------------------------------------------------------
265
266void wxApp::MacOpenFile(const wxString & fileName )
267{
268 wxDocManager* dm = wxDocManager::GetDocumentManager() ;
269 if ( dm )
270 dm->CreateDocument(fileName , wxDOC_SILENT ) ;
271}
272
273void wxApp::MacPrintFile(const wxString & fileName )
274{
275 wxDocManager* dm = wxDocManager::GetDocumentManager() ;
276 if ( dm )
277 {
278 wxDocument *doc = dm->CreateDocument(fileName , wxDOC_SILENT ) ;
279 if ( doc )
280 {
281 wxView* view = doc->GetFirstView() ;
282 if( view )
283 {
284 wxPrintout *printout = view->OnCreatePrintout();
285 if (printout)
286 {
287 wxPrinter printer;
288 printer.Print(view->GetFrame(), printout, TRUE);
289 delete printout;
290 }
291 }
292 if (doc->Close())
293 {
294 doc->DeleteAllViews();
295 dm->RemoveDocument(doc) ;
296 }
297 }
298 }
299}
300
301void wxApp::MacNewFile()
302{
303}
304
1c32ded3
SC
305void wxApp::MacReopenApp()
306{
3f42061b
SC
307 // HIG says :
308 // if there is no open window -> create a new one
309 // if all windows are hidden -> show the first
310 // if some windows are not hidden -> do nothing
311
312 wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst();
313 if ( node == NULL )
314 {
315 MacNewFile() ;
316 }
317 else
318 {
3f42061b
SC
319 wxTopLevelWindow* firstIconized = NULL ;
320 while (node)
321 {
322 wxTopLevelWindow* win = (wxTopLevelWindow*) node->GetData();
323 if ( win->IsIconized() == false )
324 {
325 firstIconized = NULL ;
326 break ;
327 }
328 else
329 {
330 if ( firstIconized == NULL )
331 firstIconized = win ;
332 }
333 node = node->GetNext();
334 }
335 if ( firstIconized )
336 firstIconized->Iconize( false ) ;
337 }
1c32ded3
SC
338}
339
c5c9378c
SC
340//----------------------------------------------------------------------
341// Carbon Event Handler
342//----------------------------------------------------------------------
9779893b 343
facd6764
SC
344static const EventTypeSpec eventList[] =
345{
346 { kEventClassCommand, kEventProcessCommand } ,
347 { kEventClassCommand, kEventCommandUpdateStatus } ,
7c9955d1 348
facd6764
SC
349 { kEventClassMenu, kEventMenuOpening },
350 { kEventClassMenu, kEventMenuClosed },
351 { kEventClassMenu, kEventMenuTargetItem },
e32f4a9f 352
facd6764
SC
353 { kEventClassApplication , kEventAppActivated } ,
354 { kEventClassApplication , kEventAppDeactivated } ,
355 // handling the quit event is not recommended by apple
356 // rather using the quit apple event - which we do
7c9955d1 357
facd6764 358 { kEventClassAppleEvent , kEventAppleEvent } ,
7c9955d1 359
facd6764
SC
360 { kEventClassMouse , kEventMouseDown } ,
361 { kEventClassMouse , kEventMouseMoved } ,
362 { kEventClassMouse , kEventMouseUp } ,
363 { kEventClassMouse , kEventMouseDragged } ,
364 { 'WXMC' , 'WXMC' }
365} ;
519cb848 366
e32f4a9f 367static pascal OSStatus
facd6764 368wxMacAppMenuEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
519cb848 369{
dae6d730
SC
370 EventRef formerEvent = (EventRef) wxTheApp->MacGetCurrentEvent() ;
371 EventHandlerCallRef formerEventHandlerCallRef = (EventHandlerCallRef) wxTheApp->MacGetCurrentEventHandlerCallRef() ;
372 wxTheApp->MacSetCurrentEvent( event , handler ) ;
852b1185 373
dae6d730
SC
374 wxMacCarbonEvent cEvent( event ) ;
375 MenuRef menuRef = cEvent.GetParameter<MenuRef>(kEventParamDirectObject) ;
376 wxMenu* menu = wxFindMenuFromMacMenu( menuRef ) ;
377
378 if ( menu )
e32f4a9f 379 {
dae6d730
SC
380 wxEventType type=0;
381 MenuCommand cmd=0;
382 switch (GetEventKind(event))
852b1185 383 {
dae6d730
SC
384 case kEventMenuOpening:
385 type = wxEVT_MENU_OPEN;
386 break;
387 case kEventMenuClosed:
388 type = wxEVT_MENU_CLOSE;
389 break;
390 case kEventMenuTargetItem:
391 cmd = cEvent.GetParameter<MenuCommand>(kEventParamMenuCommand,typeMenuCommand) ;
392 if (cmd != 0)
9f2bfce7 393 type = wxEVT_MENU_HIGHLIGHT;
dae6d730
SC
394 break;
395 default:
396 wxFAIL_MSG(wxT("Unexpected menu event kind"));
397 break;
398 }
852b1185 399
dae6d730
SC
400 if ( type )
401 {
9f2bfce7 402 wxMenuEvent wxevent(type, cmd);
dae6d730 403 wxevent.SetEventObject(menu);
e32f4a9f 404
dae6d730
SC
405 wxEvtHandler* handler = menu->GetEventHandler();
406 if (handler && handler->ProcessEvent(wxevent))
407 {
408 // handled
409 }
410 else
411 {
412 wxWindow *win = menu->GetInvokingWindow();
413 if (win)
414 win->GetEventHandler()->ProcessEvent(wxevent);
415 }
416 }
e32f4a9f 417 }
dae6d730
SC
418
419 wxTheApp->MacSetCurrentEvent( formerEvent, formerEventHandlerCallRef ) ;
e32f4a9f
VZ
420
421 return eventNotHandledErr;
519cb848
SC
422}
423
facd6764 424static pascal OSStatus wxMacAppCommandEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
15b41e90
SC
425{
426 OSStatus result = eventNotHandledErr ;
427
e40298d5 428 HICommand command ;
7c9955d1 429
dae6d730
SC
430 wxMacCarbonEvent cEvent( event ) ;
431 cEvent.GetParameter<HICommand>(kEventParamDirectObject,typeHICommand,&command) ;
432
433 wxMenuItem* item = NULL ;
e40298d5 434 MenuCommand id = command.commandID ;
dae6d730 435 // for items we don't really control
e40298d5 436 if ( id == kHICommandPreferences )
6d565349 437 {
dae6d730
SC
438 id = wxApp::s_macPreferencesMenuItemId ;
439
440 wxMenuBar* mbar = wxMenuBar::MacGetInstalledMenuBar() ;
441 if ( mbar )
6d565349 442 {
dae6d730
SC
443 wxMenu* menu = NULL ;
444 item = mbar->FindItem( id , &menu ) ;
6d565349
SC
445 }
446 }
dae6d730
SC
447 else if ( id != 0 && command.menu.menuRef != 0 && command.menu.menuItemIndex != 0 )
448 {
449 GetMenuItemRefCon( command.menu.menuRef , command.menu.menuItemIndex , (UInt32*) &item ) ;
450 }
451
452 if ( item )
453 {
454 switch( cEvent.GetKind() )
e40298d5
JS
455 {
456 case kEventProcessCommand :
457 {
458 if (item->IsCheckable())
459 {
460 item->Check( !item->IsChecked() ) ;
461 }
7c9955d1 462
dae6d730 463 item->GetMenu()->SendEvent( id , item->IsCheckable() ? item->IsChecked() : -1 ) ;
e40298d5
JS
464 result = noErr ;
465 }
dae6d730 466 break ;
e40298d5
JS
467 case kEventCommandUpdateStatus:
468 // eventually trigger an updateui round
6d565349 469 result = noErr ;
e40298d5 470 break ;
dae6d730
SC
471 default :
472 break ;
473 }
474 }
15b41e90
SC
475 return result ;
476}
477
facd6764 478static pascal OSStatus wxMacAppApplicationEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
15b41e90
SC
479{
480 OSStatus result = eventNotHandledErr ;
e40298d5
JS
481 switch ( GetEventKind( event ) )
482 {
483 case kEventAppActivated :
484 {
3470af1c 485 if ( wxTheApp )
facd6764 486 wxTheApp->SetActive( true , NULL ) ;
e40298d5
JS
487 result = noErr ;
488 }
489 break ;
490 case kEventAppDeactivated :
491 {
3470af1c 492 if ( wxTheApp )
facd6764 493 wxTheApp->SetActive( false , NULL ) ;
e40298d5
JS
494 result = noErr ;
495 }
496 break ;
497 default :
498 break ;
499 }
15b41e90
SC
500 return result ;
501}
502
facd6764 503pascal OSStatus wxMacAppEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
15b41e90
SC
504{
505 OSStatus result = eventNotHandledErr ;
506 switch( GetEventClass( event ) )
507 {
e40298d5 508 case kEventClassCommand :
facd6764 509 result = wxMacAppCommandEventHandler( handler , event , data ) ;
e40298d5
JS
510 break ;
511 case kEventClassApplication :
facd6764 512 result = wxMacAppApplicationEventHandler( handler , event , data ) ;
e40298d5
JS
513 break ;
514 case kEventClassMenu :
facd6764 515 result = wxMacAppMenuEventHandler( handler , event , data ) ;
e40298d5
JS
516 break ;
517 case kEventClassMouse :
58ddb76c 518 result = wxMacTopLevelMouseEventHandler( handler , event , NULL ) ;
e40298d5
JS
519 break ;
520 case kEventClassAppleEvent :
521 {
522 EventRecord rec ;
523 wxMacConvertEventToRecord( event , &rec ) ;
524 result = AEProcessAppleEvent( &rec ) ;
525 }
526 break ;
527 default :
528 break ;
15b41e90
SC
529 }
530
531 return result ;
532}
533
facd6764 534DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler )
15b41e90 535
21870a5d 536#if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
53fd991c
SC
537// we know it's there ;-)
538WXIMPORT char std::__throws_bad_alloc ;
539#endif
540
facd6764
SC
541pascal static void wxMacAssertOutputHandler(OSType componentSignature, UInt32 options,
542 const char *assertionString, const char *exceptionLabelString,
543 const char *errorString, const char *fileName, long lineNumber, void *value, ConstStr255Param outputMsg)
e9576ca5 544{
facd6764
SC
545 // flow into assert handling
546 wxString fileNameStr ;
547 wxString assertionStr ;
548 wxString exceptionStr ;
549 wxString errorStr ;
550#if wxUSE_UNICODE
551 fileNameStr = wxString(fileName, wxConvLocal);
552 assertionStr = wxString(assertionString, wxConvLocal);
553 exceptionStr = wxString((exceptionLabelString!=0) ? exceptionLabelString : "", wxConvLocal) ;
554 errorStr = wxString((errorString!=0) ? errorString : "", wxConvLocal) ;
555#else
556 fileNameStr = fileName;
557 assertionStr = assertionString;
558 exceptionStr = (exceptionLabelString!=0) ? exceptionLabelString : "" ;
559 errorStr = (errorString!=0) ? errorString : "" ;
560#endif
9779893b 561
facd6764
SC
562#if 1
563 // flow into log
c847adaa 564 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
facd6764
SC
565 assertionStr.c_str() ,
566 exceptionStr.c_str() ,
567 errorStr.c_str(),
568 fileNameStr.c_str(), lineNumber ,
569 value ) ;
570#else
571
572 wxOnAssert(fileNameStr, lineNumber , assertionStr ,
c847adaa 573 wxString::Format( wxT("%s %s value (%p)") ,exceptionStr, errorStr , value ) ) ;
facd6764
SC
574#endif
575}
576
577bool wxApp::Initialize(int& argc, wxChar **argv)
578{
fbbdb7cd 579 // Mac-specific
9779893b 580
facd6764
SC
581#if __WXDEBUG__
582 InstallDebugAssertOutputHandler ( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler ) );
583#endif
e128397f 584 UMAInitToolbox( 4, sm_isEmbedded ) ;
fbbdb7cd 585 SetEventMask( everyEvent ) ;
8461e4c2 586 UMAShowWatchCursor() ;
8be97d65 587
21870a5d 588#if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
fbbdb7cd
GD
589 // open shared library resources from here since we don't have
590 // __wxinitialize in Mach-O shared libraries
591 wxStAppResource::OpenSharedLibraryResource(NULL);
592#endif
84c1ffa9 593
f5c6eb5c 594#ifndef __DARWIN__
fbbdb7cd 595# if __option(profile)
882b0479 596 ProfilerInit( collectDetailed, bestTimeBase , 40000 , 50 ) ;
fbbdb7cd 597# endif
9779893b 598#endif
519cb848 599
f5c6eb5c 600#ifndef __DARWIN__
ed581ee2 601 // now avoid exceptions thrown for new (bad_alloc)
e40298d5 602 // FIXME CS for some changes outside wxMac does not compile anymore
15b41e90
SC
603#if 0
604 std::__throws_bad_alloc = 0 ;
605#endif
606
03e11df5 607#endif
7c9955d1 608
8461e4c2 609 s_macCursorRgn = ::NewRgn() ;
8be97d65 610
05e2b077
VZ
611 // Mac OS X passes a process serial number command line argument when
612 // the application is launched from the Finder. This argument must be
613 // removed from the command line arguments before being handled by the
614 // application (otherwise applications would need to handle it)
615 if ( argc > 1 )
616 {
617 static const wxChar *ARG_PSN = _T("-psn_");
46e2a2e7 618 if ( wxStrncmp(argv[1], ARG_PSN, wxStrlen(ARG_PSN)) == 0 )
05e2b077
VZ
619 {
620 // remove this argument
33f39af3
GD
621 --argc;
622 memmove(argv + 1, argv + 2, argc * sizeof(char *));
05e2b077
VZ
623 }
624 }
625
94826170
VZ
626 if ( !wxAppBase::Initialize(argc, argv) )
627 return false;
e9576ca5 628
d9d19e75
SC
629#if wxUSE_INTL
630 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
631#endif
632
e256c692
SC
633#if TARGET_API_MAC_OSX
634 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
635 wxString startupCwd = wxGetCwd() ;
6601362a 636 if ( startupCwd == wxT("/") || startupCwd.Right(15) == wxT("/Contents/MacOS") )
e256c692
SC
637 {
638 wxString cwd ;
639 CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
640 CFURLRef urlParent = CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault , url ) ;
641 CFRelease( url ) ;
642 CFStringRef path = CFURLCopyFileSystemPath ( urlParent , kCFURLPOSIXPathStyle ) ;
643 CFRelease( urlParent ) ;
644 CFIndex len = CFStringGetLength( path ) ;
645 CFIndex max = CFStringGetMaximumSizeForEncoding( len, kCFStringEncodingUTF8 ) ;
646 wxChar* buf = cwd.GetWriteBuf( max ) ;
647 CFStringGetCString( path , buf , max + 1 , kCFStringEncodingUTF8 ) ;
648 CFRelease( path ) ;
649 cwd.UngetWriteBuf() ;
650 wxSetWorkingDirectory( cwd ) ;
651 }
652#endif
d9d19e75 653
376b18ea 654 wxMacCreateNotifierTable() ;
9779893b 655
376b18ea 656 UMAShowArrowCursor() ;
8461e4c2 657
94826170 658 return true;
e9576ca5
SC
659}
660
15b41e90
SC
661bool wxApp::OnInitGui()
662{
e40298d5
JS
663 if( !wxAppBase::OnInitGui() )
664 return false ;
7c9955d1 665
e40298d5 666 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
7c9955d1 667
e128397f
DS
668 if (!sm_isEmbedded)
669 {
670 InstallApplicationEventHandler(
facd6764 671 GetwxMacAppEventHandlerUPP(),
e128397f
DS
672 GetEventTypeCount(eventList), eventList, wxTheApp, (EventHandlerRef *)&(wxTheApp->m_macEventHandler));
673 }
7c9955d1 674
e128397f
DS
675 if (!sm_isEmbedded)
676 {
e128397f
DS
677 AEInstallEventHandler( kCoreEventClass , kAEOpenDocuments ,
678 NewAEEventHandlerUPP(AEHandleODoc) ,
679 0 , FALSE ) ;
680 AEInstallEventHandler( kCoreEventClass , kAEOpenApplication ,
681 NewAEEventHandlerUPP(AEHandleOApp) ,
682 0 , FALSE ) ;
683 AEInstallEventHandler( kCoreEventClass , kAEPrintDocuments ,
684 NewAEEventHandlerUPP(AEHandlePDoc) ,
685 0 , FALSE ) ;
1c32ded3
SC
686 AEInstallEventHandler( kCoreEventClass , kAEReopenApplication ,
687 NewAEEventHandlerUPP(AEHandleRApp) ,
688 0 , FALSE ) ;
e128397f
DS
689 AEInstallEventHandler( kCoreEventClass , kAEQuitApplication ,
690 NewAEEventHandlerUPP(AEHandleQuit) ,
691 0 , FALSE ) ;
e128397f 692 }
15b41e90 693
e40298d5 694 return TRUE ;
15b41e90
SC
695}
696
e9576ca5
SC
697void wxApp::CleanUp()
698{
12cd5f34 699 wxToolTip::RemoveToolTips() ;
2f1ae414
SC
700
701 // One last chance for pending objects to be cleaned up
702 wxTheApp->DeletePendingObjects();
703
fbbdb7cd 704 wxMacDestroyNotifierTable() ;
84c1ffa9 705
f5c6eb5c 706#ifndef __DARWIN__
fbbdb7cd 707# if __option(profile)
ac2153a6 708 ProfilerDump( (StringPtr)"\papp.prof" ) ;
fbbdb7cd
GD
709 ProfilerTerm() ;
710# endif
9779893b 711#endif
519cb848 712
21870a5d 713#if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
fbbdb7cd
GD
714 // close shared library resources from here since we don't have
715 // __wxterminate in Mach-O shared libraries
716 wxStAppResource::CloseSharedLibraryResource();
717#endif
7c9955d1 718
8461e4c2 719 UMACleanupToolbox() ;
fbbdb7cd 720 if (s_macCursorRgn) {
76a5e5d2 721 ::DisposeRgn((RgnHandle)s_macCursorRgn);
fbbdb7cd 722 }
84c1ffa9 723
8461e4c2
VZ
724 #if 0
725 TerminateAE() ;
726 #endif
94826170
VZ
727
728 wxAppBase::CleanUp();
e9576ca5
SC
729}
730
92b002a4 731//----------------------------------------------------------------------
05e2b077 732// misc initialization stuff
92b002a4
RD
733//----------------------------------------------------------------------
734
fbbdb7cd
GD
735// extern variable for shared library resource id
736// need to be able to find it with NSLookupAndBindSymbol
facd6764 737short gSharedLibraryResource = kResFileNotOpened ;
fbbdb7cd 738
21870a5d 739#if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
fbbdb7cd 740CFBundleRef gSharedLibraryBundle = NULL;
21870a5d 741#endif /* WXMAKINGDLL_CORE && __DARWIN__ */
53fd991c
SC
742
743wxStAppResource::wxStAppResource()
744{
fbbdb7cd
GD
745 m_currentRefNum = CurResFile() ;
746 if ( gSharedLibraryResource != kResFileNotOpened )
747 {
748 UseResFile( gSharedLibraryResource ) ;
749 }
750}
751
752wxStAppResource::~wxStAppResource()
753{
754 if ( m_currentRefNum != kResFileNotOpened )
755 {
756 UseResFile( m_currentRefNum ) ;
757 }
758}
759
760void wxStAppResource::OpenSharedLibraryResource(const void *initBlock)
761{
762 gSharedLibraryResource = kResFileNotOpened;
763
21870a5d 764#ifdef WXMAKINGDLL_CORE
fbbdb7cd
GD
765 if ( initBlock != NULL ) {
766 const CFragInitBlock *theInitBlock = (const CFragInitBlock *)initBlock;
767 FSSpec *fileSpec = NULL;
84c1ffa9 768
fbbdb7cd
GD
769 if (theInitBlock->fragLocator.where == kDataForkCFragLocator) {
770 fileSpec = theInitBlock->fragLocator.u.onDisk.fileSpec;
771 }
772 else if (theInitBlock->fragLocator.where == kResourceCFragLocator) {
773 fileSpec = theInitBlock->fragLocator.u.inSegs.fileSpec;
774 }
84c1ffa9 775
fbbdb7cd
GD
776 if (fileSpec != NULL) {
777 gSharedLibraryResource = FSpOpenResFile(fileSpec, fsRdPerm);
778 }
779 }
780 else {
781#ifdef __DARWIN__
782 // Open the shared library resource file if it is not yet open
ed581ee2
GD
783 NSSymbol theSymbol;
784 NSModule theModule;
785 const char *theLibPath;
84c1ffa9 786
77ffb593 787 gSharedLibraryBundle = CFBundleGetBundleWithIdentifier(CFSTR("com.wxwindows.wxWidgets"));
fbbdb7cd 788 if (gSharedLibraryBundle != NULL) {
77ffb593 789 // wxWidgets has been bundled into a framework
ed581ee2 790 // load the framework resources
84c1ffa9 791
fbbdb7cd 792 gSharedLibraryResource = CFBundleOpenBundleResourceMap(gSharedLibraryBundle);
ed581ee2
GD
793 }
794 else {
77ffb593 795 // wxWidgets is a simple dynamic shared library
ed581ee2 796 // load the resources from the data fork of a separate resource file
21870a5d
RD
797 wxString theResPath;
798 wxString theName;
ed581ee2
GD
799 FSRef theResRef;
800 OSErr theErr = noErr;
84c1ffa9 801
ed581ee2 802 // get the library path
fbbdb7cd 803 theSymbol = NSLookupAndBindSymbol("_gSharedLibraryResource");
ed581ee2
GD
804 theModule = NSModuleForSymbol(theSymbol);
805 theLibPath = NSLibraryNameForModule(theModule);
ed581ee2 806
376b18ea
VZ
807 // if we call wxLogDebug from here then, as wxTheApp hasn't been
808 // created yet when we're called from wxApp::Initialize(), wxLog
809 // is going to create a default stderr-based log target instead of
810 // the expected normal GUI one -- don't do it, if we really want
811 // to see this message just use fprintf() here
812#if 0
f346733b
GD
813 wxLogDebug( wxT("wxMac library installation name is '%s'"),
814 theLibPath );
376b18ea 815#endif
f346733b 816
ed581ee2 817 // allocate copy to replace .dylib.* extension with .rsrc
21870a5d 818 if (theLibPath != NULL) {
bc93670d
GD
819#if wxUSE_UNICODE
820 theResPath = wxString(theLibPath, wxConvLocal);
821#else
822 theResPath = wxString(theLibPath);
823#endif
21870a5d
RD
824 // replace '_core' with '' in case of multi-lib build
825 theResPath.Replace(wxT("_core"), wxEmptyString);
826 // replace ".dylib" shared library extension with ".rsrc"
827 theResPath.Replace(wxT(".dylib"), wxT(".rsrc"));
828 // Find the begining of the filename
829 theName = theResPath.AfterLast('/');
84c1ffa9 830
376b18ea 831#if 0
f346733b 832 wxLogDebug( wxT("wxMac resources file name is '%s'"),
21870a5d 833 theResPath.mb_str() );
376b18ea 834#endif
ed581ee2 835
21870a5d 836 theErr = FSPathMakeRef((UInt8 *) theResPath.mb_str(), &theResRef, false);
ed581ee2
GD
837 if (theErr != noErr) {
838 // try in current directory (using name only)
21870a5d 839 theErr = FSPathMakeRef((UInt8 *) theName.mb_str(), &theResRef, false);
ed581ee2 840 }
84c1ffa9 841
ed581ee2
GD
842 // open the resource file
843 if (theErr == noErr) {
844 theErr = FSOpenResourceFile( &theResRef, 0, NULL, fsRdPerm,
fbbdb7cd 845 &gSharedLibraryResource);
ed581ee2 846 }
f346733b 847 if (theErr != noErr) {
376b18ea 848#ifdef __WXDEBUG__
bc93670d
GD
849 wxLogDebug( wxT("unable to open wxMac resource file '%s'\n"),
850 theResPath.mb_str() );
376b18ea 851#endif // __WXDEBUG__
f346733b
GD
852 }
853
ed581ee2
GD
854 }
855 }
fbbdb7cd 856#endif /* __DARWIN__ */
53fd991c 857 }
21870a5d 858#endif /* WXMAKINGDLL_CORE */
53fd991c
SC
859}
860
fbbdb7cd 861void wxStAppResource::CloseSharedLibraryResource()
53fd991c 862{
21870a5d 863#ifdef WXMAKINGDLL_CORE
ed581ee2 864 // Close the shared library resource file
fbbdb7cd
GD
865 if (gSharedLibraryResource != kResFileNotOpened) {
866#ifdef __DARWIN__
867 if (gSharedLibraryBundle != NULL) {
868 CFBundleCloseBundleResourceMap(gSharedLibraryBundle,
869 gSharedLibraryResource);
870 gSharedLibraryBundle = NULL;
ed581ee2 871 }
fbbdb7cd
GD
872 else
873#endif /* __DARWIN__ */
874 {
875 CloseResFile(gSharedLibraryResource);
ed581ee2 876 }
fbbdb7cd 877 gSharedLibraryResource = kResFileNotOpened;
84c1ffa9 878 }
21870a5d 879#endif /* WXMAKINGDLL_CORE */
53fd991c
SC
880}
881
21870a5d 882#if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
53fd991c 883
ed581ee2
GD
884// for shared libraries we have to manually get the correct resource
885// ref num upon initializing and releasing when terminating, therefore
886// the __wxinitialize and __wxterminate must be used
53fd991c 887
53fd991c 888extern "C" {
e40298d5 889 void __sinit(void); /* (generated by linker) */
fbbdb7cd
GD
890 pascal OSErr __initialize(const CFragInitBlock *theInitBlock);
891 pascal void __terminate(void);
53fd991c 892}
53fd991c
SC
893
894pascal OSErr __wxinitialize(const CFragInitBlock *theInitBlock)
895{
fbbdb7cd
GD
896 wxStAppResource::OpenSharedLibraryResource( theInitBlock ) ;
897 return __initialize( theInitBlock ) ;
53fd991c
SC
898}
899
900pascal void __wxterminate(void)
901{
fbbdb7cd 902 wxStAppResource::CloseSharedLibraryResource() ;
53fd991c
SC
903 __terminate() ;
904}
ed581ee2 905
21870a5d 906#endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
53fd991c 907
b4efa069
SC
908bool wxMacConvertEventToRecord( EventRef event , EventRecord *rec)
909{
910 bool converted = ConvertEventRefToEventRecord( event,rec) ;
911 OSStatus err = noErr ;
912 if ( !converted )
913 {
914 switch( GetEventClass( event ) )
915 {
916 case kEventClassKeyboard :
917 {
918 converted = true ;
84c1ffa9 919 switch( GetEventKind(event) )
b4efa069
SC
920 {
921 case kEventRawKeyDown :
922 rec->what = keyDown ;
923 break ;
924 case kEventRawKeyRepeat :
925 rec->what = autoKey ;
926 break ;
927 case kEventRawKeyUp :
928 rec->what = keyUp ;
929 break ;
930 case kEventRawKeyModifiersChanged :
931 rec->what = nullEvent ;
932 break ;
933 default :
934 converted = false ;
935 break ;
936 }
937 if ( converted )
938 {
939 UInt32 keyCode ;
940 unsigned char charCode ;
941 UInt32 modifiers ;
942 GetMouse( &rec->where) ;
943
944 err = GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL, 4, NULL, &modifiers);
945 err = GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL, 4, NULL, &keyCode);
946 err = GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL, 1, NULL, &charCode);
947 rec->modifiers = modifiers ;
948 rec->message = (keyCode << 8 ) + charCode ;
949 }
950 }
951 break ;
952 case kEventClassTextInput :
953 {
954 switch( GetEventKind( event ) )
955 {
956 case kEventTextInputUnicodeForKeyEvent :
957 {
958 EventRef rawEvent ;
959 err = GetEventParameter( event , kEventParamTextInputSendKeyboardEvent ,typeEventRef,NULL,sizeof(rawEvent),NULL,&rawEvent ) ;
960 converted = true ;
961 {
962 UInt32 keyCode ;
963 unsigned char charCode ;
964 UInt32 modifiers ;
965 GetMouse( &rec->where) ;
966 rec->what = keyDown ;
967 err = GetEventParameter(rawEvent, kEventParamKeyModifiers, typeUInt32, NULL, 4, NULL, &modifiers);
968 err = GetEventParameter(rawEvent, kEventParamKeyCode, typeUInt32, NULL, 4, NULL, &keyCode);
969 err = GetEventParameter(rawEvent, kEventParamKeyMacCharCodes, typeChar, NULL, 1, NULL, &charCode);
970 rec->modifiers = modifiers ;
971 rec->message = (keyCode << 8 ) + charCode ;
972 }
973 }
974 break ;
975 default :
976 break ;
977 }
978 }
979 break ;
980 }
981 }
84c1ffa9 982
b4efa069
SC
983 return converted ;
984}
985
e9576ca5
SC
986wxApp::wxApp()
987{
e9576ca5 988 m_printMode = wxPRINT_WINDOWS;
1ea39a03
SC
989
990 m_macCurrentEvent = NULL ;
991 m_macCurrentEventHandlerCallRef = NULL ;
e9576ca5
SC
992}
993
e9576ca5
SC
994int wxApp::MainLoop()
995{
e40298d5 996 m_keepGoing = TRUE;
3fbf8e7f
SC
997#if wxMAC_USE_RAEL
998 RunApplicationEventLoop() ;
999#else
e40298d5
JS
1000 while (m_keepGoing)
1001 {
1002 MacDoOneEvent() ;
1003 }
3fbf8e7f 1004#endif
e40298d5 1005 return 0;
e9576ca5
SC
1006}
1007
e9576ca5
SC
1008void wxApp::ExitMainLoop()
1009{
3fbf8e7f
SC
1010 m_keepGoing = FALSE;
1011#if wxMAC_USE_RAEL
1012 QuitApplicationEventLoop() ;
1013#endif
e9576ca5
SC
1014}
1015
1016// Is a message/event pending?
1017bool wxApp::Pending()
1018{
2dd35daa
SC
1019 // without the receive event (with pull param = false ) nothing is ever reported
1020 EventRef theEvent;
1021 ReceiveNextEvent (0, NULL, kEventDurationNoWait, false, &theEvent);
1022 return GetNumEventsInQueue( GetMainEventQueue() ) > 0 ;
e9576ca5
SC
1023}
1024
1025// Dispatch a message.
1bf77ee5 1026bool wxApp::Dispatch()
e9576ca5 1027{
8461e4c2 1028 MacDoOneEvent() ;
1bf77ee5
VZ
1029
1030 return true;
e9576ca5
SC
1031}
1032
1033void wxApp::OnIdle(wxIdleEvent& event)
1034{
955a9197 1035 wxAppBase::OnIdle(event);
21870a5d 1036
2f1ae414
SC
1037 // If they are pending events, we must process them: pending events are
1038 // either events to the threads other than main or events posted with
1039 // wxPostEvent() functions
1040 wxMacProcessNotifierAndPendingEvents();
1041
3fdac2ab
DE
1042 if(!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1043 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
e9576ca5
SC
1044}
1045
e2478fde 1046void wxApp::WakeUpIdle()
9779893b 1047{
8461e4c2 1048 wxMacWakeUp() ;
9779893b
RD
1049}
1050
e2478fde 1051void wxApp::Exit()
e9576ca5 1052{
2f1ae414 1053 wxApp::CleanUp();
8461e4c2 1054 ::ExitToShell() ;
e9576ca5
SC
1055}
1056
2f1ae414
SC
1057void wxApp::OnEndSession(wxCloseEvent& WXUNUSED(event))
1058{
1059 if (GetTopWindow())
1060 GetTopWindow()->Close(TRUE);
1061}
1062
1063// Default behaviour: close the application with prompts. The
1064// user can veto the close, and therefore the end session.
1065void wxApp::OnQueryEndSession(wxCloseEvent& event)
1066{
1067 if (GetTopWindow())
1068 {
1069 if (!GetTopWindow()->Close(!event.CanVeto()))
1070 event.Veto(TRUE);
1071 }
1072}
1073
1074extern "C" void wxCYield() ;
1075void wxCYield()
1076{
8461e4c2 1077 wxYield() ;
2f1ae414
SC
1078}
1079
e9576ca5 1080// Yield to other processes
cb2713bf 1081
8461e4c2 1082bool wxApp::Yield(bool onlyIfNeeded)
e9576ca5 1083{
8461e4c2
VZ
1084 if (s_inYield)
1085 {
1086 if ( !onlyIfNeeded )
1087 {
1088 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1089 }
1090
1091 return FALSE;
1092 }
1093
1094 s_inYield = TRUE;
cb2713bf 1095
e40298d5 1096 // by definition yield should handle all non-processed events
facd6764 1097
e40298d5
JS
1098 EventRef theEvent;
1099
1100 OSStatus status = noErr ;
1101 do
1102 {
1103 s_inReceiveEvent = true ;
1104 status = ReceiveNextEvent(0, NULL,kEventDurationNoWait,true,&theEvent) ;
1105 s_inReceiveEvent = false ;
7c9955d1 1106
e40298d5
JS
1107 if ( status == eventLoopTimedOutErr )
1108 {
1109 // make sure next time the event loop will trigger idle events
1110 sleepTime = kEventDurationNoWait ;
1111 }
1112 else if ( status == eventLoopQuitErr )
1113 {
1114 // according to QA1061 this may also occur when a WakeUp Process
1115 // is executed
1116 }
1117 else
1118 {
1119 MacHandleOneEvent( theEvent ) ;
1120 ReleaseEvent(theEvent);
1121 }
1122 } while( status == noErr ) ;
2f1ae414 1123
8461e4c2 1124 wxMacProcessNotifierAndPendingEvents() ;
8461e4c2 1125 s_inYield = FALSE;
cb2713bf 1126
8461e4c2 1127 return TRUE;
169935ad
SC
1128}
1129
9779893b 1130void wxApp::MacDoOneEvent()
169935ad 1131{
e40298d5 1132 EventRef theEvent;
c5c9378c 1133
e40298d5
JS
1134 s_inReceiveEvent = true ;
1135 OSStatus status = ReceiveNextEvent(0, NULL,sleepTime,true,&theEvent) ;
1136 s_inReceiveEvent = false ;
1137 if ( status == eventLoopTimedOutErr )
1138 {
c5c9378c 1139 if ( wxTheApp->ProcessIdle() )
e40298d5 1140 sleepTime = kEventDurationNoWait ;
c5c9378c 1141 else
820d6bac 1142 sleepTime = kEventDurationSecond;
e40298d5
JS
1143 }
1144 else if ( status == eventLoopQuitErr )
1145 {
1146 // according to QA1061 this may also occur when a WakeUp Process
1147 // is executed
1148 }
1149 else
1150 {
1151 MacHandleOneEvent( theEvent ) ;
1152 ReleaseEvent(theEvent);
3470af1c 1153 sleepTime = kEventDurationNoWait ;
e40298d5 1154 }
8461e4c2 1155 // repeaters
519cb848 1156
6264b550 1157 DeletePendingObjects() ;
8461e4c2 1158 wxMacProcessNotifierAndPendingEvents() ;
169935ad
SC
1159}
1160
e128397f
DS
1161/*virtual*/ void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr )
1162{
1163 // Override to process unhandled events as you please
1164}
1165
76a5e5d2 1166void wxApp::MacHandleOneEvent( WXEVENTREF evr )
169935ad 1167{
e40298d5
JS
1168 EventTargetRef theTarget;
1169 theTarget = GetEventDispatcherTarget();
c5c9378c 1170 m_macCurrentEvent = evr ;
e128397f
DS
1171 OSStatus status = SendEventToEventTarget ((EventRef) evr , theTarget);
1172 if(status == eventNotHandledErr)
1173 {
1174 MacHandleUnhandledEvent(evr);
1175 }
8461e4c2 1176 wxMacProcessNotifierAndPendingEvents() ;
f8df60f2
SC
1177#if wxUSE_THREADS
1178 wxMutexGuiLeaveOrEnter();
1179#endif // wxUSE_THREADS
169935ad
SC
1180}
1181
72055702 1182long wxMacTranslateKey(unsigned char key, unsigned char code) ;
7c551d95 1183long wxMacTranslateKey(unsigned char key, unsigned char code)
9779893b 1184{
8461e4c2 1185 long retval = key ;
9779893b 1186 switch (key)
519cb848 1187 {
12e049f6 1188 case kHomeCharCode :
8461e4c2
VZ
1189 retval = WXK_HOME;
1190 break;
12e049f6 1191 case kEnterCharCode :
8461e4c2
VZ
1192 retval = WXK_RETURN;
1193 break;
12e049f6 1194 case kEndCharCode :
8461e4c2
VZ
1195 retval = WXK_END;
1196 break;
12e049f6 1197 case kHelpCharCode :
8461e4c2
VZ
1198 retval = WXK_HELP;
1199 break;
12e049f6 1200 case kBackspaceCharCode :
8461e4c2
VZ
1201 retval = WXK_BACK;
1202 break;
12e049f6 1203 case kTabCharCode :
8461e4c2
VZ
1204 retval = WXK_TAB;
1205 break;
12e049f6 1206 case kPageUpCharCode :
8461e4c2
VZ
1207 retval = WXK_PAGEUP;
1208 break;
12e049f6 1209 case kPageDownCharCode :
8461e4c2
VZ
1210 retval = WXK_PAGEDOWN;
1211 break;
12e049f6 1212 case kReturnCharCode :
8461e4c2
VZ
1213 retval = WXK_RETURN;
1214 break;
12e049f6 1215 case kFunctionKeyCharCode :
8461e4c2
VZ
1216 {
1217 switch( code )
1218 {
1219 case 0x7a :
1220 retval = WXK_F1 ;
1221 break;
1222 case 0x78 :
1223 retval = WXK_F2 ;
1224 break;
1225 case 0x63 :
1226 retval = WXK_F3 ;
1227 break;
1228 case 0x76 :
1229 retval = WXK_F4 ;
1230 break;
1231 case 0x60 :
1232 retval = WXK_F5 ;
1233 break;
1234 case 0x61 :
1235 retval = WXK_F6 ;
1236 break;
1237 case 0x62:
1238 retval = WXK_F7 ;
1239 break;
1240 case 0x64 :
1241 retval = WXK_F8 ;
1242 break;
1243 case 0x65 :
1244 retval = WXK_F9 ;
1245 break;
1246 case 0x6D :
1247 retval = WXK_F10 ;
1248 break;
1249 case 0x67 :
1250 retval = WXK_F11 ;
1251 break;
1252 case 0x6F :
1253 retval = WXK_F12 ;
1254 break;
1255 case 0x69 :
1256 retval = WXK_F13 ;
1257 break;
1258 case 0x6B :
1259 retval = WXK_F14 ;
1260 break;
1261 case 0x71 :
1262 retval = WXK_F15 ;
1263 break;
1264 }
1265 }
1266 break ;
12e049f6 1267 case kEscapeCharCode :
8461e4c2
VZ
1268 retval = WXK_ESCAPE ;
1269 break ;
12e049f6 1270 case kLeftArrowCharCode :
8461e4c2
VZ
1271 retval = WXK_LEFT ;
1272 break ;
12e049f6 1273 case kRightArrowCharCode :
8461e4c2
VZ
1274 retval = WXK_RIGHT ;
1275 break ;
12e049f6 1276 case kUpArrowCharCode :
8461e4c2
VZ
1277 retval = WXK_UP ;
1278 break ;
12e049f6 1279 case kDownArrowCharCode :
8461e4c2
VZ
1280 retval = WXK_DOWN ;
1281 break ;
12e049f6 1282 case kDeleteCharCode :
8461e4c2
VZ
1283 retval = WXK_DELETE ;
1284 default:
1285 break ;
1286 } // end switch
1287
1288 return retval;
169935ad
SC
1289}
1290
facd6764 1291int wxMacKeyCodeToModifier(wxKeyCode key)
6ed892f3
RN
1292{
1293 switch (key)
1294 {
1295 case WXK_START:
15c2acd2 1296 case WXK_MENU:
6ed892f3
RN
1297 return cmdKey;
1298
1299 case WXK_SHIFT:
1300 return shiftKey;
1301
1302 case WXK_CAPITAL:
1303 return alphaLock;
1304
15c2acd2
RN
1305 case WXK_ALT:
1306 return optionKey;
6ed892f3
RN
1307
1308 case WXK_CONTROL:
1309 return controlKey;
1310
1311 default:
1312 return 0;
1313 }
1314}
1315
1316bool wxGetKeyState(wxKeyCode key) //virtual key code if < 10.2.x, else see below
1317{
7f71c4c8
RN
1318//#ifdef __DARWIN__
1319// wxHIDKeyboard keyboard;
1320// return keyboard.IsActive(key);
1321//#else
104cdef6 1322// TODO: Have it use HID Manager on OSX...
6ed892f3
RN
1323//if OS X > 10.2 (i.e. 10.2.x)
1324//a known apple bug prevents the system from determining led
1325//states with GetKeys... can only determine caps lock led
facd6764 1326 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key));
6ed892f3
RN
1327//else
1328// KeyMapByteArray keymap;
1329// GetKeys((BigEndianLong*)keymap);
1330// return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
7f71c4c8 1331//#endif
6ed892f3
RN
1332}
1333
c5c9378c 1334
12e049f6 1335bool wxApp::MacSendKeyDownEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey )
ac2d1ca6 1336{
ba12463b
SC
1337 if ( !focus )
1338 return false ;
7c9955d1 1339
12e049f6
SC
1340 short keycode ;
1341 short keychar ;
1342 keychar = short(keymessage & charCodeMask);
1343 keycode = short(keymessage & keyCodeMask) >> 8 ;
7c9955d1 1344
ef08713a 1345 if ( modifiers & ( controlKey|shiftKey|optionKey ) )
12e049f6
SC
1346 {
1347 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1348 // and look at the character after
1349 UInt32 state = 0;
ef08713a 1350 UInt32 keyInfo = KeyTranslate((Ptr)GetScriptManagerVariable(smKCHRCache), ( modifiers & (~(controlKey|shiftKey|optionKey))) | keycode, &state);
12e049f6
SC
1351 keychar = short(keyInfo & charCodeMask);
1352 keycode = short(keyInfo & keyCodeMask) >> 8 ;
1353 }
1354 long keyval = wxMacTranslateKey(keychar, keycode) ;
e40298d5
JS
1355 long realkeyval = keyval ;
1356 if ( keyval == keychar )
1357 {
1358 // we are not on a special character combo -> pass the real os event-value to EVT_CHAR, but not to EVT_KEY (make upper first)
1359 realkeyval = short(keymessage & charCodeMask) ;
1360 keyval = wxToupper( keyval ) ;
1361 }
7c9955d1 1362
ac2d1ca6 1363 wxKeyEvent event(wxEVT_KEY_DOWN);
41d368a4 1364 bool handled = false ;
ac2d1ca6
SC
1365 event.m_shiftDown = modifiers & shiftKey;
1366 event.m_controlDown = modifiers & controlKey;
1367 event.m_altDown = modifiers & optionKey;
1368 event.m_metaDown = modifiers & cmdKey;
ef08713a 1369 event.m_keyCode = keyval ;
ac2d1ca6
SC
1370
1371 event.m_x = wherex;
1372 event.m_y = wherey;
1373 event.m_timeStamp = when;
1374 event.SetEventObject(focus);
1375 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1376 if ( handled && event.GetSkipped() )
1377 handled = false ;
1378 if ( !handled )
1379 {
ba2928c6 1380#if wxUSE_ACCEL
ac2d1ca6
SC
1381 if (!handled)
1382 {
1383 wxWindow *ancestor = focus;
1384 while (ancestor)
1385 {
1386 int command = ancestor->GetAcceleratorTable()->GetCommand( event );
1387 if (command != -1)
8461e4c2 1388 {
ac2d1ca6
SC
1389 wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1390 handled = ancestor->GetEventHandler()->ProcessEvent( command_event );
1391 break;
8461e4c2 1392 }
ac2d1ca6
SC
1393 if (ancestor->IsTopLevel())
1394 break;
1395 ancestor = ancestor->GetParent();
8461e4c2 1396 }
ac2d1ca6
SC
1397 }
1398#endif // wxUSE_ACCEL
1399 }
1400 if (!handled)
1401 {
1402 event.Skip( FALSE ) ;
1403 event.SetEventType( wxEVT_CHAR ) ;
12e049f6 1404 // raw value again
ef08713a 1405 event.m_keyCode = realkeyval ;
ac2d1ca6
SC
1406
1407 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1408 if ( handled && event.GetSkipped() )
1409 handled = false ;
1410 }
bdf956fb 1411 if ( !handled && (keyval == WXK_TAB) )
ac2d1ca6 1412 {
bdf956fb
SC
1413 wxWindow* iter = focus->GetParent() ;
1414 while( iter && !handled )
1415 {
1416 if ( iter->HasFlag( wxTAB_TRAVERSAL ) )
1417 {
1418 wxNavigationKeyEvent new_event;
1419 new_event.SetEventObject( focus );
1420 new_event.SetDirection( !event.ShiftDown() );
1421 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1422 new_event.SetWindowChange( event.ControlDown() );
1423 new_event.SetCurrentFocus( focus );
1424 handled = focus->GetParent()->GetEventHandler()->ProcessEvent( new_event );
1425 if ( handled && new_event.GetSkipped() )
1426 handled = false ;
1427 }
1428 iter = iter->GetParent() ;
1429 }
ac2d1ca6
SC
1430 }
1431 // backdoor handler for default return and command escape
1432 if ( !handled && (!focus->IsKindOf(CLASSINFO(wxControl) ) || !focus->MacCanFocus() ) )
1433 {
1434 // if window is not having a focus still testing for default enter or cancel
1435 // TODO add the UMA version for ActiveNonFloatingWindow
1436 wxWindow* focus = wxFindWinFromMacWindow( FrontWindow() ) ;
e562df9b
SC
1437 if ( focus )
1438 {
1439 if ( keyval == WXK_RETURN )
1440 {
1441 wxButton *def = wxDynamicCast(focus->GetDefaultItem(),
1442 wxButton);
1443 if ( def && def->IsEnabled() )
1444 {
1445 wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, def->GetId() );
1446 event.SetEventObject(def);
1447 def->Command(event);
ac2d1ca6 1448 return true ;
e562df9b
SC
1449 }
1450 }
8461e4c2 1451 /* generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs) */
ac2d1ca6 1452 else if (keyval == WXK_ESCAPE || (keyval == '.' && modifiers & cmdKey ) )
8461e4c2 1453 {
e562df9b
SC
1454 wxCommandEvent new_event(wxEVT_COMMAND_BUTTON_CLICKED,wxID_CANCEL);
1455 new_event.SetEventObject( focus );
1456 handled = focus->GetEventHandler()->ProcessEvent( new_event );
8461e4c2 1457 }
e562df9b 1458 }
8461e4c2 1459 }
ac2d1ca6 1460 return handled ;
169935ad
SC
1461}
1462
12e049f6 1463bool wxApp::MacSendKeyUpEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey )
ac2d1ca6 1464{
ba12463b
SC
1465 if ( !focus )
1466 return false ;
1467
12e049f6
SC
1468 short keycode ;
1469 short keychar ;
1470 keychar = short(keymessage & charCodeMask);
1471 keycode = short(keymessage & keyCodeMask) >> 8 ;
ef08713a 1472 if ( modifiers & ( controlKey|shiftKey|optionKey ) )
12e049f6
SC
1473 {
1474 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1475 // and look at the character after
1476 UInt32 state = 0;
ef08713a 1477 UInt32 keyInfo = KeyTranslate((Ptr)GetScriptManagerVariable(smKCHRCache), ( modifiers & (~(controlKey|shiftKey|optionKey))) | keycode, &state);
12e049f6
SC
1478 keychar = short(keyInfo & charCodeMask);
1479 keycode = short(keyInfo & keyCodeMask) >> 8 ;
1480 }
1481 long keyval = wxMacTranslateKey(keychar, keycode) ;
1482
e40298d5
JS
1483 if ( keyval == keychar )
1484 {
7c9955d1 1485 keyval = wxToupper( keyval ) ;
e40298d5 1486 }
ac2d1ca6 1487 bool handled = false ;
ac2d1ca6 1488
ba12463b
SC
1489 wxKeyEvent event(wxEVT_KEY_UP);
1490 event.m_shiftDown = modifiers & shiftKey;
1491 event.m_controlDown = modifiers & controlKey;
1492 event.m_altDown = modifiers & optionKey;
1493 event.m_metaDown = modifiers & cmdKey;
ef08713a 1494 event.m_keyCode = keyval ;
ba12463b
SC
1495
1496 event.m_x = wherex;
1497 event.m_y = wherey;
1498 event.m_timeStamp = when;
1499 event.SetEventObject(focus);
1500 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1501
ac2d1ca6
SC
1502 return handled ;
1503}