attempt to get a 'correct' current working directory
[wxWidgets.git] / src / mac / carbon / app.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: app.cpp
3 // Purpose: wxApp
4 // Author: Stefan Csomor
5 // Modified by:
6 // Created: 1998-01-01
7 // RCS-ID: $Id$
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation "app.h"
14 #endif
15
16 #include "wx/defs.h"
17
18 #include "wx/window.h"
19 #include "wx/frame.h"
20 #include "wx/button.h"
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"
27 #include "wx/intl.h"
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"
36 #include "wx/tooltip.h"
37 #include "wx/textctrl.h"
38 #include "wx/menu.h"
39 #include "wx/docview.h"
40 #include "wx/filename.h"
41
42 #include <string.h>
43
44 // mac
45
46 #ifndef __DARWIN__
47 #if __option(profile)
48 #include <profiler.h>
49 #endif
50 #endif
51
52 // #include "apprsrc.h"
53
54 #include "wx/mac/uma.h"
55 #include "wx/mac/macnotfy.h"
56
57 #ifdef __DARWIN__
58 # include <CoreServices/CoreServices.h>
59 # if defined(WXMAKINGDLL_CORE)
60 # include <mach-o/dyld.h>
61 # endif
62 #else
63 # include <Sound.h>
64 # include <Threads.h>
65 # include <ToolUtils.h>
66 # include <DiskInit.h>
67 # include <Devices.h>
68 #endif
69
70 extern wxList wxPendingDelete;
71
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
82 #if wxUSE_THREADS
83 extern size_t g_numberOfThreads;
84 #endif // wxUSE_THREADS
85
86 // statics for implementation
87
88 static bool s_inYield = FALSE;
89
90 static bool s_inReceiveEvent = FALSE ;
91 static EventTime sleepTime = kEventDurationNoWait ;
92
93 #if !USE_SHARED_LIBRARY
94 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
95 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
96 EVT_IDLE(wxApp::OnIdle)
97 EVT_END_SESSION(wxApp::OnEndSession)
98 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
99 END_EVENT_TABLE()
100 #endif
101
102
103 const short kMacMinHeap = (29 * 1024) ;
104 // platform specific static variables
105
106 const short kwxMacMenuBarResource = 1 ;
107 const short kwxMacAppleMenuId = 1 ;
108
109 WXHRGN wxApp::s_macCursorRgn = NULL;
110 wxWindow* wxApp::s_captureWindow = NULL ;
111 int wxApp::s_lastMouseDown = 0 ;
112 long wxApp::sm_lastMessageTime = 0;
113 long wxApp::s_lastModifiers = 0 ;
114
115
116 bool wxApp::s_macSupportPCMenuShortcuts = true ;
117 long wxApp::s_macAboutMenuItemId = wxID_ABOUT ;
118 long wxApp::s_macPreferencesMenuItemId = wxID_PREFERENCES ;
119 long wxApp::s_macExitMenuItemId = wxID_EXIT ;
120 wxString wxApp::s_macHelpMenuTitleName = wxT("&Help") ;
121
122 // Normally we're not a plugin
123 bool wxApp::sm_isEmbedded = false;
124 //----------------------------------------------------------------------
125 // Core Apple Event Support
126 //----------------------------------------------------------------------
127
128 pascal OSErr AEHandleODoc( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
129 pascal OSErr AEHandleOApp( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
130 pascal OSErr AEHandlePDoc( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
131 pascal OSErr AEHandleQuit( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
132 pascal OSErr AEHandleRApp( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
133
134 pascal OSErr AEHandleODoc( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
135 {
136 return wxTheApp->MacHandleAEODoc( (AppleEvent*) event , reply) ;
137 }
138
139 pascal OSErr AEHandleOApp( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
140 {
141 return wxTheApp->MacHandleAEOApp( (AppleEvent*) event , reply ) ;
142 }
143
144 pascal OSErr AEHandlePDoc( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
145 {
146 return wxTheApp->MacHandleAEPDoc( (AppleEvent*) event , reply ) ;
147 }
148
149 pascal OSErr AEHandleQuit( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
150 {
151 return wxTheApp->MacHandleAEQuit( (AppleEvent*) event , reply) ;
152 }
153
154 pascal OSErr AEHandleRApp( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
155 {
156 return wxTheApp->MacHandleAERApp( (AppleEvent*) event , reply) ;
157 }
158
159 // AEODoc Calls MacOpenFile on each of the files passed
160
161 short 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;
174
175 err = AECountItems(&docList, &itemsInList);
176 if (err != noErr)
177 return err;
178
179 ProcessSerialNumber PSN ;
180 PSN.highLongOfPSN = 0 ;
181 PSN.lowLongOfPSN = kCurrentProcess ;
182 SetFrontProcess( &PSN ) ;
183
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;
191 }
192
193 // AEPDoc Calls MacPrintFile on each of the files passed
194
195 short wxApp::MacHandleAEPDoc(const WXEVENTREF event , WXEVENTREF WXUNUSED(reply))
196 {
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;
208
209 err = AECountItems(&docList, &itemsInList);
210 if (err != noErr)
211 return err;
212
213 ProcessSerialNumber PSN ;
214 PSN.highLongOfPSN = 0 ;
215 PSN.lowLongOfPSN = kCurrentProcess ;
216 SetFrontProcess( &PSN ) ;
217
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;
225 }
226
227 // AEOApp calls MacNewFile
228
229 short wxApp::MacHandleAEOApp(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
230 {
231 MacNewFile() ;
232 return noErr ;
233 }
234
235 // AEQuit attempts to quit the application
236
237 short wxApp::MacHandleAEQuit(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
238 {
239 wxWindow* win = GetTopWindow() ;
240 if ( win )
241 {
242 wxCommandEvent exitEvent(wxEVT_COMMAND_MENU_SELECTED, s_macExitMenuItemId);
243 if (!win->ProcessEvent(exitEvent))
244 win->Close(TRUE ) ;
245 }
246 else
247 {
248 ExitMainLoop() ;
249 }
250 return noErr ;
251 }
252
253 // AEROApp calls MacReopenApp
254
255 short wxApp::MacHandleAERApp(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
256 {
257 MacReopenApp() ;
258 return noErr ;
259 }
260
261
262 //----------------------------------------------------------------------
263 // Support Routines linking the Mac...File Calls to the Document Manager
264 //----------------------------------------------------------------------
265
266 void wxApp::MacOpenFile(const wxString & fileName )
267 {
268 wxDocManager* dm = wxDocManager::GetDocumentManager() ;
269 if ( dm )
270 dm->CreateDocument(fileName , wxDOC_SILENT ) ;
271 }
272
273 void 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
301 void wxApp::MacNewFile()
302 {
303 }
304
305 void wxApp::MacReopenApp()
306 {
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 {
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 }
338 }
339
340 //----------------------------------------------------------------------
341 // Carbon Event Handler
342 //----------------------------------------------------------------------
343
344 static const EventTypeSpec eventList[] =
345 {
346 { kEventClassCommand, kEventProcessCommand } ,
347 { kEventClassCommand, kEventCommandUpdateStatus } ,
348
349 { kEventClassMenu, kEventMenuOpening },
350 { kEventClassMenu, kEventMenuClosed },
351 { kEventClassMenu, kEventMenuTargetItem },
352
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
357
358 { kEventClassAppleEvent , kEventAppleEvent } ,
359
360 { kEventClassMouse , kEventMouseDown } ,
361 { kEventClassMouse , kEventMouseMoved } ,
362 { kEventClassMouse , kEventMouseUp } ,
363 { kEventClassMouse , kEventMouseDragged } ,
364 { 'WXMC' , 'WXMC' }
365 } ;
366
367 static pascal OSStatus
368 wxMacAppMenuEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
369 {
370 EventRef formerEvent = (EventRef) wxTheApp->MacGetCurrentEvent() ;
371 EventHandlerCallRef formerEventHandlerCallRef = (EventHandlerCallRef) wxTheApp->MacGetCurrentEventHandlerCallRef() ;
372 wxTheApp->MacSetCurrentEvent( event , handler ) ;
373
374 wxMacCarbonEvent cEvent( event ) ;
375 MenuRef menuRef = cEvent.GetParameter<MenuRef>(kEventParamDirectObject) ;
376 wxMenu* menu = wxFindMenuFromMacMenu( menuRef ) ;
377
378 if ( menu )
379 {
380 wxEventType type=0;
381 MenuCommand cmd=0;
382 switch (GetEventKind(event))
383 {
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)
393 type = wxEVT_MENU_HIGHLIGHT;
394 break;
395 default:
396 wxFAIL_MSG(wxT("Unexpected menu event kind"));
397 break;
398 }
399
400 if ( type )
401 {
402 wxMenuEvent wxevent(type, cmd);
403 wxevent.SetEventObject(menu);
404
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 }
417 }
418
419 wxTheApp->MacSetCurrentEvent( formerEvent, formerEventHandlerCallRef ) ;
420
421 return eventNotHandledErr;
422 }
423
424 static pascal OSStatus wxMacAppCommandEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
425 {
426 OSStatus result = eventNotHandledErr ;
427
428 HICommand command ;
429
430 wxMacCarbonEvent cEvent( event ) ;
431 cEvent.GetParameter<HICommand>(kEventParamDirectObject,typeHICommand,&command) ;
432
433 wxMenuItem* item = NULL ;
434 MenuCommand id = command.commandID ;
435 // for items we don't really control
436 if ( id == kHICommandPreferences )
437 {
438 id = wxApp::s_macPreferencesMenuItemId ;
439
440 wxMenuBar* mbar = wxMenuBar::MacGetInstalledMenuBar() ;
441 if ( mbar )
442 {
443 wxMenu* menu = NULL ;
444 item = mbar->FindItem( id , &menu ) ;
445 }
446 }
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() )
455 {
456 case kEventProcessCommand :
457 {
458 if (item->IsCheckable())
459 {
460 item->Check( !item->IsChecked() ) ;
461 }
462
463 item->GetMenu()->SendEvent( id , item->IsCheckable() ? item->IsChecked() : -1 ) ;
464 result = noErr ;
465 }
466 break ;
467 case kEventCommandUpdateStatus:
468 // eventually trigger an updateui round
469 result = noErr ;
470 break ;
471 default :
472 break ;
473 }
474 }
475 return result ;
476 }
477
478 static pascal OSStatus wxMacAppApplicationEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
479 {
480 OSStatus result = eventNotHandledErr ;
481 switch ( GetEventKind( event ) )
482 {
483 case kEventAppActivated :
484 {
485 if ( wxTheApp )
486 wxTheApp->SetActive( true , NULL ) ;
487 result = noErr ;
488 }
489 break ;
490 case kEventAppDeactivated :
491 {
492 if ( wxTheApp )
493 wxTheApp->SetActive( false , NULL ) ;
494 result = noErr ;
495 }
496 break ;
497 default :
498 break ;
499 }
500 return result ;
501 }
502
503 pascal OSStatus wxMacAppEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
504 {
505 OSStatus result = eventNotHandledErr ;
506 switch( GetEventClass( event ) )
507 {
508 case kEventClassCommand :
509 result = wxMacAppCommandEventHandler( handler , event , data ) ;
510 break ;
511 case kEventClassApplication :
512 result = wxMacAppApplicationEventHandler( handler , event , data ) ;
513 break ;
514 case kEventClassMenu :
515 result = wxMacAppMenuEventHandler( handler , event , data ) ;
516 break ;
517 case kEventClassMouse :
518 result = wxMacTopLevelMouseEventHandler( handler , event , NULL ) ;
519 break ;
520 case kEventClassAppleEvent :
521 {
522 EventRecord rec ;
523 wxMacConvertEventToRecord( event , &rec ) ;
524 result = AEProcessAppleEvent( &rec ) ;
525 }
526 break ;
527 default :
528 break ;
529 }
530
531 return result ;
532 }
533
534 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler )
535
536 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
537 // we know it's there ;-)
538 WXIMPORT char std::__throws_bad_alloc ;
539 #endif
540
541 pascal 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)
544 {
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
561
562 #if 1
563 // flow into log
564 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
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 ,
573 wxString::Format( wxT("%s %s value (%p)") ,exceptionStr, errorStr , value ) ) ;
574 #endif
575 }
576
577 bool wxApp::Initialize(int& argc, wxChar **argv)
578 {
579 // Mac-specific
580
581 #if __WXDEBUG__
582 InstallDebugAssertOutputHandler ( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler ) );
583 #endif
584 UMAInitToolbox( 4, sm_isEmbedded ) ;
585 SetEventMask( everyEvent ) ;
586 UMAShowWatchCursor() ;
587
588 #if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
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
593
594 #ifndef __DARWIN__
595 # if __option(profile)
596 ProfilerInit( collectDetailed, bestTimeBase , 40000 , 50 ) ;
597 # endif
598 #endif
599
600 #ifndef __DARWIN__
601 // now avoid exceptions thrown for new (bad_alloc)
602 // FIXME CS for some changes outside wxMac does not compile anymore
603 #if 0
604 std::__throws_bad_alloc = 0 ;
605 #endif
606
607 #endif
608
609 s_macCursorRgn = ::NewRgn() ;
610
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_");
618 if ( wxStrncmp(argv[1], ARG_PSN, wxStrlen(ARG_PSN)) == 0 )
619 {
620 // remove this argument
621 --argc;
622 memmove(argv + 1, argv + 2, argc * sizeof(char *));
623 }
624 }
625
626 if ( !wxAppBase::Initialize(argc, argv) )
627 return false;
628
629 #if wxUSE_INTL
630 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
631 #endif
632
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() ;
636 if ( startupCwd == "/" || startupCwd.Right(15) == "/Contents/MacOS" )
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
653
654 wxMacCreateNotifierTable() ;
655
656 UMAShowArrowCursor() ;
657
658 return true;
659 }
660
661 bool wxApp::OnInitGui()
662 {
663 if( !wxAppBase::OnInitGui() )
664 return false ;
665
666 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
667
668 if (!sm_isEmbedded)
669 {
670 InstallApplicationEventHandler(
671 GetwxMacAppEventHandlerUPP(),
672 GetEventTypeCount(eventList), eventList, wxTheApp, (EventHandlerRef *)&(wxTheApp->m_macEventHandler));
673 }
674
675 if (!sm_isEmbedded)
676 {
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 ) ;
686 AEInstallEventHandler( kCoreEventClass , kAEReopenApplication ,
687 NewAEEventHandlerUPP(AEHandleRApp) ,
688 0 , FALSE ) ;
689 AEInstallEventHandler( kCoreEventClass , kAEQuitApplication ,
690 NewAEEventHandlerUPP(AEHandleQuit) ,
691 0 , FALSE ) ;
692 }
693
694 return TRUE ;
695 }
696
697 void wxApp::CleanUp()
698 {
699 wxToolTip::RemoveToolTips() ;
700
701 // One last chance for pending objects to be cleaned up
702 wxTheApp->DeletePendingObjects();
703
704 wxMacDestroyNotifierTable() ;
705
706 #ifndef __DARWIN__
707 # if __option(profile)
708 ProfilerDump( (StringPtr)"\papp.prof" ) ;
709 ProfilerTerm() ;
710 # endif
711 #endif
712
713 #if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
714 // close shared library resources from here since we don't have
715 // __wxterminate in Mach-O shared libraries
716 wxStAppResource::CloseSharedLibraryResource();
717 #endif
718
719 UMACleanupToolbox() ;
720 if (s_macCursorRgn) {
721 ::DisposeRgn((RgnHandle)s_macCursorRgn);
722 }
723
724 #if 0
725 TerminateAE() ;
726 #endif
727
728 wxAppBase::CleanUp();
729 }
730
731 //----------------------------------------------------------------------
732 // misc initialization stuff
733 //----------------------------------------------------------------------
734
735 // extern variable for shared library resource id
736 // need to be able to find it with NSLookupAndBindSymbol
737 short gSharedLibraryResource = kResFileNotOpened ;
738
739 #if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
740 CFBundleRef gSharedLibraryBundle = NULL;
741 #endif /* WXMAKINGDLL_CORE && __DARWIN__ */
742
743 wxStAppResource::wxStAppResource()
744 {
745 m_currentRefNum = CurResFile() ;
746 if ( gSharedLibraryResource != kResFileNotOpened )
747 {
748 UseResFile( gSharedLibraryResource ) ;
749 }
750 }
751
752 wxStAppResource::~wxStAppResource()
753 {
754 if ( m_currentRefNum != kResFileNotOpened )
755 {
756 UseResFile( m_currentRefNum ) ;
757 }
758 }
759
760 void wxStAppResource::OpenSharedLibraryResource(const void *initBlock)
761 {
762 gSharedLibraryResource = kResFileNotOpened;
763
764 #ifdef WXMAKINGDLL_CORE
765 if ( initBlock != NULL ) {
766 const CFragInitBlock *theInitBlock = (const CFragInitBlock *)initBlock;
767 FSSpec *fileSpec = NULL;
768
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 }
775
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
783 NSSymbol theSymbol;
784 NSModule theModule;
785 const char *theLibPath;
786
787 gSharedLibraryBundle = CFBundleGetBundleWithIdentifier(CFSTR("com.wxwindows.wxWidgets"));
788 if (gSharedLibraryBundle != NULL) {
789 // wxWidgets has been bundled into a framework
790 // load the framework resources
791
792 gSharedLibraryResource = CFBundleOpenBundleResourceMap(gSharedLibraryBundle);
793 }
794 else {
795 // wxWidgets is a simple dynamic shared library
796 // load the resources from the data fork of a separate resource file
797 wxString theResPath;
798 wxString theName;
799 FSRef theResRef;
800 OSErr theErr = noErr;
801
802 // get the library path
803 theSymbol = NSLookupAndBindSymbol("_gSharedLibraryResource");
804 theModule = NSModuleForSymbol(theSymbol);
805 theLibPath = NSLibraryNameForModule(theModule);
806
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
813 wxLogDebug( wxT("wxMac library installation name is '%s'"),
814 theLibPath );
815 #endif
816
817 // allocate copy to replace .dylib.* extension with .rsrc
818 if (theLibPath != NULL) {
819 #if wxUSE_UNICODE
820 theResPath = wxString(theLibPath, wxConvLocal);
821 #else
822 theResPath = wxString(theLibPath);
823 #endif
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('/');
830
831 #if 0
832 wxLogDebug( wxT("wxMac resources file name is '%s'"),
833 theResPath.mb_str() );
834 #endif
835
836 theErr = FSPathMakeRef((UInt8 *) theResPath.mb_str(), &theResRef, false);
837 if (theErr != noErr) {
838 // try in current directory (using name only)
839 theErr = FSPathMakeRef((UInt8 *) theName.mb_str(), &theResRef, false);
840 }
841
842 // open the resource file
843 if (theErr == noErr) {
844 theErr = FSOpenResourceFile( &theResRef, 0, NULL, fsRdPerm,
845 &gSharedLibraryResource);
846 }
847 if (theErr != noErr) {
848 #ifdef __WXDEBUG__
849 wxLogDebug( wxT("unable to open wxMac resource file '%s'\n"),
850 theResPath.mb_str() );
851 #endif // __WXDEBUG__
852 }
853
854 }
855 }
856 #endif /* __DARWIN__ */
857 }
858 #endif /* WXMAKINGDLL_CORE */
859 }
860
861 void wxStAppResource::CloseSharedLibraryResource()
862 {
863 #ifdef WXMAKINGDLL_CORE
864 // Close the shared library resource file
865 if (gSharedLibraryResource != kResFileNotOpened) {
866 #ifdef __DARWIN__
867 if (gSharedLibraryBundle != NULL) {
868 CFBundleCloseBundleResourceMap(gSharedLibraryBundle,
869 gSharedLibraryResource);
870 gSharedLibraryBundle = NULL;
871 }
872 else
873 #endif /* __DARWIN__ */
874 {
875 CloseResFile(gSharedLibraryResource);
876 }
877 gSharedLibraryResource = kResFileNotOpened;
878 }
879 #endif /* WXMAKINGDLL_CORE */
880 }
881
882 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
883
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
887
888 extern "C" {
889 void __sinit(void); /* (generated by linker) */
890 pascal OSErr __initialize(const CFragInitBlock *theInitBlock);
891 pascal void __terminate(void);
892 }
893
894 pascal OSErr __wxinitialize(const CFragInitBlock *theInitBlock)
895 {
896 wxStAppResource::OpenSharedLibraryResource( theInitBlock ) ;
897 return __initialize( theInitBlock ) ;
898 }
899
900 pascal void __wxterminate(void)
901 {
902 wxStAppResource::CloseSharedLibraryResource() ;
903 __terminate() ;
904 }
905
906 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
907
908 bool 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 ;
919 switch( GetEventKind(event) )
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 }
982
983 return converted ;
984 }
985
986 wxApp::wxApp()
987 {
988 m_printMode = wxPRINT_WINDOWS;
989
990 m_macCurrentEvent = NULL ;
991 m_macCurrentEventHandlerCallRef = NULL ;
992 }
993
994 int wxApp::MainLoop()
995 {
996 m_keepGoing = TRUE;
997 #if wxMAC_USE_RAEL
998 RunApplicationEventLoop() ;
999 #else
1000 while (m_keepGoing)
1001 {
1002 MacDoOneEvent() ;
1003 }
1004 #endif
1005 return 0;
1006 }
1007
1008 void wxApp::ExitMainLoop()
1009 {
1010 m_keepGoing = FALSE;
1011 #if wxMAC_USE_RAEL
1012 QuitApplicationEventLoop() ;
1013 #endif
1014 }
1015
1016 // Is a message/event pending?
1017 bool wxApp::Pending()
1018 {
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 ;
1023 }
1024
1025 // Dispatch a message.
1026 bool wxApp::Dispatch()
1027 {
1028 MacDoOneEvent() ;
1029
1030 return true;
1031 }
1032
1033 void wxApp::OnIdle(wxIdleEvent& event)
1034 {
1035 wxAppBase::OnIdle(event);
1036
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
1042 if(!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1043 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1044 }
1045
1046 void wxApp::WakeUpIdle()
1047 {
1048 wxMacWakeUp() ;
1049 }
1050
1051 void wxApp::Exit()
1052 {
1053 wxApp::CleanUp();
1054 ::ExitToShell() ;
1055 }
1056
1057 void 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.
1065 void wxApp::OnQueryEndSession(wxCloseEvent& event)
1066 {
1067 if (GetTopWindow())
1068 {
1069 if (!GetTopWindow()->Close(!event.CanVeto()))
1070 event.Veto(TRUE);
1071 }
1072 }
1073
1074 extern "C" void wxCYield() ;
1075 void wxCYield()
1076 {
1077 wxYield() ;
1078 }
1079
1080 // Yield to other processes
1081
1082 bool wxApp::Yield(bool onlyIfNeeded)
1083 {
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;
1095
1096 // by definition yield should handle all non-processed events
1097
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 ;
1106
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 ) ;
1123
1124 wxMacProcessNotifierAndPendingEvents() ;
1125 s_inYield = FALSE;
1126
1127 return TRUE;
1128 }
1129
1130 void wxApp::MacDoOneEvent()
1131 {
1132 EventRef theEvent;
1133
1134 s_inReceiveEvent = true ;
1135 OSStatus status = ReceiveNextEvent(0, NULL,sleepTime,true,&theEvent) ;
1136 s_inReceiveEvent = false ;
1137 if ( status == eventLoopTimedOutErr )
1138 {
1139 if ( wxTheApp->ProcessIdle() )
1140 sleepTime = kEventDurationNoWait ;
1141 else
1142 sleepTime = kEventDurationSecond;
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);
1153 sleepTime = kEventDurationNoWait ;
1154 }
1155 // repeaters
1156
1157 DeletePendingObjects() ;
1158 wxMacProcessNotifierAndPendingEvents() ;
1159 }
1160
1161 /*virtual*/ void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr )
1162 {
1163 // Override to process unhandled events as you please
1164 }
1165
1166 void wxApp::MacHandleOneEvent( WXEVENTREF evr )
1167 {
1168 EventTargetRef theTarget;
1169 theTarget = GetEventDispatcherTarget();
1170 m_macCurrentEvent = evr ;
1171 OSStatus status = SendEventToEventTarget ((EventRef) evr , theTarget);
1172 if(status == eventNotHandledErr)
1173 {
1174 MacHandleUnhandledEvent(evr);
1175 }
1176 wxMacProcessNotifierAndPendingEvents() ;
1177 #if wxUSE_THREADS
1178 wxMutexGuiLeaveOrEnter();
1179 #endif // wxUSE_THREADS
1180 }
1181
1182 long wxMacTranslateKey(unsigned char key, unsigned char code) ;
1183 long wxMacTranslateKey(unsigned char key, unsigned char code)
1184 {
1185 long retval = key ;
1186 switch (key)
1187 {
1188 case kHomeCharCode :
1189 retval = WXK_HOME;
1190 break;
1191 case kEnterCharCode :
1192 retval = WXK_RETURN;
1193 break;
1194 case kEndCharCode :
1195 retval = WXK_END;
1196 break;
1197 case kHelpCharCode :
1198 retval = WXK_HELP;
1199 break;
1200 case kBackspaceCharCode :
1201 retval = WXK_BACK;
1202 break;
1203 case kTabCharCode :
1204 retval = WXK_TAB;
1205 break;
1206 case kPageUpCharCode :
1207 retval = WXK_PAGEUP;
1208 break;
1209 case kPageDownCharCode :
1210 retval = WXK_PAGEDOWN;
1211 break;
1212 case kReturnCharCode :
1213 retval = WXK_RETURN;
1214 break;
1215 case kFunctionKeyCharCode :
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 ;
1267 case kEscapeCharCode :
1268 retval = WXK_ESCAPE ;
1269 break ;
1270 case kLeftArrowCharCode :
1271 retval = WXK_LEFT ;
1272 break ;
1273 case kRightArrowCharCode :
1274 retval = WXK_RIGHT ;
1275 break ;
1276 case kUpArrowCharCode :
1277 retval = WXK_UP ;
1278 break ;
1279 case kDownArrowCharCode :
1280 retval = WXK_DOWN ;
1281 break ;
1282 case kDeleteCharCode :
1283 retval = WXK_DELETE ;
1284 default:
1285 break ;
1286 } // end switch
1287
1288 return retval;
1289 }
1290
1291 int wxMacKeyCodeToModifier(wxKeyCode key)
1292 {
1293 switch (key)
1294 {
1295 case WXK_START:
1296 case WXK_MENU:
1297 return cmdKey;
1298
1299 case WXK_SHIFT:
1300 return shiftKey;
1301
1302 case WXK_CAPITAL:
1303 return alphaLock;
1304
1305 case WXK_ALT:
1306 return optionKey;
1307
1308 case WXK_CONTROL:
1309 return controlKey;
1310
1311 default:
1312 return 0;
1313 }
1314 }
1315
1316 bool wxGetKeyState(wxKeyCode key) //virtual key code if < 10.2.x, else see below
1317 {
1318 //#ifdef __DARWIN__
1319 // wxHIDKeyboard keyboard;
1320 // return keyboard.IsActive(key);
1321 //#else
1322 // TODO: Have it use HID Manager on OSX...
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
1326 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key));
1327 //else
1328 // KeyMapByteArray keymap;
1329 // GetKeys((BigEndianLong*)keymap);
1330 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1331 //#endif
1332 }
1333
1334
1335 bool wxApp::MacSendKeyDownEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey )
1336 {
1337 if ( !focus )
1338 return false ;
1339
1340 short keycode ;
1341 short keychar ;
1342 keychar = short(keymessage & charCodeMask);
1343 keycode = short(keymessage & keyCodeMask) >> 8 ;
1344
1345 if ( modifiers & ( controlKey|shiftKey|optionKey ) )
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;
1350 UInt32 keyInfo = KeyTranslate((Ptr)GetScriptManagerVariable(smKCHRCache), ( modifiers & (~(controlKey|shiftKey|optionKey))) | keycode, &state);
1351 keychar = short(keyInfo & charCodeMask);
1352 keycode = short(keyInfo & keyCodeMask) >> 8 ;
1353 }
1354 long keyval = wxMacTranslateKey(keychar, keycode) ;
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 }
1362
1363 wxKeyEvent event(wxEVT_KEY_DOWN);
1364 bool handled = false ;
1365 event.m_shiftDown = modifiers & shiftKey;
1366 event.m_controlDown = modifiers & controlKey;
1367 event.m_altDown = modifiers & optionKey;
1368 event.m_metaDown = modifiers & cmdKey;
1369 event.m_keyCode = keyval ;
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 {
1380 #if wxUSE_ACCEL
1381 if (!handled)
1382 {
1383 wxWindow *ancestor = focus;
1384 while (ancestor)
1385 {
1386 int command = ancestor->GetAcceleratorTable()->GetCommand( event );
1387 if (command != -1)
1388 {
1389 wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1390 handled = ancestor->GetEventHandler()->ProcessEvent( command_event );
1391 break;
1392 }
1393 if (ancestor->IsTopLevel())
1394 break;
1395 ancestor = ancestor->GetParent();
1396 }
1397 }
1398 #endif // wxUSE_ACCEL
1399 }
1400 if (!handled)
1401 {
1402 event.Skip( FALSE ) ;
1403 event.SetEventType( wxEVT_CHAR ) ;
1404 // raw value again
1405 event.m_keyCode = realkeyval ;
1406
1407 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1408 if ( handled && event.GetSkipped() )
1409 handled = false ;
1410 }
1411 if ( !handled && (keyval == WXK_TAB) )
1412 {
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 }
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() ) ;
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);
1448 return true ;
1449 }
1450 }
1451 /* generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs) */
1452 else if (keyval == WXK_ESCAPE || (keyval == '.' && modifiers & cmdKey ) )
1453 {
1454 wxCommandEvent new_event(wxEVT_COMMAND_BUTTON_CLICKED,wxID_CANCEL);
1455 new_event.SetEventObject( focus );
1456 handled = focus->GetEventHandler()->ProcessEvent( new_event );
1457 }
1458 }
1459 }
1460 return handled ;
1461 }
1462
1463 bool wxApp::MacSendKeyUpEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey )
1464 {
1465 if ( !focus )
1466 return false ;
1467
1468 short keycode ;
1469 short keychar ;
1470 keychar = short(keymessage & charCodeMask);
1471 keycode = short(keymessage & keyCodeMask) >> 8 ;
1472 if ( modifiers & ( controlKey|shiftKey|optionKey ) )
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;
1477 UInt32 keyInfo = KeyTranslate((Ptr)GetScriptManagerVariable(smKCHRCache), ( modifiers & (~(controlKey|shiftKey|optionKey))) | keycode, &state);
1478 keychar = short(keyInfo & charCodeMask);
1479 keycode = short(keyInfo & keyCodeMask) >> 8 ;
1480 }
1481 long keyval = wxMacTranslateKey(keychar, keycode) ;
1482
1483 if ( keyval == keychar )
1484 {
1485 keyval = wxToupper( keyval ) ;
1486 }
1487 bool handled = false ;
1488
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;
1494 event.m_keyCode = keyval ;
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
1502 return handled ;
1503 }