示例#1
0
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;
  }
}
示例#2
0
__private_extern__
jstring newStringPlatform(JNIEnv *env, const char* str)
{
    jstring rv = NULL;
    CFMutableStringRef csref = CFStringCreateMutable(NULL, 0);
    if (csref == NULL) {
        JNU_ThrowOutOfMemoryError(env, "native heap");
    } else {
        CFStringAppendCString(csref, str, kCFStringEncodingUTF8);
        CFStringNormalize(csref, kCFStringNormalizationFormC);
        int clen = CFStringGetLength(csref);
        int ulen = (clen + 1) * 2;        // utf16 + zero padding
        char* chars = malloc(ulen);
        if (chars == NULL) {
            CFRelease(csref);
            JNU_ThrowOutOfMemoryError(env, "native heap");
        } else {
            if (CFStringGetCString(csref, chars, ulen, kCFStringEncodingUTF16)) {
                rv = (*env)->NewString(env, (jchar*)chars, clen);
            }
            free(chars);
            CFRelease(csref);
        }
    }
    return rv;
}
示例#3
0
UString MultiByteToUnicodeString(const AString &srcString, UINT codePage)
{
  if (!srcString.IsEmpty())
  {
    UString resultString;
    const char * path = &srcString[0];

    CFStringRef cfpath = CFStringCreateWithCString(NULL,path,kCFStringEncodingUTF8);

    if (cfpath)
    {

       CFMutableStringRef cfpath2 = CFStringCreateMutableCopy(NULL,0,cfpath);
       CFRelease(cfpath);
       CFStringNormalize(cfpath2,kCFStringNormalizationFormC);
    
       size_t n = CFStringGetLength(cfpath2);
       for(size_t i =   0 ; i< n ;i++) {
         UniChar uc = CFStringGetCharacterAtIndex(cfpath2,i);
         resultString += (wchar_t)uc; // FIXME
       }

       CFRelease(cfpath2);  

       return resultString;
    }
  }

  UString resultString;
  for (int i = 0; i < srcString.Len(); i++)
    resultString += wchar_t(srcString[i] & 255);

  return resultString;
}
示例#4
0
AString UnicodeStringToMultiByte(const UString &srcString, UINT codePage)
{
  if (!srcString.IsEmpty())
  {
    const wchar_t * wcs = &srcString[0];
    char utf8[4096];
    UniChar unipath[4096];

    size_t n = wcslen(wcs);

    for(size_t i =   0 ; i<= n ;i++) {
      unipath[i] = wcs[i];
    }

    CFStringRef cfpath = CFStringCreateWithCharacters(NULL,unipath,n);

    CFMutableStringRef cfpath2 = CFStringCreateMutableCopy(NULL,0,cfpath);
    CFRelease(cfpath);
    CFStringNormalize(cfpath2,kCFStringNormalizationFormD);
    
    CFStringGetCString(cfpath2,(char *)utf8,4096,kCFStringEncodingUTF8);

    CFRelease(cfpath2);  

    return AString(utf8);
  }

  AString resultString;
  for (int i = 0; i < srcString.Len(); i++)
  {
    if (srcString[i] >= 256) resultString += '?';
    else                     resultString += char(srcString[i]);
  }
  return resultString;
}
示例#5
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;
}
示例#6
0
bool wxOSXAudioToolboxSoundData::Play(unsigned flags)
{
    Stop();

    m_flags = flags;

    wxCFRef<CFMutableStringRef> cfMutableString(CFStringCreateMutableCopy(NULL, 0, wxCFStringRef(m_sndname)));
    CFStringNormalize(cfMutableString,kCFStringNormalizationFormD);
    wxCFRef<CFURLRef> url(CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfMutableString , kCFURLPOSIXPathStyle, false));

    AudioServicesCreateSystemSoundID(url, &m_soundID);
    AudioServicesAddSystemSoundCompletion( m_soundID, CFRunLoopGetCurrent(), NULL, wxOSXAudioToolboxSoundData::CompletionCallback, (void *) this );

    bool sync = !(flags & wxSOUND_ASYNC);

    AudioServicesPlaySystemSound(m_soundID);

    if ( sync )
    {
        while( m_soundID )
        {
            CFRunLoopRun();
        }
    }

    return true;
}
示例#7
0
const CHXString& CHXString::operator =(CFStringRef ref)
{
#ifdef _MAC_CFM
    CFStringEncoding encoding = CFStringGetSystemEncoding();
#else
    CFStringEncoding encoding = kCFStringEncodingUTF8;
#endif

    // we need the string to be canonically decomposed Unicode in case it'll be used as a path on
    // an HFS disk, so we'll make a mutable copy of the string, normalize it, and then encode that as UTF-8

    const CFIndex kNoMaxLength = 0;

    CFMutableStringRef mutableRef = CFStringCreateMutableCopy(kCFAllocatorDefault, kNoMaxLength, ref);

#ifndef __MWERKS__
    // our version of CodeWarrior doesn't have CFStringNormalize in the headers since they are pre-10.2 headers, alas
    CFStringNormalize(mutableRef, kCFStringNormalizationFormD);
#endif

    (void) SetFromCFString(mutableRef, encoding);

    CFRelease(mutableRef);

    return *this;
}
示例#8
0
void PathToFileViaFSRef(char *pathName, int pathNameMax, FSRef *theFSRef,CFStringEncoding encoding) {        
        CFURLRef sillyThing;
        CFStringRef filePath;
        Boolean isDirectory;
		
		pathName[0]=  0x00;
        sillyThing =  CFURLCreateFromFSRef (kCFAllocatorDefault, theFSRef);
		if (sillyThing == NULL)
			return;
        isDirectory = CFURLHasDirectoryPath(sillyThing);
        
        filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLPOSIXPathStyle);
        CFRelease(sillyThing);
        
  		CFMutableStringRef mutableStr= CFStringCreateMutableCopy(NULL, 0, filePath);
          CFRelease(filePath);
  
  		// HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
  		if (encoding == kCFStringEncodingUTF8) 
  			CFStringNormalize(mutableStr, kCFStringNormalizationFormC); // pre-combined
  
          CFStringGetCString (mutableStr, pathName,pathNameMax, encoding);
			CFRelease(mutableStr);
        
        if (isDirectory)
            strcat(pathName,"/");
}
示例#9
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;
}
static void secNormalize(CFMutableStringRef theString, CFLocaleRef theLocale)
{
	CFRange theRange;
	
	CFStringFold(theString, kCFCompareCaseInsensitive | kCFCompareDiacriticInsensitive | kCFCompareWidthInsensitive, theLocale);
	CFStringNormalize(theString, kCFStringNormalizationFormKC);
	CFStringTrimWhitespace(theString);
	while(CFStringFindCharacterFromSet(theString, CFCharacterSetGetPredefined(kCFCharacterSetWhitespace), CFRangeMake(0, CFStringGetLength(theString)), kCFCompareBackwards, &theRange))
		CFStringDelete(theString, theRange);
}
示例#11
0
wxString wxCFStringRef::AsStringWithNormalizationFormC( CFStringRef ref, wxFontEncoding encoding )
{
    if ( !ref )
        return wxEmptyString ;

    CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, ref);
    CFStringNormalize(cfMutableString,kCFStringNormalizationFormC);
    wxString str = wxCFStringRef::AsString(ref,encoding);
    CFRelease(cfMutableString);
    return str;
}
示例#12
0
wxMetafileRefData::wxMetafileRefData( const wxString& filename )
{
    Init();

    if ( !filename.empty() )
    {
        wxCFRef<CFMutableStringRef> cfMutableString(CFStringCreateMutableCopy(NULL, 0, wxCFStringRef(filename)));
        CFStringNormalize(cfMutableString,kCFStringNormalizationFormD);
        wxCFRef<CFURLRef> url(CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfMutableString , kCFURLPOSIXPathStyle, false));
        m_pdfDoc.reset(CGPDFDocumentCreateWithURL(url));
    }
}
示例#13
0
extern int utf8_decodestr(const u_int8_t * utf8p, size_t utf8len, u_int16_t *ucsp, size_t *ucslen,
        size_t buflen, u_int16_t altslash, int flags)
{
    int         err;
    CFStringRef str;
    CFIndex     utf16Count;
    
    assert(utf8p != NULL);
    assert(ucsp != NULL);
    assert(ucslen != NULL);
    assert(altslash == 0);
    assert(flags == UTF_PRECOMPOSED);

    err = 0;
    str = CFStringCreateWithBytes(NULL, utf8p, utf8len, kCFStringEncodingUTF8, false);
    if (str == NULL) {
        err = EINVAL;
    }
    
    if (err == 0) {
        CFMutableStringRef  tmpStr;
        
        tmpStr = CFStringCreateMutableCopy(NULL, 0, str);
        if (tmpStr != NULL) {
            CFStringNormalize(tmpStr, kCFStringNormalizationFormC);
            
            // Swap tmpStr into str.
            
            CFRelease(str);
            str = tmpStr;
        }
    }
    
    if (err == 0) {
        utf16Count = CFStringGetLength(str);
        
        if (utf16Count > (buflen / 2)) {
            utf16Count = (buflen / 2);
            err = ENAMETOOLONG;
        }
        
        CFStringGetCharacters(str, CFRangeMake(0, utf16Count), ucsp);
        
        *ucslen = utf16Count * sizeof(uint16_t);
    }
    
    if (str != NULL) {
        CFRelease(str);
    }

    return err;
}
示例#14
0
/* Some classcical Mac APIs use the encoding based on WorldScript. for example, Japanese language envrironment use
ShiftJIS encoding. So, unicode2NativePascalString, this function converts unicode encoded pascal string to suitable
encoding (came from CFStringGetSystemEncoding()).
*/
void unicode2NativePascalString(ConstStr255Param fromString, StringPtr toString) {
	if (fromString != NULL) {
		CFStringRef strRef = CFStringCreateWithPascalString(kCFAllocatorDefault, fromString, gCurrentVMEncoding);
		if (strRef != NULL) {
			CFMutableStringRef mStrRef = CFStringCreateMutableCopy(NULL, 0, strRef);
			if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
				CFStringNormalize(mStrRef, kCFStringNormalizationFormKD);
			CFStringGetPascalString (mStrRef, toString, 256, CFStringGetSystemEncoding());
			CFRelease(mStrRef);
			CFRelease(strRef);
		}
	}
}
示例#15
0
std::string digidoc::util::File::decodeName(const std::string &localFileName)
{
    CFMutableStringRef ref = CFStringCreateMutable(0, 0);
    CFStringAppendCString(ref, localFileName.c_str(), kCFStringEncodingUTF8);
    CFStringNormalize(ref, kCFStringNormalizationFormC);

    char *composed = new char[localFileName.size() * 2];
    CFStringGetCString(ref, composed, localFileName.size() * 2, kCFStringEncodingUTF8);
    CFRelease(ref);

    std::string out(composed);
    delete [] composed;

    return out;
}
示例#16
0
static pascal OSErr handle_open_doc_ae(const AppleEvent *theAppleEvent, AppleEvent *reply, SRefCon handlerRefcon)
{
  AEDescList docList;
  long index;
  long count = 0;
  int i;
  char *myFileName;
  Size actualSize;
  DescType returnedType;
  AEKeyword keywd;
  FSRef theRef;

  VS("LOADER: handle_open_doc_ae called.\n");

  OSErr err = AEGetParamDesc(theAppleEvent, keyDirectObject, typeAEList, &docList);
  if (err != noErr) return err;

  err = AECountItems(&docList, &count);
  if (err != noErr) return err;
  for (index = 1; index <= count; index++)
  {
     err = AEGetNthPtr(&docList, index, typeFSRef, &keywd, &returnedType, &theRef, sizeof(theRef), &actualSize);

     CFURLRef fullURLRef;
     fullURLRef = CFURLCreateFromFSRef(NULL, &theRef);
     CFStringRef cfString = CFURLCopyFileSystemPath(fullURLRef, kCFURLPOSIXPathStyle);
     CFRelease(fullURLRef);
     CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, cfString);
     CFRelease(cfString);
     CFStringNormalize(cfMutableString, kCFStringNormalizationFormC);
     int len = CFStringGetLength(cfMutableString);
     const int bufferSize = (len+1)*6;  // in theory up to six bytes per Unicode code point, for UTF-8.
     char* buffer = (char*)malloc(bufferSize);
     CFStringGetCString(cfMutableString, buffer, bufferSize, kCFStringEncodingUTF8);

     argv_pyi = (char**)realloc(argv_pyi,(argc_pyi+2)*sizeof(char*));
     argv_pyi[argc_pyi++] = strdup(buffer);
     argv_pyi[argc_pyi] = NULL;

     free(buffer);
  }

  err = AEDisposeDesc(&docList);


  return (err);
}
示例#17
0
static CFURLRef makeFileSystemURLFromString(char *pathString,int length, CFStringEncoding encoding) {
    CFStringRef tmpStrRef;
 	CFMutableStringRef filePath;
    CFURLRef    sillyThing;
	
	tmpStrRef = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *) pathString,
										length, encoding, true);
    if (tmpStrRef == nil)
        return null;
	filePath = CFStringCreateMutableCopy(NULL, 0, tmpStrRef);
	CFRelease(tmpStrRef);
	if (encoding == kCFStringEncodingUTF8) 
		CFStringNormalize(filePath, kCFStringNormalizationFormD); 
    sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,filePath,kCFURLPOSIXPathStyle,false);
	CFRelease(filePath);
	return sillyThing;
}
示例#18
0
/* FSSpec -> FSRef -> URL(Unix) -> HPFS+ */
int PathToFile(char *pathName, int pathNameMax, FSSpec *where,UInt32 encoding) {        
        CFURLRef sillyThing;
        CFStringRef filePath;
        FSSpec	failureRetry;
        FSRef	theFSRef;
        OSErr	error;
        Boolean isDirectory=false,retryWithDirectory=false;
        char	rememberName[256];
        
        *pathName = 0x00;
        error = FSpMakeFSRef (where, &theFSRef);
        if (error != noErr) {
            retryWithDirectory = true;
            failureRetry = *where;
            CopyCStringToPascal(":",failureRetry.name);
            CopyPascalStringToC(where->name,(char *) &rememberName);
            error = FSpMakeFSRef(&failureRetry,&theFSRef);
            if (error != noErr) 
                return -1;
	}
        
        sillyThing =  CFURLCreateFromFSRef (kCFAllocatorDefault, &theFSRef);
        isDirectory = CFURLHasDirectoryPath(sillyThing);
        
        filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle);
        CFRelease(sillyThing);
        
  		CFMutableStringRef mutableStr= CFStringCreateMutableCopy(NULL, 0, filePath);
          CFRelease(filePath);
  
  		// HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
  		if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
  			CFStringNormalize(mutableStr, kCFStringNormalizationFormKC); // pre-combined
  
          CFStringGetCString (mutableStr, pathName,pathNameMax, encoding);
        
        if (retryWithDirectory) {
            strcat(pathName,":");
            strcat(pathName,rememberName);
            isDirectory = false;
        }
        if (isDirectory)
            strcat(pathName,":");
        return 0;
}
示例#19
0
bool wxLaunchDefaultApplication(const wxString& document, int flags)
{
    wxUnusedVar(flags);

    wxCFRef<CFMutableStringRef> cfMutableString(CFStringCreateMutableCopy(NULL, 0, wxCFStringRef(document)));
    CFStringNormalize(cfMutableString,kCFStringNormalizationFormD);
    wxCFRef<CFURLRef> curl(CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfMutableString , kCFURLPOSIXPathStyle, false));
    OSStatus err = LSOpenCFURLRef( curl , NULL );

    if (err == noErr)
    {
        return true;
    }
    else
    {
        wxLogDebug(wxT("Default Application Launch error %d"), (int) err);
        return false;
    }
}
示例#20
0
int getLastPathComponentInCurrentEncoding(char *pathString,char * lastPathPart,CFStringEncoding encoding) {
    CFURLRef    sillyThing;
    CFStringRef tmpStrRef;

	sillyThing = makeFileSystemURLFromString(pathString,strlen(pathString),encoding);
	if (sillyThing == NULL) 
		return -2000;
	tmpStrRef = CFURLCopyLastPathComponent(sillyThing);
    CFRelease(sillyThing);
	CFMutableStringRef mutableStr= CFStringCreateMutableCopy(NULL, 0, tmpStrRef);
	CFRelease(tmpStrRef);
	// HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
	if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
		CFStringNormalize(mutableStr, kCFStringNormalizationFormC); // pre-combined
  
	CFStringGetCString (mutableStr, lastPathPart,256, gCurrentVMEncoding);
	CFRelease(mutableStr);
	return 0;
}
示例#21
0
OSStatus wxMacPathToFSRef( const wxString&path , FSRef *fsRef )
{
    OSStatus err = noErr ;
    CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, wxCFStringRef(path));
    CFStringNormalize(cfMutableString,kCFStringNormalizationFormD);
    CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfMutableString , kDefaultPathStyle, false);
    CFRelease( cfMutableString );
    if ( NULL != url )
    {
        if ( CFURLGetFSRef(url, fsRef) == false )
            err = fnfErr ;
        CFRelease( url ) ;
    }
    else
    {
        err = fnfErr ;
    }
    return err ;
}
示例#22
0
std::string FileSystem::precomposeFileName( const std::string& name )
{
#if EFSW_OS == EFSW_OS_MACOSX
	CFStringRef cfStringRef = CFStringCreateWithCString(kCFAllocatorDefault, name.c_str(), kCFStringEncodingUTF8);
	CFMutableStringRef cfMutable = CFStringCreateMutableCopy(NULL, 0, cfStringRef);

	CFStringNormalize(cfMutable,kCFStringNormalizationFormC);

	char c_str[255 + 1];
	CFStringGetCString(cfMutable, c_str, sizeof(c_str)-1, kCFStringEncodingUTF8);

	CFRelease(cfStringRef);
	CFRelease(cfMutable);

	return std::string(c_str);
#else
	return name;
#endif
}
int dir_Lookup(char *pathString, int pathStringLength, int index,
  /* outputs: */
  char *name, int *nameLength, int *creationDate, int *modificationDate,
  int *isDirectory, squeakFileOffsetType *sizeIfFile) {
	/* Lookup the index-th entry of the directory with the given path, starting
	   at the root of the file system. Set the name, name length, creation date,
	   creation time, directory flag, and file size (if the entry is a file).
	   Return:	0 	if a entry is found at the given index
	   			1	if the directory has fewer than index entries
	   			2	if the given path has bad syntax or does not reach a directory
	*/

	int okay;
    FSSpec      spec;
    long        parentDirectory;
    OSErr       err;
    Str255      longFileName;
		FSVolumeInfoParam fsVolumeParam;
		HFSUniStr255 uniStr;
		FSVolumeInfo volumeInfo;
    
	/* default return values */
	*name             = 0;
	*nameLength       = 0;
	*creationDate     = 0;
	*modificationDate = 0;
	*isDirectory      = false;
	*sizeIfFile       = 0;

	if ((pathStringLength == 0)) {
		/* get volume info */
		fsVolumeParam.volumeName = &uniStr;
		fsVolumeParam.ioVRefNum = kFSInvalidVolumeRefNum;
		fsVolumeParam.volumeIndex = index;
		fsVolumeParam.whichInfo = 0;
		fsVolumeParam.volumeInfo = &volumeInfo;
		fsVolumeParam.ref = NULL;
		fsVolumeParam.whichInfo = kFSVolInfoCreateDate + kFSVolInfoModDate; 
		okay = PBGetVolumeInfoSync( &fsVolumeParam) == noErr;
/*
		FSGetVolumeInfo (kFSInvalidVolumeRefNum,
			index,
			NULL,
			)
*/
		if (okay) {
			CFStringRef strRef = CFStringCreateWithCharacters( kCFAllocatorDefault, uniStr.unicode, uniStr.length );
			CFMutableStringRef mStr = CFStringCreateMutableCopy(NULL, 0, strRef);
			// HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
			if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
				CFStringNormalize(mStr, kCFStringNormalizationFormKC); // pre-combined
			Boolean result = CFStringGetCString(mStr, name, 256, gCurrentVMEncoding); // buffer size is to see primitiveDirectoryLookup
			CFRelease(strRef);
			CFRelease(mStr);
			if (result == true) {
				// strncpy(name, &(uniStr.unicode), uniStr.length);
				// *nameLength       = uniStr.length;
				*nameLength       = strlen(name);
				{	
					LocalDateTime local;
					
					ConvertUTCToLocalDateTime(&fsVolumeParam.volumeInfo->createDate,&local);
					*creationDate     = convertToSqueakTime(local.lowSeconds);
				}
				{	
					LocalDateTime local;
					
					ConvertUTCToLocalDateTime(&fsVolumeParam.volumeInfo->modifyDate,&local);
					*modificationDate     = convertToSqueakTime(local.lowSeconds);
				}
				*isDirectory      = true;
				*sizeIfFile       = 0;
				return ENTRY_FOUND;
			} else {
				return NO_MORE_ENTRIES;
			}
		} else {
			return NO_MORE_ENTRIES;
		}
	} else {
		/* get file or directory info */
		if (!equalsLastPath(pathString, pathStringLength)) {
 			/* lookup and cache the refNum for this path */
			err = lookupPath(pathString, pathStringLength, &spec,false,true);
 			if (err == noErr) 
				recordPath(pathString, pathStringLength, &spec);
			else 
				return BAD_PATH;
		}
	    spec = lastSpec;
		*sizeIfFile   = 0;
		okay = fetchFileInfo(index,&spec,(unsigned char *) name,true,
							&parentDirectory,isDirectory,creationDate,
							modificationDate,sizeIfFile,&longFileName);
		if (okay == noErr) {
			CFStringRef cfs= CFStringCreateWithPascalString(NULL, longFileName, gCurrentVMEncoding);
			CFMutableStringRef mStr= CFStringCreateMutableCopy(NULL, 0, cfs);
			CFRelease(cfs);
			// HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
			if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
				CFStringNormalize(mStr, kCFStringNormalizationFormKC); // pre-combined
			CFStringGetCString(mStr, name, 256, gCurrentVMEncoding);
			CFRelease(mStr);

			*nameLength       = strlen(name);
			*creationDate     = convertToSqueakTime(*creationDate);
			*modificationDate = convertToSqueakTime(*modificationDate);
			return ENTRY_FOUND;
		} else
			return okay == fnfErr ? NO_MORE_ENTRIES : BAD_PATH;
	}
}
示例#24
0
static void resolveLongName(short vRefNum, long parID,unsigned char*shortFileName,FSSpec *possibleSpec,Boolean isFolder,Str255 *name,squeakFileOffsetType *sizeOfFile) {
    
#if TARGET_API_MAC_CARBON 
    if ((Ptr) PBGetCatalogInfoSync != (Ptr)kUnresolvedCFragSymbolAddress) {
        FSRefParam FSRefData;
        FSRef      theFSRef;
        FSCatalogInfo theCatalogInfo;
        HFSUniStr255 	unicodeName;
        OSErr     err;

        if (possibleSpec == nil) {
            FSRefParam FSParam;
            
            FSParam.ioNamePtr = shortFileName;
            FSParam.ioVRefNum = vRefNum;
            FSParam.ioDirID = parID;
            FSParam.newRef = &theFSRef;
            FSParam.ioCompletion = null;

            err = PBMakeFSRefSync(&FSParam);

            if (err != noErr)
                goto done1;   
        } else {
            err = FSpMakeFSRef(possibleSpec,&theFSRef);
            if (err != noErr)
             goto done1;   
        }
                
        FSRefData.ref = &theFSRef;
        FSRefData.whichInfo = kFSCatInfoDataSizes;
        FSRefData.catInfo = &theCatalogInfo;
        FSRefData.spec = nil;
        FSRefData.parentRef = nil;
        FSRefData.outName = &unicodeName;
        
        if (PBGetCatalogInfoSync(&FSRefData) == noErr) {
           CFStringRef 	theString;
           
            if (isFolder) 
                *sizeOfFile = 0;
            else
                *sizeOfFile =  theCatalogInfo.dataLogicalSize; 
                
           theString = CFStringCreateWithCharacters (kCFAllocatorDefault, unicodeName.unicode, (CFIndex) unicodeName.length);
			CFMutableStringRef mStr= CFStringCreateMutableCopy(NULL, 0, theString);
           CFRelease(theString);
			// HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
			if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
				CFStringNormalize(mStr, kCFStringNormalizationFormKC); // canonical decomposition

           CFStringGetPascalString(mStr, (unsigned char *) name,256, gCurrentVMEncoding);
           CFRelease(mStr);
           return;
        }
   }
   done1:
   memcpy(name,shortFileName,sizeof(StrFileName));
#else
   if (shortFileName == nil)
   	  memcpy(name,possibleSpec->name,sizeof(StrFileName));
   else
   	  memcpy(name,shortFileName,sizeof(StrFileName));
#endif
}
示例#25
0
sqInt	ioFilenamefromStringofLengthresolveAliases(char* dst, char* src, sqInt num, sqInt resolveAlias) {
        FSRef		theFSRef;
        FSSpec		convertFileNameSpec,failureRetry;
        OSErr		err;
        Boolean		isFolder=false,isAlias=false;
        CFURLRef 	sillyThing,appendedSillyThing;
        CFStringRef 	lastPartOfPath,filePath2;
		CFMutableStringRef filePath;
        
        *dst = 0x00;
        err = quicklyMakePath((char *) src,num,dst,resolveAlias);
        if (err == noErr) 
            return;
            
        err = lookupPath((char *) src,num,&convertFileNameSpec,true,false);
        if ((err == noErr) && resolveAlias) {
            err = ResolveAliasFile(&convertFileNameSpec,true,&isFolder,&isAlias);
            if (err == fnfErr) {
				err = lookupPath((char *) src,num,&convertFileNameSpec,false,false);
	            err = ResolveAliasFile(&convertFileNameSpec,true,&isFolder,&isAlias);
            }
        }
        
        if (err == fnfErr) {
            failureRetry = convertFileNameSpec;
            CopyCStringToPascal("::",failureRetry.name);
            err = FSpMakeFSRef(&failureRetry,&theFSRef);
            if (err != noErr) 
                return;
//            filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *)src,num,gCurrentVMEncoding,false);
			CFStringRef tmpStrRef = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *)src,num,gCurrentVMEncoding,false);
            if (tmpStrRef == nil) 
                return;
			filePath = CFStringCreateMutableCopy(NULL, 0, tmpStrRef);
			if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
				CFStringNormalize(filePath, kCFStringNormalizationFormKD); // canonical decomposition

            sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,filePath,kCFURLHFSPathStyle,false);
            CFRelease(filePath);
			if (sillyThing == NULL) 
					return;

            lastPartOfPath = CFURLCopyLastPathComponent(sillyThing);
            CFRelease(sillyThing);
            sillyThing = CFURLCreateFromFSRef(kCFAllocatorDefault,&theFSRef);
            appendedSillyThing = CFURLCreateCopyAppendingPathComponent(kCFAllocatorDefault,sillyThing,lastPartOfPath,false);
