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