FSRef transition
[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 OSErr err;
169 short i;
170 err = AEGetParamDesc((AppleEvent *)event, keyDirectObject, typeAEList,&docList);
171 if (err != noErr)
172 return err;
173
174 err = AECountItems(&docList, &itemsInList);
175 if (err != noErr)
176 return err;
177
178 ProcessSerialNumber PSN ;
179 PSN.highLongOfPSN = 0 ;
180 PSN.lowLongOfPSN = kCurrentProcess ;
181 SetFrontProcess( &PSN ) ;
182
183 for (i = 1; i <= itemsInList; i++)
184 {
185 wxString fName ;
186
187 FSRef theRef ;
188 AEGetNthPtr(&docList, i, typeFSRef, &keywd, &returnedType,
189 (Ptr) & theRef, sizeof(theRef), &actualSize);
190 fName = wxMacFSRefToPath( &theRef ) ;
191
192 MacOpenFile(fName);
193 }
194 return noErr;
195 }
196
197 // AEPDoc Calls MacPrintFile on each of the files passed
198
199 short wxApp::MacHandleAEPDoc(const WXEVENTREF event , WXEVENTREF WXUNUSED(reply))
200 {
201 AEDescList docList;
202 AEKeyword keywd;
203 DescType returnedType;
204 Size actualSize;
205 long itemsInList;
206 OSErr err;
207 short i;
208 err = AEGetParamDesc((AppleEvent *)event, keyDirectObject, typeAEList,&docList);
209 if (err != noErr)
210 return err;
211
212 err = AECountItems(&docList, &itemsInList);
213 if (err != noErr)
214 return err;
215
216 ProcessSerialNumber PSN ;
217 PSN.highLongOfPSN = 0 ;
218 PSN.lowLongOfPSN = kCurrentProcess ;
219 SetFrontProcess( &PSN ) ;
220
221 for (i = 1; i <= itemsInList; i++) {
222 wxString fName ;
223
224 FSRef theRef ;
225 AEGetNthPtr(&docList, i, typeFSRef, &keywd, &returnedType,
226 (Ptr) & theRef, sizeof(theRef), &actualSize);
227 fName = wxMacFSRefToPath( &theRef ) ;
228
229 MacPrintFile(fName);
230 }
231 return noErr;
232 }
233
234 // AEOApp calls MacNewFile
235
236 short wxApp::MacHandleAEOApp(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
237 {
238 MacNewFile() ;
239 return noErr ;
240 }
241
242 // AEQuit attempts to quit the application
243
244 short wxApp::MacHandleAEQuit(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
245 {
246 wxWindow* win = GetTopWindow() ;
247 if ( win )
248 {
249 wxCommandEvent exitEvent(wxEVT_COMMAND_MENU_SELECTED, s_macExitMenuItemId);
250 if (!win->ProcessEvent(exitEvent))
251 win->Close(TRUE ) ;
252 }
253 else
254 {
255 ExitMainLoop() ;
256 }
257 return noErr ;
258 }
259
260 // AEROApp calls MacReopenApp
261
262 short wxApp::MacHandleAERApp(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
263 {
264 MacReopenApp() ;
265 return noErr ;
266 }
267
268
269 //----------------------------------------------------------------------
270 // Support Routines linking the Mac...File Calls to the Document Manager
271 //----------------------------------------------------------------------
272
273 void wxApp::MacOpenFile(const wxString & fileName )
274 {
275 wxDocManager* dm = wxDocManager::GetDocumentManager() ;
276 if ( dm )
277 dm->CreateDocument(fileName , wxDOC_SILENT ) ;
278 }
279
280 void wxApp::MacPrintFile(const wxString & fileName )
281 {
282 wxDocManager* dm = wxDocManager::GetDocumentManager() ;
283 if ( dm )
284 {
285 wxDocument *doc = dm->CreateDocument(fileName , wxDOC_SILENT ) ;
286 if ( doc )
287 {
288 wxView* view = doc->GetFirstView() ;
289 if( view )
290 {
291 wxPrintout *printout = view->OnCreatePrintout();
292 if (printout)
293 {
294 wxPrinter printer;
295 printer.Print(view->GetFrame(), printout, TRUE);
296 delete printout;
297 }
298 }
299 if (doc->Close())
300 {
301 doc->DeleteAllViews();
302 dm->RemoveDocument(doc) ;
303 }
304 }
305 }
306 }
307
308 void wxApp::MacNewFile()
309 {
310 }
311
312 void wxApp::MacReopenApp()
313 {
314 // HIG says :
315 // if there is no open window -> create a new one
316 // if all windows are hidden -> show the first
317 // if some windows are not hidden -> do nothing
318
319 wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst();
320 if ( node == NULL )
321 {
322 MacNewFile() ;
323 }
324 else
325 {
326 wxTopLevelWindow* firstIconized = NULL ;
327 while (node)
328 {
329 wxTopLevelWindow* win = (wxTopLevelWindow*) node->GetData();
330 if ( win->IsIconized() == false )
331 {
332 firstIconized = NULL ;
333 break ;
334 }
335 else
336 {
337 if ( firstIconized == NULL )
338 firstIconized = win ;
339 }
340 node = node->GetNext();
341 }
342 if ( firstIconized )
343 firstIconized->Iconize( false ) ;
344 }
345 }
346
347 //----------------------------------------------------------------------
348 // Carbon Event Handler
349 //----------------------------------------------------------------------
350
351 static const EventTypeSpec eventList[] =
352 {
353 { kEventClassCommand, kEventProcessCommand } ,
354 { kEventClassCommand, kEventCommandUpdateStatus } ,
355
356 { kEventClassMenu, kEventMenuOpening },
357 { kEventClassMenu, kEventMenuClosed },
358 { kEventClassMenu, kEventMenuTargetItem },
359
360 { kEventClassApplication , kEventAppActivated } ,
361 { kEventClassApplication , kEventAppDeactivated } ,
362 // handling the quit event is not recommended by apple
363 // rather using the quit apple event - which we do
364
365 { kEventClassAppleEvent , kEventAppleEvent } ,
366
367 { kEventClassMouse , kEventMouseDown } ,
368 { kEventClassMouse , kEventMouseMoved } ,
369 { kEventClassMouse , kEventMouseUp } ,
370 { kEventClassMouse , kEventMouseDragged } ,
371 { 'WXMC' , 'WXMC' }
372 } ;
373
374 static pascal OSStatus
375 wxMacAppMenuEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
376 {
377 wxMacCarbonEvent cEvent( event ) ;
378 MenuRef menuRef = cEvent.GetParameter<MenuRef>(kEventParamDirectObject) ;
379 wxMenu* menu = wxFindMenuFromMacMenu( menuRef ) ;
380
381 if ( menu )
382 {
383 wxEventType type=0;
384 MenuCommand cmd=0;
385 switch (GetEventKind(event))
386 {
387 case kEventMenuOpening:
388 type = wxEVT_MENU_OPEN;
389 break;
390 case kEventMenuClosed:
391 type = wxEVT_MENU_CLOSE;
392 break;
393 case kEventMenuTargetItem:
394 cmd = cEvent.GetParameter<MenuCommand>(kEventParamMenuCommand,typeMenuCommand) ;
395 if (cmd != 0)
396 type = wxEVT_MENU_HIGHLIGHT;
397 break;
398 default:
399 wxFAIL_MSG(wxT("Unexpected menu event kind"));
400 break;
401 }
402
403 if ( type )
404 {
405 wxMenuEvent wxevent(type, cmd);
406 wxevent.SetEventObject(menu);
407
408 wxEvtHandler* handler = menu->GetEventHandler();
409 if (handler && handler->ProcessEvent(wxevent))
410 {
411 // handled
412 }
413 else
414 {
415 wxWindow *win = menu->GetInvokingWindow();
416 if (win)
417 win->GetEventHandler()->ProcessEvent(wxevent);
418 }
419 }
420 }
421
422 return eventNotHandledErr;
423 }
424
425 static pascal OSStatus wxMacAppCommandEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
426 {
427 OSStatus result = eventNotHandledErr ;
428
429 HICommand command ;
430
431 wxMacCarbonEvent cEvent( event ) ;
432 cEvent.GetParameter<HICommand>(kEventParamDirectObject,typeHICommand,&command) ;
433
434 wxMenuItem* item = NULL ;
435 MenuCommand id = command.commandID ;
436 // for items we don't really control
437 if ( id == kHICommandPreferences )
438 {
439 id = wxApp::s_macPreferencesMenuItemId ;
440
441 wxMenuBar* mbar = wxMenuBar::MacGetInstalledMenuBar() ;
442 if ( mbar )
443 {
444 wxMenu* menu = NULL ;
445 item = mbar->FindItem( id , &menu ) ;
446 }
447 }
448 else if ( id != 0 && command.menu.menuRef != 0 && command.menu.menuItemIndex != 0 )
449 {
450 GetMenuItemRefCon( command.menu.menuRef , command.menu.menuItemIndex , (UInt32*) &item ) ;
451 }
452
453 if ( item )
454 {
455 switch( cEvent.GetKind() )
456 {
457 case kEventProcessCommand :
458 {
459 if (item->IsCheckable())
460 {
461 item->Check( !item->IsChecked() ) ;
462 }
463
464 item->GetMenu()->SendEvent( id , item->IsCheckable() ? item->IsChecked() : -1 ) ;
465 result = noErr ;
466 }
467 break ;
468 case kEventCommandUpdateStatus:
469 // eventually trigger an updateui round
470 result = noErr ;
471 break ;
472 default :
473 break ;
474 }
475 }
476 return result ;
477 }
478
479 static pascal OSStatus wxMacAppApplicationEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
480 {
481 OSStatus result = eventNotHandledErr ;
482 switch ( GetEventKind( event ) )
483 {
484 case kEventAppActivated :
485 {
486 if ( wxTheApp )
487 wxTheApp->SetActive( true , NULL ) ;
488 result = noErr ;
489 }
490 break ;
491 case kEventAppDeactivated :
492 {
493 if ( wxTheApp )
494 wxTheApp->SetActive( false , NULL ) ;
495 result = noErr ;
496 }
497 break ;
498 default :
499 break ;
500 }
501 return result ;
502 }
503
504 pascal OSStatus wxMacAppEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
505 {
506 EventRef formerEvent = (EventRef) wxTheApp->MacGetCurrentEvent() ;
507 EventHandlerCallRef formerEventHandlerCallRef = (EventHandlerCallRef) wxTheApp->MacGetCurrentEventHandlerCallRef() ;
508 wxTheApp->MacSetCurrentEvent( event , handler ) ;
509
510 OSStatus result = eventNotHandledErr ;
511 switch( GetEventClass( event ) )
512 {
513 case kEventClassCommand :
514 result = wxMacAppCommandEventHandler( handler , event , data ) ;
515 break ;
516 case kEventClassApplication :
517 result = wxMacAppApplicationEventHandler( handler , event , data ) ;
518 break ;
519 case kEventClassMenu :
520 result = wxMacAppMenuEventHandler( handler , event , data ) ;
521 break ;
522 case kEventClassMouse :
523 result = wxMacTopLevelMouseEventHandler( handler , event , NULL ) ;
524 break ;
525 case kEventClassAppleEvent :
526 {
527 EventRecord rec ;
528 wxMacConvertEventToRecord( event , &rec ) ;
529 result = AEProcessAppleEvent( &rec ) ;
530 }
531 break ;
532 default :
533 break ;
534 }
535
536 wxTheApp->MacSetCurrentEvent( formerEvent, formerEventHandlerCallRef ) ;
537
538 return result ;
539 }
540
541 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler )
542
543 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
544 // we know it's there ;-)
545 WXIMPORT char std::__throws_bad_alloc ;
546 #endif
547
548 pascal static void wxMacAssertOutputHandler(OSType componentSignature, UInt32 options,
549 const char *assertionString, const char *exceptionLabelString,
550 const char *errorString, const char *fileName, long lineNumber, void *value, ConstStr255Param outputMsg)
551 {
552 // flow into assert handling
553 wxString fileNameStr ;
554 wxString assertionStr ;
555 wxString exceptionStr ;
556 wxString errorStr ;
557 #if wxUSE_UNICODE
558 fileNameStr = wxString(fileName, wxConvLocal);
559 assertionStr = wxString(assertionString, wxConvLocal);
560 exceptionStr = wxString((exceptionLabelString!=0) ? exceptionLabelString : "", wxConvLocal) ;
561 errorStr = wxString((errorString!=0) ? errorString : "", wxConvLocal) ;
562 #else
563 fileNameStr = fileName;
564 assertionStr = assertionString;
565 exceptionStr = (exceptionLabelString!=0) ? exceptionLabelString : "" ;
566 errorStr = (errorString!=0) ? errorString : "" ;
567 #endif
568
569 #if 1
570 // flow into log
571 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
572 assertionStr.c_str() ,
573 exceptionStr.c_str() ,
574 errorStr.c_str(),
575 fileNameStr.c_str(), lineNumber ,
576 value ) ;
577 #else
578
579 wxOnAssert(fileNameStr, lineNumber , assertionStr ,
580 wxString::Format( wxT("%s %s value (%p)") ,exceptionStr, errorStr , value ) ) ;
581 #endif
582 }
583
584 bool wxApp::Initialize(int& argc, wxChar **argv)
585 {
586 // Mac-specific
587
588 #if __WXDEBUG__
589 InstallDebugAssertOutputHandler ( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler ) );
590 #endif
591 UMAInitToolbox( 4, sm_isEmbedded ) ;
592 SetEventMask( everyEvent ) ;
593 UMAShowWatchCursor() ;
594
595 #if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
596 // open shared library resources from here since we don't have
597 // __wxinitialize in Mach-O shared libraries
598 wxStAppResource::OpenSharedLibraryResource(NULL);
599 #endif
600
601 #ifndef __DARWIN__
602 # if __option(profile)
603 ProfilerInit( collectDetailed, bestTimeBase , 40000 , 50 ) ;
604 # endif
605 #endif
606
607 #ifndef __DARWIN__
608 // now avoid exceptions thrown for new (bad_alloc)
609 // FIXME CS for some changes outside wxMac does not compile anymore
610 #if 0
611 std::__throws_bad_alloc = 0 ;
612 #endif
613
614 #endif
615
616 s_macCursorRgn = ::NewRgn() ;
617
618 // Mac OS X passes a process serial number command line argument when
619 // the application is launched from the Finder. This argument must be
620 // removed from the command line arguments before being handled by the
621 // application (otherwise applications would need to handle it)
622 if ( argc > 1 )
623 {
624 static const wxChar *ARG_PSN = _T("-psn_");
625 if ( wxStrncmp(argv[1], ARG_PSN, wxStrlen(ARG_PSN)) == 0 )
626 {
627 // remove this argument
628 --argc;
629 memmove(argv + 1, argv + 2, argc * sizeof(char *));
630 }
631 }
632
633 if ( !wxAppBase::Initialize(argc, argv) )
634 return false;
635
636 #if wxUSE_INTL
637 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
638 #endif
639
640 #if TARGET_API_MAC_OSX
641 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
642 wxString startupCwd = wxGetCwd() ;
643 if ( startupCwd == wxT("/") || startupCwd.Right(15) == wxT("/Contents/MacOS") )
644 {
645 CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
646 CFURLRef urlParent = CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault , url ) ;
647 CFRelease( url ) ;
648 CFStringRef path = CFURLCopyFileSystemPath ( urlParent , kCFURLPOSIXPathStyle ) ;
649 CFRelease( urlParent ) ;
650 wxString cwd = wxMacCFStringHolder(path).AsString(wxLocale::GetSystemEncoding());
651 wxSetWorkingDirectory( cwd ) ;
652 }
653 #endif
654
655 wxMacCreateNotifierTable() ;
656
657 UMAShowArrowCursor() ;
658
659 return true;
660 }
661
662 bool wxApp::OnInitGui()
663 {
664 if( !wxAppBase::OnInitGui() )
665 return false ;
666
667 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
668
669 if (!sm_isEmbedded)
670 {
671 InstallApplicationEventHandler(
672 GetwxMacAppEventHandlerUPP(),
673 GetEventTypeCount(eventList), eventList, wxTheApp, (EventHandlerRef *)&(wxTheApp->m_macEventHandler));
674 }
675
676 if (!sm_isEmbedded)
677 {
678 AEInstallEventHandler( kCoreEventClass , kAEOpenDocuments ,
679 NewAEEventHandlerUPP(AEHandleODoc) ,
680 0 , FALSE ) ;
681 AEInstallEventHandler( kCoreEventClass , kAEOpenApplication ,
682 NewAEEventHandlerUPP(AEHandleOApp) ,
683 0 , FALSE ) ;
684 AEInstallEventHandler( kCoreEventClass , kAEPrintDocuments ,
685 NewAEEventHandlerUPP(AEHandlePDoc) ,
686 0 , FALSE ) ;
687 AEInstallEventHandler( kCoreEventClass , kAEReopenApplication ,
688 NewAEEventHandlerUPP(AEHandleRApp) ,
689 0 , FALSE ) ;
690 AEInstallEventHandler( kCoreEventClass , kAEQuitApplication ,
691 NewAEEventHandlerUPP(AEHandleQuit) ,
692 0 , FALSE ) ;
693 }
694
695 return TRUE ;
696 }
697
698 void wxApp::CleanUp()
699 {
700 wxToolTip::RemoveToolTips() ;
701
702 // One last chance for pending objects to be cleaned up
703 wxTheApp->DeletePendingObjects();
704
705 wxMacDestroyNotifierTable() ;
706
707 #ifndef __DARWIN__
708 # if __option(profile)
709 ProfilerDump( (StringPtr)"\papp.prof" ) ;
710 ProfilerTerm() ;
711 # endif
712 #endif
713
714 #if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
715 // close shared library resources from here since we don't have
716 // __wxterminate in Mach-O shared libraries
717 wxStAppResource::CloseSharedLibraryResource();
718 #endif
719
720 UMACleanupToolbox() ;
721 if (s_macCursorRgn) {
722 ::DisposeRgn((RgnHandle)s_macCursorRgn);
723 }
724
725 #if 0
726 TerminateAE() ;
727 #endif
728
729 wxAppBase::CleanUp();
730 }
731
732 //----------------------------------------------------------------------
733 // misc initialization stuff
734 //----------------------------------------------------------------------
735
736 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
737
738 // for shared libraries we have to manually get the correct resource
739 // ref num upon initializing and releasing when terminating, therefore
740 // the __wxinitialize and __wxterminate must be used
741
742 extern "C" {
743 void __sinit(void); /* (generated by linker) */
744 pascal OSErr __initialize(const CFragInitBlock *theInitBlock);
745 pascal void __terminate(void);
746 }
747
748 pascal OSErr __wxinitialize(const CFragInitBlock *theInitBlock)
749 {
750 return __initialize( theInitBlock ) ;
751 }
752
753 pascal void __wxterminate(void)
754 {
755 __terminate() ;
756 }
757
758 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
759
760 bool wxMacConvertEventToRecord( EventRef event , EventRecord *rec)
761 {
762 bool converted = ConvertEventRefToEventRecord( event,rec) ;
763 OSStatus err = noErr ;
764 if ( !converted )
765 {
766 switch( GetEventClass( event ) )
767 {
768 case kEventClassKeyboard :
769 {
770 converted = true ;
771 switch( GetEventKind(event) )
772 {
773 case kEventRawKeyDown :
774 rec->what = keyDown ;
775 break ;
776 case kEventRawKeyRepeat :
777 rec->what = autoKey ;
778 break ;
779 case kEventRawKeyUp :
780 rec->what = keyUp ;
781 break ;
782 case kEventRawKeyModifiersChanged :
783 rec->what = nullEvent ;
784 break ;
785 default :
786 converted = false ;
787 break ;
788 }
789 if ( converted )
790 {
791 UInt32 keyCode ;
792 unsigned char charCode ;
793 UInt32 modifiers ;
794 GetMouse( &rec->where) ;
795
796 err = GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL, 4, NULL, &modifiers);
797 err = GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL, 4, NULL, &keyCode);
798 err = GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL, 1, NULL, &charCode);
799 rec->modifiers = modifiers ;
800 rec->message = (keyCode << 8 ) + charCode ;
801 }
802 }
803 break ;
804 case kEventClassTextInput :
805 {
806 switch( GetEventKind( event ) )
807 {
808 case kEventTextInputUnicodeForKeyEvent :
809 {
810 EventRef rawEvent ;
811 err = GetEventParameter( event , kEventParamTextInputSendKeyboardEvent ,typeEventRef,NULL,sizeof(rawEvent),NULL,&rawEvent ) ;
812 converted = true ;
813 {
814 UInt32 keyCode ;
815 unsigned char charCode ;
816 UInt32 modifiers ;
817 GetMouse( &rec->where) ;
818 rec->what = keyDown ;
819 err = GetEventParameter(rawEvent, kEventParamKeyModifiers, typeUInt32, NULL, 4, NULL, &modifiers);
820 err = GetEventParameter(rawEvent, kEventParamKeyCode, typeUInt32, NULL, 4, NULL, &keyCode);
821 err = GetEventParameter(rawEvent, kEventParamKeyMacCharCodes, typeChar, NULL, 1, NULL, &charCode);
822 rec->modifiers = modifiers ;
823 rec->message = (keyCode << 8 ) + charCode ;
824 }
825 }
826 break ;
827 default :
828 break ;
829 }
830 }
831 break ;
832 }
833 }
834
835 return converted ;
836 }
837
838 wxApp::wxApp()
839 {
840 m_printMode = wxPRINT_WINDOWS;
841
842 m_macCurrentEvent = NULL ;
843 m_macCurrentEventHandlerCallRef = NULL ;
844 }
845
846 int wxApp::MainLoop()
847 {
848 m_keepGoing = TRUE;
849 #if wxMAC_USE_RAEL
850 RunApplicationEventLoop() ;
851 #else
852 while (m_keepGoing)
853 {
854 MacDoOneEvent() ;
855 }
856 #endif
857 return 0;
858 }
859
860 void wxApp::ExitMainLoop()
861 {
862 m_keepGoing = FALSE;
863 #if wxMAC_USE_RAEL
864 QuitApplicationEventLoop() ;
865 #endif
866 }
867
868 // Is a message/event pending?
869 bool wxApp::Pending()
870 {
871 // without the receive event (with pull param = false ) nothing is ever reported
872 EventRef theEvent;
873 ReceiveNextEvent (0, NULL, kEventDurationNoWait, false, &theEvent);
874 return GetNumEventsInQueue( GetMainEventQueue() ) > 0 ;
875 }
876
877 // Dispatch a message.
878 bool wxApp::Dispatch()
879 {
880 MacDoOneEvent() ;
881
882 return true;
883 }
884
885 void wxApp::OnIdle(wxIdleEvent& event)
886 {
887 wxAppBase::OnIdle(event);
888
889 // If they are pending events, we must process them: pending events are
890 // either events to the threads other than main or events posted with
891 // wxPostEvent() functions
892 wxMacProcessNotifierAndPendingEvents();
893
894 if(!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
895 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
896 }
897
898 void wxApp::WakeUpIdle()
899 {
900 wxMacWakeUp() ;
901 }
902
903 void wxApp::Exit()
904 {
905 wxApp::CleanUp();
906 ::ExitToShell() ;
907 }
908
909 void wxApp::OnEndSession(wxCloseEvent& WXUNUSED(event))
910 {
911 if (GetTopWindow())
912 GetTopWindow()->Close(TRUE);
913 }
914
915 // Default behaviour: close the application with prompts. The
916 // user can veto the close, and therefore the end session.
917 void wxApp::OnQueryEndSession(wxCloseEvent& event)
918 {
919 if (GetTopWindow())
920 {
921 if (!GetTopWindow()->Close(!event.CanVeto()))
922 event.Veto(TRUE);
923 }
924 }
925
926 extern "C" void wxCYield() ;
927 void wxCYield()
928 {
929 wxYield() ;
930 }
931
932 // Yield to other processes
933
934 bool wxApp::Yield(bool onlyIfNeeded)
935 {
936 if (s_inYield)
937 {
938 if ( !onlyIfNeeded )
939 {
940 wxFAIL_MSG( wxT("wxYield called recursively" ) );
941 }
942
943 return FALSE;
944 }
945
946 s_inYield = TRUE;
947
948 // by definition yield should handle all non-processed events
949
950 EventRef theEvent;
951
952 OSStatus status = noErr ;
953 do
954 {
955 s_inReceiveEvent = true ;
956 status = ReceiveNextEvent(0, NULL,kEventDurationNoWait,true,&theEvent) ;
957 s_inReceiveEvent = false ;
958
959 if ( status == eventLoopTimedOutErr )
960 {
961 // make sure next time the event loop will trigger idle events
962 sleepTime = kEventDurationNoWait ;
963 }
964 else if ( status == eventLoopQuitErr )
965 {
966 // according to QA1061 this may also occur when a WakeUp Process
967 // is executed
968 }
969 else
970 {
971 MacHandleOneEvent( theEvent ) ;
972 ReleaseEvent(theEvent);
973 }
974 } while( status == noErr ) ;
975
976 wxMacProcessNotifierAndPendingEvents() ;
977 s_inYield = FALSE;
978
979 return TRUE;
980 }
981
982 void wxApp::MacDoOneEvent()
983 {
984 EventRef theEvent;
985
986 s_inReceiveEvent = true ;
987 OSStatus status = ReceiveNextEvent(0, NULL,sleepTime,true,&theEvent) ;
988 s_inReceiveEvent = false ;
989 if ( status == eventLoopTimedOutErr )
990 {
991 if ( wxTheApp->ProcessIdle() )
992 sleepTime = kEventDurationNoWait ;
993 else
994 sleepTime = kEventDurationSecond;
995 }
996 else if ( status == eventLoopQuitErr )
997 {
998 // according to QA1061 this may also occur when a WakeUp Process
999 // is executed
1000 }
1001 else
1002 {
1003 MacHandleOneEvent( theEvent ) ;
1004 ReleaseEvent(theEvent);
1005 sleepTime = kEventDurationNoWait ;
1006 }
1007 // repeaters
1008
1009 DeletePendingObjects() ;
1010 wxMacProcessNotifierAndPendingEvents() ;
1011 }
1012
1013 /*virtual*/ void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr )
1014 {
1015 // Override to process unhandled events as you please
1016 }
1017
1018 void wxApp::MacHandleOneEvent( WXEVENTREF evr )
1019 {
1020 EventTargetRef theTarget;
1021 theTarget = GetEventDispatcherTarget();
1022 m_macCurrentEvent = evr ;
1023 OSStatus status = SendEventToEventTarget ((EventRef) evr , theTarget);
1024 if(status == eventNotHandledErr)
1025 {
1026 MacHandleUnhandledEvent(evr);
1027 }
1028 wxMacProcessNotifierAndPendingEvents() ;
1029 #if wxUSE_THREADS
1030 wxMutexGuiLeaveOrEnter();
1031 #endif // wxUSE_THREADS
1032 }
1033
1034 long wxMacTranslateKey(unsigned char key, unsigned char code) ;
1035 long wxMacTranslateKey(unsigned char key, unsigned char code)
1036 {
1037 long retval = key ;
1038 switch (key)
1039 {
1040 case kHomeCharCode :
1041 retval = WXK_HOME;
1042 break;
1043 case kEnterCharCode :
1044 retval = WXK_RETURN;
1045 break;
1046 case kEndCharCode :
1047 retval = WXK_END;
1048 break;
1049 case kHelpCharCode :
1050 retval = WXK_HELP;
1051 break;
1052 case kBackspaceCharCode :
1053 retval = WXK_BACK;
1054 break;
1055 case kTabCharCode :
1056 retval = WXK_TAB;
1057 break;
1058 case kPageUpCharCode :
1059 retval = WXK_PAGEUP;
1060 break;
1061 case kPageDownCharCode :
1062 retval = WXK_PAGEDOWN;
1063 break;
1064 case kReturnCharCode :
1065 retval = WXK_RETURN;
1066 break;
1067 case kFunctionKeyCharCode :
1068 {
1069 switch( code )
1070 {
1071 case 0x7a :
1072 retval = WXK_F1 ;
1073 break;
1074 case 0x78 :
1075 retval = WXK_F2 ;
1076 break;
1077 case 0x63 :
1078 retval = WXK_F3 ;
1079 break;
1080 case 0x76 :
1081 retval = WXK_F4 ;
1082 break;
1083 case 0x60 :
1084 retval = WXK_F5 ;
1085 break;
1086 case 0x61 :
1087 retval = WXK_F6 ;
1088 break;
1089 case 0x62:
1090 retval = WXK_F7 ;
1091 break;
1092 case 0x64 :
1093 retval = WXK_F8 ;
1094 break;
1095 case 0x65 :
1096 retval = WXK_F9 ;
1097 break;
1098 case 0x6D :
1099 retval = WXK_F10 ;
1100 break;
1101 case 0x67 :
1102 retval = WXK_F11 ;
1103 break;
1104 case 0x6F :
1105 retval = WXK_F12 ;
1106 break;
1107 case 0x69 :
1108 retval = WXK_F13 ;
1109 break;
1110 case 0x6B :
1111 retval = WXK_F14 ;
1112 break;
1113 case 0x71 :
1114 retval = WXK_F15 ;
1115 break;
1116 }
1117 }
1118 break ;
1119 case kEscapeCharCode :
1120 retval = WXK_ESCAPE ;
1121 break ;
1122 case kLeftArrowCharCode :
1123 retval = WXK_LEFT ;
1124 break ;
1125 case kRightArrowCharCode :
1126 retval = WXK_RIGHT ;
1127 break ;
1128 case kUpArrowCharCode :
1129 retval = WXK_UP ;
1130 break ;
1131 case kDownArrowCharCode :
1132 retval = WXK_DOWN ;
1133 break ;
1134 case kDeleteCharCode :
1135 retval = WXK_DELETE ;
1136 default:
1137 break ;
1138 } // end switch
1139
1140 return retval;
1141 }
1142
1143 int wxMacKeyCodeToModifier(wxKeyCode key)
1144 {
1145 switch (key)
1146 {
1147 case WXK_START:
1148 case WXK_MENU:
1149 return cmdKey;
1150
1151 case WXK_SHIFT:
1152 return shiftKey;
1153
1154 case WXK_CAPITAL:
1155 return alphaLock;
1156
1157 case WXK_ALT:
1158 return optionKey;
1159
1160 case WXK_CONTROL:
1161 return controlKey;
1162
1163 default:
1164 return 0;
1165 }
1166 }
1167
1168 bool wxGetKeyState(wxKeyCode key) //virtual key code if < 10.2.x, else see below
1169 {
1170 //#ifdef __DARWIN__
1171 // wxHIDKeyboard keyboard;
1172 // return keyboard.IsActive(key);
1173 //#else
1174 // TODO: Have it use HID Manager on OSX...
1175 //if OS X > 10.2 (i.e. 10.2.x)
1176 //a known apple bug prevents the system from determining led
1177 //states with GetKeys... can only determine caps lock led
1178 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key));
1179 //else
1180 // KeyMapByteArray keymap;
1181 // GetKeys((BigEndianLong*)keymap);
1182 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1183 //#endif
1184 }
1185
1186
1187 bool wxApp::MacSendKeyDownEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey )
1188 {
1189 if ( !focus )
1190 return false ;
1191
1192 short keycode ;
1193 short keychar ;
1194 keychar = short(keymessage & charCodeMask);
1195 keycode = short(keymessage & keyCodeMask) >> 8 ;
1196
1197 if ( modifiers & ( controlKey|shiftKey|optionKey ) )
1198 {
1199 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1200 // and look at the character after
1201 UInt32 state = 0;
1202 UInt32 keyInfo = KeyTranslate((Ptr)GetScriptManagerVariable(smKCHRCache), ( modifiers & (~(controlKey|shiftKey|optionKey))) | keycode, &state);
1203 keychar = short(keyInfo & charCodeMask);
1204 keycode = short(keyInfo & keyCodeMask) >> 8 ;
1205 }
1206 long keyval = wxMacTranslateKey(keychar, keycode) ;
1207 long realkeyval = keyval ;
1208 if ( keyval == keychar )
1209 {
1210 // 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)
1211 realkeyval = short(keymessage & charCodeMask) ;
1212 keyval = wxToupper( keyval ) ;
1213 }
1214
1215 wxKeyEvent event(wxEVT_KEY_DOWN);
1216 bool handled = false ;
1217 event.m_shiftDown = modifiers & shiftKey;
1218 event.m_controlDown = modifiers & controlKey;
1219 event.m_altDown = modifiers & optionKey;
1220 event.m_metaDown = modifiers & cmdKey;
1221 event.m_keyCode = keyval ;
1222
1223 event.m_x = wherex;
1224 event.m_y = wherey;
1225 event.m_timeStamp = when;
1226 event.SetEventObject(focus);
1227 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1228 if ( handled && event.GetSkipped() )
1229 handled = false ;
1230 if ( !handled )
1231 {
1232 #if wxUSE_ACCEL
1233 if (!handled)
1234 {
1235 wxWindow *ancestor = focus;
1236 while (ancestor)
1237 {
1238 int command = ancestor->GetAcceleratorTable()->GetCommand( event );
1239 if (command != -1)
1240 {
1241 wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1242 handled = ancestor->GetEventHandler()->ProcessEvent( command_event );
1243 break;
1244 }
1245 if (ancestor->IsTopLevel())
1246 break;
1247 ancestor = ancestor->GetParent();
1248 }
1249 }
1250 #endif // wxUSE_ACCEL
1251 }
1252 if (!handled)
1253 {
1254 event.Skip( FALSE ) ;
1255 event.SetEventType( wxEVT_CHAR ) ;
1256 // raw value again
1257 event.m_keyCode = realkeyval ;
1258
1259 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1260 if ( handled && event.GetSkipped() )
1261 handled = false ;
1262 }
1263 if ( !handled && (keyval == WXK_TAB) )
1264 {
1265 wxWindow* iter = focus->GetParent() ;
1266 while( iter && !handled )
1267 {
1268 if ( iter->HasFlag( wxTAB_TRAVERSAL ) )
1269 {
1270 wxNavigationKeyEvent new_event;
1271 new_event.SetEventObject( focus );
1272 new_event.SetDirection( !event.ShiftDown() );
1273 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1274 new_event.SetWindowChange( event.ControlDown() );
1275 new_event.SetCurrentFocus( focus );
1276 handled = focus->GetParent()->GetEventHandler()->ProcessEvent( new_event );
1277 if ( handled && new_event.GetSkipped() )
1278 handled = false ;
1279 }
1280 iter = iter->GetParent() ;
1281 }
1282 }
1283 // backdoor handler for default return and command escape
1284 if ( !handled && (!focus->IsKindOf(CLASSINFO(wxControl) ) || !focus->MacCanFocus() ) )
1285 {
1286 // if window is not having a focus still testing for default enter or cancel
1287 // TODO add the UMA version for ActiveNonFloatingWindow
1288 wxWindow* focus = wxFindWinFromMacWindow( FrontWindow() ) ;
1289 if ( focus )
1290 {
1291 if ( keyval == WXK_RETURN )
1292 {
1293 wxButton *def = wxDynamicCast(focus->GetDefaultItem(),
1294 wxButton);
1295 if ( def && def->IsEnabled() )
1296 {
1297 wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, def->GetId() );
1298 event.SetEventObject(def);
1299 def->Command(event);
1300 return true ;
1301 }
1302 }
1303 /* generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs) */
1304 else if (keyval == WXK_ESCAPE || (keyval == '.' && modifiers & cmdKey ) )
1305 {
1306 wxCommandEvent new_event(wxEVT_COMMAND_BUTTON_CLICKED,wxID_CANCEL);
1307 new_event.SetEventObject( focus );
1308 handled = focus->GetEventHandler()->ProcessEvent( new_event );
1309 }
1310 }
1311 }
1312 return handled ;
1313 }
1314
1315 bool wxApp::MacSendKeyUpEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey )
1316 {
1317 if ( !focus )
1318 return false ;
1319
1320 short keycode ;
1321 short keychar ;
1322 keychar = short(keymessage & charCodeMask);
1323 keycode = short(keymessage & keyCodeMask) >> 8 ;
1324 if ( modifiers & ( controlKey|shiftKey|optionKey ) )
1325 {
1326 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1327 // and look at the character after
1328 UInt32 state = 0;
1329 UInt32 keyInfo = KeyTranslate((Ptr)GetScriptManagerVariable(smKCHRCache), ( modifiers & (~(controlKey|shiftKey|optionKey))) | keycode, &state);
1330 keychar = short(keyInfo & charCodeMask);
1331 keycode = short(keyInfo & keyCodeMask) >> 8 ;
1332 }
1333 long keyval = wxMacTranslateKey(keychar, keycode) ;
1334
1335 if ( keyval == keychar )
1336 {
1337 keyval = wxToupper( keyval ) ;
1338 }
1339 bool handled = false ;
1340
1341 wxKeyEvent event(wxEVT_KEY_UP);
1342 event.m_shiftDown = modifiers & shiftKey;
1343 event.m_controlDown = modifiers & controlKey;
1344 event.m_altDown = modifiers & optionKey;
1345 event.m_metaDown = modifiers & cmdKey;
1346 event.m_keyCode = keyval ;
1347
1348 event.m_x = wherex;
1349 event.m_y = wherey;
1350 event.m_timeStamp = when;
1351 event.SetEventObject(focus);
1352 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1353
1354 return handled ;
1355 }