#if defined(__MWERKS__) && !defined(__APPLE__) && !defined(__MACH__)
            filePath2 = CFURLCopyFileSystemPath (appendedSillyThing, kCFURLHFSPathStyle);
#else
            filePath2 = CFURLCopyFileSystemPath (appendedSillyThing, kCFURLPOSIXPathStyle);
#endif
            CFStringGetCString (filePath2,dst,1000, gCurrentVMEncoding);
            CFRelease(sillyThing);
            CFRelease(appendedSillyThing);
            CFRelease(lastPartOfPath);
            CFRelease(filePath2);        
            return; 
        }
        	
        err = FSpMakeFSRef(&convertFileNameSpec,&theFSRef);
#if defined(__MWERKS__) && !defined(__APPLE__) && !defined(__MACH__)
		sillyThing = CFURLCreateFromFSRef(kCFAllocatorDefault,&theFSRef);
        filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle);
        CFStringGetCString (filePath,dst,1000, gCurrentVMEncoding);
		CFRelease(sillyThing);
        CFRelease(filePath);        
        return;
 #else
        err = FSRefMakePath(&theFSRef,(UInt8 *)dst,1000); 
 #endif
}
示例#26
0
bool wxDataObject::GetFromPasteboard( void * pb )
{
    PasteboardRef pasteboard = (PasteboardRef) pb;

    size_t formatcount = GetFormatCount(wxDataObject::Set);
    wxDataFormat *array = new wxDataFormat[ formatcount ];
    GetAllFormats(array, wxDataObject::Set);
    
    ItemCount itemCount = 0;
    wxString filenamesPassed;
    bool transferred = false;
    bool pastelocationset = false;

    // we synchronize here once again, so we don't mind which flags get returned
    PasteboardSynchronize( pasteboard );

    OSStatus err = PasteboardGetItemCount( pasteboard, &itemCount );
    if ( err == noErr )
    {
        for (size_t i = 0; !transferred && i < formatcount; i++)
        {
            // go through the data in our order of preference
            wxDataFormat dataFormat = array[ i ];

            for( UInt32 itemIndex = 1; itemIndex <= itemCount && transferred == false ; itemIndex++ )
            {
                PasteboardItemID    itemID = 0;
                CFArrayRef          flavorTypeArray = NULL;
                CFIndex             flavorCount = 0;

                err = PasteboardGetItemIdentifier( pasteboard, itemIndex, &itemID );
                if ( err != noErr )
                    continue;

                err = PasteboardCopyItemFlavors( pasteboard, itemID, &flavorTypeArray );
                if ( err != noErr )
                    continue;

                flavorCount = CFArrayGetCount( flavorTypeArray );

                for( CFIndex flavorIndex = 0; !transferred && flavorIndex < flavorCount ; flavorIndex++ )
                {
                    CFStringRef             flavorType;
                    CFDataRef               flavorData;
                    CFIndex                 flavorDataSize;

                    flavorType = (CFStringRef)CFArrayGetValueAtIndex( flavorTypeArray,
                                                                         flavorIndex );

                    wxDataFormat flavorFormat( (wxDataFormat::NativeFormat) flavorType );

                    if ( dataFormat == flavorFormat )
                    {
                        if ( UTTypeConformsTo( (CFStringRef)flavorType, kPasteboardTypeFileURLPromise) )
                        {
                            if ( !pastelocationset )
                            {
                                wxString tempdir = wxFileName::GetTempDir() + wxFILE_SEP_PATH + "wxtemp.XXXXXX";
                                char* result = mkdtemp((char*)tempdir.fn_str().data());
                                
                                if (!result)
                                    continue;
                                
                                wxCFRef<CFURLRef> dest(CFURLCreateFromFileSystemRepresentation(NULL,(const UInt8*)result,strlen(result),true));
                                PasteboardSetPasteLocation(pasteboard, dest);
                                pastelocationset = true;
                           }
                        }
                        else if ( flavorFormat.GetType() != wxDF_PRIVATE )
                        {
                            // indicate the expected format for the type, benefiting from native conversions eg utf8 -> utf16
                            flavorType = (CFStringRef) wxDataFormat( flavorFormat.GetType()).GetFormatId();
                        }
                        
                        err = PasteboardCopyItemFlavorData( pasteboard, itemID, flavorType , &flavorData );
                        if ( err == noErr )
                        {
                            flavorDataSize = CFDataGetLength( flavorData );
                            if (dataFormat.GetType() == wxDF_FILENAME )
                            {
                                 // revert the translation and decomposition to arrive at a proper utf8 string again
                                CFURLRef url = CFURLCreateWithBytes( kCFAllocatorDefault, CFDataGetBytePtr( flavorData ), flavorDataSize, kCFStringEncodingUTF8, NULL );
                                CFStringRef cfString = CFURLCopyFileSystemPath( url, kCFURLPOSIXPathStyle );
                                CFRelease( url );
                                CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, cfString);
                                CFRelease( cfString );
                                CFStringNormalize(cfMutableString,kCFStringNormalizationFormC);
                                wxString path = wxCFStringRef(cfMutableString).AsString();
                                if (!path.empty())
                                    filenamesPassed += path + wxT("\n");
                            }
                            else
                            {
                                // because some data implementation expect trailing a trailing NUL, we add some headroom
                                void *buf = malloc( flavorDataSize + 4 );
                                if ( buf )
                                {
                                    memset( buf, 0, flavorDataSize + 4 );
                                    memcpy( buf, CFDataGetBytePtr( flavorData ), flavorDataSize );

                                    if (dataFormat.GetType() == wxDF_TEXT)
                                        wxMacConvertNewlines10To13( (char*) buf );
                                    SetData( flavorFormat, flavorDataSize, buf );
                                    transferred = true;
                                    free( buf );
                                }
                            }
                            CFRelease (flavorData);
                        }
                    }
                    else if ( dataFormat.GetType() == wxDF_UNICODETEXT && flavorFormat.GetType() == wxDF_TEXT )
                    {
                        err = PasteboardCopyItemFlavorData( pasteboard, itemID, flavorType, &flavorData );
                        if ( err == noErr )
                        {
                            flavorDataSize = CFDataGetLength( flavorData );
                            void *asciibuf = malloc( flavorDataSize + 1 );
                            if ( asciibuf )
                            {
                                memset( asciibuf, 0, flavorDataSize + 1 );
                                memcpy( asciibuf, CFDataGetBytePtr( flavorData ), flavorDataSize );
                                CFRelease (flavorData);

                                SetData( wxDF_TEXT, flavorDataSize, asciibuf );
                                transferred = true;
                                free( asciibuf );
                            }
                            else
                                CFRelease (flavorData);
                        }
                    }
                }
                CFRelease( flavorTypeArray );
            }
            if ( !filenamesPassed.empty() )
            {
                wxCharBuffer buf = filenamesPassed.fn_str();
                SetData( wxDF_FILENAME, strlen( buf ), (const char*)buf );
                transferred = true;
            }
        }
    }
    return transferred;
}
示例#27
0
static int quicklyMakePath(char *pathString, int pathStringLength,char *dst, Boolean resolveAlias) {
	CFStringRef 	filePath;
        CFURLRef 	sillyThing,firstPartOfPath;
        FSRef		theFSRef;   
        Boolean		isFolder,isAlias;
        OSErr		err;
        
        filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,
                    (UInt8 *)pathString,pathStringLength,gCurrentVMEncoding,false);
        if (filePath == nil)
            return -1;
		CFMutableStringRef str= CFStringCreateMutableCopy(NULL, 0, filePath);
		// HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
		if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
			CFStringNormalize(str, kCFStringNormalizationFormKC); // canonical decomposition

		sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault, str, kCFURLHFSPathStyle,false);
		if (sillyThing == NULL) {
			CFRelease(filePath);
			return -2;
		}
		CFRelease(str);
        
        if (!CFURLGetFSRef(sillyThing,&theFSRef)) {
            firstPartOfPath = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault,sillyThing);
            if (!CFURLGetFSRef(firstPartOfPath,&theFSRef)) {
                CFRelease(firstPartOfPath);
                CFRelease(filePath);
                CFRelease(sillyThing);
                return -1;
            } else {
                CFStringRef lastPathPart;
                char	 lastpart[256];
                
                CFRelease(filePath);
                CFRelease(firstPartOfPath);
                lastPathPart = CFURLCopyLastPathComponent(sillyThing);
                CFRelease(sillyThing);
                
                err = noErr;
                if (resolveAlias) 
                    err = FSResolveAliasFile (&theFSRef,true,&isFolder,&isAlias);

                if (err) 
                    return 2;
                
                err = FSRefMakePath(&theFSRef,(UInt8 *)dst,1000); 
                CFStringGetCString(lastPathPart,lastpart,256, kCFStringEncodingUTF8);
                CFRelease(lastPathPart);
                if (strlen(dst)+1+strlen(lastpart) < 1000) {
                    strcat(dst,"/");
                    strcat(dst,lastpart);
                    
#if defined(__MWERKS__) && !defined(__APPLE__) && !defined(__MACH__)
        filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *)dst,strlen(dst),gCurrentVMEncoding,false);
        if (filePath == nil) 
            return 2;
        sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,filePath,kCFURLPOSIXPathStyle,true);
		CFRelease(filePath);
        filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle);
        CFStringGetCString (filePath,dst,1000, gCurrentVMEncoding);
		CFRelease(sillyThing);
        CFRelease(filePath);        
