1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Various utilities
4 // Author: Stefan Csomor
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
13 // Note: this is done in utilscmn.cpp now.
14 // #pragma implementation "utils.h"
20 #include "wx/apptrait.h"
23 #include "wx/mac/uma.h"
34 # include "MoreFilesX.h"
36 # include "MoreFiles.h"
37 # include "MoreFilesExtras.h"
45 #include "ATSUnicode.h"
46 #include "TextCommon.h"
47 #include "TextEncodingConverter.h"
49 #if defined(__WXMAC__)
50 #include "wx/mac/private.h" // includes mac headers
53 #if defined(__MWERKS__) && wxUSE_UNICODE
60 // defined in unix/utilsunx.cpp for Mac OS X
62 // get full hostname (with domain name if possible)
63 bool wxGetFullHostName(wxChar *buf, int maxSize)
65 return wxGetHostName(buf, maxSize);
68 // Get hostname only (without domain name)
69 bool wxGetHostName(wxChar *buf, int maxSize)
71 // Gets Chooser name of user by examining a System resource.
73 const short kComputerNameID = -16413;
75 short oldResFile = CurResFile() ;
77 StringHandle chooserName = (StringHandle)::GetString(kComputerNameID);
78 UseResFile(oldResFile);
80 if (chooserName && *chooserName)
82 HLock( (Handle) chooserName ) ;
83 wxString name = wxMacMakeStringFromPascal( *chooserName ) ;
84 HUnlock( (Handle) chooserName ) ;
85 ReleaseResource( (Handle) chooserName ) ;
86 wxStrncpy( buf , name , maxSize - 1 ) ;
94 // Get user ID e.g. jacs
95 bool wxGetUserId(wxChar *buf, int maxSize)
97 return wxGetUserName( buf , maxSize ) ;
100 const wxChar* wxGetHomeDir(wxString *pstr)
102 *pstr = wxMacFindFolder( (short) kOnSystemDisk, kPreferencesFolderType, kDontCreateFolder ) ;
103 return pstr->c_str() ;
106 // Get user name e.g. Stefan Csomor
107 bool wxGetUserName(wxChar *buf, int maxSize)
109 // Gets Chooser name of user by examining a System resource.
111 const short kChooserNameID = -16096;
113 short oldResFile = CurResFile() ;
115 StringHandle chooserName = (StringHandle)::GetString(kChooserNameID);
116 UseResFile(oldResFile);
118 if (chooserName && *chooserName)
120 HLock( (Handle) chooserName ) ;
121 wxString name = wxMacMakeStringFromPascal( *chooserName ) ;
122 HUnlock( (Handle) chooserName ) ;
123 ReleaseResource( (Handle) chooserName ) ;
124 wxStrncpy( buf , name , maxSize - 1 ) ;
132 int wxKill(long pid, wxSignal sig , wxKillError *rc )
138 WXDLLEXPORT bool wxGetEnv(const wxString& var, wxString *value)
140 // TODO : under classic there is no environement support, under X yes
144 // set the env var name to the given value, return TRUE on success
145 WXDLLEXPORT bool wxSetEnv(const wxString& var, const wxChar *value)
147 // TODO : under classic there is no environement support, under X yes
152 // Execute a program in an Interactive Shell
154 bool wxShell(const wxString& command)
160 // Shutdown or reboot the PC
161 bool wxShutdown(wxShutdownFlags wFlags)
167 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
168 long wxGetFreeMemory()
173 void wxUsleep(unsigned long milliseconds)
175 clock_t start = clock() ;
179 } while( clock() - start < milliseconds / 1000.0 * CLOCKS_PER_SEC ) ;
182 void wxSleep(int nSecs)
184 wxUsleep(1000*nSecs);
187 // Consume all events until no more left
192 #endif // !__DARWIN__
200 // our OS version is the same in non GUI and GUI cases
201 static int DoGetOSVersion(int *majorVsn, int *minorVsn)
205 // are there x-platform conventions ?
207 Gestalt(gestaltSystemVersion, &theSystem) ;
208 if (minorVsn != NULL) {
209 *minorVsn = (theSystem & 0xFF ) ;
211 if (majorVsn != NULL) {
212 *majorVsn = (theSystem >> 8 ) ;
221 wxToolkitInfo& wxConsoleAppTraits::GetToolkitInfo()
223 static wxToolkitInfo info;
224 info.os = DoGetOSVersion(&info.majorVersion, &info.minorVersion);
225 info.name = _T("wxBase");
233 wxToolkitInfo& wxGUIAppTraits::GetToolkitInfo()
235 static wxToolkitInfo info;
236 info.os = DoGetOSVersion(&info.majorVersion, &info.minorVersion);
237 info.shortName = _T("mac");
238 info.name = _T("wxMac");
239 #ifdef __WXUNIVERSAL__
240 info.shortName << _T("univ");
241 info.name << _T("/wxUniversal");
246 // Reading and writing resources (eg WIN.INI, .Xdefaults)
248 bool wxWriteResource(const wxString& section, const wxString& entry, const wxString& value, const wxString& file)
254 bool wxWriteResource(const wxString& section, const wxString& entry, float value, const wxString& file)
257 buf.Printf(wxT("%.4f"), value);
259 return wxWriteResource(section, entry, buf, file);
262 bool wxWriteResource(const wxString& section, const wxString& entry, long value, const wxString& file)
265 buf.Printf(wxT("%ld"), value);
267 return wxWriteResource(section, entry, buf, file);
270 bool wxWriteResource(const wxString& section, const wxString& entry, int value, const wxString& file)
273 buf.Printf(wxT("%d"), value);
275 return wxWriteResource(section, entry, buf, file);
278 bool wxGetResource(const wxString& section, const wxString& entry, char **value, const wxString& file)
284 bool wxGetResource(const wxString& section, const wxString& entry, float *value, const wxString& file)
287 bool succ = wxGetResource(section, entry, (char **)&s, file);
290 *value = (float)strtod(s, NULL);
297 bool wxGetResource(const wxString& section, const wxString& entry, long *value, const wxString& file)
300 bool succ = wxGetResource(section, entry, (char **)&s, file);
303 *value = strtol(s, NULL, 10);
310 bool wxGetResource(const wxString& section, const wxString& entry, int *value, const wxString& file)
313 bool succ = wxGetResource(section, entry, (char **)&s, file);
316 *value = (int)strtol(s, NULL, 10);
322 #endif // wxUSE_RESOURCES
324 int gs_wxBusyCursorCount = 0;
325 extern wxCursor gMacCurrentCursor ;
326 wxCursor gMacStoredActiveCursor ;
328 // Set the cursor to the busy cursor for all windows
329 void wxBeginBusyCursor(wxCursor *cursor)
331 if (gs_wxBusyCursorCount++ == 0)
333 gMacStoredActiveCursor = gMacCurrentCursor ;
334 cursor->MacInstall() ;
336 //else: nothing to do, already set
339 // Restore cursor to normal
340 void wxEndBusyCursor()
342 wxCHECK_RET( gs_wxBusyCursorCount > 0,
343 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
345 if (--gs_wxBusyCursorCount == 0)
347 gMacStoredActiveCursor.MacInstall() ;
348 gMacStoredActiveCursor = wxNullCursor ;
352 // TRUE if we're between the above two calls
355 return (gs_wxBusyCursorCount > 0);
358 wxString wxMacFindFolder( short vol,
360 Boolean createFolder)
366 if ( FindFolder( vol, folderType, createFolder, &vRefNum, &dirID) == noErr)
369 if ( FSMakeFSSpec( vRefNum , dirID , "\p" , &file ) == noErr )
371 strDir = wxMacFSSpec2MacFilename( &file ) + wxFILE_SEP_PATH ;
377 // Check whether this window wants to process messages, e.g. Stop button
378 // in long calculations.
379 bool wxCheckForInterrupt(wxWindow *wnd)
385 void wxGetMousePosition( int* x, int* y )
390 LocalToGlobal( &pt ) ;
395 // Return TRUE if we have a colour display
396 bool wxColourDisplay()
401 // Returns depth of screen
405 SetRect(&globRect, -32760, -32760, 32760, 32760);
406 GDHandle theMaxDevice;
409 theMaxDevice = GetMaxDevice(&globRect);
410 if (theMaxDevice != nil)
411 theDepth = (**(**theMaxDevice).gdPMap).pixelSize;
416 // Get size of display
417 void wxDisplaySize(int *width, int *height)
420 GetQDGlobalsScreenBits( &screenBits );
423 *width = screenBits.bounds.right - screenBits.bounds.left ;
425 if (height != NULL) {
426 *height = screenBits.bounds.bottom - screenBits.bounds.top ;
430 void wxDisplaySizeMM(int *width, int *height)
432 wxDisplaySize(width, height);
433 // on mac 72 is fixed (at least now ;-)
434 float cvPt2Mm = 25.4 / 72;
437 *width = int( *width * cvPt2Mm );
439 if (height != NULL) {
440 *height = int( *height * cvPt2Mm );
444 void wxClientDisplayRect(int *x, int *y, int *width, int *height)
447 GetQDGlobalsScreenBits( &screenBits );
453 *width = screenBits.bounds.right - screenBits.bounds.left ;
455 if (height != NULL) {
456 *height = screenBits.bounds.bottom - screenBits.bounds.top ;
461 GetThemeMenuBarHeight( &mheight ) ;
463 mheight = LMGetMBarHeight() ;
465 if (height != NULL) {
472 wxWindow* wxFindWindowAtPoint(const wxPoint& pt)
474 return wxGenericFindWindowAtPoint(pt);
481 wxString wxGetOsDescription()
483 #ifdef WXWIN_OS_DESCRIPTION
484 // use configure generated description if available
485 return wxString("MacOS (") + WXWIN_OS_DESCRIPTION + wxString(")");
487 return wxT("MacOS") ; //TODO:define further
492 wxChar *wxGetUserHome (const wxString& user)
498 bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
508 int pos = p.Find(':') ;
509 if ( pos != wxNOT_FOUND ) {
518 wxMacStringToPascal( p , volumeName ) ;
519 OSErr err = XGetVolumeInfoNoName( volumeName , 0 , &pb ) ;
520 if ( err == noErr ) {
522 (*pTotal) = wxLongLong( pb.ioVTotalBytes ) ;
525 (*pFree) = wxLongLong( pb.ioVFreeBytes ) ;
529 return err == noErr ;
531 #endif // !__DARWIN__
537 //---------------------------------------------------------------------------
538 // wxMac Specific utility functions
539 //---------------------------------------------------------------------------
541 char StringMac[] = "\x0d\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f"
542 "\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f"
543 "\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xae\xaf"
544 "\xb1\xb4\xb5\xb6\xbb\xbc\xbe\xbf"
545 "\xc0\xc1\xc2\xc4\xc7\xc8\xc9\xcb\xcc\xcd\xce\xcf"
546 "\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xca\xdb" ;
548 char StringANSI[] = "\x0a\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8"
549 "\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC"
550 "\x86\xBA\xA2\xA3\xA7\x95\xB6\xDF\xAE\xA9\x99\xB4\xA8\xC6\xD8"
551 "\xB1\xA5\xB5\xF0\xAA\xBA\xE6\xF8"
552 "\xBF\xA1\xAC\x83\xAB\xBB\x85\xC0\xC3\xD5\x8C\x9C"
553 "\x96\x97\x93\x94\x91\x92\xF7\xFF\xA0\x80" ;
555 void wxMacConvertFromPC( const char *from , char *to , int len )
560 for( int i = 0 ; i < len ; ++ i )
562 c = strchr( StringANSI , *from ) ;
565 *to = StringMac[ c - StringANSI] ;
573 for( int i = 0 ; i < len ; ++ i )
575 c = strchr( StringANSI , *from ) ;
578 *to = StringMac[ c - StringANSI] ;
590 void wxMacConvertToPC( const char *from , char *to , int len )
595 for( int i = 0 ; i < len ; ++ i )
597 c = strchr( StringMac , *from ) ;
600 *to = StringANSI[ c - StringMac] ;
608 for( int i = 0 ; i < len ; ++ i )
610 c = strchr( StringMac , *from ) ;
613 *to = StringANSI[ c - StringMac] ;
625 TECObjectRef s_TECNativeCToUnicode = NULL ;
626 TECObjectRef s_TECUnicodeToNativeC = NULL ;
627 TECObjectRef s_TECPlatformToNativeC = NULL ;
628 TECObjectRef s_TECNativeCToPlatform = NULL ;
629 void wxMacSetupConverters()
631 // if we assume errors are happening here we need low level debugging
632 // since the high level assert will use the encoders that are not yet
634 const int kEncoding = wxApp::s_macDefaultEncodingIsPC
635 ? (int)kTextEncodingWindowsLatin1
636 : (int)kTextEncodingMacRoman;
638 OSStatus status = noErr ;
639 status = TECCreateConverter(&s_TECNativeCToUnicode,
641 kTextEncodingUnicodeDefault);
644 status = TECCreateConverter(&s_TECUnicodeToNativeC,
645 kTextEncodingUnicodeDefault,
648 if ( wxApp::s_macDefaultEncodingIsPC )
650 status = TECCreateConverter(&s_TECPlatformToNativeC,
651 kTextEncodingMacRoman,
652 kTextEncodingWindowsLatin1);
655 status = TECCreateConverter(&s_TECNativeCToPlatform,
656 kTextEncodingWindowsLatin1,
657 kTextEncodingMacRoman);
661 void wxMacCleanupConverters()
663 OSStatus status = noErr ;
664 status = TECDisposeConverter(s_TECNativeCToUnicode);
666 status = TECDisposeConverter(s_TECUnicodeToNativeC);
668 status = TECDisposeConverter(s_TECPlatformToNativeC);
670 status = TECDisposeConverter(s_TECNativeCToPlatform);
673 wxWCharBuffer wxMacStringToWString( const wxString &from )
676 wxWCharBuffer result( from.wc_str() ) ;
678 OSStatus status = noErr ;
679 ByteCount byteOutLen ;
680 ByteCount byteInLen = from.Length() ;
681 ByteCount byteBufferLen = byteInLen *2 ;
682 wxWCharBuffer result( from.Length() ) ;
683 status = TECConvertText(s_TECNativeCToUnicode, (ConstTextPtr)from.c_str() , byteInLen, &byteInLen,
684 (TextPtr)result.data(), byteBufferLen, &byteOutLen);
685 result.data()[byteOutLen/2] = 0 ;
690 wxString wxMacMakeStringFromCString( const char * from , int len )
692 OSStatus status = noErr ;
694 wxChar* buf = result.GetWriteBuf( len ) ;
696 ByteCount byteOutLen ;
697 ByteCount byteInLen = len ;
698 ByteCount byteBufferLen = len *2 ;
700 status = TECConvertText(s_TECNativeCToUnicode, (ConstTextPtr)from , byteInLen, &byteInLen,
701 (TextPtr)buf, byteBufferLen, &byteOutLen);
703 if ( !wxApp::s_macDefaultEncodingIsPC )
704 memcpy( buf , from , len ) ;
707 ByteCount byteOutLen ;
708 ByteCount byteInLen = len ;
709 ByteCount byteBufferLen = byteInLen ;
711 status = TECConvertText(s_TECPlatformToNativeC, (ConstTextPtr)from , byteInLen, &byteInLen,
712 (TextPtr)buf, byteBufferLen, &byteOutLen);
716 result.UngetWriteBuf() ;
720 wxString wxMacMakeStringFromCString( const char * from )
722 return wxMacMakeStringFromCString( from , strlen(from) ) ;
725 wxCharBuffer wxMacStringToCString( const wxString &from )
728 OSStatus status = noErr ;
729 ByteCount byteOutLen ;
730 ByteCount byteInLen = from.Length() * 2 ;
731 ByteCount byteBufferLen = from.Length() ;
732 wxCharBuffer result( from.Length() ) ;
733 status = TECConvertText(s_TECUnicodeToNativeC , (ConstTextPtr)from.wc_str() , byteInLen, &byteInLen,
734 (TextPtr)result.data(), byteBufferLen, &byteOutLen);
737 if ( !wxApp::s_macDefaultEncodingIsPC )
738 return wxCharBuffer( from.c_str() ) ;
741 wxCharBuffer result( from.Length() ) ;
742 OSStatus status = noErr ;
743 ByteCount byteOutLen ;
744 ByteCount byteInLen = from.Length() ;
745 ByteCount byteBufferLen = byteInLen ;
747 status = TECConvertText(s_TECNativeCToPlatform, (ConstTextPtr)from.c_str() , byteInLen, &byteInLen,
748 (TextPtr)result.data(), byteBufferLen, &byteOutLen);
754 void wxMacStringToPascal( const wxString&from , StringPtr to )
756 wxCharBuffer buf = wxMacStringToCString( from ) ;
757 int len = strlen(buf) ;
762 memcpy( (char*) &to[1] , buf , len ) ;
765 wxString wxMacMakeStringFromPascal( ConstStringPtr from )
767 return wxMacMakeStringFromCString( (char*) &from[1] , from[0] ) ;
771 // CFStringRefs (Carbon only)
775 // converts this string into a carbon foundation string with optional pc 2 mac encoding
776 void wxMacCFStringHolder::Assign( const wxString &str )
779 m_cfs = CFStringCreateWithCharacters( kCFAllocatorDefault,
780 (const unsigned short*)str.wc_str(), str.Len() );
782 m_cfs = CFStringCreateWithCString( kCFAllocatorSystemDefault , str.c_str() ,
783 wxApp::s_macDefaultEncodingIsPC ?
784 kCFStringEncodingWindowsLatin1 : CFStringGetSystemEncoding() ) ;
789 wxString wxMacCFStringHolder::AsString()
792 Size len = CFStringGetLength( m_cfs ) ;
793 wxChar* buf = result.GetWriteBuf( len ) ;
795 CFStringGetCharacters( m_cfs , CFRangeMake( 0 , len ) , (UniChar*) buf ) ;
797 CFStringGetCString( m_cfs , buf , len+1 , wxApp::s_macDefaultEncodingIsPC ?
798 kCFStringEncodingWindowsLatin1 : CFStringGetSystemEncoding() ) ;
801 result.UngetWriteBuf() ;
807 wxString wxMacMakeMacStringFromPC( const wxChar * p )
810 int len = wxStrlen ( p ) ;
813 wxChar* ptr = result.GetWriteBuf(len) ;
814 wxMacConvertFromPC( p , ptr , len ) ;
816 result.UngetWriteBuf( len ) ;
821 wxString wxMacMakePCStringFromMac( const wxChar * p )
824 int len = wxStrlen ( p ) ;
827 wxChar* ptr = result.GetWriteBuf(len) ;
828 wxMacConvertToPC( p , ptr , len ) ;
830 result.UngetWriteBuf( len ) ;
835 wxString wxMacMakeStringFromMacString( const wxChar* from , bool mac2pcEncoding )
839 return wxMacMakePCStringFromMac( from ) ;
843 return wxString( from ) ;
851 wxString wxMacMakeStringFromPascal( ConstStringPtr from , bool mac2pcEncoding )
853 // this is safe since a pascal string can never be larger than 256 bytes
855 CopyPascalStringToC( from , s ) ;
858 return wxMacMakePCStringFromMac( s ) ;
862 return wxString( s ) ;
866 void wxMacStringToPascal( const wxChar * from , StringPtr to , bool pc2macEncoding )
870 CopyCStringToPascal( wxMacMakeMacStringFromPC( from ) , to ) ;
874 CopyCStringToPascal( from , to ) ;
880 #endif //TARGET_CARBON
882 // ----------------------------------------------------------------------------
884 // ----------------------------------------------------------------------------
886 #if defined(__WXMAC__) && !defined(__DARWIN__) && defined(__MWERKS__) && (__MWERKS__ >= 0x2400)
888 // MetroNub stuff doesn't seem to work in CodeWarrior 5.3 Carbon builds...
890 #ifndef __MetroNubUtils__
891 #include "MetroNubUtils.h"
898 #if TARGET_API_MAC_CARBON
900 #include <CodeFragments.h>
902 extern "C" long CallUniversalProc(UniversalProcPtr theProcPtr, ProcInfoType procInfo, ...);
904 ProcPtr gCallUniversalProc_Proc = NULL;
908 static MetroNubUserEntryBlock* gMetroNubEntry = NULL;
910 static long fRunOnce = false;
912 /* ---------------------------------------------------------------------------
914 --------------------------------------------------------------------------- */
916 Boolean IsMetroNubInstalled()
923 gMetroNubEntry = NULL;
925 if (Gestalt(gestaltSystemVersion, &value) == noErr && value < 0x1000)
927 /* look for MetroNub's Gestalt selector */
928 if (Gestalt(kMetroNubUserSignature, &result) == noErr)
931 #if TARGET_API_MAC_CARBON
932 if (gCallUniversalProc_Proc == NULL)
934 CFragConnectionID connectionID;
937 ProcPtr symbolAddress;
939 CFragSymbolClass symbolClass;
941 symbolAddress = NULL;
942 err = GetSharedLibrary("\pInterfaceLib", kPowerPCCFragArch, kFindCFrag,
943 &connectionID, &mainAddress, errorString);
947 gCallUniversalProc_Proc = NULL;
951 err = FindSymbol(connectionID, "\pCallUniversalProc",
952 (Ptr *) &gCallUniversalProc_Proc, &symbolClass);
956 gCallUniversalProc_Proc = NULL;
963 MetroNubUserEntryBlock* block = (MetroNubUserEntryBlock *)result;
965 /* make sure the version of the API is compatible */
966 if (block->apiLowVersion <= kMetroNubUserAPIVersion &&
967 kMetroNubUserAPIVersion <= block->apiHiVersion)
968 gMetroNubEntry = block; /* success! */
977 #if TARGET_API_MAC_CARBON
978 return (gMetroNubEntry != NULL && gCallUniversalProc_Proc != NULL);
980 return (gMetroNubEntry != NULL);
984 /* ---------------------------------------------------------------------------
985 IsMWDebuggerRunning [v1 API]
986 --------------------------------------------------------------------------- */
988 Boolean IsMWDebuggerRunning()
990 if (IsMetroNubInstalled())
991 return CallIsDebuggerRunningProc(gMetroNubEntry->isDebuggerRunning);
996 /* ---------------------------------------------------------------------------
997 AmIBeingMWDebugged [v1 API]
998 --------------------------------------------------------------------------- */
1000 Boolean AmIBeingMWDebugged()
1002 if (IsMetroNubInstalled())
1003 return CallAmIBeingDebuggedProc(gMetroNubEntry->amIBeingDebugged);
1008 extern bool WXDLLEXPORT wxIsDebuggerRunning()
1010 return IsMWDebuggerRunning() && AmIBeingMWDebugged();
1015 extern bool WXDLLEXPORT wxIsDebuggerRunning()
1020 #endif // defined(__WXMAC__) && !defined(__DARWIN__) && (__MWERKS__ >= 0x2400)