Exemple #1
0
void
__create_message (HWND hwnd,
    SQLPOINTER dsn,
    SQLPOINTER text,
    SQLCHAR waMode,
    AlertType id)
{
  CFStringRef msg, msg1;
  DialogRef dlg;
  SInt16 out;
  char buf[1024];

  if (hwnd == NULL)
    return;

  if (waMode == 'A')
    {
      if (dsn)
        {
          STRCPY(buf, "DSN: ");
          STRCAT(buf, dsn);
          msg = CFStringCreateWithBytes (NULL, (unsigned char*)buf, STRLEN(buf),
            kCFStringEncodingUTF8, false);
          msg1 = CFStringCreateWithBytes (NULL, (unsigned char*)text, STRLEN(text), 
            kCFStringEncodingUTF8, false);
        }
      else
        {
          STRCPY(buf, "");
          msg = CFStringCreateWithBytes (NULL, (unsigned char*)text, STRLEN(text),
            kCFStringEncodingUTF8, false);
          msg1 = CFStringCreateWithBytes (NULL, (unsigned char*)buf, STRLEN(buf), 
            kCFStringEncodingUTF8, false);
        }
    }
  else
    {
      if (dsn)
        {
          WCSCPY(buf, L"DSN: ");
          WCSCAT(buf, dsn);
          msg = convert_wchar_to_CFString((wchar_t*)buf);
          msg1 = convert_wchar_to_CFString((wchar_t*)text);
        }
      else
        {
          WCSCPY(buf, L"");
          msg = convert_wchar_to_CFString((wchar_t*)text);
          msg1 = convert_wchar_to_CFString((wchar_t*)buf);
        }
    }

  CreateStandardAlert (id, msg, msg1, NULL, &dlg);
  RunStandardAlert (dlg, NULL, &out);

  CFRelease(msg);
  CFRelease(msg1);

  return;
}
Exemple #2
0
int rktio_strcoll_utf16(rktio_t *rktio,
                        rktio_char16_t *s1, intptr_t l1,
                        rktio_char16_t *s2, intptr_t l2,
                        rktio_bool_t cvt_case)
{
#ifdef MACOS_UNICODE_SUPPORT
  CFStringRef str1, str2;
  CFComparisonResult r;

  str1 = CFStringCreateWithBytes(NULL, (unsigned char *)s1, (l1 * sizeof(rktio_char16_t)), 
				 kCFStringEncodingUnicode, FALSE);
  str2 = CFStringCreateWithBytes(NULL, (unsigned char *)s2, (l2 * sizeof(rktio_char16_t)), 
				 kCFStringEncodingUnicode, FALSE);

  r = CFStringCompare(str1, str2, (kCFCompareLocalized
				   | (cvt_case ? kCFCompareCaseInsensitive : 0)));

  CFRelease(str1);
  CFRelease(str2);

  return (int)r;
#elif defined(RKTIO_SYSTEM_WINDOWS)
  int r;
  r = CompareStringW(LOCALE_USER_DEFAULT,
		     ((cvt_case ? NORM_IGNORECASE : 0)
		      | NORM_IGNOREKANATYPE
		      | NORM_IGNOREWIDTH),
		     (wchar_t *)s1, l1, (wchar_t *)s2, l2);
  
  return r - 2;
#else
  return 0;
#endif
}
void *quartz_new_layout(char* fontname, double fontsize, char* text)
{
	CFStringRef fontnameref = CFStringCreateWithBytes(kCFAllocatorDefault, (const UInt8 *)fontname, strlen(fontname), kCFStringEncodingUTF8, FALSE);
	CFStringRef textref = CFStringCreateWithBytes(kCFAllocatorDefault, (const UInt8 *)text, strlen(text), kCFStringEncodingUTF8, FALSE);
	CTLineRef line = NULL;
	
	if (fontnameref && textref) {
		/* set up the Core Text line */
		CTFontRef font = CTFontCreateWithName(fontnameref, fontsize, NULL);
		
		CFDictionaryRef attributes = CFDictionaryCreate(
			kCFAllocatorDefault,
			(const void**)&kCTFontAttributeName,
			(const void**)&font,
			1,
			&kCFTypeDictionaryKeyCallBacks,
			&kCFTypeDictionaryValueCallBacks);
		CFAttributedStringRef attributed = CFAttributedStringCreate(kCFAllocatorDefault, textref, attributes);
		line = CTLineCreateWithAttributedString(attributed);
		
		CFRelease(attributed);
		CFRelease(attributes);
		CFRelease(font);
	}
	
	if (textref)
		CFRelease(textref);
	if (fontnameref)
		CFRelease(fontnameref);
	return (void *)line;
}
Exemple #4
0
static int do_msgbox(const char *str, AlertType alert_type,
                     AlertStdCFStringAlertParamRec *param,
                     DialogItemIndex *idx, const char *desc)
{
    const char *_title = desc ? desc : "Setup";
    int retval = 0;
    DialogItemIndex val = 0;
    CFStringRef title = CFStringCreateWithBytes(NULL, BAD_CAST _title, strlen(_title),
                                                kCFStringEncodingUTF8, 0);
    CFStringRef msg = CFStringCreateWithBytes(NULL, BAD_CAST str, strlen(str),
                                                kCFStringEncodingUTF8, 0);
    if ((msg != NULL) && (title != NULL))
    {
        DialogRef dlg = NULL;

        if (CreateStandardAlert(alert_type, title, msg, param, &dlg) == noErr)
        {
            RunStandardAlert(dlg, NULL, (idx) ? idx : &val);
            retval = 1;
        } /* if */
    } /* if */

    if (msg != NULL)
        CFRelease(msg);

    if (title != NULL)
        CFRelease(title);

    return(retval);
} /* do_msgbox */
Exemple #5
0
void
create_error_Internal (HWND hwnd,
    SQLPOINTER dsn,
    SQLPOINTER text,
    SQLPOINTER errmsg,
    SQLCHAR waMode)
{
  CFStringRef msg, msg1;
  DialogRef dlg;
  SInt16 out;

  if (hwnd == NULL)
    return;

  if (waMode == 'A')
    {
      msg = CFStringCreateWithBytes (NULL, (unsigned char*)text, STRLEN(text), 
        kCFStringEncodingUTF8, false);
      msg1 = CFStringCreateWithBytes (NULL, (unsigned char*)errmsg, STRLEN(errmsg), 
        kCFStringEncodingUTF8, false);
    }
  else
    {
      msg = convert_wchar_to_CFString((wchar_t*)text);
      msg1 = convert_wchar_to_CFString((wchar_t*)errmsg);
    }

  CreateStandardAlert (kAlertStopAlert, msg, msg1, NULL, &dlg);
  RunStandardAlert (dlg, NULL, &out);

  CFRelease(msg);
  CFRelease(msg1);

  return;
}
Exemple #6
0
static CFStringRef frameTextStr(const ST_ID3v2 *tag, ST_ID3v2_FrameCode code,
                                ST_ID3v2_FrameCode code22, ST_Error *err) {
    const ST_Frame *frame;
    const ST_TextFrame *tframe;
    const ST_CommentFrame *cframe;
    ST_Error tmp, *e = err;

    if(!err)
        e = &tmp;

    if(!tag || tag->base.type != ST_TagType_ID3v2) {
        *e = ST_Error_InvalidArgument;
        return NULL;
    }

    if(tag->majorver == 2) {
        if(!(frame = ST_ID3v2_frameForKey(tag, code22, 0))) {
            *e = ST_Error_NotFound;
            return NULL;
        }
    }
    else {
        if(!(frame = ST_ID3v2_frameForKey(tag, code, 0))) {
            *e = ST_Error_NotFound;
            return NULL;
        }
    }

    if(frame->type == ST_FrameType_Text) {
        tframe = (const ST_TextFrame *)frame;
        *e = ST_Error_None;

        return CFStringCreateWithBytes(kCFAllocatorDefault, tframe->string,
                                       tframe->size, encs[tframe->encoding],
                                       tframe->encoding ==
                                       ST_TextEncoding_UTF16);
    }
    else if(frame->type == ST_FrameType_Comment) {
        cframe = (const ST_CommentFrame *)frame;
        *e = ST_Error_None;

        return CFStringCreateWithBytes(kCFAllocatorDefault, cframe->string,
                                       cframe->string_size,
                                       encs[cframe->encoding],
                                       cframe->encoding ==
                                       ST_TextEncoding_UTF16);
    }
    else {
        *e = ST_Error_InvalidArgument;
        return NULL;
    }
}
Exemple #7
0
void QuartzBitmap_Output(QuartzDesc_t dev, QuartzBitmapDevice *qbd)
{
    if(qbd->path && qbd->uti) {
        /* On 10.4+ we can employ the CGImageDestination API to create a
           variety of different bitmap formats */
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
	char buf[PATH_MAX+1];
	snprintf(buf, PATH_MAX, qbd->path, qbd->page); buf[PATH_MAX] = '\0';
        CFStringRef pathString = CFStringCreateWithBytes(kCFAllocatorDefault, (UInt8*) buf, strlen(buf), kCFStringEncodingUTF8, FALSE);
        CFURLRef path;
        if(CFStringFind(pathString, CFSTR("://"), 0).location != kCFNotFound) {
            CFStringRef pathEscaped = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, pathString, NULL, NULL, kCFStringEncodingUTF8);
            path = CFURLCreateWithString(kCFAllocatorDefault, pathEscaped, NULL);
            CFRelease(pathEscaped);
        } else {
            path = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const UInt8*) buf, strlen(buf), FALSE);
        }
        CFRelease(pathString);

        CFStringRef scheme = CFURLCopyScheme(path);
       	CFStringRef type  = CFStringCreateWithBytes(kCFAllocatorDefault, (UInt8*) qbd->uti, strlen(qbd->uti), kCFStringEncodingUTF8, FALSE);
    	CGImageRef image = CGBitmapContextCreateImage(qbd->bitmap);
        if(CFStringCompare(scheme,CFSTR("file"), 0) == 0) { /* file output */
            CGImageDestinationRef dest = CGImageDestinationCreateWithURL(path, type, 1, NULL);
	    if(dest) {
		CGImageDestinationAddImage(dest, image, NULL);
		CGImageDestinationFinalize(dest);
		CFRelease(dest);
	    } else 
		error(_("QuartzBitmap_Output - unable to open file '%s'"), buf);
        } else if(CFStringCompare(scheme, CFSTR("clipboard"), 0) == 0) { /* clipboard output */
            CFMutableDataRef      data = CFDataCreateMutable(kCFAllocatorDefault, 0);
            CGImageDestinationRef dest = CGImageDestinationCreateWithData(data, type, 1, NULL);
            CGImageDestinationAddImage(dest, image, NULL);
            CGImageDestinationFinalize(dest);
            CFRelease(dest);
            PasteboardRef pb = NULL;
            if(PasteboardCreate(kPasteboardClipboard, &pb) == noErr) {
                PasteboardClear(pb);
                PasteboardSynchronize(pb);
                PasteboardPutItemFlavor(pb, (PasteboardItemID) 1, type, data, 0);
            }
            CFRelease(data);
        } else
            warning(_("not a supported scheme, no image data written"));
        CFRelease(scheme);
       	CFRelease(type);
        CFRelease(path);
        CFRelease(image);