#endif

                    return 0;
                } else
                    return 2;
            }
        }
        
        CFRelease(filePath);
        CFRelease(sillyThing);
        
        if (resolveAlias) 
            err = FSResolveAliasFile (&theFSRef,true,&isFolder,&isAlias);

#if defined(__MWERKS__) && !defined(__APPLE__) && !defined(__MACH__)
		sillyThing = CFURLCreateFromFSRef(kCFAllocatorDefault,&theFSRef);
        filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle);
        CFStringGetCString (filePath,dst,1000, gCurrentVMEncoding);
		CFRelease(sillyThing);
        CFRelease(filePath);        
        return 0;
#else
        err = FSRefMakePath(&theFSRef,(UInt8 *)dst,1000); 
        return err;
#endif 
}
示例#28
0
void GourceSettings::importGourceSettings(ConfFile& conffile, ConfSection* gource_settings) {

    setGourceDefaults();

    if(gource_settings == 0) gource_settings = conffile.getSection(default_section_name);

    if(gource_settings == 0) {
        gource_settings = conffile.addSection("gource");
    }

    ConfEntry* entry = 0;

    //hide flags

    std::vector<std::string> hide_fields;

    if((entry = gource_settings->getEntry("hide")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        std::string hide_string = entry->getString();

        size_t sep;
        while((sep = hide_string.find(",")) != std::string::npos) {

            if(sep == 0 && hide_string.size()==1) break;

            if(sep == 0) {
                hide_string = hide_string.substr(sep+1, hide_string.size()-1);
                continue;
            }

            std::string hide_field  = hide_string.substr(0, sep);
            hide_fields.push_back(hide_field);
            hide_string = hide_string.substr(sep+1, hide_string.size()-1);
        }

        if(hide_string.size() > 0 && hide_string != ",") hide_fields.push_back(hide_string);

        //validate field list

        for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) {
            std::string hide_field = (*it);

            if(   hide_field != "date"
               && hide_field != "users"
               && hide_field != "tree"
               && hide_field != "files"
               && hide_field != "usernames"
               && hide_field != "filenames"
               && hide_field != "dirnames"
               && hide_field != "bloom"
               && hide_field != "progress"
               && hide_field != "mouse"
               && hide_field != "root") {
                std::string unknown_hide_option = std::string("unknown option hide ") + hide_field;
                conffile.entryException(entry, unknown_hide_option);
            }
        }
    }

    //check hide booleans
    for(std::map<std::string,std::string>::iterator it = arg_types.begin(); it != arg_types.end(); it++) {
        if(it->first.find("hide-") == 0 && it->second == "bool") {

            if(gource_settings->getBool(it->first)) {
                std::string hide_field = it->first.substr(5, it->first.size()-5);
                hide_fields.push_back(hide_field);
            }
        }
    }

    if(hide_fields.size()>0) {

        for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) {
            std::string hidestr = (*it);

                if(hidestr == "date")       hide_date      = true;
            else if(hidestr == "users")     hide_users     = true;
            else if(hidestr == "tree")      hide_tree      = true;
            else if(hidestr == "files")     hide_files     = true;
            else if(hidestr == "usernames") hide_usernames = true;
            else if(hidestr == "filenames") hide_filenames = true;
            else if(hidestr == "dirnames")  hide_dirnames  = true;
            else if(hidestr == "bloom")     hide_bloom     = true;
            else if(hidestr == "progress")  hide_progress  = true;
            else if(hidestr == "root")      hide_root      = true;
            else if(hidestr == "mouse")     {
                hide_mouse     = true;
                hide_progress  = true;
            }
        }
    }

    if((entry = gource_settings->getEntry("date-format")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        date_format = entry->getString();
    }

    if(gource_settings->getBool("disable-auto-rotate")) {
        disable_auto_rotate=true;
    }

    if(gource_settings->getBool("disable-auto-skip")) {
        auto_skip_seconds = -1.0;
    }

    if(gource_settings->getBool("loop")) {
        loop = true;
    }

    if((entry = gource_settings->getEntry("git-branch")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        Regex branch_regex("^(?!-)[/\\w.,;_=+{}\\[\\]-]+$");

        std::string branch = entry->getString();

        if(branch_regex.match(branch)) {
            git_branch = branch;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if(gource_settings->getBool("colour-images")) {
        colour_user_images = true;
    }

    if((entry = gource_settings->getEntry("crop")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify crop (vertical,horizontal)");

        std::string crop = entry->getString();

        if(crop == "vertical") {
            crop_vertical = true;
        } else if (crop == "horizontal") {
            crop_horizontal = true;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("log-format")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify log-format (format)");

        log_format = entry->getString();

        if(log_format == "cvs") {
            conffile.entryException(entry, "please use either 'cvs2cl' or 'cvs-exp'");
        }

        if(   log_format != "git"
           && log_format != "cvs-exp"
           && log_format != "cvs2cl"
           && log_format != "svn"
           && log_format != "custom"
           && log_format != "hg"
           && log_format != "bzr"
           && log_format != "apache") {

            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("default-user-image")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify default-user-image (image path)");

        default_user_image = entry->getString();
    }

    if((entry = gource_settings->getEntry("user-image-dir")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-image-dir (directory)");

        user_image_dir = entry->getString();

        //append slash
        if(user_image_dir[user_image_dir.size()-1] != '/') {
            user_image_dir += std::string("/");
        }

        user_image_map.clear();

        boost::filesystem::path image_dir_path(user_image_dir);

        if(!is_directory(image_dir_path)) {
             conffile.entryException(entry, "specified user-image-dir is not a directory");
        }

        std::vector<boost::filesystem::path> image_dir_files;

        try {
            copy(boost::filesystem::directory_iterator(image_dir_path), boost::filesystem::directory_iterator(), back_inserter(image_dir_files));
        } catch(const boost::filesystem::filesystem_error& exception) {
             conffile.entryException(entry, "error reading specified user-image-dir");
        }

        for(boost::filesystem::path& p : image_dir_files) {

            std::string dirfile;

#ifdef _WIN32
            std::wstring dirfile_16 = p.filename().wstring();
            utf8::utf16to8(dirfile_16.begin(), dirfile_16.end(), back_inserter(dirfile));
#else
            dirfile = p.filename().string();
#endif
            std::string file_ext = extension(p);
            boost::algorithm::to_lower(file_ext);

            if(file_ext != ".jpg" && file_ext != ".jpeg" && file_ext != ".png") continue;

            std::string image_path = gGourceSettings.user_image_dir + dirfile;
            std::string name       = dirfile.substr(0,dirfile.size() - file_ext.size());

#ifdef __APPLE__
                CFMutableStringRef help = CFStringCreateMutable(kCFAllocatorDefault, 0);
                CFStringAppendCString(help, name.c_str(), kCFStringEncodingUTF8);
                CFStringNormalize(help, kCFStringNormalizationFormC);
                char data[4096];
                CFStringGetCString(help,
                                   data,
                                   sizeof(data),
                                   kCFStringEncodingUTF8);
                name = data;
#endif

            debugLog("%s => %s", name.c_str(), image_path.c_str());

            user_image_map[name] = image_path;
        }
    }

    if((entry = gource_settings->getEntry("caption-file")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption file (filename)");

        caption_file = entry->getString();

        if(!boost::filesystem::exists(caption_file)) {
            conffile.entryException(entry, "caption file not found");
        }
    }

    if((entry = gource_settings->getEntry("caption-duration")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption duration (seconds)");

        caption_duration = entry->getFloat();

        if(caption_duration <= 0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("caption-size")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption size");

        caption_size = entry->getInt();

        if(caption_size<1 || caption_size>100) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("caption-offset")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption offset");

        caption_offset = entry->getInt();
    }

    if((entry = gource_settings->getEntry("caption-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            caption_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            caption_colour = vec3(r,g,b);
            caption_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("filename-colour")) != 0) {
        if(!entry->hasValue()) conffile.entryException(entry, "specify filename colour (FFFFFF)");

	int r,g,b;

	std::string colstring = entry->getString();

	if(entry->isVec3()) {
	    filename_colour = entry->getVec3();
	} else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            filename_colour = vec3(r,g,b);
            filename_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("filename-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify duration to keep files on screen (float)");

        filename_time = entry->getFloat();

        if(filename_time<2.0f) {
            conffile.entryException(entry, "filename-time must be >= 2.0");
        }
    }

    if((entry = gource_settings->getEntry("bloom-intensity")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-intensity (float)");

        bloom_intensity = entry->getFloat();

        if(bloom_intensity<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("bloom-multiplier")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-multiplier (float)");

        bloom_multiplier = entry->getFloat();

        if(bloom_multiplier<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("elasticity")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify elasticity (float)");

        elasticity = entry->getFloat();

        if(elasticity<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("font-size")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify font size");

        font_size = entry->getInt();

        if(font_size<1 || font_size>100) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("hash-seed")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify hash seed (integer)");

        gStringHashSeed = entry->getInt();
    }

    if((entry = gource_settings->getEntry("font-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify font colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            font_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            font_colour = vec3(r,g,b);
            font_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("background-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify background colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            background_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            background_colour = vec3(r,g,b);
            background_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("highlight-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify highlight colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            highlight_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            highlight_colour = vec3(r,g,b);
            highlight_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("selection-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify selection colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            selection_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            selection_colour = vec3(r,g,b);
            selection_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("dir-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            dir_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            dir_colour = vec3(r,g,b);
            dir_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("background-image")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify background image (image path)");

        background_image = entry->getString();
    }

    if((entry = gource_settings->getEntry("title")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify title");

        title = entry->getString();
    }

    if((entry = gource_settings->getEntry("logo")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify logo (image path)");

        logo = entry->getString();
    }

    if((entry = gource_settings->getEntry("logo-offset")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify logo-offset (XxY)");

        std::string logo_offset_str = entry->getString();

        int posx = 0;
        int posy = 0;

        if(parseRectangle(logo_offset_str, posx, posy)) {
            logo_offset = vec2(posx, posy);
        } else {
            conffile.invalidValueException(entry);
        }

    }

    if((entry = gource_settings->getEntry("seconds-per-day")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify seconds-per-day (seconds)");

        float seconds_per_day = entry->getFloat();

        if(seconds_per_day<=0.0f) {
            conffile.invalidValueException(entry);
        }

        // convert seconds-per-day to days-per-second
        days_per_second = 1.0 / seconds_per_day;
    }

    if((entry = gource_settings->getEntry("auto-skip-seconds")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify auto-skip-seconds (seconds)");

        auto_skip_seconds = entry->getFloat();

        if(auto_skip_seconds <= 0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("file-idle-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify file-idle-time (seconds)");

        std::string file_idle_str = entry->getString();

        file_idle_time = (float) atoi(file_idle_str.c_str());

        if(file_idle_time<0.0f || (file_idle_time == 0.0f && file_idle_str[0] != '0') ) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("user-idle-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-idle-time (seconds)");

        user_idle_time = entry->getFloat();

        if(user_idle_time < 0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("time-scale")) != 0) {

        if(!entry->hasValue())
            conffile.entryException(entry, "specify time-scale (scale)");

        time_scale = entry->getFloat();

        if(time_scale <= 0.0f || time_scale > 4.0f) {
            conffile.entryException(entry, "time-scale outside of range 0.0 - 4.0");
        }
    }

    if((entry = gource_settings->getEntry("start-date")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify start-date (YYYY-MM-DD hh:mm:ss)");

        std::string start_date_string = entry->getString();

        if(parseDateTime(start_date_string, start_timestamp)) {

            char datestr[256];
            strftime(datestr, 256, "%Y-%m-%d", localtime ( &start_timestamp ));
            start_date = datestr;

        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("stop-date")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-date (YYYY-MM-DD hh:mm:ss)");

        std::string end_date_string = entry->getString();

        if(parseDateTime(end_date_string, stop_timestamp)) {

            struct tm * timeinfo;
            timeinfo = localtime ( &stop_timestamp );

            time_t stop_timestamp_rounded = stop_timestamp;

            if(timeinfo->tm_hour > 0 || timeinfo->tm_min > 0 || timeinfo->tm_sec > 0) {
                stop_timestamp_rounded += 60*60*24;
            }

            char datestr[256];
            strftime(datestr, 256, "%Y-%m-%d", localtime ( &stop_timestamp_rounded ));
            stop_date = datestr;

        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("start-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify start-position (float,random)");

        if(entry->getString() == "random") {
            srand(time(0));
            start_position = (rand() % 1000) / 1000.0f;
        } else {
            start_position = entry->getFloat();

            if(start_position<=0.0 || start_position>=1.0) {
                conffile.entryException(entry, "start-position outside of range 0.0 - 1.0 (non-inclusive)");
            }
        }
    }

    if((entry = gource_settings->getEntry("stop-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-position (float)");

        stop_position = entry->getFloat();

        if(stop_position<=0.0 || stop_position>1.0) {
            conffile.entryException(entry, "stop-position outside of range 0.0 - 1.0 (inclusive)");
        }
    }

    if((entry = gource_settings->getEntry("stop-at-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-at-time (seconds)");

        stop_at_time = entry->getFloat();

        if(stop_at_time <= 0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if(gource_settings->getBool("key")) {
        show_key = true;
    }

    if(gource_settings->getBool("ffp")) {
        ffp = true;
    }

    if(gource_settings->getBool("realtime")) {
        days_per_second = 1.0 / 86400.0;
    }

    if(gource_settings->getBool("no-time-travel")) {
        no_time_travel = true;
    }

    if(gource_settings->getBool("dont-stop")) {
        dont_stop = true;
    }

    if(gource_settings->getBool("stop-at-end")) {
        stop_at_end = true;
    }

    //NOTE: this no longer does anything
    if(gource_settings->getBool("stop-on-idle")) {
        stop_on_idle = true;
    }

    if((entry = gource_settings->getEntry("max-files")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-files (number)");

        max_files = entry->getInt();

        if( max_files<0 || (max_files == 0 && entry->getString() != "0") ) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("max-file-lag")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-file-lag (seconds)");

        max_file_lag = entry->getFloat();

        if(max_file_lag==0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("user-friction")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-friction (seconds)");

        user_friction = entry->getFloat();

        if(user_friction<=0.0) {
            conffile.invalidValueException(entry);
        }

        user_friction = 1.0 / user_friction;
    }

    if((entry = gource_settings->getEntry("user-scale")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-scale (scale)");

        user_scale = entry->getFloat();

        if(user_scale<=0.0 || user_scale>100.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("max-user-speed")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-user-speed (units)");

        max_user_speed = entry->getFloat();

        if(max_user_speed<=0) {
            conffile.invalidValueException(entry);
        }
    }

    if(   gource_settings->getBool("highlight-users")
       || gource_settings->getBool("highlight-all-users")) {
        highlight_all_users = true;
    }

    if(gource_settings->getBool("highlight-dirs")) {
        highlight_dirs = true;
    }

    if((entry = gource_settings->getEntry("camera-mode")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify camera-mode (overview,track)");

        camera_mode = entry->getString();

        if(camera_mode != "overview" && camera_mode != "track") {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("padding")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify padding (float)");

        padding = entry->getFloat();

        if(padding <= 0.0f || padding >= 2.0f) {
            conffile.invalidValueException(entry);
        }
    }

    // multi-value entries

    if((entry = gource_settings->getEntry("highlight-user")) != 0) {

        ConfEntryList* highlight_user_entries = gource_settings->getEntries("highlight-user");

        for(ConfEntryList::iterator it = highlight_user_entries->begin(); it != highlight_user_entries->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify highlight-user (user)");

            highlight_users.push_back(entry->getString());
        }
    }

    if((entry = gource_settings->getEntry("follow-user")) != 0) {

        ConfEntryList* follow_user_entries = gource_settings->getEntries("follow-user");

        for(ConfEntryList::iterator it = follow_user_entries->begin(); it != follow_user_entries->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify follow-user (user)");

            follow_users.push_back(entry->getString());
        }
    }

    if(gource_settings->getBool("file-extensions")) {
        file_extensions=true;
    }

    if(gource_settings->getBool("file-extension-fallback")) {
        file_extension_fallback=true;
    }

    if((entry = gource_settings->getEntry("file-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("file-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify file-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid file-filter regular expression");
            }

            file_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("file-show-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("file-show-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify file-show-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid file-show-filter regular expression");
            }

            file_show_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("user-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("user-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify user-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid user-filter regular expression");
            }

            user_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("user-show-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("user-show-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify user-show-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid user-show-filter regular expression");
            }

            user_show_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("dir-name-depth")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir-name-depth (depth)");

        dir_name_depth = entry->getInt();

        if(dir_name_depth <= 0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("dir-name-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir-name-position (float)");

        dir_name_position = entry->getFloat();

        if(dir_name_position < 0.1f || dir_name_position > 1.0f) {
            conffile.entryException(entry, "dir-name-position outside of range 0.1 - 1.0 (inclusive)");
        }
    }

    //validate path
    if(gource_settings->hasValue("path")) {
        path = gource_settings->getString("path");
        default_path = false;
    }

    if(path == "-") {

        if(log_format.size() == 0) {
            throw ConfFileException("log-format required when reading from STDIN", "", 0);
        }

#ifdef _WIN32
        DWORD available_bytes;
        HANDLE stdin_handle = GetStdHandle(STD_INPUT_HANDLE);

        while(PeekNamedPipe(stdin_handle, 0, 0, 0,
            &available_bytes, 0) && available_bytes==0 && !std::cin.fail()) {
            SDL_Delay(100);
        }
#else
        while(std::cin.peek() == EOF && !std::cin.fail()) SDL_Delay(100);
#endif

        std::cin.clear();

    } else if(!path.empty() && path != ".") {

        //remove trailing slash
        if(path[path.size()-1] == '\\' || path[path.size()-1] == '/') {
            path.resize(path.size()-1);
        }

        // check path exists
        if(!boost::filesystem::exists(path)) {
            throw ConfFileException(str(boost::format("'%s' does not appear to be a valid file or directory") % path), "", 0);
        }
    }
}
示例#29
0
void get_files_in_dir(const std::string &directory,
					  std::vector<std::string>* files,
					  std::vector<std::string>* dirs,
					  file_name_option mode,
					  file_filter_option filter,
					  file_reorder_option reorder,
					  file_tree_checksum* checksum)
{
	// If we have a path to find directories in,
	// then convert relative pathnames to be rooted
	// on the wesnoth path
	if(!directory.empty() && directory[0] != '/' && !game_config::path.empty()){
		std::string dir = game_config::path + "/" + directory;
		if(is_directory(dir)) {
			get_files_in_dir(dir,files,dirs,mode,filter,reorder,checksum);
			return;
		}
	}

	struct stat st;

	if (reorder == DO_REORDER) {
		LOG_FS << "searching for _main.cfg in directory " << directory << '\n';
		std::string maincfg;
		if (directory.empty() || directory[directory.size()-1] == '/')
			maincfg = directory + maincfg_filename;
		else
			maincfg = (directory + "/") + maincfg_filename;

		if (::stat(maincfg.c_str(), &st) != -1) {
			LOG_FS << "_main.cfg found : " << maincfg << '\n';
			if (files != NULL) {
				if (mode == ENTIRE_FILE_PATH)
					files->push_back(maincfg);
				else
					files->push_back(maincfg_filename);
			}
			return;
		}
	}

	DIR* dir = opendir(directory.c_str());

	if(dir == NULL) {
		return;
	}

	struct dirent* entry;
	while((entry = readdir(dir)) != NULL) {
		if(entry->d_name[0] == '.')
			continue;
#ifdef __APPLE__
		// HFS Mac OS X decomposes filenames using combining unicode characters.
		// Try to get the precomposed form.
		char macname[MAXNAMLEN+1];
		CFStringRef cstr = CFStringCreateWithCString(NULL,
							 entry->d_name,
							 kCFStringEncodingUTF8);
		CFMutableStringRef mut_str = CFStringCreateMutableCopy(NULL,
							 0, cstr);
		CFStringNormalize(mut_str, kCFStringNormalizationFormC);
		CFStringGetCString(mut_str,
				macname,sizeof(macname)-1,
				kCFStringEncodingUTF8);
		CFRelease(cstr);
		CFRelease(mut_str);
		const std::string basename = macname;
#else
		// generic Unix
		const std::string basename = entry->d_name;
#endif /* !APPLE */

		std::string fullname;
		if (directory.empty() || directory[directory.size()-1] == '/')
			fullname = directory + basename;
		else
			fullname = directory + "/" + basename;

		if (::stat(fullname.c_str(), &st) != -1) {
			if (S_ISREG(st.st_mode)) {
				if(filter == SKIP_PBL_FILES && looks_like_pbl(basename)) {
					continue;
				}
				if (files != NULL) {
					if (mode == ENTIRE_FILE_PATH)
						files->push_back(fullname);
					else
						files->push_back(basename);
				}
				if (checksum != NULL) {
					if(st.st_mtime > checksum->modified) {
						checksum->modified = st.st_mtime;
					}
					checksum->sum_size += st.st_size;
					checksum->nfiles++;
				}
			} else if (S_ISDIR(st.st_mode)) {
				if (filter == SKIP_MEDIA_DIR
						&& (basename == "images"|| basename == "sounds"))
					continue;

				if (reorder == DO_REORDER &&
						::stat((fullname+"/"+maincfg_filename).c_str(), &st)!=-1 &&
						S_ISREG(st.st_mode)) {
					LOG_FS << "_main.cfg found : ";
					if (files != NULL) {
						if (mode == ENTIRE_FILE_PATH) {
							files->push_back(fullname + "/" + maincfg_filename);
							LOG_FS << fullname << "/" << maincfg_filename << '\n';
						} else {
							files->push_back(basename + "/" + maincfg_filename);
							LOG_FS << basename << "/" << maincfg_filename << '\n';
					}
					} else {
					// Show what I consider strange
						LOG_FS << fullname << "/" << maincfg_filename << " not used now but skip the directory \n";
					}
				} else if (dirs != NULL) {
					if (mode == ENTIRE_FILE_PATH)
						dirs->push_back(fullname);
					else
						dirs->push_back(basename);
				}
			}
		}
	}

	closedir(dir);

	if(files != NULL)
		std::sort(files->begin(),files->end());

	if (dirs != NULL)
		std::sort(dirs->begin(),dirs->end());

	if (files != NULL && reorder == DO_REORDER) {
		// move finalcfg_filename, if present, to the end of the vector
		for (unsigned int i = 0; i < files->size(); i++) {
			if (ends_with((*files)[i], "/" + finalcfg_filename)) {
				files->push_back((*files)[i]);
				files->erase(files->begin()+i);
				break;
			}
		}
		// move initialcfg_filename, if present, to the beginning of the vector
		unsigned int foundit = 0;
		for (unsigned int i = 0; i < files->size(); i++)
			if (ends_with((*files)[i], "/" + initialcfg_filename)) {
				foundit = i;
				break;
			}
		// If _initial.cfg needs to be moved (it was found, but not at index 0).
		if (foundit > 0) {
			std::string initialcfg = (*files)[foundit];
			for (unsigned int i = foundit; i > 0; --i)
				(*files)[i] = (*files)[i-1];
			(*files)[0] = initialcfg;
		}
	}
}
示例#30
0
bool wxDataObject::GetFromPasteboard( void * pb )
{
    PasteboardRef pasteboard = (PasteboardRef) pb;
    size_t formatcount = GetFormatCount() + 1;
    wxDataFormat *array = new wxDataFormat[ formatcount ];
    array[0] = GetPreferredFormat();
    GetAllFormats( &array[1] );
    ItemCount itemCount = 0;
    wxString filenamesPassed;
    bool transferred = false;

    // we synchronize here once again, so we don't mind which flags get returned
    PasteboardSynchronize( pasteboard );

    OSStatus err = PasteboardGetItemCount( pasteboard, &itemCount );
    if ( err == noErr )
    {
        for (size_t i = 0; !transferred && i < formatcount; i++)
        {
            // go through the data in our order of preference
            wxDataFormat dataFormat = array[ i ];

            for( UInt32 itemIndex = 1; itemIndex <= itemCount && transferred == false ; itemIndex++ )
            {
                PasteboardItemID    itemID = 0;
                CFArrayRef          flavorTypeArray = NULL;
                CFIndex             flavorCount = 0;

                err = PasteboardGetItemIdentifier( pasteboard, itemIndex, &itemID );
                if ( err != noErr )
                    continue;

                err = PasteboardCopyItemFlavors( pasteboard, itemID, &flavorTypeArray );
                if ( err != noErr )
                    continue;
                    
                flavorCount = CFArrayGetCount( flavorTypeArray );

                for( CFIndex flavorIndex = 0; !transferred && flavorIndex < flavorCount ; flavorIndex++ )
                {
                    CFStringRef             flavorType;
                    CFDataRef               flavorData;
                    CFIndex                 flavorDataSize;
         
                    flavorType = (CFStringRef)CFArrayGetValueAtIndex( flavorTypeArray,
                                                                         flavorIndex );

                    // avoid utf8 being treated closer to plain-text than unicode by forcing a conversion
                    if ( UTTypeConformsTo(flavorType, CFSTR("public.utf8-plain-text") ) )
                    {
                        flavorType = CFSTR("public.utf16-plain-text");
                    }
                    wxDataFormat flavorFormat( (wxDataFormat::NativeFormat) flavorType );
 
                    if ( dataFormat == flavorFormat )
                    {
                        err = PasteboardCopyItemFlavorData( pasteboard, itemID, flavorType , &flavorData );
                        if ( err == noErr )
                        {
                            flavorDataSize = CFDataGetLength( flavorData );
                            if (dataFormat.GetType() == wxDF_FILENAME )
                            {
                                // revert the translation and decomposition to arrive at a proper utf8 string again
                                CFURLRef url = CFURLCreateWithBytes( kCFAllocatorDefault, CFDataGetBytePtr( flavorData ), flavorDataSize, kCFStringEncodingUTF8, NULL );
                                CFStringRef cfString = CFURLCopyFileSystemPath( url, kCFURLPOSIXPathStyle );
                                CFRelease( url );
                                CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, cfString);
                                CFRelease( cfString );
                                CFStringNormalize(cfMutableString,kCFStringNormalizationFormC);
                                wxString path = wxMacCFStringHolder(cfMutableString).AsString();
                                if (!path.empty())
                                    filenamesPassed += path + wxT("\n");
                            }
                            else
                            {
                                // because some data implementation expect trailing a trailing NUL, we add some headroom
                                void *buf = malloc( flavorDataSize + 4 );
                                if ( buf )
                                {
                                    memset( buf, 0, flavorDataSize + 4 );
                                    memcpy( buf, CFDataGetBytePtr( flavorData ), flavorDataSize );
 
                                    if (dataFormat.GetType() == wxDF_TEXT)
                                        wxMacConvertNewlines10To13( (char*) buf );
                                    SetData( flavorFormat, flavorDataSize, buf );
                                    transferred = true;
                                    free( buf );
                                }
                            }
                            CFRelease (flavorData);
                        }
                    }
                    else if ( dataFormat.GetType() == wxDF_UNICODETEXT && flavorFormat.GetType() == wxDF_TEXT )
                    {
                        err = PasteboardCopyItemFlavorData( pasteboard, itemID, flavorType, &flavorData );
                        if ( err == noErr )
                        {
                            flavorDataSize = CFDataGetLength( flavorData );
                            void *asciibuf = malloc( flavorDataSize + 1 );
                            if ( asciibuf )
                            {
                                memset( asciibuf, 0, flavorDataSize + 1 );
                                memcpy( asciibuf, CFDataGetBytePtr( flavorData ), flavorDataSize );
                                CFRelease (flavorData);

                                SetData( wxDF_TEXT, flavorDataSize, asciibuf );
                                transferred = true;
                                free( asciibuf );
                            }
                            else
                                CFRelease (flavorData);
                        }
                    }
                }
                CFRelease( flavorTypeArray );
            }
            if (filenamesPassed.length() > 0)
            {
                wxCharBuffer buf = filenamesPassed.fn_str();
                SetData( wxDF_FILENAME, strlen( buf ), (const char*)buf );
                transferred = true;
            }
        }
    }
    return transferred;
}