]> git.saurik.com Git - wxWidgets.git/blob - src/mac/carbon/app.cpp
don't declare inline function with dllexport declaration, this provokes mingw32 warni...
[wxWidgets.git] / src / mac / carbon / app.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/mac/carbon/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 #include "wx/wxprec.h"
13
14 #include "wx/app.h"
15
16 #ifndef WX_PRECOMP
17 #include "wx/intl.h"
18 #include "wx/log.h"
19 #include "wx/utils.h"
20 #include "wx/window.h"
21 #include "wx/frame.h"
22 #include "wx/dc.h"
23 #include "wx/button.h"
24 #include "wx/menu.h"
25 #include "wx/pen.h"
26 #include "wx/brush.h"
27 #include "wx/palette.h"
28 #include "wx/icon.h"
29 #include "wx/cursor.h"
30 #include "wx/dialog.h"
31 #include "wx/msgdlg.h"
32 #include "wx/textctrl.h"
33 #include "wx/memory.h"
34 #include "wx/gdicmn.h"
35 #include "wx/module.h"
36 #endif
37
38 #include "wx/tooltip.h"
39 #include "wx/docview.h"
40 #include "wx/filename.h"
41 #include "wx/link.h"
42
43 #include <string.h>
44
45 // mac
46
47 #ifndef __DARWIN__
48 #if __option(profile)
49 #include <profiler.h>
50 #endif
51 #endif
52
53 // #include "apprsrc.h"
54
55 #include "wx/mac/uma.h"
56 #include "wx/mac/macnotfy.h"
57
58 #ifdef __DARWIN__
59 # include <CoreServices/CoreServices.h>
60 # if defined(WXMAKINGDLL_CORE)
61 # include <mach-o/dyld.h>
62 # endif
63 #else
64 # include <Sound.h>
65 # include <Threads.h>
66 # include <ToolUtils.h>
67 # include <DiskInit.h>
68 # include <Devices.h>
69 #endif
70
71 // Keep linker from discarding wxStockGDIMac
72 wxFORCE_LINK_MODULE(gdiobj)
73
74 // statics for implementation
75 static bool s_inYield = false;
76 static bool s_inReceiveEvent = false ;
77 static EventTime sleepTime = kEventDurationNoWait ;
78
79
80 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
81 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
82 EVT_IDLE(wxApp::OnIdle)
83 EVT_END_SESSION(wxApp::OnEndSession)
84 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
85 END_EVENT_TABLE()
86
87
88 // platform specific static variables
89 static const short kwxMacAppleMenuId = 1 ;
90
91 wxWindow* wxApp::s_captureWindow = NULL ;
92 long wxApp::s_lastModifiers = 0 ;
93
94 long wxApp::s_macAboutMenuItemId = wxID_ABOUT ;
95 long wxApp::s_macPreferencesMenuItemId = wxID_PREFERENCES ;
96 long wxApp::s_macExitMenuItemId = wxID_EXIT ;
97 wxString wxApp::s_macHelpMenuTitleName = wxT("&Help") ;
98
99 bool wxApp::sm_isEmbedded = false; // Normally we're not a plugin
100
101 //----------------------------------------------------------------------
102 // Core Apple Event Support
103 //----------------------------------------------------------------------
104
105 pascal OSErr AEHandleODoc( const AppleEvent *event , AppleEvent *reply , SRefCon refcon ) ;
106 pascal OSErr AEHandleOApp( const AppleEvent *event , AppleEvent *reply , SRefCon refcon ) ;
107 pascal OSErr AEHandlePDoc( const AppleEvent *event , AppleEvent *reply , SRefCon refcon ) ;
108 pascal OSErr AEHandleQuit( const AppleEvent *event , AppleEvent *reply , SRefCon refcon ) ;
109 pascal OSErr AEHandleRApp( const AppleEvent *event , AppleEvent *reply , SRefCon refcon ) ;
110
111 pascal OSErr AEHandleODoc( const AppleEvent *event , AppleEvent *reply , SRefCon WXUNUSED(refcon) )
112 {
113 return wxTheApp->MacHandleAEODoc( (AppleEvent*) event , reply) ;
114 }
115
116 pascal OSErr AEHandleOApp( const AppleEvent *event , AppleEvent *reply , SRefCon WXUNUSED(refcon) )
117 {
118 return wxTheApp->MacHandleAEOApp( (AppleEvent*) event , reply ) ;
119 }
120
121 pascal OSErr AEHandlePDoc( const AppleEvent *event , AppleEvent *reply , SRefCon WXUNUSED(refcon) )
122 {
123 return wxTheApp->MacHandleAEPDoc( (AppleEvent*) event , reply ) ;
124 }
125
126 pascal OSErr AEHandleQuit( const AppleEvent *event , AppleEvent *reply , SRefCon WXUNUSED(refcon) )
127 {
128 return wxTheApp->MacHandleAEQuit( (AppleEvent*) event , reply) ;
129 }
130
131 pascal OSErr AEHandleRApp( const AppleEvent *event , AppleEvent *reply , SRefCon WXUNUSED(refcon) )
132 {
133 return wxTheApp->MacHandleAERApp( (AppleEvent*) event , reply) ;
134 }
135
136 pascal OSErr AEHandleGURL( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
137 {
138 return wxTheApp->MacHandleAEGURL((WXEVENTREF *)event , reply) ;
139 }
140
141
142 // AEODoc Calls MacOpenFile on each of the files passed
143
144 short wxApp::MacHandleAEODoc(const WXEVENTREF event, WXEVENTREF WXUNUSED(reply))
145 {
146 AEDescList docList;
147 AEKeyword keywd;
148 DescType returnedType;
149 Size actualSize;
150 long itemsInList;
151 OSErr err;
152 short i;
153
154 err = AEGetParamDesc((AppleEvent *)event, keyDirectObject, typeAEList,&docList);
155 if (err != noErr)
156 return err;
157
158 err = AECountItems(&docList, &itemsInList);
159 if (err != noErr)
160 return err;
161
162 ProcessSerialNumber PSN ;
163 PSN.highLongOfPSN = 0 ;
164 PSN.lowLongOfPSN = kCurrentProcess ;
165 SetFrontProcess( &PSN ) ;
166
167 wxString fName ;
168 FSRef theRef ;
169
170 for (i = 1; i <= itemsInList; i++)
171 {
172 AEGetNthPtr(
173 &docList, i, typeFSRef, &keywd, &returnedType,
174 (Ptr)&theRef, sizeof(theRef), &actualSize);
175 fName = wxMacFSRefToPath( &theRef ) ;
176
177 MacOpenFile(fName);
178 }
179
180 return noErr;
181 }
182
183 // AEODoc Calls MacOpenURL on the url passed
184
185 short wxApp::MacHandleAEGURL(const WXEVENTREF event, WXEVENTREF WXUNUSED(reply))
186 {
187 DescType returnedType;
188 Size actualSize;
189 char url[255];
190 OSErr err = AEGetParamPtr((AppleEvent *)event, keyDirectObject, typeChar,
191 &returnedType, url, sizeof(url)-1,
192 &actualSize);
193 if (err != noErr)
194 return err;
195
196 url[actualSize] = '\0'; // Terminate the C string
197
198 ProcessSerialNumber PSN ;
199 PSN.highLongOfPSN = 0 ;
200 PSN.lowLongOfPSN = kCurrentProcess ;
201 SetFrontProcess( &PSN ) ;
202
203 MacOpenURL(wxString(url, wxConvUTF8));
204
205 return noErr;
206 }
207
208 // AEPDoc Calls MacPrintFile on each of the files passed
209
210 short wxApp::MacHandleAEPDoc(const WXEVENTREF event , WXEVENTREF WXUNUSED(reply))
211 {
212 AEDescList docList;
213 AEKeyword keywd;
214 DescType returnedType;
215 Size actualSize;
216 long itemsInList;
217 OSErr err;
218 short i;
219
220 err = AEGetParamDesc((AppleEvent *)event, keyDirectObject, typeAEList,&docList);
221 if (err != noErr)
222 return err;
223
224 err = AECountItems(&docList, &itemsInList);
225 if (err != noErr)
226 return err;
227
228 ProcessSerialNumber PSN ;
229 PSN.highLongOfPSN = 0 ;
230 PSN.lowLongOfPSN = kCurrentProcess ;
231 SetFrontProcess( &PSN ) ;
232
233 wxString fName ;
234 FSRef theRef ;
235
236 for (i = 1; i <= itemsInList; i++)
237 {
238 AEGetNthPtr(
239 &docList, i, typeFSRef, &keywd, &returnedType,
240 (Ptr)&theRef, sizeof(theRef), &actualSize);
241 fName = wxMacFSRefToPath( &theRef ) ;
242
243 MacPrintFile(fName);
244 }
245
246 return noErr;
247 }
248
249 // AEOApp calls MacNewFile
250
251 short wxApp::MacHandleAEOApp(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
252 {
253 MacNewFile() ;
254 return noErr ;
255 }
256
257 // AEQuit attempts to quit the application
258
259 short wxApp::MacHandleAEQuit(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
260 {
261 wxWindow* win = GetTopWindow() ;
262 if ( win )
263 {
264 wxCommandEvent exitEvent(wxEVT_COMMAND_MENU_SELECTED, s_macExitMenuItemId);
265 if (!win->ProcessEvent(exitEvent))
266 win->Close(true) ;
267 }
268 else
269 {
270 ExitMainLoop() ;
271 }
272
273 return noErr ;
274 }
275
276 // AEROApp calls MacReopenApp
277
278 short wxApp::MacHandleAERApp(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
279 {
280 MacReopenApp() ;
281
282 return noErr ;
283 }
284
285 //----------------------------------------------------------------------
286 // Support Routines linking the Mac...File Calls to the Document Manager
287 //----------------------------------------------------------------------
288
289 void wxApp::MacOpenFile(const wxString & fileName )
290 {
291 #if wxUSE_DOC_VIEW_ARCHITECTURE
292 wxDocManager* dm = wxDocManager::GetDocumentManager() ;
293 if ( dm )
294 dm->CreateDocument(fileName , wxDOC_SILENT ) ;
295 #endif
296 }
297
298 void wxApp::MacOpenURL(const wxString & url )
299 {
300 }
301
302 void wxApp::MacPrintFile(const wxString & fileName )
303 {
304 #if wxUSE_DOC_VIEW_ARCHITECTURE
305
306 #if wxUSE_PRINTING_ARCHITECTURE
307 wxDocManager* dm = wxDocManager::GetDocumentManager() ;
308 if ( dm )
309 {
310 wxDocument *doc = dm->CreateDocument(fileName , wxDOC_SILENT ) ;
311 if ( doc )
312 {
313 wxView* view = doc->GetFirstView() ;
314 if ( view )
315 {
316 wxPrintout *printout = view->OnCreatePrintout();
317 if (printout)
318 {
319 wxPrinter printer;
320 printer.Print(view->GetFrame(), printout, true);
321 delete printout;
322 }
323 }
324
325 if (doc->Close())
326 {
327 doc->DeleteAllViews();
328 dm->RemoveDocument(doc) ;
329 }
330 }
331 }
332 #endif //print
333
334 #endif //docview
335 }
336
337
338
339 void wxApp::MacNewFile()
340 {
341 }
342
343 void wxApp::MacReopenApp()
344 {
345 // HIG says :
346 // if there is no open window -> create a new one
347 // if all windows are hidden -> show the first
348 // if some windows are not hidden -> do nothing
349
350 wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst();
351 if ( node == NULL )
352 {
353 MacNewFile() ;
354 }
355 else
356 {
357 wxTopLevelWindow* firstIconized = NULL ;
358 while (node)
359 {
360 wxTopLevelWindow* win = (wxTopLevelWindow*) node->GetData();
361 if ( !win->IsIconized() )
362 {
363 firstIconized = NULL ;
364 break ;
365 }
366 else
367 {
368 if ( firstIconized == NULL )
369 firstIconized = win ;
370 }
371
372 node = node->GetNext();
373 }
374
375 if ( firstIconized )
376 firstIconized->Iconize( false ) ;
377 }
378 }
379
380 //----------------------------------------------------------------------
381 // Macintosh CommandID support - converting between native and wx IDs
382 //----------------------------------------------------------------------
383
384 // if no native match they just return the passed-in id
385
386 struct IdPair
387 {
388 UInt32 macId ;
389 int wxId ;
390 } ;
391
392 IdPair gCommandIds [] =
393 {
394 { kHICommandCut , wxID_CUT } ,
395 { kHICommandCopy , wxID_COPY } ,
396 { kHICommandPaste , wxID_PASTE } ,
397 { kHICommandSelectAll , wxID_SELECTALL } ,
398 { kHICommandClear , wxID_CLEAR } ,
399 { kHICommandUndo , wxID_UNDO } ,
400 { kHICommandRedo , wxID_REDO } ,
401 } ;
402
403 int wxMacCommandToId( UInt32 macCommandId )
404 {
405 int wxid = 0 ;
406
407 switch ( macCommandId )
408 {
409 case kHICommandPreferences :
410 wxid = wxApp::s_macPreferencesMenuItemId ;
411 break ;
412
413 case kHICommandQuit :
414 wxid = wxApp::s_macExitMenuItemId ;
415 break ;
416
417 case kHICommandAbout :
418 wxid = wxApp::s_macAboutMenuItemId ;
419 break ;
420
421 default :
422 {
423 for ( size_t i = 0 ; i < WXSIZEOF(gCommandIds) ; ++i )
424 {
425 if ( gCommandIds[i].macId == macCommandId )
426 {
427 wxid = gCommandIds[i].wxId ;
428 break ;
429 }
430 }
431 }
432 break ;
433 }
434
435 if ( wxid == 0 )
436 wxid = (int) macCommandId ;
437
438 return wxid ;
439 }
440
441 UInt32 wxIdToMacCommand( int wxId )
442 {
443 UInt32 macId = 0 ;
444
445 if ( wxId == wxApp::s_macPreferencesMenuItemId )
446 macId = kHICommandPreferences ;
447 else if (wxId == wxApp::s_macExitMenuItemId)
448 macId = kHICommandQuit ;
449 else if (wxId == wxApp::s_macAboutMenuItemId)
450 macId = kHICommandAbout ;
451 else
452 {
453 for ( size_t i = 0 ; i < WXSIZEOF(gCommandIds) ; ++i )
454 {
455 if ( gCommandIds[i].wxId == wxId )
456 {
457 macId = gCommandIds[i].macId ;
458 break ;
459 }
460 }
461 }
462
463 if ( macId == 0 )
464 macId = (int) wxId ;
465
466 return macId ;
467 }
468
469 wxMenu* wxFindMenuFromMacCommand( const HICommand &command , wxMenuItem* &item )
470 {
471 wxMenu* itemMenu = NULL ;
472 int id = 0 ;
473
474 // for 'standard' commands which don't have a wx-menu
475 if ( command.commandID == kHICommandPreferences || command.commandID == kHICommandQuit || command.commandID == kHICommandAbout )
476 {
477 id = wxMacCommandToId( command.commandID ) ;
478
479 wxMenuBar* mbar = wxMenuBar::MacGetInstalledMenuBar() ;
480 if ( mbar )
481 item = mbar->FindItem( id , &itemMenu ) ;
482 }
483 else if ( command.commandID != 0 && command.menu.menuRef != 0 && command.menu.menuItemIndex != 0 )
484 {
485 id = wxMacCommandToId( command.commandID ) ;
486 // make sure it is one of our own menus, or of the 'synthetic' apple and help menus , otherwise don't touch
487 MenuItemIndex firstUserHelpMenuItem ;
488 static MenuHandle helpMenuHandle = NULL ;
489 if ( helpMenuHandle == NULL )
490 {
491 if ( UMAGetHelpMenuDontCreate( &helpMenuHandle , &firstUserHelpMenuItem) != noErr )
492 helpMenuHandle = NULL ;
493 }
494
495 // is it part of the application or the Help menu, then look for the id directly
496 if ( ( GetMenuHandle( kwxMacAppleMenuId ) != NULL && command.menu.menuRef == GetMenuHandle( kwxMacAppleMenuId ) ) ||
497 ( helpMenuHandle != NULL && command.menu.menuRef == helpMenuHandle ) ||
498 wxMenuBar::MacGetWindowMenuHMenu() != NULL && command.menu.menuRef == wxMenuBar::MacGetWindowMenuHMenu() )
499 {
500 wxMenuBar* mbar = wxMenuBar::MacGetInstalledMenuBar() ;
501 if ( mbar )
502 item = mbar->FindItem( id , &itemMenu ) ;
503 }
504 else
505 {
506 URefCon refCon ;
507
508 GetMenuItemRefCon( command.menu.menuRef , command.menu.menuItemIndex , &refCon ) ;
509 itemMenu = wxFindMenuFromMacMenu( command.menu.menuRef ) ;
510 if ( itemMenu != NULL )
511 item = (wxMenuItem*) refCon ;
512 }
513 }
514
515 return itemMenu ;
516 }
517
518 //----------------------------------------------------------------------
519 // Carbon Event Handler
520 //----------------------------------------------------------------------
521
522 static const EventTypeSpec eventList[] =
523 {
524 { kEventClassCommand, kEventProcessCommand } ,
525 { kEventClassCommand, kEventCommandUpdateStatus } ,
526
527 { kEventClassMenu, kEventMenuOpening },
528 { kEventClassMenu, kEventMenuClosed },
529 { kEventClassMenu, kEventMenuTargetItem },
530
531 { kEventClassApplication , kEventAppActivated } ,
532 { kEventClassApplication , kEventAppDeactivated } ,
533 // handling the quit event is not recommended by apple
534 // rather using the quit apple event - which we do
535
536 { kEventClassAppleEvent , kEventAppleEvent } ,
537
538 { kEventClassMouse , kEventMouseDown } ,
539 { kEventClassMouse , kEventMouseMoved } ,
540 { kEventClassMouse , kEventMouseUp } ,
541 { kEventClassMouse , kEventMouseDragged } ,
542 { 'WXMC' , 'WXMC' }
543 } ;
544
545 static pascal OSStatus
546 wxMacAppMenuEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
547 {
548 wxMacCarbonEvent cEvent( event ) ;
549 MenuRef menuRef = cEvent.GetParameter<MenuRef>(kEventParamDirectObject) ;
550 wxMenu* menu = wxFindMenuFromMacMenu( menuRef ) ;
551
552 if ( menu )
553 {
554 wxEventType type=0;
555 MenuCommand cmd=0;
556 switch (GetEventKind(event))
557 {
558 case kEventMenuOpening:
559 type = wxEVT_MENU_OPEN;
560 break;
561
562 case kEventMenuClosed:
563 type = wxEVT_MENU_CLOSE;
564 break;
565
566 case kEventMenuTargetItem:
567 cmd = cEvent.GetParameter<MenuCommand>(kEventParamMenuCommand,typeMenuCommand) ;
568 if (cmd != 0)
569 type = wxEVT_MENU_HIGHLIGHT;
570 break;
571
572 default:
573 wxFAIL_MSG(wxT("Unexpected menu event kind"));
574 break;
575 }
576
577 if ( type )
578 {
579 wxMenuEvent wxevent(type, cmd, menu);
580 wxevent.SetEventObject(menu);
581
582 wxEvtHandler* handler = menu->GetEventHandler();
583 if (handler && handler->ProcessEvent(wxevent))
584 {
585 // handled
586 }
587 else
588 {
589 wxWindow *win = menu->GetInvokingWindow();
590 if (win)
591 win->GetEventHandler()->ProcessEvent(wxevent);
592 }
593 }
594 }
595
596 return eventNotHandledErr;
597 }
598
599 static pascal OSStatus wxMacAppCommandEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
600 {
601 OSStatus result = eventNotHandledErr ;
602
603 HICommand command ;
604
605 wxMacCarbonEvent cEvent( event ) ;
606 cEvent.GetParameter<HICommand>(kEventParamDirectObject,typeHICommand,&command) ;
607
608 wxMenuItem* item = NULL ;
609 wxMenu* itemMenu = wxFindMenuFromMacCommand( command , item ) ;
610 int id = wxMacCommandToId( command.commandID ) ;
611
612 if ( item )
613 {
614 wxASSERT( itemMenu != NULL ) ;
615
616 switch ( cEvent.GetKind() )
617 {
618 case kEventProcessCommand :
619 {
620 if (item->IsCheckable())
621 item->Check( !item->IsChecked() ) ;
622
623 if ( itemMenu->SendEvent( id , item->IsCheckable() ? item->IsChecked() : -1 ) )
624 result = noErr ;
625 }
626 break ;
627
628 case kEventCommandUpdateStatus:
629 {
630 wxUpdateUIEvent event(id);
631 event.SetEventObject( itemMenu );
632
633 bool processed = false;
634
635 // Try the menu's event handler
636 {
637 wxEvtHandler *handler = itemMenu->GetEventHandler();
638 if ( handler )
639 processed = handler->ProcessEvent(event);
640 }
641
642 // Try the window the menu was popped up from
643 // (and up through the hierarchy)
644 if ( !processed )
645 {
646 const wxMenuBase *menu = itemMenu;
647 while ( menu )
648 {
649 wxWindow *win = menu->GetInvokingWindow();
650 if ( win )
651 {
652 processed = win->GetEventHandler()->ProcessEvent(event);
653 break;
654 }
655
656 menu = menu->GetParent();
657 }
658 }
659
660 if ( processed )
661 {
662 // if anything changed, update the changed attribute
663 if (event.GetSetText())
664 itemMenu->SetLabel(id, event.GetText());
665 if (event.GetSetChecked())
666 itemMenu->Check(id, event.GetChecked());
667 if (event.GetSetEnabled())
668 itemMenu->Enable(id, event.GetEnabled());
669
670 result = noErr ;
671 }
672 }
673 break ;
674
675 default :
676 break ;
677 }
678 }
679 return result ;
680 }
681
682 static pascal OSStatus wxMacAppApplicationEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
683 {
684 OSStatus result = eventNotHandledErr ;
685 switch ( GetEventKind( event ) )
686 {
687 case kEventAppActivated :
688 if ( wxTheApp )
689 wxTheApp->SetActive( true , NULL ) ;
690 result = noErr ;
691 break ;
692
693 case kEventAppDeactivated :
694 if ( wxTheApp )
695 wxTheApp->SetActive( false , NULL ) ;
696 result = noErr ;
697 break ;
698
699 default :
700 break ;
701 }
702
703 return result ;
704 }
705
706 pascal OSStatus wxMacAppEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
707 {
708 EventRef formerEvent = (EventRef) wxTheApp->MacGetCurrentEvent() ;
709 EventHandlerCallRef formerEventHandlerCallRef = (EventHandlerCallRef) wxTheApp->MacGetCurrentEventHandlerCallRef() ;
710 wxTheApp->MacSetCurrentEvent( event , handler ) ;
711
712 OSStatus result = eventNotHandledErr ;
713 switch ( GetEventClass( event ) )
714 {
715 case kEventClassCommand :
716 result = wxMacAppCommandEventHandler( handler , event , data ) ;
717 break ;
718
719 case kEventClassApplication :
720 result = wxMacAppApplicationEventHandler( handler , event , data ) ;
721 break ;
722
723 case kEventClassMenu :
724 result = wxMacAppMenuEventHandler( handler , event , data ) ;
725 break ;
726
727 case kEventClassMouse :
728 {
729 wxMacCarbonEvent cEvent( event ) ;
730
731 WindowRef window ;
732 Point screenMouseLocation = cEvent.GetParameter<Point>(kEventParamMouseLocation) ;
733 ::FindWindow(screenMouseLocation, &window);
734 // only send this event in case it had not already been sent to a tlw, as we get
735 // double events otherwise (in case event.skip) was called
736 if ( window == NULL )
737 result = wxMacTopLevelMouseEventHandler( handler , event , NULL ) ;
738 }
739 break ;
740
741 case kEventClassAppleEvent :
742 {
743 EventRecord rec ;
744
745 wxMacConvertEventToRecord( event , &rec ) ;
746 result = AEProcessAppleEvent( &rec ) ;
747 }
748 break ;
749
750 default :
751 break ;
752 }
753
754 wxTheApp->MacSetCurrentEvent( formerEvent, formerEventHandlerCallRef ) ;
755
756 return result ;
757 }
758
759 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler )
760
761 #ifdef __WXDEBUG__
762
763 pascal static void wxMacAssertOutputHandler(OSType componentSignature, UInt32 options,
764 const char *assertionString, const char *exceptionLabelString,
765 const char *errorString, const char *fileName, long lineNumber, void *value, ConstStr255Param outputMsg)
766 {
767 // flow into assert handling
768 wxString fileNameStr ;
769 wxString assertionStr ;
770 wxString exceptionStr ;
771 wxString errorStr ;
772
773 #if wxUSE_UNICODE
774 fileNameStr = wxString(fileName, wxConvLocal);
775 assertionStr = wxString(assertionString, wxConvLocal);
776 exceptionStr = wxString((exceptionLabelString!=0) ? exceptionLabelString : "", wxConvLocal) ;
777 errorStr = wxString((errorString!=0) ? errorString : "", wxConvLocal) ;
778 #else
779 fileNameStr = fileName;
780 assertionStr = assertionString;
781 exceptionStr = (exceptionLabelString!=0) ? exceptionLabelString : "" ;
782 errorStr = (errorString!=0) ? errorString : "" ;
783 #endif
784
785 #if 1
786 // flow into log
787 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
788 assertionStr.c_str() ,
789 exceptionStr.c_str() ,
790 errorStr.c_str(),
791 fileNameStr.c_str(), lineNumber ,
792 value ) ;
793 #else
794
795 wxOnAssert(fileNameStr, lineNumber , assertionStr ,
796 wxString::Format( wxT("%s %s value (%p)") , exceptionStr, errorStr , value ) ) ;
797 #endif
798 }
799
800 #endif //__WXDEBUG__
801
802 #ifdef __WXMAC_OSX__
803 extern "C"
804 {
805 // m_macEventPosted run loop source callback:
806 void macPostedEventCallback(void *unused);
807 }
808
809 void macPostedEventCallback(void *unused)
810 {
811 wxTheApp->ProcessPendingEvents();
812 }
813 #endif
814
815 bool wxApp::Initialize(int& argc, wxChar **argv)
816 {
817 // Mac-specific
818
819 #ifdef __WXDEBUG__
820 InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler ) );
821 #endif
822
823 UMAInitToolbox( 4, sm_isEmbedded ) ;
824 SetEventMask( everyEvent ) ;
825 UMAShowWatchCursor() ;
826
827 #ifndef __DARWIN__
828 # if __option(profile)
829 ProfilerInit( collectDetailed, bestTimeBase , 40000 , 50 ) ;
830 # endif
831 #endif
832
833 #ifndef __DARWIN__
834 // now avoid exceptions thrown for new (bad_alloc)
835 // FIXME CS for some changes outside wxMac does not compile anymore
836 #if 0
837 std::__throws_bad_alloc = 0 ;
838 #endif
839
840 #endif
841
842 // Mac OS X passes a process serial number command line argument when
843 // the application is launched from the Finder. This argument must be
844 // removed from the command line arguments before being handled by the
845 // application (otherwise applications would need to handle it)
846 if ( argc > 1 )
847 {
848 static const wxChar *ARG_PSN = _T("-psn_");
849 if ( wxStrncmp(argv[1], ARG_PSN, wxStrlen(ARG_PSN)) == 0 )
850 {
851 // remove this argument
852 --argc;
853 memmove(argv + 1, argv + 2, argc * sizeof(char *));
854 }
855 }
856
857 if ( !wxAppBase::Initialize(argc, argv) )
858 return false;
859
860 #if wxUSE_INTL
861 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
862 #endif
863
864 #if TARGET_API_MAC_OSX
865 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
866 wxString startupCwd = wxGetCwd() ;
867 if ( startupCwd == wxT("/") || startupCwd.Right(15) == wxT("/Contents/MacOS") )
868 {
869 CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
870 CFURLRef urlParent = CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault , url ) ;
871 CFRelease( url ) ;
872 CFStringRef path = CFURLCopyFileSystemPath ( urlParent , kCFURLPOSIXPathStyle ) ;
873 CFRelease( urlParent ) ;
874 wxString cwd = wxMacCFStringHolder(path).AsString(wxLocale::GetSystemEncoding());
875 wxSetWorkingDirectory( cwd ) ;
876 }
877 #endif
878
879 wxMacCreateNotifierTable() ;
880
881 #ifdef __WXMAC_OSX__
882 /* connect posted events to common-mode run loop so that wxPostEvent events
883 are handled even while we're in the menu or on a scrollbar */
884 CFRunLoopSourceContext event_posted_context = {0};
885 event_posted_context.perform = macPostedEventCallback;
886 m_macEventPosted = CFRunLoopSourceCreate(NULL,0,&event_posted_context);
887 CFRunLoopAddSource(CFRunLoopGetCurrent(), m_macEventPosted, kCFRunLoopCommonModes);
888 // run loop takes ownership
889 CFRelease(m_macEventPosted);
890 #endif
891
892 UMAShowArrowCursor() ;
893
894 return true;
895 }
896
897 AEEventHandlerUPP sODocHandler = NULL ;
898 AEEventHandlerUPP sGURLHandler = NULL ;
899 AEEventHandlerUPP sOAppHandler = NULL ;
900 AEEventHandlerUPP sPDocHandler = NULL ;
901 AEEventHandlerUPP sRAppHandler = NULL ;
902 AEEventHandlerUPP sQuitHandler = NULL ;
903
904 bool wxApp::OnInitGui()
905 {
906 if ( !wxAppBase::OnInitGui() )
907 return false ;
908
909 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
910
911 if (!sm_isEmbedded)
912 {
913 InstallApplicationEventHandler(
914 GetwxMacAppEventHandlerUPP(),
915 GetEventTypeCount(eventList), eventList, wxTheApp, (EventHandlerRef *)&(wxTheApp->m_macEventHandler));
916 }
917
918 if (!sm_isEmbedded)
919 {
920 sODocHandler = NewAEEventHandlerUPP(AEHandleODoc) ;
921 sGURLHandler = NewAEEventHandlerUPP(AEHandleGURL) ;
922 sOAppHandler = NewAEEventHandlerUPP(AEHandleOApp) ;
923 sPDocHandler = NewAEEventHandlerUPP(AEHandlePDoc) ;
924 sRAppHandler = NewAEEventHandlerUPP(AEHandleRApp) ;
925 sQuitHandler = NewAEEventHandlerUPP(AEHandleQuit) ;
926
927 AEInstallEventHandler( kCoreEventClass , kAEOpenDocuments ,
928 sODocHandler , 0 , FALSE ) ;
929 AEInstallEventHandler( kInternetEventClass, kAEGetURL,
930 sGURLHandler , 0 , FALSE ) ;
931 AEInstallEventHandler( kCoreEventClass , kAEOpenApplication ,
932 sOAppHandler , 0 , FALSE ) ;
933 AEInstallEventHandler( kCoreEventClass , kAEPrintDocuments ,
934 sPDocHandler , 0 , FALSE ) ;
935 AEInstallEventHandler( kCoreEventClass , kAEReopenApplication ,
936 sRAppHandler , 0 , FALSE ) ;
937 AEInstallEventHandler( kCoreEventClass , kAEQuitApplication ,
938 sQuitHandler , 0 , FALSE ) ;
939 }
940
941 return true ;
942 }
943
944 void wxApp::CleanUp()
945 {
946 #if wxUSE_TOOLTIPS
947 wxToolTip::RemoveToolTips() ;
948 #endif
949
950 #ifdef __WXMAC_OSX__
951 if (m_macEventPosted)
952 {
953 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m_macEventPosted, kCFRunLoopCommonModes);
954 m_macEventPosted = NULL;
955 }
956 #endif
957
958 // One last chance for pending objects to be cleaned up
959 wxTheApp->DeletePendingObjects();
960
961 wxMacDestroyNotifierTable() ;
962
963 #ifndef __DARWIN__
964 # if __option(profile)
965 ProfilerDump( (StringPtr)"\papp.prof" ) ;
966 ProfilerTerm() ;
967 # endif
968 #endif
969
970 UMACleanupToolbox() ;
971
972 if (!sm_isEmbedded)
973 RemoveEventHandler( (EventHandlerRef)(wxTheApp->m_macEventHandler) );
974
975 if (!sm_isEmbedded)
976 {
977 AERemoveEventHandler( kCoreEventClass , kAEOpenDocuments ,
978 sODocHandler , FALSE ) ;
979 AERemoveEventHandler( kInternetEventClass, kAEGetURL,
980 sGURLHandler , FALSE ) ;
981 AERemoveEventHandler( kCoreEventClass , kAEOpenApplication ,
982 sOAppHandler , FALSE ) ;
983 AERemoveEventHandler( kCoreEventClass , kAEPrintDocuments ,
984 sPDocHandler , FALSE ) ;
985 AERemoveEventHandler( kCoreEventClass , kAEReopenApplication ,
986 sRAppHandler , FALSE ) ;
987 AERemoveEventHandler( kCoreEventClass , kAEQuitApplication ,
988 sQuitHandler , FALSE ) ;
989
990 DisposeAEEventHandlerUPP( sODocHandler ) ;
991 DisposeAEEventHandlerUPP( sGURLHandler ) ;
992 DisposeAEEventHandlerUPP( sOAppHandler ) ;
993 DisposeAEEventHandlerUPP( sPDocHandler ) ;
994 DisposeAEEventHandlerUPP( sRAppHandler ) ;
995 DisposeAEEventHandlerUPP( sQuitHandler ) ;
996 }
997
998 wxAppBase::CleanUp();
999 }
1000
1001 //----------------------------------------------------------------------
1002 // misc initialization stuff
1003 //----------------------------------------------------------------------
1004
1005 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
1006
1007 // for shared libraries we have to manually get the correct resource
1008 // ref num upon initializing and releasing when terminating, therefore
1009 // the __wxinitialize and __wxterminate must be used
1010
1011 extern "C"
1012 {
1013 void __sinit(void); // (generated by linker)
1014 pascal OSErr __initialize(const CFragInitBlock *theInitBlock);
1015 pascal void __terminate(void);
1016 }
1017
1018 pascal OSErr __wxinitialize(const CFragInitBlock *theInitBlock)
1019 {
1020 return __initialize( theInitBlock ) ;
1021 }
1022
1023 pascal void __wxterminate(void)
1024 {
1025 __terminate() ;
1026 }
1027
1028 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
1029
1030 bool wxMacConvertEventToRecord( EventRef event , EventRecord *rec)
1031 {
1032 OSStatus err = noErr ;
1033 bool converted = ConvertEventRefToEventRecord( event, rec) ;
1034
1035 if ( !converted )
1036 {
1037 switch ( GetEventClass( event ) )
1038 {
1039 case kEventClassKeyboard :
1040 {
1041 converted = true ;
1042 switch ( GetEventKind(event) )
1043 {
1044 case kEventRawKeyDown :
1045 rec->what = keyDown ;
1046 break ;
1047
1048 case kEventRawKeyRepeat :
1049 rec->what = autoKey ;
1050 break ;
1051
1052 case kEventRawKeyUp :
1053 rec->what = keyUp ;
1054 break ;
1055
1056 case kEventRawKeyModifiersChanged :
1057 rec->what = nullEvent ;
1058 break ;
1059
1060 default :
1061 converted = false ;
1062 break ;
1063 }
1064
1065 if ( converted )
1066 {
1067 UInt32 keyCode ;
1068 unsigned char charCode ;
1069 UInt32 modifiers ;
1070 #ifndef __LP64__
1071 GetMouse( &rec->where) ;
1072 #endif
1073 err = GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL, 4, NULL, &modifiers);
1074 err = GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL, 4, NULL, &keyCode);
1075 err = GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL, 1, NULL, &charCode);
1076 rec->modifiers = modifiers ;
1077 rec->message = (keyCode << 8 ) + charCode ;
1078 }
1079 }
1080 break ;
1081
1082 case kEventClassTextInput :
1083 {
1084 switch ( GetEventKind( event ) )
1085 {
1086 case kEventTextInputUnicodeForKeyEvent :
1087 {
1088 EventRef rawEvent ;
1089 err = GetEventParameter(
1090 event, kEventParamTextInputSendKeyboardEvent, typeEventRef, NULL,
1091 sizeof(rawEvent), NULL, &rawEvent ) ;
1092 converted = true ;
1093
1094 {
1095 UInt32 keyCode, modifiers;
1096 unsigned char charCode ;
1097 #ifndef __LP64__
1098
1099 GetMouse( &rec->where) ;
1100 #endif
1101 rec->what = keyDown ;
1102 err = GetEventParameter(rawEvent, kEventParamKeyModifiers, typeUInt32, NULL, 4, NULL, &modifiers);
1103 err = GetEventParameter(rawEvent, kEventParamKeyCode, typeUInt32, NULL, 4, NULL, &keyCode);
1104 err = GetEventParameter(rawEvent, kEventParamKeyMacCharCodes, typeChar, NULL, 1, NULL, &charCode);
1105 rec->modifiers = modifiers ;
1106 rec->message = (keyCode << 8 ) + charCode ;
1107 }
1108 }
1109 break ;
1110
1111 default :
1112 break ;
1113 }
1114 }
1115 break ;
1116
1117 default :
1118 break ;
1119 }
1120 }
1121
1122 return converted ;
1123 }
1124
1125 wxApp::wxApp()
1126 {
1127 m_printMode = wxPRINT_WINDOWS;
1128
1129 m_macCurrentEvent = NULL ;
1130 m_macCurrentEventHandlerCallRef = NULL ;
1131
1132 #ifdef __WXMAC_OSX__
1133 m_macEventPosted = NULL ;
1134 #endif
1135 }
1136
1137 void wxApp::OnIdle(wxIdleEvent& event)
1138 {
1139 wxAppBase::OnIdle(event);
1140
1141 // If they are pending events, we must process them: pending events are
1142 // either events to the threads other than main or events posted with
1143 // wxPostEvent() functions
1144 wxMacProcessNotifierAndPendingEvents();
1145
1146 if (!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
1147 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
1148 }
1149
1150 void wxApp::WakeUpIdle()
1151 {
1152 #ifdef __WXMAC_OSX__
1153 if (m_macEventPosted)
1154 {
1155 CFRunLoopSourceSignal(m_macEventPosted);
1156 }
1157 #endif
1158
1159 wxMacWakeUp() ;
1160 }
1161
1162 void wxApp::OnEndSession(wxCloseEvent& WXUNUSED(event))
1163 {
1164 if (GetTopWindow())
1165 GetTopWindow()->Close(true);
1166 }
1167
1168 // Default behaviour: close the application with prompts. The
1169 // user can veto the close, and therefore the end session.
1170 void wxApp::OnQueryEndSession(wxCloseEvent& event)
1171 {
1172 if (GetTopWindow())
1173 {
1174 if (!GetTopWindow()->Close(!event.CanVeto()))
1175 event.Veto(true);
1176 }
1177 }
1178
1179 extern "C" void wxCYield() ;
1180 void wxCYield()
1181 {
1182 wxYield() ;
1183 }
1184
1185 // Yield to other processes
1186
1187 bool wxApp::Yield(bool onlyIfNeeded)
1188 {
1189 if (s_inYield)
1190 {
1191 if ( !onlyIfNeeded )
1192 {
1193 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1194 }
1195
1196 return false;
1197 }
1198
1199 s_inYield = true;
1200
1201 // by definition yield should handle all non-processed events
1202
1203 EventRef theEvent;
1204
1205 OSStatus status = noErr ;
1206
1207 while ( status == noErr )
1208 {
1209 s_inReceiveEvent = true ;
1210 status = ReceiveNextEvent(0, NULL,kEventDurationNoWait,true,&theEvent) ;
1211 s_inReceiveEvent = false ;
1212
1213 if ( status == eventLoopTimedOutErr )
1214 {
1215 // make sure next time the event loop will trigger idle events
1216 sleepTime = kEventDurationNoWait ;
1217 }
1218 else if ( status == eventLoopQuitErr )
1219 {
1220 // according to QA1061 this may also occur when a WakeUp Process
1221 // is executed
1222 }
1223 else
1224 {
1225 MacHandleOneEvent( theEvent ) ;
1226 ReleaseEvent(theEvent);
1227 }
1228 }
1229
1230 wxMacProcessNotifierAndPendingEvents() ;
1231 s_inYield = false;
1232
1233 return true;
1234 }
1235
1236 void wxApp::MacDoOneEvent()
1237 {
1238 EventRef theEvent;
1239
1240 s_inReceiveEvent = true ;
1241 OSStatus status = ReceiveNextEvent(0, NULL, sleepTime, true, &theEvent) ;
1242 s_inReceiveEvent = false ;
1243
1244 switch (status)
1245 {
1246 case eventLoopTimedOutErr :
1247 if ( wxTheApp->ProcessIdle() )
1248 sleepTime = kEventDurationNoWait ;
1249 else
1250 sleepTime = kEventDurationSecond;
1251 break;
1252
1253 case eventLoopQuitErr :
1254 // according to QA1061 this may also occur
1255 // when a WakeUp Process is executed
1256 break;
1257
1258 default:
1259 MacHandleOneEvent( theEvent ) ;
1260 ReleaseEvent( theEvent );
1261 sleepTime = kEventDurationNoWait ;
1262 break;
1263 }
1264 // repeaters
1265
1266 DeletePendingObjects() ;
1267 wxMacProcessNotifierAndPendingEvents() ;
1268 }
1269
1270 // virtual
1271 void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr )
1272 {
1273 // Override to process unhandled events as you please
1274 }
1275
1276 CFMutableArrayRef GetAutoReleaseArray()
1277 {
1278 static CFMutableArrayRef array = 0;
1279 if ( array == 0)
1280 array= CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
1281 return array;
1282 }
1283
1284 void wxApp::MacHandleOneEvent( WXEVENTREF evr )
1285 {
1286 EventTargetRef theTarget;
1287 theTarget = GetEventDispatcherTarget();
1288 m_macCurrentEvent = evr ;
1289
1290 OSStatus status = SendEventToEventTarget((EventRef) evr , theTarget);
1291 if (status == eventNotHandledErr)
1292 MacHandleUnhandledEvent(evr);
1293
1294 wxMacProcessNotifierAndPendingEvents() ;
1295
1296 #if wxUSE_THREADS
1297 wxMutexGuiLeaveOrEnter();
1298 #endif // wxUSE_THREADS
1299
1300 CFArrayRemoveAllValues( GetAutoReleaseArray() );
1301 }
1302
1303 void wxApp::MacAddToAutorelease( void* cfrefobj )
1304 {
1305 CFArrayAppendValue( GetAutoReleaseArray(), cfrefobj );
1306 }
1307
1308 long wxMacTranslateKey(unsigned char key, unsigned char code)
1309 {
1310 long retval = key ;
1311 switch (key)
1312 {
1313 case kHomeCharCode :
1314 retval = WXK_HOME;
1315 break;
1316
1317 case kEnterCharCode :
1318 retval = WXK_RETURN;
1319 break;
1320 case kEndCharCode :
1321 retval = WXK_END;
1322 break;
1323
1324 case kHelpCharCode :
1325 retval = WXK_HELP;
1326 break;
1327
1328 case kBackspaceCharCode :
1329 retval = WXK_BACK;
1330 break;
1331
1332 case kTabCharCode :
1333 retval = WXK_TAB;
1334 break;
1335
1336 case kPageUpCharCode :
1337 retval = WXK_PAGEUP;
1338 break;
1339
1340 case kPageDownCharCode :
1341 retval = WXK_PAGEDOWN;
1342 break;
1343
1344 case kReturnCharCode :
1345 retval = WXK_RETURN;
1346 break;
1347
1348 case kFunctionKeyCharCode :
1349 {
1350 switch ( code )
1351 {
1352 case 0x7a :
1353 retval = WXK_F1 ;
1354 break;
1355
1356 case 0x78 :
1357 retval = WXK_F2 ;
1358 break;
1359
1360 case 0x63 :
1361 retval = WXK_F3 ;
1362 break;
1363
1364 case 0x76 :
1365 retval = WXK_F4 ;
1366 break;
1367
1368 case 0x60 :
1369 retval = WXK_F5 ;
1370 break;
1371
1372 case 0x61 :
1373 retval = WXK_F6 ;
1374 break;
1375
1376 case 0x62:
1377 retval = WXK_F7 ;
1378 break;
1379
1380 case 0x64 :
1381 retval = WXK_F8 ;
1382 break;
1383
1384 case 0x65 :
1385 retval = WXK_F9 ;
1386 break;
1387
1388 case 0x6D :
1389 retval = WXK_F10 ;
1390 break;
1391
1392 case 0x67 :
1393 retval = WXK_F11 ;
1394 break;
1395
1396 case 0x6F :
1397 retval = WXK_F12 ;
1398 break;
1399
1400 case 0x69 :
1401 retval = WXK_F13 ;
1402 break;
1403
1404 case 0x6B :
1405 retval = WXK_F14 ;
1406 break;
1407
1408 case 0x71 :
1409 retval = WXK_F15 ;
1410 break;
1411
1412 default:
1413 break;
1414 }
1415 }
1416 break ;
1417
1418 case kEscapeCharCode :
1419 retval = WXK_ESCAPE ;
1420 break ;
1421
1422 case kLeftArrowCharCode :
1423 retval = WXK_LEFT ;
1424 break ;
1425
1426 case kRightArrowCharCode :
1427 retval = WXK_RIGHT ;
1428 break ;
1429
1430 case kUpArrowCharCode :
1431 retval = WXK_UP ;
1432 break ;
1433
1434 case kDownArrowCharCode :
1435 retval = WXK_DOWN ;
1436 break ;
1437
1438 case kDeleteCharCode :
1439 retval = WXK_DELETE ;
1440 break ;
1441
1442 default:
1443 break ;
1444 } // end switch
1445
1446 return retval;
1447 }
1448
1449 int wxMacKeyCodeToModifier(wxKeyCode key)
1450 {
1451 switch (key)
1452 {
1453 case WXK_START:
1454 case WXK_MENU:
1455 return cmdKey;
1456
1457 case WXK_SHIFT:
1458 return shiftKey;
1459
1460 case WXK_CAPITAL:
1461 return alphaLock;
1462
1463 case WXK_ALT:
1464 return optionKey;
1465
1466 case WXK_CONTROL:
1467 return controlKey;
1468
1469 default:
1470 return 0;
1471 }
1472 }
1473
1474 #ifndef __DARWIN__
1475 bool wxGetKeyState(wxKeyCode key) //virtual key code if < 10.2.x, else see below
1476 {
1477 wxASSERT_MSG(key != WXK_LBUTTON && key != WXK_RBUTTON && key !=
1478 WXK_MBUTTON, wxT("can't use wxGetKeyState() for mouse buttons"));
1479
1480 //if OS X > 10.2 (i.e. 10.2.x)
1481 //a known apple bug prevents the system from determining led
1482 //states with GetKeys... can only determine caps lock led
1483 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key));
1484 //else
1485 // KeyMapByteArray keymap;
1486 // GetKeys((BigEndianLong*)keymap);
1487 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1488 }
1489 #endif
1490
1491
1492 wxMouseState wxGetMouseState()
1493 {
1494 wxMouseState ms;
1495
1496 wxPoint pt = wxGetMousePosition();
1497 ms.SetX(pt.x);
1498 ms.SetY(pt.y);
1499
1500 #if TARGET_API_MAC_OSX
1501 UInt32 buttons = GetCurrentButtonState();
1502 ms.SetLeftDown( (buttons & 0x01) != 0 );
1503 ms.SetMiddleDown( (buttons & 0x04) != 0 );
1504 ms.SetRightDown( (buttons & 0x02) != 0 );
1505 #else
1506 ms.SetLeftDown( Button() );
1507 ms.SetMiddleDown( 0 );
1508 ms.SetRightDown( 0 );
1509 #endif
1510
1511 UInt32 modifiers = GetCurrentKeyModifiers();
1512 ms.SetControlDown(modifiers & controlKey);
1513 ms.SetShiftDown(modifiers & shiftKey);
1514 ms.SetAltDown(modifiers & optionKey);
1515 ms.SetMetaDown(modifiers & cmdKey);
1516
1517 return ms;
1518 }
1519
1520 // TODO : once the new key/char handling is tested, move all the code to wxWindow
1521
1522 bool wxApp::MacSendKeyDownEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey , wxChar uniChar )
1523 {
1524 if ( !focus )
1525 return false ;
1526
1527 bool handled;
1528 wxKeyEvent event(wxEVT_KEY_DOWN) ;
1529 MacCreateKeyEvent( event, focus , keymessage , modifiers , when , wherex , wherey , uniChar ) ;
1530
1531 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1532 if ( handled && event.GetSkipped() )
1533 handled = false ;
1534
1535 #if wxUSE_ACCEL
1536 if ( !handled )
1537 {
1538 wxWindow *ancestor = focus;
1539 while (ancestor)
1540 {
1541 int command = ancestor->GetAcceleratorTable()->GetCommand( event );
1542 if (command != -1)
1543 {
1544 wxEvtHandler * const handler = ancestor->GetEventHandler();
1545
1546 wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1547 handled = handler->ProcessEvent( command_event );
1548
1549 if ( !handled )
1550 {
1551 // accelerators can also be used with buttons, try them too
1552 command_event.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED);
1553 handled = handler->ProcessEvent( command_event );
1554 }
1555
1556 break;
1557 }
1558
1559 if (ancestor->IsTopLevel())
1560 break;
1561
1562 ancestor = ancestor->GetParent();
1563 }
1564 }
1565 #endif // wxUSE_ACCEL
1566
1567 return handled ;
1568 }
1569
1570 bool wxApp::MacSendKeyUpEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey , wxChar uniChar )
1571 {
1572 if ( !focus )
1573 return false ;
1574
1575 bool handled;
1576 wxKeyEvent event( wxEVT_KEY_UP ) ;
1577 MacCreateKeyEvent( event, focus , keymessage , modifiers , when , wherex , wherey , uniChar ) ;
1578 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1579
1580 return handled ;
1581 }
1582
1583 bool wxApp::MacSendCharEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey , wxChar uniChar )
1584 {
1585 if ( !focus )
1586 return false ;
1587
1588 wxKeyEvent event(wxEVT_CHAR) ;
1589 MacCreateKeyEvent( event, focus , keymessage , modifiers , when , wherex , wherey , uniChar ) ;
1590 long keyval = event.m_keyCode ;
1591
1592 bool handled = false ;
1593
1594 wxTopLevelWindowMac *tlw = focus->MacGetTopLevelWindow() ;
1595
1596 if (tlw)
1597 {
1598 event.SetEventType( wxEVT_CHAR_HOOK );
1599 handled = tlw->GetEventHandler()->ProcessEvent( event );
1600 if ( handled && event.GetSkipped() )
1601 handled = false ;
1602 }
1603
1604 if ( !handled )
1605 {
1606 event.SetEventType( wxEVT_CHAR );
1607 event.Skip( false ) ;
1608 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1609 }
1610
1611 if ( !handled && (keyval == WXK_TAB) )
1612 {
1613 wxWindow* iter = focus->GetParent() ;
1614 while ( iter && !handled )
1615 {
1616 if ( iter->HasFlag( wxTAB_TRAVERSAL ) )
1617 {
1618 wxNavigationKeyEvent new_event;
1619 new_event.SetEventObject( focus );
1620 new_event.SetDirection( !event.ShiftDown() );
1621 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1622 new_event.SetWindowChange( event.ControlDown() );
1623 new_event.SetCurrentFocus( focus );
1624 handled = focus->GetParent()->GetEventHandler()->ProcessEvent( new_event );
1625 if ( handled && new_event.GetSkipped() )
1626 handled = false ;
1627 }
1628
1629 iter = iter->GetParent() ;
1630 }
1631 }
1632
1633 // backdoor handler for default return and command escape
1634 if ( !handled && (!focus->IsKindOf(CLASSINFO(wxControl) ) || !focus->MacCanFocus() ) )
1635 {
1636 // if window is not having a focus still testing for default enter or cancel
1637 // TODO: add the UMA version for ActiveNonFloatingWindow
1638 wxWindow* focus = wxFindWinFromMacWindow( FrontWindow() ) ;
1639 if ( focus )
1640 {
1641 if ( keyval == WXK_RETURN || keyval == WXK_NUMPAD_ENTER )
1642 {
1643 wxTopLevelWindow *tlw = wxDynamicCast(wxGetTopLevelParent(focus), wxTopLevelWindow);
1644 if ( tlw && tlw->GetDefaultItem() )
1645 {
1646 wxButton *def = wxDynamicCast(tlw->GetDefaultItem(), wxButton);
1647 if ( def && def->IsEnabled() )
1648 {
1649 wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, def->GetId() );
1650 event.SetEventObject(def);
1651 def->Command(event);
1652
1653 return true ;
1654 }
1655 }
1656 }
1657 else if (keyval == WXK_ESCAPE || (keyval == '.' && modifiers & cmdKey ) )
1658 {
1659 // generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs)
1660 wxCommandEvent new_event(wxEVT_COMMAND_BUTTON_CLICKED,wxID_CANCEL);
1661 new_event.SetEventObject( focus );
1662 handled = focus->GetEventHandler()->ProcessEvent( new_event );
1663 }
1664 }
1665 }
1666 return handled ;
1667 }
1668
1669 // This method handles common code for SendKeyDown, SendKeyUp, and SendChar events.
1670 void wxApp::MacCreateKeyEvent( wxKeyEvent& event, wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey , wxChar uniChar )
1671 {
1672 short keycode, keychar ;
1673
1674 keychar = short(keymessage & charCodeMask);
1675 keycode = short(keymessage & keyCodeMask) >> 8 ;
1676 if ( !(event.GetEventType() == wxEVT_CHAR) && (modifiers & (controlKey | shiftKey | optionKey) ) )
1677 {
1678 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1679 // and look at the character after
1680 UInt32 state = 0;
1681 UInt32 keyInfo = KeyTranslate((Ptr)GetScriptManagerVariable(smKCHRCache), ( modifiers & (~(controlKey | shiftKey | optionKey))) | keycode, &state);
1682 keychar = short(keyInfo & charCodeMask);
1683 }
1684
1685 long keyval = wxMacTranslateKey(keychar, keycode) ;
1686 if ( keyval == keychar && ( event.GetEventType() == wxEVT_KEY_UP || event.GetEventType() == wxEVT_KEY_DOWN ) )
1687 keyval = wxToupper( keyval ) ;
1688
1689 // Check for NUMPAD keys
1690 if (keyval >= '0' && keyval <= '9' && keycode >= 82 && keycode <= 92)
1691 {
1692 keyval = (keyval - '0') + WXK_NUMPAD0;
1693 }
1694 else if (keycode >= 67 && keycode <= 81)
1695 {
1696 switch (keycode)
1697 {
1698 case 76 :
1699 keyval = WXK_NUMPAD_ENTER;
1700 break;
1701
1702 case 81:
1703 keyval = WXK_NUMPAD_EQUAL;
1704 break;
1705
1706 case 67:
1707 keyval = WXK_NUMPAD_MULTIPLY;
1708 break;
1709
1710 case 75:
1711 keyval = WXK_NUMPAD_DIVIDE;
1712 break;
1713
1714 case 78:
1715 keyval = WXK_NUMPAD_SUBTRACT;
1716 break;
1717
1718 case 69:
1719 keyval = WXK_NUMPAD_ADD;
1720 break;
1721
1722 case 65:
1723 keyval = WXK_NUMPAD_DECIMAL;
1724 break;
1725
1726 default:
1727 break;
1728 } // end switch
1729 }
1730
1731 event.m_shiftDown = modifiers & shiftKey;
1732 event.m_controlDown = modifiers & controlKey;
1733 event.m_altDown = modifiers & optionKey;
1734 event.m_metaDown = modifiers & cmdKey;
1735 event.m_keyCode = keyval ;
1736 #if wxUSE_UNICODE
1737 event.m_uniChar = uniChar ;
1738 #endif
1739
1740 event.m_rawCode = keymessage;
1741 event.m_rawFlags = modifiers;
1742 event.m_x = wherex;
1743 event.m_y = wherey;
1744 event.SetTimestamp(when);
1745 event.SetEventObject(focus);
1746 }