#endif
    }
}
char* formatUnicodeString(long* input, size_t size_of_one_char, int identifier)
{
	if (!input)
		return kNullInputError;
	
	size_t length = 0;
	CFStringEncoding encoding;
	
	if (size_of_one_char == 2)
	{
		short* temp = (short*) input;
		while (*temp++ && (length < max_length)) length++;
		encoding = kCFStringEncodingUTF16LE;
	}
	else
	{
		long* temp = (long*) input;
		while (*temp++ && (length < max_length)) length++;
		encoding = kCFStringEncodingUTF32LE;
	}
	
	CFStringRef string = CFStringCreateWithBytes(NULL, (UInt8*) input, length * size_of_one_char, encoding, false);
	char* result = ConvertStringToEncoding(string, kCFStringEncodingUTF8, identifier);
	CFRelease(string);

	return result;
}
int convertChars(char *from, int fromLen, void *fromCode, char *to, int toLen, void *toCode, int norm, int term)
{
  CFStringRef	     cfs= CFStringCreateWithBytes(NULL, (UInt8 *) from, fromLen, (CFStringEncoding)fromCode, 0);
  if (cfs == NULL) {
      toLen = 0;
	  to[toLen]= '\0';
	  return toLen;
	}
	
  CFMutableStringRef str= CFStringCreateMutableCopy(NULL, 0, cfs);
  CFRelease(cfs);
  if (norm) // HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
    CFStringNormalize(str, kCFStringNormalizationFormD); // canonical decomposition
  else
    CFStringNormalize(str, kCFStringNormalizationFormC); // pre-combined
  {
    CFRange rng= CFRangeMake(0, CFStringGetLength(str));
    CFIndex len= 0;
    CFIndex num= CFStringGetBytes(str, rng, (CFStringEncoding)toCode, '?', 0, (UInt8 *)to, toLen - term, &len);
    CFRelease(str);
    if (!num)
      return convertCopy(from, fromLen, to, toLen, term);
    if (term)
      to[len]= '\0';
    return len;
  }
}
Exemple #10
0
OSErr makeFSSpec(char *pathString, int pathStringLength,FSSpec *spec)
{	
    CFURLRef    sillyThing;
    CFStringRef tmpStrRef;
	CFMutableStringRef filePath;
    FSRef	theFSRef;
    OSErr	err;
    
    tmpStrRef = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *) pathString,
										pathStringLength, gCurrentVMEncoding, true);
    if (tmpStrRef == nil)
        return -1000;
	filePath = CFStringCreateMutableCopy(NULL, 0, tmpStrRef);
	if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
		CFStringNormalize(filePath, kCFStringNormalizationFormD);
    sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,filePath,kCFURLHFSPathStyle,false);
	if (sillyThing == NULL) 
		return -2000;
		
    if (CFURLGetFSRef(sillyThing,&theFSRef) == false) {
        // name contains multiple aliases or does not exist, so fallback to lookupPath
        CFRelease(filePath);
        CFRelease(sillyThing);
        return lookupPath(pathString,pathStringLength,spec,true,true);
    } 
            
    CFRelease(filePath);
    err = FSGetCatalogInfo (&theFSRef,kFSCatInfoNone,nil,nil,spec,nil);
    CFRelease(sillyThing);
    return err;
}
Exemple #11
0
// wchar_t to wchar_t conversion
void CharConvWW(charconv* Conv, wchar_t* Out, size_t OutLen, const wchar_t* In)
{
	if (OutLen>0)
	{
        // assume wchar_t is 16 bits even if it's not true
        charconv_osx *CC = (charconv_osx *)Conv;
        if (CC)
        {
            CFStringRef TmpIn = CFStringCreateWithBytes(NULL, (const UInt8*)In, (utf16len((const uint16_t*)In)+1)*sizeof(uint16_t), CC->EncFrom, false);
            assert(TmpIn);
            CFIndex Read;
            CFRange		r;
            r.location = 0;
            r.length = CFStringGetLength(TmpIn);
            CFStringGetBytes(TmpIn, r, CC->EncTo,
                    LOSSY_CHAR, /* no lossy conversion */
                    0, /* not external representation */
                    (UInt8*)Out, OutLen, &Read);
            CFRelease(TmpIn);
            memset((UInt8*)Out+Read,0,sizeof(uint16_t));
        }
        else
        {
            fprintf(stderr, "Not supported yet: %s with no CC\n", __FUNCTION__);
        }
    }
}
Exemple #12
0
static PyObject *AE_ConvertPathToURL(PyObject* self, PyObject* args)
{
	char *cStr;
	CFURLPathStyle style;
	CFStringRef str;
	CFURLRef url;
	CFIndex len;
	char buffer[PATH_MAX];
	
	if (!PyArg_ParseTuple(args, "esl", "utf8", &cStr, &style))
		return NULL;
	str = CFStringCreateWithBytes(NULL,
								  (UInt8 *)cStr,
								  (CFIndex)strlen(cStr),
								  kCFStringEncodingUTF8,
								  false);
	if (!str) return AE_MacOSError(1000);
	url = CFURLCreateWithFileSystemPath(NULL,
										str,
										(CFURLPathStyle)style,
										false);
	PyMem_Free(cStr);
	if (!url) return AE_MacOSError(1001);
	len = CFURLGetBytes(url, (UInt8 *)buffer, PATH_MAX);
	CFRelease(url);
	return PyUnicode_DecodeUTF8(buffer, len, NULL);
}
inline SQLite3StatementRef SQLite3StatementCreateWithBundleResource(SQLite3ConnectionRef connection, CFBundleRef bundle, CFStringRef type, CFStringRef name, CFStringRef subdir) {
  SQLite3StatementRef statement = NULL;
  if (connection) {
    SInt32 errorCode = 0;
    CFDictionaryRef properties = NULL;
    CFDataRef data = NULL;
    CFURLRef url = CFBundleCopyResourceURL(bundle, name, type, subdir);
    if (url) {
      if (CFURLCreateDataAndPropertiesFromResource(connection->allocator, url, &data, &properties, NULL, &errorCode)) {
        CFStringRef sql = CFStringCreateWithBytes(connection->allocator, CFDataGetBytePtr(data), CFDataGetLength(data), kCFStringEncodingUTF8, 0);
        if (sql) {
          statement = SQLite3StatementCreate(connection, sql);
          CFRelease(sql);
        }
        CFRelease(data);
        if (properties)
          CFRelease(properties);
      } else {
        // TODO: Error
      }
      CFRelease(url);
    }
  }
  return statement;
}
Exemple #14
0
// Function to convert and copy string literals to the format expected by the exporter API.
// On Win: Pass the input directly to the output
// On Mac: All conversion happens through the CFString format
void copyConvertStringLiteralIntoUTF16(const wchar_t* inputString, prUTF16Char* destination)
{
#ifdef PRMAC_ENV
    int length = wcslen(inputString);
    CFRange	range = {0, kPrMaxPath};
    range.length = length;
    CFStringRef inputStringCFSR = CFStringCreateWithBytes(	kCFAllocatorDefault,
                                  reinterpret_cast<const UInt8 *>(inputString),
                                  length * sizeof(wchar_t),
                                  kCFStringEncodingUTF32LE,
                                  kPrFalse);
    CFStringGetBytes(	inputStringCFSR,
                        range,
                        kCFStringEncodingUTF16,
                        0,
                        kPrFalse,
                        reinterpret_cast<UInt8 *>(destination),
                        length * (sizeof (prUTF16Char)),
                        NULL);
    destination[length] = 0; // Set NULL-terminator, since CFString calls don't set it, and MediaCore hosts expect it
    CFRelease(inputStringCFSR);
#elif defined PRWIN_ENV
    size_t length = wcslen(inputString);
    wcscpy_s(destination, length + 1, inputString);
#endif
}
OSStatus WBKeychainFindGenericPassword(CFTypeRef keychain, CFStringRef service, CFStringRef account, CFStringRef *password, SecKeychainItemRef *itemRef) {
  OSStatus status;
  if (password) *password = NULL;
  char *serviceStr = (char *)__WBCFStringCopyUTF8Characters(service);
  char *accountStr = (char *)__WBCFStringCopyUTF8Characters(account);
  require_action_string(serviceStr != NULL && accountStr != NULL, bail, status = paramErr, "Unable to get service or account characters");

  UInt32 length;
  UTF8Char *passwordStr;
  status = SecKeychainFindGenericPassword(keychain,
                                          (UInt32)strlen(serviceStr), serviceStr,
                                          (UInt32)strlen(accountStr), accountStr,
                                          password ? &length : NULL,
                                          password ? (void **)&passwordStr : NULL,
                                          itemRef);
  if ((noErr == status) && password) {
    *password = CFStringCreateWithBytes(kCFAllocatorDefault, passwordStr, length, kCFStringEncodingUTF8, FALSE);
    SecKeychainItemFreeContent(NULL, passwordStr);
  }

bail:
    if (serviceStr) free(serviceStr);
  if (accountStr) free(accountStr);
  return status;
}
/*
 * Given a CFTypeRef passphrase which may be a CFDataRef or a CFStringRef,
 * return a refcounted CFStringRef suitable for use with the PKCS12 library.
 * PKCS12 passphrases in CFData format must be UTF8 encoded.
 */
