Пример #1
0
static CFDataRef
CFDataCreate_internal (CFAllocatorRef allocator, const UInt8 *bytes,
  CFIndex length, CFAllocatorRef bytesDealloc, Boolean copy)
{
  struct __CFData *newData;
  CFIndex size;
  
  size = CFDATA_SIZE + (copy == true ? length : 0);
  
  if (allocator == NULL)
    allocator = CFAllocatorGetDefault ();
  
  newData = (struct __CFData*)_CFRuntimeCreateInstance (allocator,
    _kCFDataTypeID, size, NULL);
  if (newData)
    {
      newData->_length = length;
      
      if (copy)
        {
          memcpy (&(newData[1]), bytes, length);
          bytes = (const UInt8*)&(newData[1]);
        }
      else
        {
          if (bytesDealloc == NULL)
            bytesDealloc = CFAllocatorGetDefault ();
          newData->_deallocator = CFRetain(bytesDealloc);
          CFDataSetFreeBytes (newData);
        }
      newData->_contents = bytes;
    }
  
  return (CFDataRef)newData;
}
CFComparisonResult
CFStringCompareWithOptionsAndLocale (CFStringRef str1,
  CFStringRef str2, CFRange rangeToCompare,
  CFStringCompareFlags compareOptions, CFLocaleRef locale)
{
  CFComparisonResult ret;
  UniChar *string1;
  UniChar *string2;
  CFIndex length1;
  CFIndex length2;
  CFAllocatorRef alloc;
  UCollator *ucol;
  
  alloc = CFAllocatorGetDefault ();
  
  length1 = rangeToCompare.length;
  string1 = CFAllocatorAllocate (alloc, (length1) * sizeof(UniChar), 0);
  CFStringGetCharacters (str1, rangeToCompare, string1);
  
  length2 = CFStringGetLength (str2);
  string2 = CFAllocatorAllocate (alloc, (length2) * sizeof(UniChar), 0);
  CFStringGetCharacters (str2, CFRangeMake(0, length2), string2);
  
  ucol = CFStringICUCollatorOpen (compareOptions, locale);
  ret = ucol_strcoll (ucol, string2, length2, string1, length1);
  CFStringICUCollatorClose (ucol);
  
  CFAllocatorDeallocate (alloc, string1);
  CFAllocatorDeallocate (alloc, string2);
  return ret;
}
Пример #3
0
static void *writeDataCreate(struct _CFStream *stream, void *info) {
    _CFWriteDataStreamContext *ctxt = (_CFWriteDataStreamContext *)info;
    _CFWriteDataStreamContext *newCtxt;
    if (ctxt->bufferAllocator != kCFAllocatorNull) {
        if (ctxt->bufferAllocator == NULL) ctxt->bufferAllocator = CFAllocatorGetDefault();
        CFRetain(ctxt->bufferAllocator);
        newCtxt = (_CFWriteDataStreamContext *)CFAllocatorAllocate(CFGetAllocator(stream), sizeof(_CFWriteDataStreamContext) + sizeof(_CFStreamByteBuffer) + BUF_SIZE, 0);
        newCtxt->firstBuf = (_CFStreamByteBuffer *)(newCtxt + 1);
        newCtxt->firstBuf->bytes = (UInt8 *)(newCtxt->firstBuf + 1);
        newCtxt->firstBuf->capacity = BUF_SIZE;
        newCtxt->firstBuf->length = 0;
        newCtxt->firstBuf->next = NULL;
        newCtxt->currentBuf = newCtxt->firstBuf;
        newCtxt->bufferAllocator = ctxt->bufferAllocator;
        newCtxt->scheduled = FALSE;
    } else {
        newCtxt = (_CFWriteDataStreamContext *)CFAllocatorAllocate(CFGetAllocator(stream), sizeof(_CFWriteDataStreamContext) + sizeof(_CFStreamByteBuffer), 0);
        newCtxt->firstBuf = (_CFStreamByteBuffer *)(newCtxt+1);
        newCtxt->firstBuf->bytes = ctxt->firstBuf->bytes;
        newCtxt->firstBuf->capacity = ctxt->firstBuf->capacity;
        newCtxt->firstBuf->length = 0;
        newCtxt->firstBuf->next = NULL;
        newCtxt->currentBuf = newCtxt->firstBuf;
        newCtxt->bufferAllocator = kCFAllocatorNull;
        newCtxt->scheduled = FALSE;
    }
    return (void *)newCtxt;
}
Пример #4
0
/* Returns a shared empty dictionary (unless the allocator is not 
 *  kCFAllocatorSystemDefault, in which case returns a newly allocated one).
 */
