]> git.saurik.com Git - wxWidgets.git/blame - src/mac/carbon/app.cpp
SetValue is not adding a line if values does not exist
[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 )
27740109 369{
dae6d730
SC
370 wxMacCarbonEvent cEvent( event ) ;
371 MenuRef menuRef = cEvent.GetParameter<MenuRef>(kEventParamDirectObject) ;
372 wxMenu* menu = wxFindMenuFromMacMenu( menuRef ) ;
373
374 if ( menu )
e32f4a9f 375 {
dae6d730
SC
376 wxEventType type=0;
377 MenuCommand cmd=0;
378 switch (GetEventKind(event))
852b1185 379 {
dae6d730
SC
380 case kEventMenuOpening:
381 type = wxEVT_MENU_OPEN;
382 break;
383 case kEventMenuClosed:
384 type = wxEVT_MENU_CLOSE;
385 break;
386 case kEventMenuTargetItem:
387 cmd = cEvent.GetParameter<MenuCommand>(kEventParamMenuCommand,typeMenuCommand) ;
388 if (cmd != 0)
9f2bfce7 389 type = wxEVT_MENU_HIGHLIGHT;
dae6d730
SC
390 break;
391 default:
392 wxFAIL_MSG(wxT("Unexpected menu event kind"));
393 break;
394 }
852b1185 395
dae6d730
SC
396 if ( type )
397 {
9f2bfce7 398 wxMenuEvent wxevent(type, cmd);
dae6d730 399 wxevent.SetEventObject(menu);
e32f4a9f 400
dae6d730
SC
401 wxEvtHandler* handler = menu->GetEventHandler();
402 if (handler && handler->ProcessEvent(wxevent))
403 {
404 // handled
405 }
406 else
407 {
408 wxWindow *win = menu->GetInvokingWindow();
409 if (win)
410 win->GetEventHandler()->ProcessEvent(wxevent);
411 }
412 }
e32f4a9f 413 }
dae6d730 414
e32f4a9f 415 return eventNotHandledErr;
519cb848
SC
416}
417
facd6764 418static pascal OSStatus wxMacAppCommandEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
15b41e90
SC
419{
420 OSStatus result = eventNotHandledErr ;
421
e40298d5 422 HICommand command ;
7c9955d1 423
dae6d730
SC
424 wxMacCarbonEvent cEvent( event ) ;
425 cEvent.GetParameter<HICommand>(kEventParamDirectObject,typeHICommand,&command) ;
426
427 wxMenuItem* item = NULL ;
e40298d5 428 MenuCommand id = command.commandID ;
dae6d730 429 // for items we don't really control
e40298d5 430 if ( id == kHICommandPreferences )
6d565349 431 {
dae6d730
SC
432 id = wxApp::s_macPreferencesMenuItemId ;
433
434 wxMenuBar* mbar = wxMenuBar::MacGetInstalledMenuBar() ;
435 if ( mbar )
6d565349 436 {
dae6d730
SC
437 wxMenu* menu = NULL ;
438 item = mbar->FindItem( id , &menu ) ;
6d565349
SC
439 }
440 }
dae6d730
SC
441 else if ( id != 0 && command.menu.menuRef != 0 && command.menu.menuItemIndex != 0 )
442 {
443 GetMenuItemRefCon( command.menu.menuRef , command.menu.menuItemIndex , (UInt32*) &item ) ;
444 }
445
446 if ( item )
447 {
448 switch( cEvent.GetKind() )
e40298d5
JS
449 {
450 case kEventProcessCommand :
451 {
452 if (item->IsCheckable())
453 {
454 item->Check( !item->IsChecked() ) ;
455 }
7c9955d1 456
dae6d730 457 item->GetMenu()->SendEvent( id , item->IsCheckable() ? item->IsChecked() : -1 ) ;
e40298d5
JS
458 result = noErr ;
459 }
dae6d730 460 break ;
e40298d5
JS
461 case kEventCommandUpdateStatus:
462 // eventually trigger an updateui round
6d565349 463 result = noErr ;
e40298d5 464 break ;
dae6d730
SC
465 default :
466 break ;
467 }
468 }
15b41e90
SC
469 return result ;
470}
471
facd6764 472static pascal OSStatus wxMacAppApplicationEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
15b41e90
SC
473{
474 OSStatus result = eventNotHandledErr ;
e40298d5
JS
475 switch ( GetEventKind( event ) )
476 {
477 case kEventAppActivated :
478 {
3470af1c 479 if ( wxTheApp )
facd6764 480 wxTheApp->SetActive( true , NULL ) ;
e40298d5
JS
481 result = noErr ;
482 }
483 break ;
484 case kEventAppDeactivated :
485 {
3470af1c 486 if ( wxTheApp )
facd6764 487 wxTheApp->SetActive( false , NULL ) ;
e40298d5
JS
488 result = noErr ;
489 }
490 break ;
491 default :
492 break ;
493 }
15b41e90
SC
494 return result ;
495}
496
facd6764 497pascal OSStatus wxMacAppEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
15b41e90 498{
27740109
SC
499 EventRef formerEvent = (EventRef) wxTheApp->MacGetCurrentEvent() ;
500 EventHandlerCallRef formerEventHandlerCallRef = (EventHandlerCallRef) wxTheApp->MacGetCurrentEventHandlerCallRef() ;
501 wxTheApp->MacSetCurrentEvent( event , handler ) ;
502
15b41e90
SC
503 OSStatus result = eventNotHandledErr ;
504 switch( GetEventClass( event ) )
505 {
e40298d5 506 case kEventClassCommand :
facd6764 507 result = wxMacAppCommandEventHandler( handler , event , data ) ;
e40298d5
JS
508 break ;
509 case kEventClassApplication :
facd6764 510 result = wxMacAppApplicationEventHandler( handler , event , data ) ;
e40298d5
JS
511 break ;
512 case kEventClassMenu :
facd6764 513 result = wxMacAppMenuEventHandler( handler , event , data ) ;
e40298d5
JS
514 break ;
515 case kEventClassMouse :
58ddb76c 516 result = wxMacTopLevelMouseEventHandler( handler , event , NULL ) ;
e40298d5
JS
517 break ;
518 case kEventClassAppleEvent :
519 {
520 EventRecord rec ;
521 wxMacConvertEventToRecord( event , &rec ) ;
522 result = AEProcessAppleEvent( &rec ) ;
523 }
524 break ;
525 default :
526 break ;
15b41e90
SC
527 }
528
27740109
SC
529 wxTheApp->MacSetCurrentEvent( formerEvent, formerEventHandlerCallRef ) ;
530
15b41e90
SC
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 637 {
e256c692
SC
638 CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
639 CFURLRef urlParent = CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault , url ) ;
640 CFRelease( url ) ;
641 CFStringRef path = CFURLCopyFileSystemPath ( urlParent , kCFURLPOSIXPathStyle ) ;
642 CFRelease( urlParent ) ;
a2cffa18 643 wxString cwd = wxMacCFStringHolder(path).AsString(wxLocale::GetSystemEncoding());
e256c692
SC
644 wxSetWorkingDirectory( cwd ) ;
645 }
646#endif
d9d19e75 647
376b18ea 648 wxMacCreateNotifierTable() ;
9779893b 649
376b18ea 650 UMAShowArrowCursor() ;
8461e4c2 651
94826170 652 return true;
e9576ca5
SC
653}
654
15b41e90
SC
655bool wxApp::OnInitGui()
656{
e40298d5
JS
657 if( !wxAppBase::OnInitGui() )
658 return false ;
7c9955d1 659
e40298d5 660 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
7c9955d1 661
e128397f
DS
662 if (!sm_isEmbedded)
663 {
664 InstallApplicationEventHandler(
facd6764 665 GetwxMacAppEventHandlerUPP(),
e128397f
DS
666 GetEventTypeCount(eventList), eventList, wxTheApp, (EventHandlerRef *)&(wxTheApp->m_macEventHandler));
667 }
7c9955d1 668
e128397f
DS
669 if (!sm_isEmbedded)
670 {
e128397f
DS
671 AEInstallEventHandler( kCoreEventClass , kAEOpenDocuments ,
672 NewAEEventHandlerUPP(AEHandleODoc) ,
673 0 , FALSE ) ;
674 AEInstallEventHandler( kCoreEventClass , kAEOpenApplication ,
675 NewAEEventHandlerUPP(AEHandleOApp) ,
676 0 , FALSE ) ;
677 AEInstallEventHandler( kCoreEventClass , kAEPrintDocuments ,
678 NewAEEventHandlerUPP(AEHandlePDoc) ,
679 0 , FALSE ) ;
1c32ded3
SC
680 AEInstallEventHandler( kCoreEventClass , kAEReopenApplication ,
681 NewAEEventHandlerUPP(AEHandleRApp) ,
682 0 , FALSE ) ;
e128397f
DS
683 AEInstallEventHandler( kCoreEventClass , kAEQuitApplication ,
684 NewAEEventHandlerUPP(AEHandleQuit) ,
685 0 , FALSE ) ;
e128397f 686 }
15b41e90 687
e40298d5 688 return TRUE ;
15b41e90
SC
689}
690
e9576ca5
SC
691void wxApp::CleanUp()
692{
12cd5f34 693 wxToolTip::RemoveToolTips() ;
2f1ae414
SC
694
695 // One last chance for pending objects to be cleaned up
696 wxTheApp->DeletePendingObjects();
697
fbbdb7cd 698 wxMacDestroyNotifierTable() ;
84c1ffa9 699
f5c6eb5c 700#ifndef __DARWIN__
fbbdb7cd 701# if __option(profile)
ac2153a6 702 ProfilerDump( (StringPtr)"\papp.prof" ) ;
fbbdb7cd
GD
703 ProfilerTerm() ;
704# endif
9779893b 705#endif
519cb848 706
21870a5d 707#if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
fbbdb7cd
GD
708 // close shared library resources from here since we don't have
709 // __wxterminate in Mach-O shared libraries
710 wxStAppResource::CloseSharedLibraryResource();
711#endif
7c9955d1 712
8461e4c2 713 UMACleanupToolbox() ;
fbbdb7cd 714 if (s_macCursorRgn) {
76a5e5d2 715 ::DisposeRgn((RgnHandle)s_macCursorRgn);
fbbdb7cd 716 }
84c1ffa9 717
8461e4c2
VZ
718 #if 0
719 TerminateAE() ;
720 #endif
94826170
VZ
721
722 wxAppBase::CleanUp();
e9576ca5
SC
723}
724
92b002a4 725//----------------------------------------------------------------------
05e2b077 726// misc initialization stuff
92b002a4
RD
727//----------------------------------------------------------------------
728
fbbdb7cd
GD
729// extern variable for shared library resource id
730// need to be able to find it with NSLookupAndBindSymbol
facd6764 731short gSharedLibraryResource = kResFileNotOpened ;
fbbdb7cd 732
21870a5d 733#if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
fbbdb7cd 734CFBundleRef gSharedLibraryBundle = NULL;
21870a5d 735#endif /* WXMAKINGDLL_CORE && __DARWIN__ */
53fd991c
SC
736
737wxStAppResource::wxStAppResource()
738{
fbbdb7cd
GD
739 m_currentRefNum = CurResFile() ;
740 if ( gSharedLibraryResource != kResFileNotOpened )
741 {
742 UseResFile( gSharedLibraryResource ) ;
743 }
744}
745
746wxStAppResource::~wxStAppResource()
747{
748 if ( m_currentRefNum != kResFileNotOpened )
749 {
750 UseResFile( m_currentRefNum ) ;
751 }
752}
753
754void wxStAppResource::OpenSharedLibraryResource(const void *initBlock)
755{
756 gSharedLibraryResource = kResFileNotOpened;
757
21870a5d 758#ifdef WXMAKINGDLL_CORE
fbbdb7cd
GD
759 if ( initBlock != NULL ) {
760 const CFragInitBlock *theInitBlock = (const CFragInitBlock *)initBlock;
761 FSSpec *fileSpec = NULL;
84c1ffa9 762
fbbdb7cd
GD
763 if (theInitBlock->fragLocator.where == kDataForkCFragLocator) {
764 fileSpec = theInitBlock->fragLocator.u.onDisk.fileSpec;
765 }
766 else if (theInitBlock->fragLocator.where == kResourceCFragLocator) {
767 fileSpec = theInitBlock->fragLocator.u.inSegs.fileSpec;
768 }
84c1ffa9 769
fbbdb7cd
GD
770 if (fileSpec != NULL) {
771 gSharedLibraryResource = FSpOpenResFile(fileSpec, fsRdPerm);
772 }
773 }
774 else {
775#ifdef __DARWIN__
776 // Open the shared library resource file if it is not yet open
ed581ee2
GD
777 NSSymbol theSymbol;
778 NSModule theModule;
779 const char *theLibPath;
84c1ffa9 780
77ffb593 781 gSharedLibraryBundle = CFBundleGetBundleWithIdentifier(CFSTR("com.wxwindows.wxWidgets"));
fbbdb7cd 782 if (gSharedLibraryBundle != NULL) {
77ffb593 783 // wxWidgets has been bundled into a framework
ed581ee2 784 // load the framework resources
84c1ffa9 785
fbbdb7cd 786 gSharedLibraryResource = CFBundleOpenBundleResourceMap(gSharedLibraryBundle);
ed581ee2
GD
787 }
788 else {
77ffb593 789 // wxWidgets is a simple dynamic shared library
ed581ee2 790 // load the resources from the data fork of a separate resource file
21870a5d
RD
791 wxString theResPath;
792 wxString theName;
ed581ee2
GD
793 FSRef theResRef;
794 OSErr theErr = noErr;
84c1ffa9 795
ed581ee2 796 // get the library path
fbbdb7cd 797 theSymbol = NSLookupAndBindSymbol("_gSharedLibraryResource");
ed581ee2
GD
798 theModule = NSModuleForSymbol(theSymbol);
799 theLibPath = NSLibraryNameForModule(theModule);
ed581ee2 800
376b18ea
VZ
801 // if we call wxLogDebug from here then, as wxTheApp hasn't been
802 // created yet when we're called from wxApp::Initialize(), wxLog
803 // is going to create a default stderr-based log target instead of
804 // the expected normal GUI one -- don't do it, if we really want
805 // to see this message just use fprintf() here
806#if 0
f346733b
GD
807 wxLogDebug( wxT("wxMac library installation name is '%s'"),
808 theLibPath );
376b18ea 809#endif
f346733b 810
ed581ee2 811 // allocate copy to replace .dylib.* extension with .rsrc
21870a5d 812 if (theLibPath != NULL) {
bc93670d
GD
813#if wxUSE_UNICODE
814 theResPath = wxString(theLibPath, wxConvLocal);
815#else
816 theResPath = wxString(theLibPath);
817#endif
21870a5d
RD
818 // replace '_core' with '' in case of multi-lib build
819 theResPath.Replace(wxT("_core"), wxEmptyString);
820 // replace ".dylib" shared library extension with ".rsrc"
821 theResPath.Replace(wxT(".dylib"), wxT(".rsrc"));
822 // Find the begining of the filename
823 theName = theResPath.AfterLast('/');
84c1ffa9 824
376b18ea 825#if 0
f346733b 826 wxLogDebug( wxT("wxMac resources file name is '%s'"),
21870a5d 827 theResPath.mb_str() );
376b18ea 828#endif
ed581ee2 829
21870a5d 830 theErr = FSPathMakeRef((UInt8 *) theResPath.mb_str(), &theResRef, false);
ed581ee2
GD
831 if (theErr != noErr) {
832 // try in current directory (using name only)
21870a5d 833 theErr = FSPathMakeRef((UInt8 *) theName.mb_str(), &theResRef, false);
ed581ee2 834 }
84c1ffa9 835
ed581ee2
GD
836 // open the resource file
837 if (theErr == noErr) {
838 theErr = FSOpenResourceFile( &theResRef, 0, NULL, fsRdPerm,
fbbdb7cd 839 &gSharedLibraryResource);
ed581ee2 840 }
f346733b 841 if (theErr != noErr) {
376b18ea 842#ifdef __WXDEBUG__
bc93670d
GD
843 wxLogDebug( wxT("unable to open wxMac resource file '%s'\n"),
844 theResPath.mb_str() );
376b18ea 845#endif // __WXDEBUG__
f346733b
GD
846 }
847
ed581ee2
GD
848 }
849 }
fbbdb7cd 850#endif /* __DARWIN__ */
53fd991c 851 }
21870a5d 852#endif /* WXMAKINGDLL_CORE */
53fd991c
SC
853}
854
fbbdb7cd 855void wxStAppResource::CloseSharedLibraryResource()
53fd991c 856{
21870a5d 857#ifdef WXMAKINGDLL_CORE
ed581ee2 858 // Close the shared library resource file
fbbdb7cd
GD
859 if (gSharedLibraryResource != kResFileNotOpened) {
860#ifdef __DARWIN__
861 if (gSharedLibraryBundle != NULL) {
862 CFBundleCloseBundleResourceMap(gSharedLibraryBundle,
863 gSharedLibraryResource);
864 gSharedLibraryBundle = NULL;
ed581ee2 865 }
fbbdb7cd
GD
866 else
867#endif /* __DARWIN__ */
868 {
869 CloseResFile(gSharedLibraryResource);
ed581ee2 870 }
fbbdb7cd 871 gSharedLibraryResource = kResFileNotOpened;
84c1ffa9 872 }
21870a5d 873#endif /* WXMAKINGDLL_CORE */
53fd991c
SC
874}
875
21870a5d 876#if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
53fd991c 877
ed581ee2
GD
878// for shared libraries we have to manually get the correct resource
879// ref num upon initializing and releasing when terminating, therefore
880// the __wxinitialize and __wxterminate must be used
53fd991c 881
53fd991c 882extern "C" {
e40298d5 883 void __sinit(void); /* (generated by linker) */
fbbdb7cd
GD
884 pascal OSErr __initialize(const CFragInitBlock *theInitBlock);
885 pascal void __terminate(void);
53fd991c 886}
53fd991c
SC
887
888pascal OSErr __wxinitialize(const CFragInitBlock *theInitBlock)
889{
fbbdb7cd
GD
890 wxStAppResource::OpenSharedLibraryResource( theInitBlock ) ;
891 return __initialize( theInitBlock ) ;
53fd991c
SC
892}
893
894pascal void __wxterminate(void)
895{
fbbdb7cd 896 wxStAppResource::CloseSharedLibraryResource() ;
53fd991c
SC
897 __terminate() ;
898}
ed581ee2 899
21870a5d 900#endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
53fd991c 901
b4efa069
SC
902bool wxMacConvertEventToRecord( EventRef event , EventRecord *rec)
903{
904 bool converted = ConvertEventRefToEventRecord( event,rec) ;
905 OSStatus err = noErr ;
906 if ( !converted )
907 {
908 switch( GetEventClass( event ) )
909 {
910 case kEventClassKeyboard :
911 {
912 converted = true ;
84c1ffa9 913 switch( GetEventKind(event) )
b4efa069
SC
914 {
915 case kEventRawKeyDown :
916 rec->what = keyDown ;
917 break ;
918 case kEventRawKeyRepeat :
919 rec->what = autoKey ;
920 break ;
921 case kEventRawKeyUp :
922 rec->what = keyUp ;
923 break ;
924 case kEventRawKeyModifiersChanged :
925 rec->what = nullEvent ;
926 break ;
927 default :
928 converted = false ;
929 break ;
930 }
931 if ( converted )
932 {
933 UInt32 keyCode ;
934 unsigned char charCode ;
935 UInt32 modifiers ;
936 GetMouse( &rec->where) ;
937
938 err = GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL, 4, NULL, &modifiers);
939 err = GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL, 4, NULL, &keyCode);
940 err = GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL, 1, NULL, &charCode);
941 rec->modifiers = modifiers ;
942 rec->message = (keyCode << 8 ) + charCode ;
943 }
944 }
945 break ;
946 case kEventClassTextInput :
947 {
948 switch( GetEventKind( event ) )
949 {
950 case kEventTextInputUnicodeForKeyEvent :
951 {
952 EventRef rawEvent ;
953 err = GetEventParameter( event , kEventParamTextInputSendKeyboardEvent ,typeEventRef,NULL,sizeof(rawEvent),NULL,&rawEvent ) ;
954 converted = true ;
955 {
956 UInt32 keyCode ;
957 unsigned char charCode ;
958 UInt32 modifiers ;
959 GetMouse( &rec->where) ;
960 rec->what = keyDown ;
961 err = GetEventParameter(rawEvent, kEventParamKeyModifiers, typeUInt32, NULL, 4, NULL, &modifiers);
962 err = GetEventParameter(rawEvent, kEventParamKeyCode, typeUInt32, NULL, 4, NULL, &keyCode);
963 err = GetEventParameter(rawEvent, kEventParamKeyMacCharCodes, typeChar, NULL, 1, NULL, &charCode);
964 rec->modifiers = modifiers ;
965 rec->message = (keyCode << 8 ) + charCode ;
966 }
967 }
968 break ;
969 default :
970 break ;
971 }
972 }
973 break ;
974 }
975 }
84c1ffa9 976
b4efa069
SC
977 return converted ;
978}
979
e9576ca5
SC
980wxApp::wxApp()
981{
e9576ca5 982 m_printMode = wxPRINT_WINDOWS;
1ea39a03
SC
983
984 m_macCurrentEvent = NULL ;
985 m_macCurrentEventHandlerCallRef = NULL ;
e9576ca5
SC
986}
987
e9576ca5
SC
988int wxApp::MainLoop()
989{
e40298d5 990 m_keepGoing = TRUE;
3fbf8e7f
SC
991#if wxMAC_USE_RAEL
992 RunApplicationEventLoop() ;
993#else
e40298d5
JS
994 while (m_keepGoing)
995 {
996 MacDoOneEvent() ;
997 }
3fbf8e7f 998#endif
e40298d5 999 return 0;
e9576ca5
SC
1000}
1001
e9576ca5
SC
1002void wxApp::ExitMainLoop()
1003{
3fbf8e7f
SC
1004 m_keepGoing = FALSE;
1005#if wxMAC_USE_RAEL
1006 QuitApplicationEventLoop() ;
1007#endif
e9576ca5
SC
1008}
1009
1010// Is a message/event pending?
1011bool wxApp::Pending()
1012{
2dd35daa
SC
1013 // without the receive event (with pull param = false ) nothing is ever reported
1014 EventRef theEvent;
1015 ReceiveNextEvent (0, NULL, kEventDurationNoWait, false, &theEvent);
1016 return GetNumEventsInQueue( GetMainEventQueue() ) > 0 ;
e9576ca5
SC
1017}
1018
1019// Dispatch a message.
1bf77ee5 1020bool wxApp::Dispatch()
e9576ca5 1021{
8461e4c2 1022 MacDoOneEvent() ;
1bf77ee5
VZ
1023
1024 return true;
e9576ca5
SC
1025}
1026
1027void wxApp::OnIdle(wxIdleEvent& event)
1028{
955a9197 1029 wxAppBase::OnIdle(event);
21870a5d 1030
2f1ae414
SC
1031 // If they are pending events, we must process them: pending events are
1032 // either events to the threads other than main or events posted with
1033 // wxPostEvent() functions
1034 wxMacProcessNotifierAndPendingEvents();
1035
3fdac2ab
DE
1036 if(!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1037 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
e9576ca5
SC
1038}
1039
e2478fde 1040void wxApp::WakeUpIdle()
9779893b 1041{
8461e4c2 1042 wxMacWakeUp() ;
9779893b
RD
1043}
1044
e2478fde 1045void wxApp::Exit()
e9576ca5 1046{
2f1ae414 1047 wxApp::CleanUp();
8461e4c2 1048 ::ExitToShell() ;
e9576ca5
SC
1049}
1050
2f1ae414
SC
1051void wxApp::OnEndSession(wxCloseEvent& WXUNUSED(event))
1052{
1053 if (GetTopWindow())
1054 GetTopWindow()->Close(TRUE);
1055}
1056
1057// Default behaviour: close the application with prompts. The
1058// user can veto the close, and therefore the end session.
1059void wxApp::OnQueryEndSession(wxCloseEvent& event)
1060{
1061 if (GetTopWindow())
1062 {
1063 if (!GetTopWindow()->Close(!event.CanVeto()))
1064 event.Veto(TRUE);
1065 }
1066}
1067
1068extern "C" void wxCYield() ;
1069void wxCYield()
1070{
8461e4c2 1071 wxYield() ;
2f1ae414
SC
1072}
1073
e9576ca5 1074// Yield to other processes
cb2713bf 1075
8461e4c2 1076bool wxApp::Yield(bool onlyIfNeeded)
e9576ca5 1077{
8461e4c2
VZ
1078 if (s_inYield)
1079 {
1080 if ( !onlyIfNeeded )
1081 {
1082 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1083 }
1084
1085 return FALSE;
1086 }
1087
1088 s_inYield = TRUE;
cb2713bf 1089
e40298d5 1090 // by definition yield should handle all non-processed events
facd6764 1091
e40298d5
JS
1092 EventRef theEvent;
1093
1094 OSStatus status = noErr ;
1095 do
1096 {
1097 s_inReceiveEvent = true ;
1098 status = ReceiveNextEvent(0, NULL,kEventDurationNoWait,true,&theEvent) ;
1099 s_inReceiveEvent = false ;
7c9955d1 1100
e40298d5
JS
1101 if ( status == eventLoopTimedOutErr )
1102 {
1103 // make sure next time the event loop will trigger idle events
1104 sleepTime = kEventDurationNoWait ;
1105 }
1106 else if ( status == eventLoopQuitErr )
1107 {
1108 // according to QA1061 this may also occur when a WakeUp Process
1109 // is executed
1110 }
1111 else
1112 {
1113 MacHandleOneEvent( theEvent ) ;
1114 ReleaseEvent(theEvent);
1115 }
1116 } while( status == noErr ) ;
2f1ae414 1117
8461e4c2 1118 wxMacProcessNotifierAndPendingEvents() ;
8461e4c2 1119 s_inYield = FALSE;
cb2713bf 1120
8461e4c2 1121 return TRUE;
169935ad
SC
1122}
1123
9779893b 1124void wxApp::MacDoOneEvent()
169935ad 1125{
e40298d5 1126 EventRef theEvent;
c5c9378c 1127
e40298d5
JS
1128 s_inReceiveEvent = true ;
1129 OSStatus status = ReceiveNextEvent(0, NULL,sleepTime,true,&theEvent) ;
1130 s_inReceiveEvent = false ;
1131 if ( status == eventLoopTimedOutErr )
1132 {
c5c9378c 1133 if ( wxTheApp->ProcessIdle() )
e40298d5 1134 sleepTime = kEventDurationNoWait ;
c5c9378c 1135 else
820d6bac 1136 sleepTime = kEventDurationSecond;
e40298d5
JS
1137 }
1138 else if ( status == eventLoopQuitErr )
1139 {
1140 // according to QA1061 this may also occur when a WakeUp Process
1141 // is executed
1142 }
1143 else
1144 {
1145 MacHandleOneEvent( theEvent ) ;
1146 ReleaseEvent(theEvent);
3470af1c 1147 sleepTime = kEventDurationNoWait ;
e40298d5 1148 }
8461e4c2 1149 // repeaters
519cb848 1150
6264b550 1151 DeletePendingObjects() ;
8461e4c2 1152 wxMacProcessNotifierAndPendingEvents() ;
169935ad
SC
1153}
1154
e128397f
DS
1155/*virtual*/ void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr )
1156{
1157 // Override to process unhandled events as you please
1158}
1159
76a5e5d2 1160void wxApp::MacHandleOneEvent( WXEVENTREF evr )
169935ad 1161{
e40298d5
JS
1162 EventTargetRef theTarget;
1163 theTarget = GetEventDispatcherTarget();
c5c9378c 1164 m_macCurrentEvent = evr ;
e128397f
DS
1165 OSStatus status = SendEventToEventTarget ((EventRef) evr , theTarget);
1166 if(status == eventNotHandledErr)
1167 {
1168 MacHandleUnhandledEvent(evr);
1169 }
8461e4c2 1170 wxMacProcessNotifierAndPendingEvents() ;
f8df60f2
SC
1171#if wxUSE_THREADS
1172 wxMutexGuiLeaveOrEnter();
1173#endif // wxUSE_THREADS
169935ad
SC
1174}
1175
72055702 1176long wxMacTranslateKey(unsigned char key, unsigned char code) ;
7c551d95 1177long wxMacTranslateKey(unsigned char key, unsigned char code)
9779893b 1178{
8461e4c2 1179 long retval = key ;
9779893b 1180 switch (key)
519cb848 1181 {
12e049f6 1182 case kHomeCharCode :
8461e4c2
VZ
1183 retval = WXK_HOME;
1184 break;
12e049f6 1185 case kEnterCharCode :
8461e4c2
VZ
1186 retval = WXK_RETURN;
1187 break;
12e049f6 1188 case kEndCharCode :
8461e4c2
VZ
1189 retval = WXK_END;
1190 break;
12e049f6 1191 case kHelpCharCode :
8461e4c2
VZ
1192 retval = WXK_HELP;
1193 break;
12e049f6 1194 case kBackspaceCharCode :
8461e4c2
VZ
1195 retval = WXK_BACK;
1196 break;
12e049f6 1197 case kTabCharCode :
8461e4c2
VZ
1198 retval = WXK_TAB;
1199 break;
12e049f6 1200 case kPageUpCharCode :
8461e4c2
VZ
1201 retval = WXK_PAGEUP;
1202 break;
12e049f6 1203 case kPageDownCharCode :
8461e4c2
VZ
1204 retval = WXK_PAGEDOWN;
1205 break;
12e049f6 1206 case kReturnCharCode :
8461e4c2
VZ
1207 retval = WXK_RETURN;
1208 break;
12e049f6 1209 case kFunctionKeyCharCode :
8461e4c2
VZ
1210 {
1211 switch( code )
1212 {
1213 case 0x7a :
1214 retval = WXK_F1 ;
1215 break;
1216 case 0x78 :
1217 retval = WXK_F2 ;
1218 break;
1219 case 0x63 :
1220 retval = WXK_F3 ;
1221 break;
1222 case 0x76 :
1223 retval = WXK_F4 ;
1224 break;
1225 case 0x60 :
1226 retval = WXK_F5 ;
1227 break;
1228 case 0x61 :
1229 retval = WXK_F6 ;
1230 break;
1231 case 0x62:
1232 retval = WXK_F7 ;
1233 break;
1234 case 0x64 :
1235 retval = WXK_F8 ;
1236 break;
1237 case 0x65 :
1238 retval = WXK_F9 ;
1239 break;
1240 case 0x6D :
1241 retval = WXK_F10 ;
1242 break;
1243 case 0x67 :
1244 retval = WXK_F11 ;
1245 break;
1246 case 0x6F :
1247 retval = WXK_F12 ;
1248 break;
1249 case 0x69 :
1250 retval = WXK_F13 ;
1251 break;
1252 case 0x6B :
1253 retval = WXK_F14 ;
1254 break;
1255 case 0x71 :
1256 retval = WXK_F15 ;
1257 break;
1258 }
1259 }
1260 break ;
12e049f6 1261 case kEscapeCharCode :
8461e4c2
VZ
1262 retval = WXK_ESCAPE ;
1263 break ;
12e049f6 1264 case kLeftArrowCharCode :
8461e4c2
VZ
1265 retval = WXK_LEFT ;
1266 break ;
12e049f6 1267 case kRightArrowCharCode :
8461e4c2
VZ
1268 retval = WXK_RIGHT ;
1269 break ;
12e049f6 1270 case kUpArrowCharCode :
8461e4c2
VZ
1271 retval = WXK_UP ;
1272 break ;
12e049f6 1273 case kDownArrowCharCode :
8461e4c2
VZ
1274 retval = WXK_DOWN ;
1275 break ;
12e049f6 1276 case kDeleteCharCode :
8461e4c2
VZ
1277 retval = WXK_DELETE ;
1278 default:
1279 break ;
1280 } // end switch
1281
1282 return retval;
169935ad
SC
1283}
1284
facd6764 1285int wxMacKeyCodeToModifier(wxKeyCode key)
6ed892f3
RN
1286{
1287 switch (key)
1288 {
1289 case WXK_START:
15c2acd2 1290 case WXK_MENU:
6ed892f3
RN
1291 return cmdKey;
1292
1293 case WXK_SHIFT:
1294 return shiftKey;
1295
1296 case WXK_CAPITAL:
1297 return alphaLock;
1298
15c2acd2
RN
1299 case WXK_ALT:
1300 return optionKey;
6ed892f3
RN
1301
1302 case WXK_CONTROL:
1303 return controlKey;
1304
1305 default:
1306 return 0;
1307 }
1308}
1309
1310bool wxGetKeyState(wxKeyCode key) //virtual key code if < 10.2.x, else see below
1311{
7f71c4c8
RN
1312//#ifdef __DARWIN__
1313// wxHIDKeyboard keyboard;
1314// return keyboard.IsActive(key);
1315//#else
104cdef6 1316// TODO: Have it use HID Manager on OSX...
6ed892f3
RN
1317//if OS X > 10.2 (i.e. 10.2.x)
1318//a known apple bug prevents the system from determining led
1319//states with GetKeys... can only determine caps lock led
facd6764 1320 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key));
6ed892f3
RN
1321//else
1322// KeyMapByteArray keymap;
1323// GetKeys((BigEndianLong*)keymap);
1324// return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
7f71c4c8 1325//#endif
6ed892f3
RN
1326}
1327
c5c9378c 1328
12e049f6 1329bool wxApp::MacSendKeyDownEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey )
ac2d1ca6 1330{
ba12463b
SC
1331 if ( !focus )
1332 return false ;
7c9955d1 1333
12e049f6
SC
1334 short keycode ;
1335 short keychar ;
1336 keychar = short(keymessage & charCodeMask);
1337 keycode = short(keymessage & keyCodeMask) >> 8 ;
7c9955d1 1338
ef08713a 1339 if ( modifiers & ( controlKey|shiftKey|optionKey ) )
12e049f6
SC
1340 {
1341 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1342 // and look at the character after
1343 UInt32 state = 0;
ef08713a 1344 UInt32 keyInfo = KeyTranslate((Ptr)GetScriptManagerVariable(smKCHRCache), ( modifiers & (~(controlKey|shiftKey|optionKey))) | keycode, &state);
12e049f6
SC
1345 keychar = short(keyInfo & charCodeMask);
1346 keycode = short(keyInfo & keyCodeMask) >> 8 ;
1347 }
1348 long keyval = wxMacTranslateKey(keychar, keycode) ;
e40298d5
JS
1349 long realkeyval = keyval ;
1350 if ( keyval == keychar )
1351 {
1352 // 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)
1353 realkeyval = short(keymessage & charCodeMask) ;
1354 keyval = wxToupper( keyval ) ;
1355 }
7c9955d1 1356
ac2d1ca6 1357 wxKeyEvent event(wxEVT_KEY_DOWN);
41d368a4 1358 bool handled = false ;
ac2d1ca6
SC
1359 event.m_shiftDown = modifiers & shiftKey;
1360 event.m_controlDown = modifiers & controlKey;
1361 event.m_altDown = modifiers & optionKey;
1362 event.m_metaDown = modifiers & cmdKey;
ef08713a 1363 event.m_keyCode = keyval ;
ac2d1ca6
SC
1364
1365 event.m_x = wherex;
1366 event.m_y = wherey;
1367 event.m_timeStamp = when;
1368 event.SetEventObject(focus);
1369 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1370 if ( handled && event.GetSkipped() )
1371 handled = false ;
1372 if ( !handled )
1373 {
ba2928c6 1374#if wxUSE_ACCEL
ac2d1ca6
SC
1375 if (!handled)
1376 {
1377 wxWindow *ancestor = focus;
1378 while (ancestor)
1379 {
1380 int command = ancestor->GetAcceleratorTable()->GetCommand( event );
1381 if (command != -1)
8461e4c2 1382 {
ac2d1ca6
SC
1383 wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1384 handled = ancestor->GetEventHandler()->ProcessEvent( command_event );
1385 break;
8461e4c2 1386 }
ac2d1ca6
SC
1387 if (ancestor->IsTopLevel())
1388 break;
1389 ancestor = ancestor->GetParent();
8461e4c2 1390 }
ac2d1ca6
SC
1391 }
1392#endif // wxUSE_ACCEL
1393 }
1394 if (!handled)
1395 {
1396 event.Skip( FALSE ) ;
1397 event.SetEventType( wxEVT_CHAR ) ;
12e049f6 1398 // raw value again
ef08713a 1399 event.m_keyCode = realkeyval ;
ac2d1ca6
SC
1400
1401 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1402 if ( handled && event.GetSkipped() )
1403 handled = false ;
1404 }
bdf956fb 1405 if ( !handled && (keyval == WXK_TAB) )
ac2d1ca6 1406 {
bdf956fb
SC
1407 wxWindow* iter = focus->GetParent() ;
1408 while( iter && !handled )
1409 {
1410 if ( iter->HasFlag( wxTAB_TRAVERSAL ) )
1411 {
1412 wxNavigationKeyEvent new_event;
1413 new_event.SetEventObject( focus );
1414 new_event.SetDirection( !event.ShiftDown() );
1415 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1416 new_event.SetWindowChange( event.ControlDown() );
1417 new_event.SetCurrentFocus( focus );
1418 handled = focus->GetParent()->GetEventHandler()->ProcessEvent( new_event );
1419 if ( handled && new_event.GetSkipped() )
1420 handled = false ;
1421 }
1422 iter = iter->GetParent() ;
1423 }
ac2d1ca6
SC
1424 }
1425 // backdoor handler for default return and command escape
1426 if ( !handled && (!focus->IsKindOf(CLASSINFO(wxControl) ) || !focus->MacCanFocus() ) )
1427 {
1428 // if window is not having a focus still testing for default enter or cancel
1429 // TODO add the UMA version for ActiveNonFloatingWindow
1430 wxWindow* focus = wxFindWinFromMacWindow( FrontWindow() ) ;
e562df9b
SC
1431 if ( focus )
1432 {
1433 if ( keyval == WXK_RETURN )
1434 {
1435 wxButton *def = wxDynamicCast(focus->GetDefaultItem(),
1436 wxButton);
1437 if ( def && def->IsEnabled() )
1438 {
1439 wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, def->GetId() );
1440 event.SetEventObject(def);
1441 def->Command(event);
ac2d1ca6 1442 return true ;
e562df9b
SC
1443 }
1444 }
8461e4c2 1445 /* generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs) */
ac2d1ca6 1446 else if (keyval == WXK_ESCAPE || (keyval == '.' && modifiers & cmdKey ) )
8461e4c2 1447 {
e562df9b
SC
1448 wxCommandEvent new_event(wxEVT_COMMAND_BUTTON_CLICKED,wxID_CANCEL);
1449 new_event.SetEventObject( focus );
1450 handled = focus->GetEventHandler()->ProcessEvent( new_event );
8461e4c2 1451 }
e562df9b 1452 }
8461e4c2 1453 }
ac2d1ca6 1454 return handled ;
169935ad
SC
1455}
1456
12e049f6 1457bool wxApp::MacSendKeyUpEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey )
ac2d1ca6 1458{
ba12463b
SC
1459 if ( !focus )
1460 return false ;
1461
12e049f6
SC
1462 short keycode ;
1463 short keychar ;
1464 keychar = short(keymessage & charCodeMask);
1465 keycode = short(keymessage & keyCodeMask) >> 8 ;
ef08713a 1466 if ( modifiers & ( controlKey|shiftKey|optionKey ) )
12e049f6
SC
1467 {
1468 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1469 // and look at the character after
1470 UInt32 state = 0;
ef08713a 1471 UInt32 keyInfo = KeyTranslate((Ptr)GetScriptManagerVariable(smKCHRCache), ( modifiers & (~(controlKey|shiftKey|optionKey))) | keycode, &state);
12e049f6
SC
1472 keychar = short(keyInfo & charCodeMask);
1473 keycode = short(keyInfo & keyCodeMask) >> 8 ;
1474 }
1475 long keyval = wxMacTranslateKey(keychar, keycode) ;
1476
e40298d5
JS
1477 if ( keyval == keychar )
1478 {
7c9955d1 1479 keyval = wxToupper( keyval ) ;
e40298d5 1480 }
ac2d1ca6 1481 bool handled = false ;
ac2d1ca6 1482
ba12463b
SC
1483 wxKeyEvent event(wxEVT_KEY_UP);
1484 event.m_shiftDown = modifiers & shiftKey;
1485 event.m_controlDown = modifiers & controlKey;
1486 event.m_altDown = modifiers & optionKey;
1487 event.m_metaDown = modifiers & cmdKey;
ef08713a 1488 event.m_keyCode = keyval ;
ba12463b
SC
1489
1490 event.m_x = wherex;
1491 event.m_y = wherey;
1492 event.m_timeStamp = when;
1493 event.SetEventObject(focus);
1494 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1495
ac2d1ca6
SC
1496 return handled ;
1497}