OSStatus impExpPassphraseToCFString(
	CFTypeRef   passin,
	CFStringRef *passout)	// may be the same as passin, but refcounted
{
	if(CFGetTypeID(passin) == CFStringGetTypeID()) {
		CFStringRef passInStr = (CFStringRef)passin;
		CFRetain(passInStr);
		*passout = passInStr;
		return errSecSuccess;
	}
	else if(CFGetTypeID(passin) == CFDataGetTypeID()) {
		CFDataRef cfData = (CFDataRef)passin;
		CFIndex len = CFDataGetLength(cfData);
		CFStringRef cfStr = CFStringCreateWithBytes(NULL,
			CFDataGetBytePtr(cfData), len, kCFStringEncodingUTF8, true);
		if(cfStr == NULL) {
			SecImpExpDbg("Passphrase not in UTF8 format");
			return errSecParam;
		}
		*passout = cfStr;
		return errSecSuccess;
	}
	else {
		SecImpExpDbg("Passphrase not CFData or CFString");
		return errSecParam;
	}
}
Exemple #17
0
OSErr getURLFromUTextDesc(const AEDesc *utdesc_p, CFURLRef *urlRef_p)
{
	OSErr err;
	Size theLength = AEGetDescDataSize(utdesc_p);
	
	UInt8 *theData = malloc(theLength);
	err = AEGetDescData(utdesc_p, theData, theLength);
	if (err != noErr) goto bail;
	
	CFStringRef pathStr = CFStringCreateWithBytes(NULL, theData, theLength, kCFStringEncodingUnicode, false);
	
	CFURLPathStyle pathStyle;
	if (CFStringHasPrefix(pathStr, CFSTR("/"))) {
		pathStyle = kCFURLPOSIXPathStyle;
	}
	else {
		pathStyle = kCFURLHFSPathStyle;
	}	
	*urlRef_p = CFURLCreateWithFileSystemPath(NULL, pathStr, pathStyle, true);
	CFRelease(pathStr);
	
bail:
	free(theData);
	return err;
}
Exemple #18
0
bool LaunchBrowser(const char* url)
{
#ifdef WIN32
  int r =  (int)ShellExecuteA(0, "open", url, "", "", 1);
  return (r > 32);

#else 

#ifdef MACOSX

  CFStringRef strurl =                //CFSTR("http://www.amju.com"); // TODO HACK 
    CFStringCreateWithBytes(
    0, 
    (const unsigned char*)url, 
    strlen(url),
    kCFStringEncodingMacRoman,
    false);

  CFURLRef cfurl = CFURLCreateWithString(0, strurl, 0);
  OSStatus ret = LSOpenCFURLRef(cfurl, 0);

std::cout << "Launch URL: " << CFStringGetCStringPtr(strurl, kCFStringEncodingMacRoman) << "\n";
std::cout << "Launch result: " << ret << "\n";

  // TODO deal with ret
  return true;

#else
  // Not implemented for this platform
  return false;
#endif
#endif

}
Exemple #19
0
static int AE_GetCFStringRef(PyObject *v, CFStringRef *p_itself)
{
	if (v == Py_None) { *p_itself = NULL; return 1; }
	if (PyBytes_Check(v)) {
	    char *cStr;
	    if (!PyArg_Parse(v, "es", "ascii", &cStr))
	    	return 0;
		*p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, kCFStringEncodingASCII);
		PyMem_Free(cStr);
		return 1;
	}
	if (PyUnicode_Check(v)) {
#ifdef Py_UNICODE_WIDE
	CFIndex size = PyUnicode_GET_DATA_SIZE(v);
	UTF32Char *unichars = PyUnicode_AsUnicode(v);
	*p_itself = CFStringCreateWithBytes((CFAllocatorRef)NULL,
										unichars,
										size,
										kCFStringEncodingUTF32, // 10.4+
										false); // ?
#else
		CFIndex size = PyUnicode_GetSize(v);
		UniChar *unichars = PyUnicode_AsUnicode(v);
		if (!unichars) return 0;
		*p_itself = CFStringCreateWithCharacters((CFAllocatorRef)NULL, unichars, size);
#endif
		return 1;
	}
	PyErr_SetString(PyExc_TypeError, "str/unicode required");
	return 0;
}
void ARRAY_TEXT::convertFromUTF8(const CUTF8String* fromString, CUTF16String* toString)	
{
#ifdef _WIN32
	int len = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)fromString->c_str(), fromString->length(), NULL, 0);
	
	if(len){
		std::vector<uint8_t> buf((len + 1) * sizeof(PA_Unichar));
		if(MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)fromString->c_str(), fromString->length(), (LPWSTR)&buf[0], len)){
			*toString = CUTF16String((const PA_Unichar *)&buf[0]);
		}
    }else{
			*toString = CUTF16String((const PA_Unichar *)L"");
	}
           
