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