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