#else
           CFStringRef str = CFStringCreateWithBytes(kCFAllocatorDefault, fromString->c_str(), fromString->length(), kCFStringEncodingUTF8, true);
           if(str){
               int len = CFStringGetLength(str)+1;
               std::vector<uint8_t> buf(len * sizeof(PA_Unichar));
               CFStringGetCharacters(str, CFRangeMake(0, len), (UniChar *)&buf[0]);
               *toString = CUTF16String((const PA_Unichar *)&buf[0]);
               CFRelease(str);
           }
#endif	
}
Exemple #21
0
// utf16_t to char conversion
void CharConvSU(charconv* Conv, char* Out, size_t OutLen, const utf16_t* In)
{
	if (OutLen>0)
	{
        // assume wchar_t is 16 bits even if it's not true
        CFStringEncoding EncFrom,EncTo;
        if (Conv)
        {
            EncFrom = ((charconv_osx *)Conv)->EncFrom;
            EncTo = ((charconv_osx *)Conv)->EncTo;
        }
        else
        {
            EncFrom = kCFStringEncodingUTF16;
            EncTo = kCFStringEncodingUTF8;
        }

        CFStringRef TmpIn = CFStringCreateWithBytes(NULL, (const UInt8*)In, (utf16len(In)+1)*sizeof(utf16_t), EncFrom, false);
        CFIndex Read;
        CFRange		r;
        r.location = 0;
        r.length = CFStringGetLength(TmpIn);
        CFStringGetBytes(TmpIn, r, EncTo,
                LOSSY_CHAR, /* no lossy conversion */
                0, /* not external representation */
                (UInt8*)Out, OutLen, &Read);
        CFRelease(TmpIn);
        Out[Read]=0;
	}
}
Exemple #22
0
RetainPtr<CFStringRef> StringImpl::createCFString()
{
    // Since garbage collection isn't compatible with custom allocators, we
    // can't use the NoCopy variants of CFStringCreate*() when GC is enabled.
    if (!m_length || !isMainThread() || garbageCollectionEnabled()) {
        if (is8Bit())
            return adoptCF(CFStringCreateWithBytes(0, reinterpret_cast<const UInt8*>(characters8()), m_length, kCFStringEncodingISOLatin1, false));
        return adoptCF(CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar*>(characters16()), m_length));
    }
    CFAllocatorRef allocator = StringWrapperCFAllocator::allocator();

    // Put pointer to the StringImpl in a global so the allocator can store it with the CFString.
    ASSERT(!StringWrapperCFAllocator::currentString);
    StringWrapperCFAllocator::currentString = this;

    CFStringRef string;
    if (is8Bit())
        string = CFStringCreateWithBytesNoCopy(allocator, reinterpret_cast<const UInt8*>(characters8()), m_length, kCFStringEncodingISOLatin1, false, kCFAllocatorNull);
    else
        string = CFStringCreateWithCharactersNoCopy(allocator, reinterpret_cast<const UniChar*>(characters16()), m_length, kCFAllocatorNull);
    // CoreFoundation might not have to allocate anything, we clear currentString in case we did not execute allocate().
    StringWrapperCFAllocator::currentString = 0;

    return adoptCF(string);
}
Exemple #23
0
wxCFStringRef::wxCFStringRef( const wxString &st , wxFontEncoding WXUNUSED_IN_UNICODE(encoding) )
{
    if (st.IsEmpty())
    {
        reset( wxCFRetain( CFSTR("") ) );
    }
    else
    {
        wxString str = st ;
        wxMacConvertNewlines13To10( &str ) ;
#if wxUSE_UNICODE
#if wxUSE_UNICODE_WCHAR
        // native = wchar_t 4 bytes for us
        const wchar_t * const data = str.wc_str();
        const size_t size = str.length()*sizeof(wchar_t);
        CFStringBuiltInEncodings cfencoding = kCFStringEncodingUTF32Native;
#elif wxUSE_UNICODE_UTF8
        // native = utf8
        const char * const data = str.utf8_str();
        const size_t size = str.utf8_length();
        CFStringBuiltInEncodings cfencoding = kCFStringEncodingUTF8;
#else
    #error "unsupported Unicode representation"
#endif

        reset( CFStringCreateWithBytes( kCFAllocatorDefault,
            (const UInt8*)data, size, cfencoding, false /* no BOM */ ) );
#else // not wxUSE_UNICODE
        reset( CFStringCreateWithCString( kCFAllocatorSystemDefault , str.c_str() ,
            wxMacGetSystemEncFromFontEnc( encoding ) ) );
#endif
    }
}
static CFStringRef CreateStringFromData(CFDataRef data)
	// Some IOKit strings are encoded in CFDataRefs; extract as a CFStringRef.
	// Also remove any trailing null characters, which can lurk in the 
	// I/O Registry strings.
{
    CFIndex len;

	assert(data != NULL);
	
	// Decrement len until to eliminate any trailing null characters.
	    
    len = CFDataGetLength(data);
    do {
        char ch;
        
        if (len < 1) {
            break;
        }
        CFDataGetBytes(data, CFRangeMake(len - 1, 1), (UInt8 *) &ch);
        if (ch != 0) {
            break;
        }
        len -= 1;
    } while (true);
    
    return CFStringCreateWithBytes(NULL, 
                            CFDataGetBytePtr(data), len, kCFStringEncodingMacRoman, false );
}
Exemple #25
0
static CFStringRef rb_copy_item_class(SecKeychainItemRef item){
  SecItemClass secItemClass;
  SecKeychainItemCopyContent(item, &secItemClass, NULL, NULL, NULL);
  secItemClass = CFSwapInt32HostToBig(secItemClass);
  CFStringRef cfclass = CFStringCreateWithBytes(NULL, (UInt8*)&secItemClass, sizeof(secItemClass), kCFStringEncodingUTF8, false);
  return cfclass;
}
FString FMacErrorReport::FindCrashedAppPath() const
{
	TArray<uint8> Data;
	if(FFileHelper::LoadFileToArray(Data, *(ReportDirectory / TEXT("Report.wer"))))
	{
		CFStringRef CFString = CFStringCreateWithBytes(NULL, Data.GetData(), Data.Num(), kCFStringEncodingUTF16LE, true);
		FString FileData((NSString*)CFString);
		CFRelease(CFString);
		
		static const TCHAR AppPathLineStart[] = TEXT("AppPath=");
		static const int AppPathIdLength = ARRAY_COUNT(AppPathLineStart) - 1;
		int32 AppPathStart = FileData.Find(AppPathLineStart);
		if(AppPathStart >= 0)
		{
			FString PathData = FileData.Mid(AppPathStart + AppPathIdLength);
			int32 LineEnd = -1;
			if(PathData.FindChar( TCHAR('\r'), LineEnd ))
			{
				PathData = PathData.Left(LineEnd);
			}
			if(PathData.FindChar( TCHAR('\n'), LineEnd ))
			{
				PathData = PathData.Left(LineEnd);
			}
			return PathData;
		}
	}
	else
	{
		UE_LOG(LogStreaming, Error,	TEXT("Failed to read file '%s' error."),*(ReportDirectory / TEXT("Report.wer")));
	}
	return "";
}
Exemple #27
0
int makeHFSFromPosixPath(char *pathString, int pathStringLength,char *dst,char *lastpart) {
		CFStringRef filePath;
        CFURLRef 	sillyThing;
        CFStringRef	filePath2,lastPathPart;
		
        dst[0] = 0x00;
		if (lastpart)
			lastpart[0] = 0x00;
		filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,
                    (UInt8 *)pathString,pathStringLength,gCurrentVMEncoding,false);
        if (filePath == nil)
            return -1;
			
		// HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
		CFMutableStringRef str= CFStringCreateMutableCopy(NULL, 0, filePath);
		if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
			CFStringNormalize(str, kCFStringNormalizationFormKC); // canonical decomposition

		sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault, str, kCFURLPOSIXPathStyle,false);
		CFRelease(str);
		if (sillyThing == NULL) 
			return -2;
		
		filePath2 = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle);
		CFStringGetCString (filePath2,dst,1000, gCurrentVMEncoding);
		if (lastpart) {
			lastPathPart = CFURLCopyLastPathComponent(sillyThing);
			CFStringGetCString(lastPathPart,lastpart,256, gCurrentVMEncoding);
			CFRelease(lastPathPart);
		}
        CFRelease(filePath);
        CFRelease(sillyThing);
        CFRelease(filePath2);
        return 0;
}
Exemple #28
0
ST_FUNC CFStringRef ST_APE_copyItemForKey(const ST_APE *tag, const char *key,
                                          ST_Error *err) {
    const void **value;
    int count;
    ST_APE_item *val;

    if(!tag || tag->base.type != ST_TagType_APE) {
        if(err)
            *err = ST_Error_InvalidArgument;

        return NULL;
    }

    if((value = ST_Dict_find(tag->tags, key, &count))) {
        if(count) {
            val = (ST_APE_item *)value[0];
            if(err)
                *err = ST_Error_None;

            return CFStringCreateWithBytes(kCFAllocatorDefault, val->data,
                                           val->length, kCFStringEncodingUTF8,
                                           false);
        }
    }

    if(err)
        *err = ST_Error_NotFound;

    return NULL;
}
/*
 *  Retrieve a string for a specified string index from the USB device
 *
 *  device      - USB device pointer
 *  stringIndex - String index to retrieve
 *  output      - Output buffer
 *  len         - Output buffer len
 *
 *  returns true or false on error
 */