static CFDictionaryRef _CFErrorCreateEmptyDictionary(CFAllocatorRef allocator) {
    if (allocator == NULL) {
        allocator = CFAllocatorGetDefault();
    }
    if (allocator == kCFAllocatorSystemDefault) {
        static CFDictionaryRef emptyErrorDictionary = NULL;
        if (emptyErrorDictionary == NULL) {
            CFDictionaryRef tmp = CFDictionaryCreate(
				allocator,
				NULL, NULL, 0,
				&kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
            CFSpinLock(&_CFErrorSpinlock);
            if (emptyErrorDictionary == NULL) {
                emptyErrorDictionary = tmp;
                CFSpinUnlock(&_CFErrorSpinlock);
            } else {
                CFSpinUnlock(&_CFErrorSpinlock);
                CFRelease(tmp);
            }
        }
        return (CFDictionaryRef)CFRetain(emptyErrorDictionary);
    } else {
        return CFDictionaryCreate(
			allocator,
			NULL, NULL, 0,
			&kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    }
}
Пример #5
0
CFMutableDataRef
CFDataCreateMutable (CFAllocatorRef allocator, CFIndex capacity)
{
  struct __CFMutableData *newData;
  
  if (allocator == NULL)
    allocator = CFAllocatorGetDefault ();
  
  newData = (struct __CFMutableData*)_CFRuntimeCreateInstance (allocator,
    _kCFDataTypeID, CFMUTABLEDATA_SIZE, NULL);
  
  if (newData)
    {
      if (capacity < DEFAULT_CAPACITY)
        capacity = DEFAULT_CAPACITY;
      newData->_capacity = capacity;
      newData->_allocator = CFRetain(allocator);
      newData->_contents = CFAllocatorAllocate (allocator, capacity, 0);
      
      CFDataSetMutable ((CFDataRef)newData);
      CFDataSetFreeBytes((CFDataRef)newData);
    }
  
  return (CFMutableDataRef)newData;
}
Пример #6
0
int initMIDI(int numIn, int numOut)
{
	midiCleanUp();
	numIn = sc_clip(numIn, 1, kMaxMidiPorts);
	numOut = sc_clip(numOut, 1, kMaxMidiPorts);

	int enc = kCFStringEncodingMacRoman;
	CFAllocatorRef alloc = CFAllocatorGetDefault();

	CFStringRef clientName = CFStringCreateWithCString(alloc, "SuperCollider", enc);

	OSStatus err = MIDIClientCreate(clientName, midiNotifyProc, nil, &gMIDIClient);
	if (err) {
		post("Could not create MIDI client. error %d\n", err);
		return errFailed;
	}
	CFRelease(clientName);

	for (int i=0; i<numIn; ++i) {
		char str[32];
		sprintf(str, "in%d\n", i);
		CFStringRef inputPortName = CFStringCreateWithCString(alloc, str, enc);

		err = MIDIInputPortCreate(gMIDIClient, inputPortName, midiReadProc, &i, gMIDIInPort+i);
		if (err) {
			gNumMIDIInPorts = i;
			post("Could not create MIDI port %s. error %d\n", str, err);
			return errFailed;
		}
		CFRelease(inputPortName);
	}

	/*int n = MIDIGetNumberOfSources();
	printf("%d sources\n", n);
	for (i = 0; i < n; ++i) {
		MIDIEndpointRef src = MIDIGetSource(i);
		MIDIPortConnectSource(inPort, src, NULL);
	}*/

	gNumMIDIInPorts = numIn;

	for (int i=0; i<numOut; ++i) {
		char str[32];
		sprintf(str, "out%d\n", i);
		CFStringRef outputPortName = CFStringCreateWithCString(alloc, str, enc);

		err = MIDIOutputPortCreate(gMIDIClient, outputPortName, gMIDIOutPort+i);
		if (err) {
			gNumMIDIOutPorts = i;
			post("Could not create MIDI out port. error %d\n", err);
			return errFailed;
		}

		CFRelease(outputPortName);
	}
	gNumMIDIOutPorts = numOut;
	return errNone;
}
Пример #7
0
CF_EXPORT CFAllocatorRef
rwsched_instance_CFAllocatorGetDefault(rwsched_instance_ptr_t instance)
{
    // Validate input parameters
    RW_CF_TYPE_VALIDATE(instance, rwsched_instance_ptr_t);

    // Call the native CFRunLoopStop function
    return CFAllocatorGetDefault();
}
Пример #8
0
void simpleStringExample(void) {

    CFStringRef str;
    CFDataRef data;
    char *bytes;

    show(CFSTR("------------------Simple Strings---------------"));

    // Create a simple immutable string from a Pascal string and convert it to Unicode
#if defined(__APPLE__)
    str = CFStringCreateWithPascalString(NULL, "\pFoo Bar", kCFStringEncodingASCII);
#else
    str = CFStringCreateWithCString(NULL, "Hello World", kCFStringEncodingASCII);
#endif

    // Create the Unicode representation of the string
    // "0", lossByte, indicates that if there's a conversion error, fail (and return NULL)
    data = CFStringCreateExternalRepresentation(NULL, str, kCFStringEncodingUnicode, 0);

    show(CFSTR("String          : %@"), str);
    show(CFSTR("Unicode data    : %@"), data);

    CFRelease(str);
 
    // Create a string from the Unicode data...
    str = CFStringCreateFromExternalRepresentation(NULL, data, kCFStringEncodingUnicode);

    show(CFSTR("String Out      : %@"), str);

    CFRelease(str);

    // Create a string for which you already have some allocated contents which you want to 
    // pass ownership of to the CFString. The last argument, "NULL," indicates that the default allocator
    // should be used to free the contents when the CFString is freed (or you can pass in CFAllocatorGetDefault()).

    bytes = (char*)CFAllocatorAllocate(CFAllocatorGetDefault(), 6, 0);
    strcpy(bytes, "Hello");

    str = CFStringCreateWithCStringNoCopy(NULL, bytes, kCFStringEncodingASCII, NULL);
    CFRelease(str);

#if defined(__APPLE__)
    // Now create a string with a Pascal string which is not copied, and not freed when the string is
    // This is an advanced usage; obviously you need to guarantee that the string bytes do not go away
    // before the CFString does. 
    str = CFStringCreateWithPascalStringNoCopy(NULL, "\pFoo Bar", kCFStringEncodingASCII, kCFAllocatorNull);
    CFRelease(str);
#endif
}
Пример #9
0
void stringWithExternalContentsExample(void) {
#define BufferSize 1000
    CFMutableStringRef mutStr;
    UniChar *myBuffer;

    show(CFSTR("------------------External Contents Examples---------------"));

    // Allocate a contents store that is empty (but has space for BufferSize chars)...
    myBuffer = (UniChar*)malloc(BufferSize * sizeof(UniChar));

    // Now create a mutable CFString which uses this buffer
    // The 0 and BufferSize indicate the length and capacity (in UniChars)
    // The kCFAllocatorNull indicates how the CFString should reallocate or free this buffer (in this case, do nothing)

    mutStr = CFStringCreateMutableWithExternalCharactersNoCopy(NULL, myBuffer, 0, BufferSize, kCFAllocatorNull);
    CFStringAppend(mutStr, CFSTR("Appended string... "));
    CFStringAppend(mutStr, CFSTR("More stuff... "));
#if defined(__APPLE__)
    CFStringAppendPascalString(mutStr, "\pA pascal string. ", kCFStringEncodingASCII);
#else
    CFStringAppendCString(mutStr, "A C string. ", kCFStringEncodingASCII);
#endif
    CFStringAppendFormat(mutStr, NULL, CFSTR("%d %4.2f %@..."), 42, -3.14, CFSTR("Hello"));
    
    show(CFSTR("String: %@"), mutStr);

    CFRelease(mutStr);
    free(myBuffer);

    // Now create a similar string, but give CFString the ability to reallocate or free the buffer
    // The last "NULL" argument specifies that the default allocator should be used
    // Here we provide an initial buffer of 32 characters, but if it grows beyond this, it's OK
    // (unlike the previous example, where if the string grew beyond 1000, it's an error)

    myBuffer = (UniChar*)CFAllocatorAllocate(CFAllocatorGetDefault(), 32 * sizeof(UniChar), 0);
    mutStr = CFStringCreateMutableWithExternalCharactersNoCopy(NULL, myBuffer, 0, 32, NULL);

    CFStringAppend(mutStr, CFSTR("Appended string... "));
    CFStringAppend(mutStr, CFSTR("Appended string... "));
    CFStringAppend(mutStr, CFSTR("Appended string... "));
    CFStringAppend(mutStr, CFSTR("Appended string... "));
    CFStringAppend(mutStr, CFSTR("Appended string... "));

    show(CFSTR("String: %@"), mutStr);

    CFRelease(mutStr);
    // Here we don't free the buffer, as CFString does that
}
static Boolean _IOFileURLCreateDataAndPropertiesFromResource(CFAllocatorRef alloc, CFURLRef url, CFDataRef *fetchedData, CFArrayRef desiredProperties, CFDictionaryRef *fetchedProperties, SInt32 *errorCode) {
    char buffer[CFMaxPathSize];
    Boolean success = TRUE;

    if (!CFURLGetFileSystemRepresentation(url, TRUE, buffer, CFMaxPathSize)) {
        if (fetchedData) *fetchedData = NULL;
        if (fetchedProperties) *fetchedProperties = NULL;
        if (errorCode) *errorCode = kIOURLImproperArgumentsError;
        return FALSE;
    }

    if (errorCode) *errorCode = 0;
    if (fetchedData) {
        void *bytes;
        CFIndex length;
        Boolean releaseAlloc = FALSE;

        if (alloc == NULL) {
            // We need a real allocator to pass to _IOReadBytesFromFile
            alloc = CFRetain(CFAllocatorGetDefault());
            releaseAlloc = TRUE;
        }
        if (!_IOReadBytesFromFile(alloc, buffer, &bytes, &length, 0)) {
            if (errorCode) *errorCode = kIOURLUnknownError;
            *fetchedData = NULL;
            success = FALSE;
        } else {
            *fetchedData = CFDataCreateWithBytesNoCopy(alloc, bytes, length, alloc);
        }
        if (releaseAlloc) {
            // Now the CFData should be hanging on to it.
            CFRelease(alloc);
        }
    }

    if (fetchedProperties) {
        *fetchedProperties = _IOFileURLCreatePropertiesFromResource(alloc, url, desiredProperties, errorCode);
        if (!*fetchedProperties) success = FALSE;
    }

    return success;
}
Boolean
CFStringFindWithOptionsAndLocale (CFStringRef str,
                                  CFStringRef stringToFind,
                                  CFRange rangeToSearch,
                                  CFStringCompareFlags searchOptions,
                                  CFLocaleRef locale, CFRange *result)
{
  UniChar *pattern;
  UniChar *text;
  CFIndex patternLength;
  CFIndex textLength;
  CFIndex start;
  CFIndex end;
  CFAllocatorRef alloc;
  UCollator *ucol;
  UStringSearch *usrch;
  UErrorCode err = U_ZERO_ERROR;
  
  if (rangeToSearch.length == 0)
    return false;
  
  alloc = CFAllocatorGetDefault ();
  textLength = CFStringGetLength (stringToFind);
  if (textLength == 0)
    return false;
  
  patternLength = rangeToSearch.length;
  pattern = CFAllocatorAllocate (alloc, patternLength * sizeof(UniChar), 0);
  CFStringGetCharacters (str, rangeToSearch, pattern);
  
  text = CFAllocatorAllocate (alloc, textLength * sizeof(UniChar), 0);
  CFStringGetCharacters (stringToFind, CFRangeMake(0, textLength), text);
  
  ucol = CFStringICUCollatorOpen (searchOptions, locale);
  usrch = usearch_openFromCollator (text, textLength, pattern, patternLength,
                                    ucol, NULL, &err);
  if (U_FAILURE(err))
    return false;
  
  /* FIXME: need to handle kCFCompareAnchored */
  if (searchOptions & kCFCompareBackwards)
    {
      start = usearch_last (usrch, &err);
    }
  else
    {
      start = usearch_first (usrch, &err);
    }
  if (start == USEARCH_DONE)
    {
      CFAllocatorDeallocate (alloc, pattern);
      CFAllocatorDeallocate (alloc, text);
      return false;
    }
  end = usearch_getMatchedLength (usrch);
  usearch_close (usrch);
  CFStringICUCollatorClose (ucol);
  
  if (result)
    *result = CFRangeMake (start + rangeToSearch.location, end);
  
  CFAllocatorDeallocate (alloc, pattern);
  CFAllocatorDeallocate (alloc, text);
  return true;
}
Пример #12
0
void display_mac_alert(char *message, int error)
{
	window	*wind;
	d_event	event;
	int		fullscreen;
	bool	osX = FALSE;
	uint 	response;
	int16_t itemHit;

	// Handle Descent's windows properly
	if ((wind = window_get_front()))
		WINDOW_SEND_EVENT(wind, EVENT_WINDOW_DEACTIVATED);

	if (grd_curscreen && (fullscreen = gr_check_fullscreen()))
		gr_toggle_fullscreen();
	
	osX = ( Gestalt(gestaltSystemVersion, (long *) &response) == noErr)
		&& (response >= 0x01000 );

    ShowCursor();

	if (osX)
	{
#ifdef TARGET_API_MAC_CARBON
		DialogRef	alert;
		CFStringRef	error_text = CFSTR("Sorry, a critical error has occurred.");
		CFStringRef	text = NULL;

		text = CFStringCreateWithCString(CFAllocatorGetDefault(), message, kCFStringEncodingMacRoman);
		if (!text)
		{
			if (wind) WINDOW_SEND_EVENT(wind, EVENT_WINDOW_ACTIVATED);
			return;
		}

		if (CreateStandardAlert(error ? kAlertStopAlert : kAlertNoteAlert, error ? error_text : text, error ? text : NULL, 0, &alert) != noErr)
		{
			CFRelease(text);
			if (wind) WINDOW_SEND_EVENT(wind, EVENT_WINDOW_ACTIVATED);
			return;
		}
		
		RunStandardAlert(alert, 0, &itemHit);
		CFRelease(text);
#endif
	}
	else
	{
		// This #if guard removes both compiler warnings
		// and complications if we didn't link the (older) Mac OS X SDK that actually supports the following.
#if !defined(MAC_OS_X_VERSION_MAX_ALLOWED) || (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_4)
		Str255 	error_text = "\pSorry, a critical error has occurred.";
		Str255 	text;
		
		CopyCStringToPascal(message, text);
		StandardAlert(error ? kAlertStopAlert : kAlertNoteAlert, error ? error_text : text, error ? text : NULL, 0, &itemHit);
#endif
	}

	if ((wind = window_get_front()))
		WINDOW_SEND_EVENT(wind, EVENT_WINDOW_ACTIVATED);
	
	if (grd_curscreen && !error && fullscreen)
		gr_toggle_fullscreen();
}
Пример #13
0
CFNumberRef CFNumberCreate(CFAllocatorRef allocator, CFNumberType type, const void* valuePtr) {
    CF_VALIDATE_NUMBERTYPE_ARG(type);

    // Look for cases where we can return a cached instance.
    // We only use cached objects if the allocator is the system
    // default allocator, except for the special floating point
    // constant objects, where we return the cached object
    // regardless of allocator, since that is what has always
    // been done (and now must for compatibility).
    if (!allocator) {
        allocator = CFAllocatorGetDefault();
    }
    int64_t valToBeCached = NotToBeCached;

    if (__CFNumberTypeTable[type].floatBit) {
        CFNumberRef cached = NULL;
        if (!__CFNumberTypeTable[type].storageBit) {
            Float32 f = *(Float32*)valuePtr;
            if (isnan(f)) {
                cached = kCFNumberNaN;
            }
            if (isinf(f)) {
                cached = (f < 0.0) ? kCFNumberNegativeInfinity : kCFNumberPositiveInfinity;
            }
        } else {
            Float64 d = *(Float64*)valuePtr;
            if (isnan(d)) {
                cached = kCFNumberNaN;
            }
            if (isinf(d)) {
                cached = (d < 0.0) ? kCFNumberNegativeInfinity : kCFNumberPositiveInfinity;
            }
        }
        if (cached) {
            return (CFNumberRef)CFRetain(cached);
        }
    } else if (kCFAllocatorSystemDefault == allocator) {
        switch (__CFNumberTypeTable[type].canonicalType) {
            case kCFNumberSInt8Type:
            {
                int8_t val = *(int8_t*)valuePtr;
                if (MinCachedInt <= val && val <= MaxCachedInt) {
                    valToBeCached = (int64_t)val;
                }
                break;
            }
            case kCFNumberSInt16Type:
            {
                int16_t val = *(int16_t*)valuePtr;
                if (MinCachedInt <= val && val <= MaxCachedInt) {
                    valToBeCached = (int64_t)val;
                }
                break;
            }
            case kCFNumberSInt32Type:
            {
                int32_t val = *(int32_t*)valuePtr;
                if (MinCachedInt <= val && val <= MaxCachedInt) {
                    valToBeCached = (int64_t)val;
                }
                break;
            }
            case kCFNumberSInt64Type:
            {
                int64_t val = *(int64_t*)valuePtr;
                if (MinCachedInt <= val && val <= MaxCachedInt) {
                    valToBeCached = (int64_t)val;
                }
                break;
            }
        }
        if (NotToBeCached != valToBeCached) {
            CFNumberRef cached = __CFNumberCache[valToBeCached - MinCachedInt]; // Atomic to access the value in the cache
            if (cached) {
                return (CFNumberRef)CFRetain(cached);
            }
        }
    }

    CFIndex size = 8 + ((!__CFNumberTypeTable[type].floatBit && __CFNumberTypeTable[type].storageBit) ? 8 : 0);
    CFNumberRef result = (CFNumberRef)_CFRuntimeCreateInstance(allocator, __kCFNumberTypeID, size, NULL);
    if (!result) {
        return NULL;
    }
    __CFNumberSetType(result, __CFNumberTypeTable[type].canonicalType);

    // for a value to be cached, we already have the value handy
    if (NotToBeCached != valToBeCached) {
        memmove((void*)&result->_pad, &valToBeCached, 8);
        // Put this in the cache unless the cache is already filled (by another thread).  If we do put it in the cache, retain it an extra time for the cache.
        // Note that we don't bother freeing this result and returning the cached value if the cache was filled, since cached CFNumbers are not guaranteed unique.
        // Barrier assures that the number that is placed in the cache is properly formed.
        CFNumberType origType = __CFNumberGetType(result);
        // Force all cached numbers to have the same type, so that the type does not
        // depend on the order and original type in/with which the numbers are created.
        // Forcing the type AFTER it was cached would cause a race condition with other
        // threads pulling the number object out of the cache and using it.
        __CFNumberSetType(result, kCFNumberSInt32Type);
        if (OSAtomicCompareAndSwapPtrBarrier(NULL, CF_CONST_CAST(void*, result), (void* volatile*)&__CFNumberCache[valToBeCached - MinCachedInt])) {
            CFRetain(result);
        } else {
Пример #14
0
/*** TYPE TO CORE FOUNDATION STRING ***/
void TypeToCFString( const OSType type, CFStringRef *string )
{
	char cString[5];
	TypeToCString( type, (char *) &cString );
	*string = CFStringCreateWithCString( CFAllocatorGetDefault(), (char *) &cString, kCFStringEncodingMacRoman );
}