bool retrieveString(IOUSBDeviceInterface300** device, const unsigned char stringIndex, char* output, const int len)
{
    IOUSBDevRequest request;
    CFStringRef string;
    const UInt8 buf[512];
    
    // Perform a device request to read the string descriptor.
    request.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
    request.bRequest = kUSBRqGetDescriptor;
    request.wValue = (kUSBStringDesc << 8) | stringIndex;
    request.wIndex = 0; // Language (Optionally 0x409 for US English)
    request.wLength = sizeof(buf);
    request.pData = (void *)buf;
    
    bzero((void *)buf, sizeof(buf));
    
    if ((*device)->DeviceRequest(device, &request) == kIOReturnSuccess)
    {
        int length;
        length = buf[0] - 2; // First byte is length (in bytes)
        
        // Convert from UTF-16 Little Endian
        string = CFStringCreateWithBytes(kCFAllocatorDefault,
                                         &buf[2],
                                         length,
                                         kCFStringEncodingUTF16LE,
                                         false);
        
        // To C String
        CFStringGetCString(string, output, len, kCFStringEncodingUTF8);
        CFRelease(string);
    }
    
    return false;
}
Exemple #30
0
// LOOK OUT! Appending to key array, not the value array
inline int __JSONParserAppendMapKeyWithBytes(void *context, const unsigned char *value, size_t length) {
  __JSONRef json = (__JSONRef)context;
  CFTypeRef __json_element = CFStringCreateWithBytes(json->allocator, value, length, kCFStringEncodingUTF8, 0);
  int __json_return = __JSONStackAppendKeyAtTop(json->stack, __JSONElementsAppend(json, __json_element));
  CFRelease(__json_element);
  return __json_return;
}