示例#1
0
文件: main.c 项目: Deanzou/ppp
/* -----------------------------------------------------------------------------
plugin entry point, called by pppd
----------------------------------------------------------------------------- */
int start(CFBundleRef ref)
{
    CFStringRef 	strref;
    CFURLRef 		urlref;
   
    bundle = ref;
    CFRetain(bundle);
    
    url = CFBundleCopyBundleURL(bundle);

    // hookup our handlers
    old_check_options = the_channel->check_options;
    the_channel->check_options = serial_check_options;
    
    old_connect = the_channel->connect;
    the_channel->connect = serial_connect;
    
    old_process_extra_options = the_channel->process_extra_options;
    the_channel->process_extra_options = serial_process_extra_options;

    add_notifier(&connect_fail_notify, serial_connect_notifier, 0);
    add_notifier(&lcp_lowerdown_notify, serial_lcpdown_notifier, 0);

    cancelstrref = CFBundleCopyLocalizedString(bundle, CFSTR("Cancel"), CFSTR("Cancel"), NULL);
    if (cancelstrref == 0) return 1;
    CFStringGetCString(cancelstrref, (char*)cancelstr, sizeof(cancelstr), kCFStringEncodingUTF8);
    
    icstrref = CFBundleCopyLocalizedString(bundle, CFSTR("Network Connection"), CFSTR("Network Connection"), NULL);
    if (icstrref == 0) return 1;
    CFStringGetCString(icstrref, (char*)icstr, sizeof(icstr), kCFStringEncodingUTF8);
    
    urlref = CFBundleCopyResourceURL(bundle, CFSTR("NetworkConnect.icns"), NULL, NULL);
    if (urlref == 0 || ((strref = CFURLGetString(urlref)) == 0)) {
		if (urlref)
            CFRelease(urlref);
        return 1;
    }
    CFStringGetCString(strref, (char*)iconstr, sizeof(iconstr), kCFStringEncodingUTF8);
	
	iconstrref = CFStringCreateCopy(NULL, strref);
    CFRelease(urlref);

	urlref = CFBundleCopyBuiltInPlugInsURL(bundle);
	if (urlref == 0 || ((CFURLGetFileSystemRepresentation(urlref, TRUE, pathccl, sizeof(pathccl))) == FALSE)) {
		if (urlref)
            CFRelease(urlref);
        return 1;
    }
    strlcat((char*)pathccl, SUFFIX_CCLENGINE, sizeof(pathccl));
    CFRelease(urlref);
    
    // add the socket specific options
    add_options(serial_options);

    return 0;
}
CF_EXPORT Boolean _CFBundleDlfcnPreflight(CFBundleRef bundle, CFErrorRef *error) {
    Boolean retval = true;
    CFErrorRef localError = NULL;
    if (!bundle->_isLoaded) {
        CFURLRef executableURL = CFBundleCopyExecutableURL(bundle);
        char buff[CFMaxPathSize];
        
        retval = false;
        if (executableURL && CFURLGetFileSystemRepresentation(executableURL, true, (uint8_t *)buff, CFMaxPathSize)) {
#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
            retval = dlopen_preflight(buff);
#endif
            if (!retval && error) {
                CFArrayRef archs = CFBundleCopyExecutableArchitectures(bundle);
                CFStringRef debugString = NULL;
                const char *errorString = dlerror();
                if (errorString && strlen(errorString) > 0) debugString = CFStringCreateWithFileSystemRepresentation(kCFAllocatorSystemDefault, errorString);
                if (archs) {
                    Boolean hasSuitableArch = false, hasRuntimeMismatch = false;
                    CFIndex i, count = CFArrayGetCount(archs);
                    SInt32 arch, curArch = _CFBundleCurrentArchitecture();
                    for (i = 0; !hasSuitableArch && i < count; i++) {
                        if (CFNumberGetValue((CFNumberRef)CFArrayGetValueAtIndex(archs, i), kCFNumberSInt32Type, (void *)&arch) && arch == curArch) hasSuitableArch = true;
                    }
#if defined(BINARY_SUPPORT_DYLD)
                    if (hasSuitableArch) {
                        uint32_t mainFlags = 0;
                        if (_CFBundleGrokObjCImageInfoFromMainExecutable(NULL, &mainFlags) && (mainFlags & 0x2) != 0) {
#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
                            uint32_t bundleFlags = 0;
                            if (_CFBundleGetObjCImageInfo(bundle, NULL, &bundleFlags) && (bundleFlags & 0x2) == 0) hasRuntimeMismatch = true;
#endif
                        }
                    }
#endif /* BINARY_SUPPORT_DYLD */
                    if (hasRuntimeMismatch) {
                        localError = _CFBundleCreateErrorDebug(CFGetAllocator(bundle), bundle, CFBundleExecutableRuntimeMismatchError, debugString);
                    } else if (!hasSuitableArch) {
                        localError = _CFBundleCreateErrorDebug(CFGetAllocator(bundle), bundle, CFBundleExecutableArchitectureMismatchError, debugString);
                    } else {
                        localError = _CFBundleCreateErrorDebug(CFGetAllocator(bundle), bundle, CFBundleExecutableLoadError, debugString);
                    }
                    CFRelease(archs);
                } else {
                    localError = _CFBundleCreateErrorDebug(CFGetAllocator(bundle), bundle, CFBundleExecutableLoadError, debugString);
                }
                if (debugString) CFRelease(debugString);
            }
        } else {
            if (error) localError = _CFBundleCreateError(CFGetAllocator(bundle), bundle, CFBundleExecutableNotFoundError);
        }
        if (executableURL) CFRelease(executableURL);
    }
    if (!retval && error) *error = localError;
    return retval;
}
示例#3
0
void setcwd(void) {
	// make sure cwd is where the app is (launching from Finder sets it to / by default)
	unsigned char parentdir[MAXPATHLEN];
	CFURLRef url = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
	
	if (CFURLGetFileSystemRepresentation(url, true, parentdir, MAXPATHLEN)) {
		chdir((char *)parentdir);
	}
	CFRelease(url);
}
示例#4
0
    std::string getExecutablePath()
    {
      CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());

      FixedStrT<512> buf;

      CFURLGetFileSystemRepresentation(url, true,
                       (UInt8*) buf.str(), buf.capacity());
      return buf.str();
    }
示例#5
0
const String application_path() {
    cf::Url url(CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle()));
    cf::String url_string(CFStringCreateCopy(NULL, CFURLGetString(url.c_obj())));
    char path_buffer[PATH_MAX];
    if (!CFURLGetFileSystemRepresentation(
                url.c_obj(), true, reinterpret_cast<UInt8*>(path_buffer), PATH_MAX)) {
        throw Exception("couldn't get application_path()");
    }
    return String(utf8::decode(path_buffer));
}
示例#6
0
char *HostFilesys::getDataFolder(char *buffer, unsigned int bufsize)
{
	UInt8 main_bundle_loc[MAXPATHLEN];
	CFURLRef url = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
	CFURLGetFileSystemRepresentation(url, true, main_bundle_loc, sizeof(main_bundle_loc));
	CFRelease(url);
	
 	//printf("Data folder ---------> %s\n", main_bundle_loc);
	return safe_strncpy(buffer, (char*)main_bundle_loc, bufsize);
}
示例#7
0
__private_extern__ SInt32 _CFGetFileProperties(CFAllocatorRef alloc, CFURLRef pathURL, Boolean *exists, SInt32 *posixMode, int64_t *size, CFDateRef *modTime, SInt32 *ownerID, CFArrayRef *dirContents) {
    
    char path[CFMaxPathSize];

    if (!CFURLGetFileSystemRepresentation(pathURL, true, (uint8_t *)path, CFMaxPathLength)) {
        return -1;
    }

    return _CFGetPathProperties(alloc, path, exists, posixMode, size, modTime, ownerID, dirContents);
}
char* bundle_path() {
  CFBundleRef mainBundle = CFBundleGetMainBundle();
  CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
  int len = 4096;
  char* path = malloc(len);
  
  CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8*)path, len);
  
  return path;
}
示例#9
0
void DAMountRemoveMountPoint( CFURLRef mountpoint )
{
    char path[MAXPATHLEN];

    /*
     * Obtain the mount point path.
     */

    if ( CFURLGetFileSystemRepresentation( mountpoint, TRUE, ( void * ) path, sizeof( path ) ) )
    {
        if ( ___isautofs( path ) == 0 )
        {
            Boolean remove;

            remove = FALSE;

            if ( strncmp( path, kDAMainMountPointFolder, strlen( kDAMainMountPointFolder ) ) == 0 )
            {
                if ( strrchr( path + strlen( kDAMainMountPointFolder ), '/' ) == path + strlen( kDAMainMountPointFolder ) )
                {
                    remove = TRUE;
                }
            }

///w:start
//          if ( remove == FALSE )
///w:stop
            {
                char file[MAXPATHLEN];

                strlcpy( file, path,                              sizeof( file ) );
                strlcat( file, "/",                               sizeof( file ) );
                strlcat( file, kDAMainMountPointFolderCookieFile, sizeof( file ) );

                /*
                 * Remove the mount point cookie file.
                 */

                if ( unlink( file ) == 0 )
                {
                    remove = TRUE;
                }
            }

            if ( remove )
            {
                /*
                 * Remove the mount point.
                 */

                rmdir( path );
            }
        }
    }
}
示例#10
0
void InitDirs(const std::string& argv0)
{
    if (g_initialized)
        return;

    // store working dir
    fs::initial_path();
    fs::path bundle_path;
    fs::path app_path;

    CFBundleRef bundle = CFBundleGetMainBundle();
    char bundle_dir[MAXPATHLEN];

    if (bundle) {
        CFURLRef bundleurl = CFBundleCopyBundleURL(bundle);
        CFURLGetFileSystemRepresentation(bundleurl, true, reinterpret_cast<UInt8*>(bundle_dir), MAXPATHLEN);
    } else {
        // executable is not the main binary in application bundle (i.e. Server or AI)
        uint32_t size = sizeof(bundle_dir);
        if (_NSGetExecutablePath(bundle_dir, &size) != 0) {
            std::cerr << "_NSGetExecutablePath() failed: buffer too small; need size " << size << std::endl;
            exit(-1);
        }
    }

    bundle_path = fs::path(bundle_dir);

    // search bundle_path for a directory named "FreeOrion.app", exiting if not found, else constructing a path to application bundle contents
    fs::path::iterator appiter =   std::find(bundle_path.begin(), bundle_path.end(), "FreeOrion.app");
    if (appiter == bundle_path.end()) {
        std::cerr << "Error: Application bundle must be named 'FreeOrion.app' and executables must not be called from outside of it." << std::endl;
        exit(-1);
    } else {
        for (fs::path::iterator piter = bundle_path.begin(); piter != appiter; ++piter) {
            app_path /= *piter;
        }
        app_path /= "FreeOrion.app/Contents";
    }

    s_root_data_dir =   app_path / "Resources";
    s_user_dir      =   fs::path(getenv("HOME")) / "Library" / "Application Support" / "FreeOrion";
    s_bin_dir       =   app_path / "Executables";
    s_config_path   =   s_user_dir / "config.xml";
    s_python_home   =   app_path / "Frameworks" / "Python.framework" / "Versions" / "Current";

    fs::path p = s_user_dir;
    if (!exists(p))
        fs::create_directories(p);

    p /= "save";
    if (!exists(p))
        fs::create_directories(p);

    g_initialized = true;
}
示例#11
0
__private_extern__ Boolean _CFWriteBytesToFile(CFURLRef url, const void *bytes, CFIndex length) {
    struct stat statBuf;
    int fd = -1;
    int mode;
    char path[CFMaxPathSize];
    if (!CFURLGetFileSystemRepresentation(url, true, (uint8_t *)path, CFMaxPathSize)) {
        return false;
    }

#if DEPLOYMENT_TARGET_WINDOWS || 0
    mode = 0666;
    if (0 == stat(path, &statBuf)) {
        mode = statBuf.st_mode;
    } else if (thread_errno() != ENOENT) {
        return false;
    }
    fd = open(path, O_WRONLY|O_CREAT|O_TRUNC|CF_OPENFLGS, 0666|_S_IWRITE);
    if (fd < 0) {
        return false;
    }
    if (length && write(fd, bytes, length) != length) {
        int saveerr = thread_errno();
        close(fd);
        thread_set_errno(saveerr);
        return false;
    }
    FlushFileBuffers((HANDLE)_get_osfhandle(fd));
    close(fd);
#else
    int no_hang_fd = open("/dev/autofs_nowait", 0);
    mode = 0666;
    if (0 == stat(path, &statBuf)) {
        mode = statBuf.st_mode;
    } else if (thread_errno() != ENOENT) {
	close(no_hang_fd);
        return false;
    }
    fd = open(path, O_WRONLY|O_CREAT|O_TRUNC|CF_OPENFLGS, 0666);
    if (fd < 0) {
	close(no_hang_fd);
        return false;
    }
    if (length && write(fd, bytes, length) != length) {
        int saveerr = thread_errno();
        close(fd);
	close(no_hang_fd);
        thread_set_errno(saveerr);
        return false;
    }
    fsync(fd);
    close(fd);
    close(no_hang_fd);
#endif
    return true;
}
示例#12
0
__private_extern__ Boolean _CFReadBytesFromFile(CFAllocatorRef alloc, CFURLRef url, void **bytes, CFIndex *length, CFIndex maxLength) {
    // maxLength is the number of bytes desired, or 0 if the whole file is desired regardless of length.
    struct stat statBuf;
    int fd = -1;
    char path[CFMaxPathSize];
    if (!CFURLGetFileSystemRepresentation(url, true, path, CFMaxPathSize)) {
        return false;
    }

    *bytes = NULL;

__CFSetNastyFile(url);

#if defined(__WIN32__)
    fd = open(path, O_RDONLY|CF_OPENFLGS, 0666|_S_IREAD);
#else
    fd = open(path, O_RDONLY|CF_OPENFLGS, 0666);
#endif
    if (fd < 0) {
        return false;
    }
    if (fstat(fd, &statBuf) < 0) {
        int saveerr = thread_errno();
        close(fd);
        thread_set_errno(saveerr);
        return false;
    }
    if ((statBuf.st_mode & S_IFMT) != S_IFREG) {
        close(fd);
        thread_set_errno(EACCES);
        return false;
    }
    if (statBuf.st_size == 0) {
        *bytes = CFAllocatorAllocate(alloc, 4, 0); // don't return constant string -- it's freed!
	if (__CFOASafe) __CFSetLastAllocationEventName(*bytes, "CFUtilities (file-bytes)");
        *length = 0;
    } else {
        CFIndex desiredLength;
        if ((maxLength >= statBuf.st_size) || (maxLength == 0)) {
            desiredLength = statBuf.st_size;
        } else {
            desiredLength = maxLength;
        }
        *bytes = CFAllocatorAllocate(alloc, desiredLength, 0);
	if (__CFOASafe) __CFSetLastAllocationEventName(*bytes, "CFUtilities (file-bytes)");
        if (read(fd, *bytes, desiredLength) < 0) {
            CFAllocatorDeallocate(alloc, *bytes);
            close(fd);
            return false;
        }
        *length = desiredLength;
    }
    close(fd);
    return true;
}
static bool SecExtractFilesystemPathForKeychainFile(CFStringRef file, UInt8 *buffer, CFIndex maxBufLen)
{
    bool translated = false;
    CFURLRef fileURL = SecCopyURLForFileInKeychainDirectory(file);
    
    if (fileURL && CFURLGetFileSystemRepresentation(fileURL, false, buffer, maxBufLen))
        translated = true;
    CFReleaseSafe(fileURL);
    
    return translated;
}
示例#14
0
string cfString(CFURLRef inUrl)
{
	if (!inUrl)
		CFError::throwMe();
	
	UInt8 buffer[PATH_MAX+1];
	if (CFURLGetFileSystemRepresentation(inUrl, true, buffer, sizeof(buffer)))
		return string(reinterpret_cast<char *>(buffer));
	else
		CFError::throwMe();
}
示例#15
0
bool SFB::Audio::WAVEMetadata::_WriteMetadata(CFErrorRef *error)
{
	UInt8 buf [PATH_MAX];
	if(!CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))
		return false;

	std::unique_ptr<TagLib::FileStream> stream(new TagLib::FileStream((const char *)buf));
	if(!stream->isOpen()) {
		if(error) {
			SFB::CFString description = CFCopyLocalizedString(CFSTR("The file “%@” could not be opened for writing."), "");
			SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Input/output error"), "");
			SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("The file may have been renamed, moved, deleted, or you may not have appropriate permissions."), "");

			*error = CreateErrorForURL(Metadata::ErrorDomain, Metadata::InputOutputError, description, mURL, failureReason, recoverySuggestion);
		}

		return false;
	}

	TagLib::RIFF::WAV::File file(stream.get(), false);
	if(!file.isValid()) {
		if(error) {
			SFB::CFString description = CFCopyLocalizedString(CFSTR("The file “%@” is not a valid WAVE file."), "");
			SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Not a WAVE file"), "");
			SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "");
			
			*error = CreateErrorForURL(Metadata::ErrorDomain, Metadata::InputOutputError, description, mURL, failureReason, recoverySuggestion);
		}
		
		return false;
	}

	// An Info tag is only written if present, but ID3v2 tags are always written

	// TODO: Should other field names from the Info tag be handled?
	if(file.InfoTag())
		SetTagFromMetadata(*this, file.InfoTag());

	SetID3v2TagFromMetadata(*this, file.ID3v2Tag());

	if(!file.save()) {
		if(error) {
			SFB::CFString description = CFCopyLocalizedString(CFSTR("The file “%@” is not a valid WAVE file."), "");
			SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Unable to write metadata"), "");
			SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "");
			
			*error = CreateErrorForURL(Metadata::ErrorDomain, Metadata::InputOutputError, description, mURL, failureReason, recoverySuggestion);
		}
		
		return false;
	}

	return true;
}
示例#16
0
	SDLApplication::SDLApplication () {
		
		if (SDL_Init (SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_TIMER | SDL_INIT_JOYSTICK) != 0) {
			
			printf ("Could not initialize SDL: %s.\n", SDL_GetError ());
			
		}
		
		SDL_LogSetPriority (SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_WARN);
		
		currentApplication = this;
		
		framePeriod = 1000.0 / 60.0;
		
		#ifdef EMSCRIPTEN
		emscripten_cancel_main_loop ();
		emscripten_set_main_loop (UpdateFrame, 0, 0);
		emscripten_set_main_loop_timing (EM_TIMING_RAF, 1);
		#endif
		
		currentUpdate = 0;
		lastUpdate = 0;
		nextUpdate = 0;
		
		ApplicationEvent applicationEvent;
		DropEvent dropEvent;
		GamepadEvent gamepadEvent;
		JoystickEvent joystickEvent;
		KeyEvent keyEvent;
		MouseEvent mouseEvent;
		RenderEvent renderEvent;
		SensorEvent sensorEvent;
		TextEvent textEvent;
		TouchEvent touchEvent;
		WindowEvent windowEvent;
		
		SDL_EventState (SDL_DROPFILE, SDL_ENABLE);
		SDLJoystick::Init ();
		
		#ifdef HX_MACOS
		CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL (CFBundleGetMainBundle ());
		char path[PATH_MAX];
		
		if (CFURLGetFileSystemRepresentation (resourcesURL, TRUE, (UInt8 *)path, PATH_MAX)) {
			
			chdir (path);
			
		}
		
		CFRelease (resourcesURL);
		#endif
		
	}
bool SFB::Audio::TrueAudioMetadata::_ReadMetadata(CFErrorRef *error)
{
    UInt8 buf [PATH_MAX];
    if(!CFURLGetFileSystemRepresentation(mURL, FALSE, buf, PATH_MAX))
        return false;

    std::unique_ptr<TagLib::FileStream> stream(new TagLib::FileStream((const char *)buf, true));
    if(!stream->isOpen()) {
        if(error) {
            SFB::CFString description = CFCopyLocalizedString(CFSTR("The file “%@” could not be opened for reading."), "");
            SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Input/output error"), "");
            SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("The file may have been renamed, moved, deleted, or you may not have appropriate permissions."), "");

            *error = CreateErrorForURL(Metadata::ErrorDomain, Metadata::InputOutputError, description, mURL, failureReason, recoverySuggestion);
        }

        return false;
    }

    TagLib::TrueAudio::File file(stream.get());
    if(!file.isValid()) {
        if(nullptr != error) {
            SFB::CFString description = CFCopyLocalizedString(CFSTR("The file “%@” is not a valid True Audio file."), "");
            SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Not a True Audio file"), "");
            SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "");

            *error = CreateErrorForURL(Metadata::ErrorDomain, Metadata::InputOutputError, description, mURL, failureReason, recoverySuggestion);
        }

        return false;
    }

    CFDictionarySetValue(mMetadata, kFormatNameKey, CFSTR("True Audio"));

    if(file.audioProperties()) {
        auto properties = file.audioProperties();
        AddAudioPropertiesToDictionary(mMetadata, properties);

        if(properties->bitsPerSample())
            AddIntToDictionary(mMetadata, kBitsPerChannelKey, properties->bitsPerSample());
        if(properties->sampleFrames())
            AddIntToDictionary(mMetadata, kTotalFramesKey, (int)properties->sampleFrames());
    }

    // Add all tags that are present
    if(file.ID3v1Tag())
        AddID3v1TagToDictionary(mMetadata, file.ID3v1Tag());

    if(file.ID3v2Tag())
        AddID3v2TagToDictionary(mMetadata, mPictures, file.ID3v2Tag());

    return true;
}
bool WavPackMetadata::ReadMetadata(CFErrorRef *error)
{
	// Start from scratch
	CFDictionaryRemoveAllValues(mMetadata);
	CFDictionaryRemoveAllValues(mChangedMetadata);

	UInt8 buf [PATH_MAX];
	if(!CFURLGetFileSystemRepresentation(mURL, FALSE, buf, PATH_MAX))
		return false;

	auto stream = new TagLib::FileStream(reinterpret_cast<const char *>(buf), true);
	TagLib::WavPack::File file(stream);

	if(!file.isValid()) {
		if(nullptr != error) {
			CFStringRef description = CFCopyLocalizedString(CFSTR("The file “%@” is not a valid WavPack file."), "");
			CFStringRef failureReason = CFCopyLocalizedString(CFSTR("Not a WavPack file"), "");
			CFStringRef recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "");
			
			*error = CreateErrorForURL(AudioMetadataErrorDomain, AudioMetadataInputOutputError, description, mURL, failureReason, recoverySuggestion);
			
			CFRelease(description), description = nullptr;
			CFRelease(failureReason), failureReason = nullptr;
			CFRelease(recoverySuggestion), recoverySuggestion = nullptr;
		}

		return false;
	}
	
	CFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR("WavPack"));
	
	if(file.audioProperties()) {
		auto properties = file.audioProperties();
		AddAudioPropertiesToDictionary(mMetadata, properties);
		
		if(properties->bitsPerSample())
			AddIntToDictionary(mMetadata, kPropertiesBitsPerChannelKey, properties->bitsPerSample());
		if(properties->sampleFrames())
			AddIntToDictionary(mMetadata, kPropertiesTotalFramesKey, properties->sampleFrames());
	}
	
	if(file.ID3v1Tag())
		AddID3v1TagToDictionary(mMetadata, file.ID3v1Tag());

	if(file.APETag()) {
		std::vector<AttachedPicture *> pictures;
		AddAPETagToDictionary(mMetadata, pictures, file.APETag());
		for(auto picture : pictures)
			AddSavedPicture(picture);
	}

	return true;
}
示例#19
0
文件: i18n.cpp 项目: JCDG/warzone2100
void initI18n(void)
{
	const char *textdomainDirectory = NULL;

	if (!setLanguage("")) // set to system default
	{
		// no system default?
		debug(LOG_ERROR, "initI18n: No system language found");
	}
#if defined(WZ_OS_WIN)
	{
		// Retrieve an absolute path to the locale directory
		char localeDir[PATH_MAX];
		sstrcpy(localeDir, PHYSFS_getBaseDir());
		sstrcat(localeDir, "\\" LOCALEDIR);

		// Set locale directory and translation domain name
		textdomainDirectory = bindtextdomain(PACKAGE, localeDir);
	}
#else
	#ifdef WZ_OS_MAC
	{
		char resourcePath[PATH_MAX];
		CFURLRef resourceURL = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
		if( CFURLGetFileSystemRepresentation( resourceURL, true, (UInt8 *) resourcePath, PATH_MAX) )
		{
			sstrcat(resourcePath, "/locale");
			textdomainDirectory = bindtextdomain(PACKAGE, resourcePath);
		}
		else
		{
			debug( LOG_ERROR, "Could not change to resources directory." );
		}

		if (resourceURL != NULL)
		{
			CFRelease(resourceURL);
		}

		debug(LOG_INFO, "resourcePath is %s", resourcePath);
	}
	#else
	textdomainDirectory = bindtextdomain(PACKAGE, LOCALEDIR);
	#endif
#endif
	if (!textdomainDirectory)
	{
		debug(LOG_ERROR, "initI18n: bindtextdomain failed!");
	}

	(void)bind_textdomain_codeset(PACKAGE, "UTF-8");
	(void)textdomain(PACKAGE);
}
bool WavPackMetadata::WriteMetadata(CFErrorRef *error)
{
	UInt8 buf [PATH_MAX];
	if(!CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))
		return false;

	auto stream = new TagLib::FileStream(reinterpret_cast<const char *>(buf));
	TagLib::WavPack::File file(stream, false);

	if(!file.isValid()) {
		if(nullptr != error) {
			CFStringRef description = CFCopyLocalizedString(CFSTR("The file “%@” is not a valid WavPack file."), "");
			CFStringRef failureReason = CFCopyLocalizedString(CFSTR("Not a WavPack file"), "");
			CFStringRef recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "");
			
			*error = CreateErrorForURL(AudioMetadataErrorDomain, AudioMetadataInputOutputError, description, mURL, failureReason, recoverySuggestion);
			
			CFRelease(description), description = nullptr;
			CFRelease(failureReason), failureReason = nullptr;
			CFRelease(recoverySuggestion), recoverySuggestion = nullptr;
		}
		
		return false;
	}
	
	// ID3v1 tags are only written if present, but an APE tag is always written
	
	if(file.ID3v1Tag())
		SetID3v1TagFromMetadata(*this, file.ID3v1Tag());

	SetAPETagFromMetadata(*this, file.APETag(true));

	if(!file.save()) {
		if(error) {
			CFStringRef description = CFCopyLocalizedString(CFSTR("The file “%@” is not a valid WavPack file."), "");
			CFStringRef failureReason = CFCopyLocalizedString(CFSTR("Unable to write metadata"), "");
			CFStringRef recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "");
			
			*error = CreateErrorForURL(AudioMetadataErrorDomain, AudioMetadataInputOutputError, description, mURL, failureReason, recoverySuggestion);
			
			CFRelease(description), description = nullptr;
			CFRelease(failureReason), failureReason = nullptr;
			CFRelease(recoverySuggestion), recoverySuggestion = nullptr;
		}
		
		return false;
	}

	MergeChangedMetadataIntoMetadata();

	return true;
}
ExitStatus checkKextForProblems(
        KcgenArgs         * toolArgs,
        OSKextRef           theKext,
        const NXArchInfo  * arch)
{
    ExitStatus          result        = EX_SOFTWARE;
    char                kextPath[PATH_MAX];

    if (!CFURLGetFileSystemRepresentation(OSKextGetURL(theKext),
                              /* resolveToBase */ false, (UInt8 *)kextPath, sizeof(kextPath))) 
    {
        strlcpy(kextPath, "(unknown)", sizeof(kextPath));
    }
    
    /* Skip kexts we have no interest in for the current arch.
     */
    if (!OSKextSupportsArchitecture(theKext, arch)) {
        OSKextLog(/* kext */ NULL,
                  kOSKextLogErrorLevel | kOSKextLogArchiveFlag,
                  "%s doesn't support architecture '%s'; ommiting.", kextPath,
                  arch->name);
        goto finish;
    }
    
    if (!OSKextIsValid(theKext)) {
        OSKextLog(/* kext */ NULL,
                  kOSKextLogErrorLevel | kOSKextLogArchiveFlag |
                  kOSKextLogValidationFlag | kOSKextLogGeneralFlag, 
                  "%s is not valid; omitting.", kextPath);
        if (toolArgs->printTestResults) {
            OSKextLogDiagnostics(theKext, kOSKextDiagnosticsFlagAll);
        }
        goto finish;
    }
    
    if (!OSKextResolveDependencies(theKext)) {
        OSKextLog(/* kext */ NULL,
                  kOSKextLogWarningLevel | kOSKextLogArchiveFlag |
                  kOSKextLogDependenciesFlag | kOSKextLogGeneralFlag, 
                  "%s is missing dependencies (including anyway; "
                  "dependencies may be available from elsewhere)", kextPath);
        if (toolArgs->printTestResults) {
            OSKextLogDiagnostics(theKext, kOSKextDiagnosticsFlagAll);
        }
    }

    result = EX_OK;
    
finish:
    return result;

}
	void* AppleCMIODPSampleNewPlugIn(CFAllocatorRef allocator, CFUUIDRef requestedTypeUUID) 
	{
		if (not CFEqual(requestedTypeUUID, kCMIOHardwarePlugInTypeID))
			return 0;
		
		try
		{
			// Before going any further, make sure the SampleAssistant process is registerred with Mach's bootstrap service.  Normally, this would be done by having an appropriately
			// configured plist in /Library/LaunchDaemons, but if that is done then the process will be owned by root, thus complicating the debugging process.  Therefore, in the event that the
			// plist is missing (as would be the case for most debugging efforts) attempt to register the SampleAssistant now.  It will fail gracefully if allready registered.
			mach_port_t assistantServicePort;		
			name_t assistantServiceName = "com.apple.cmio.DPA.Sample";
			kern_return_t err = bootstrap_look_up(bootstrap_port, assistantServiceName, &assistantServicePort);
			if (BOOTSTRAP_SUCCESS != err)
			{
				// Create an URL to SampleAssistant that resides at "/Library/CoreMediaIO/Plug-Ins/DAL/Sample.plugin/Contents/Resources/SampleAssistant" 
				CACFURL assistantURL(CFURLCreateWithFileSystemPath(NULL, CFSTR("/Library/CoreMediaIO/Plug-Ins/DAL/Sample.plugin/Contents/Resources/SampleAssistant"), kCFURLPOSIXPathStyle, false));
				ThrowIf(not assistantURL.IsValid(), CAException(-1), "AppleCMIODPSampleNewPlugIn: unable to create URL for the SampleAssistant");

				// Get the maximum size of the of the file system representation of the SampleAssistant's absolute path
				CFIndex length = CFStringGetMaximumSizeOfFileSystemRepresentation(CACFString(CFURLCopyFileSystemPath(CACFURL(CFURLCopyAbsoluteURL(assistantURL.GetCFObject())).GetCFObject(), kCFURLPOSIXPathStyle)).GetCFString());

				// Get the file system representation
				CAAutoFree<char> path(length);
				(void) CFURLGetFileSystemRepresentation(assistantURL.GetCFObject(), true, reinterpret_cast<UInt8*>(path.get()), length);

				mach_port_t assistantServerPort;
				err = bootstrap_create_server(bootstrap_port, path, getuid(), true, &assistantServerPort);
				ThrowIf(BOOTSTRAP_SUCCESS != err, CAException(err), "AppleCMIODPSampleNewPlugIn: couldn't create server");
				
				err = bootstrap_check_in(assistantServerPort, assistantServiceName, &assistantServicePort);

				// The server port is no longer needed so get rid of it
				(void) mach_port_deallocate(mach_task_self(), assistantServerPort);

				// Make sure the call to bootstrap_create_service() succeeded
				ThrowIf(BOOTSTRAP_SUCCESS != err, CAException(err), "AppleCMIODPSampleNewPlugIn: couldn't create SampleAssistant service port");
			}

			// The service port is not longer needed so get rid of it
			(void) mach_port_deallocate(mach_task_self(), assistantServicePort);


			CMIO::DP::Sample::PlugIn* plugIn = new CMIO::DP::Sample::PlugIn(requestedTypeUUID);
			plugIn->Retain();
			return plugIn->GetInterface();
		}
		catch (...)
		{
			return NULL;
		}
	}
示例#23
0
void msGetExecutableDir(string &path)
{
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
    char path1[PATH_MAX];

    if (CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path1, PATH_MAX))
    {
        CFRelease(resourcesURL);
        
        path = path1;
    }    
}
示例#24
0
CF_PRIVATE Boolean _CFWriteBytesToFileAsync(CFURLRef url, const void *bytes, CFIndex length) {
    char path[CFMaxPathSize];
    if (!CFURLGetFileSystemRepresentation(url, true, (uint8_t *)path, CFMaxPathSize)) {
        return false;
    }

    wchar_t wpath[CFMaxPathSize];
    int convertedLength = MultiByteToWideChar(CP_UTF8, 0, path, CFMaxPathSize, wpath, CFMaxPathSize);
    if (0 == convertedLength) {
        unsigned error = GetLastError();
        CFLog(kCFLogLevelWarning, CFSTR("_CFWriteBytesToFileAsync failed to convert the path (error %u)"), error);
        return false;
    }

    HANDLE fileHandle = NULL;
    CREATEFILE2_EXTENDED_PARAMETERS createExParams;
    createExParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
    createExParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
    createExParams.dwFileFlags = FILE_FLAG_OVERLAPPED;
    createExParams.dwSecurityQosFlags = 0;
    createExParams.lpSecurityAttributes = NULL;
    createExParams.hTemplateFile = NULL;

    OVERLAPPED* overlapped = (OVERLAPPED*)calloc(1, sizeof(OVERLAPPED));

    if ((fileHandle = CreateFile2(wpath, GENERIC_WRITE, FILE_SHARE_READ, CREATE_ALWAYS, &createExParams)) == INVALID_HANDLE_VALUE) {
        unsigned error = GetLastError();
        CFLog(kCFLogLevelWarning, CFSTR("_CFWriteBytesToFileAsync failed to open the file (error %u)"), error);
        free(overlapped);
        return false;
    }

    PTP_IO threadPoolIo = CreateThreadpoolIo(fileHandle, _threadpoolCallback, NULL, NULL);
    StartThreadpoolIo(threadPoolIo);

    if (!WriteFile(fileHandle, bytes, length, NULL, overlapped)) {
        unsigned error = GetLastError();
        if (ERROR_IO_PENDING != error) {
            CFLog(kCFLogLevelWarning, CFSTR("_CFWriteBytesToFileAsync failed to write to the file (error %u)"), error);
            CloseHandle(fileHandle);
            CancelThreadpoolIo(threadPoolIo);
            CloseThreadpoolIo(threadPoolIo);
            free(overlapped);
            return false;
        }
    }

    CloseHandle(fileHandle);

    return true;
}
CF_PRIVATE Boolean _CFBundleDYLDLoadFramework(CFBundleRef bundle, CFErrorRef *error) {
    // !!! Framework loading should be better.  Can't unload frameworks.
    CFErrorRef localError = NULL, *subError = (error ? &localError : NULL);
    NSLinkEditErrors c = NSLinkEditUndefinedError;
    int errorNumber = 0;
    const char *fileName = NULL;
    const char *errorString = NULL;

    if (!bundle->_isLoaded) {
        CFURLRef executableURL = CFBundleCopyExecutableURL(bundle);
        char buff[CFMaxPathSize];

        if (executableURL && CFURLGetFileSystemRepresentation(executableURL, true, (uint8_t *)buff, CFMaxPathSize)) {
            void *image = (void *)NSAddImage(buff, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
#if LOG_BUNDLE_LOAD
            printf("dyld load framework %p, add image of %s returns image %p\n", bundle, buff, image);
#endif /* LOG_BUNDLE_LOAD */
            if (image) {
                bundle->_imageCookie = image;
                bundle->_isLoaded = true;
            } else {
                NSLinkEditError(&c, &errorNumber, &fileName, &errorString);
                if (error) {
#if defined(BINARY_SUPPORT_DLFCN)
                    _CFBundleDlfcnPreflight(bundle, subError);
#endif /* BINARY_SUPPORT_DLFCN */
                    if (!localError) {
                        CFStringRef tempString = CFStringCreateWithFileSystemRepresentation(kCFAllocatorSystemDefault, errorString), debugString = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("error code %d, error number %d (%@)"), c, errorNumber, tempString);
                        localError = _CFBundleCreateErrorDebug(CFGetAllocator(bundle), bundle, CFBundleExecutableLinkError, debugString);
                        if (tempString) CFRelease(tempString);
                        if (debugString) CFRelease(debugString);
                    }
                } else {
                    CFStringRef tempString = CFStringCreateWithFileSystemRepresentation(kCFAllocatorSystemDefault, errorString), executableString = CFStringCreateWithFileSystemRepresentation(kCFAllocatorSystemDefault, fileName);
                    CFLog(__kCFLogBundle, CFSTR("Error loading %@:  error code %d, error number %d (%@)"), executableString, c, errorNumber, tempString);
                    if (tempString) CFRelease(tempString);
                    if (executableString) CFRelease(executableString);
                }
            }
        } else {
            if (error) {
                localError = _CFBundleCreateError(CFGetAllocator(bundle), bundle, CFBundleExecutableNotFoundError);
            } else {
                CFLog(__kCFLogBundle, CFSTR("Cannot find executable for bundle %@"), bundle);
            }
        }
        if (executableURL) CFRelease(executableURL);
    }
    if (!bundle->_isLoaded && error) *error = localError;
    return bundle->_isLoaded;
}
示例#26
0
void mac_get_resource_path(const char *_path,MyString& _resPath)
{
    CFURLRef resourceURL;
    _resPath.Empty();
    
    // Look for the resource in the main bundle by name and type.
    
#ifdef ACTIVEGSPLUGIN
    CFBundleRef bundle =  CFBundleGetBundleWithIdentifier(__CFStringMakeConstantString("com.freetoolsassociation.activegs"));
#else
    CFBundleRef bundle = CFBundleGetMainBundle();

#endif
    CFStringRef ce =   CFStringCreateWithCString(
                                                 NULL,
                                                 _path,
                                                 kCFStringEncodingASCII);
    resourceURL = CFBundleCopyResourceURL(
    bundle,
    ce,
    NULL,
    NULL
    );
    
    if(!resourceURL)
    {
        printf("Failed to locate a file in the loaded bundle! (%s)",_path);
        return;
    }
    
    char fileurl[1024]; 
    
    if(!CFURLGetFileSystemRepresentation(
                                         resourceURL,
                                         true,
                                         (UInt8*)
                                         fileurl,
                                         1024))
        
    {
        printf("Failed to turn a bundle resource URL into a filesystem path representation!");
        return;
    }
    

    
    _resPath = fileurl;
        
    
}
示例#27
0
CFStringRef Resources::getResourcesPathFromBundleId() { //@@TODO
    char buffer[PATH_MAX];
    CFBundleRef bundle = CFBundleGetBundleWithIdentifier(CFSTR("SuperColldierAU") );
    if (bundle == NULL) return NULL;
    CFURLRef bundleURL = CFBundleCopyBundleURL(bundle);
    CFURLGetFileSystemRepresentation(bundleURL, TRUE, (UInt8*)buffer,PATH_MAX);
    CFStringRef bundlePath = CFStringCreateWithCString(NULL,buffer, kCFStringEncodingUTF8);
    CFURLRef bundleResourcesURL = CFBundleCopyResourcesDirectoryURL(bundle);
    CFStringRef resourcesRelativePath = CFURLGetString(bundleResourcesURL);
    CFMutableStringRef resourcesPath = CFStringCreateMutable(NULL,0);
    CFStringAppend(resourcesPath,bundlePath);
    CFStringAppend(resourcesPath,resourcesRelativePath);
    return resourcesPath;
}
示例#28
0
void setWorkdir(){
#ifdef __APPLE__
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
    char path[PATH_MAX];
    if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
    {
        throw TetrisException("Could not initialize workdir.");
    }
    CFRelease(resourcesURL);
	
    chdir(path);
#endif
}
示例#29
0
void OSystem_IPHONE::addSysArchivesToSearchSet(Common::SearchSet &s, int priority) {
	// Get URL of the Resource directory of the .app bundle
	CFURLRef fileUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
	if (fileUrl) {
		// Try to convert the URL to an absolute path
		UInt8 buf[MAXPATHLEN];
		if (CFURLGetFileSystemRepresentation(fileUrl, true, buf, sizeof(buf))) {
			// Success: Add it to the search path
			Common::String bundlePath((const char *)buf);
			s.add("__OSX_BUNDLE__", new Common::FSDirectory(bundlePath), priority);
		}
		CFRelease(fileUrl);
	}
}
示例#30
0
void setMacOSXLibLoc(void) {
  /* lib-tkeden is located within the tkeden.app "bundle" directory
     (which is represented to the user in the Finder as an application
     icon).  Get the reference to where it is. */
  CFBundleRef mainBundleRef;
  mainBundleRef = CFBundleGetMainBundle();
  if (mainBundleRef != NULL) {
    CFURLRef libtkedenURL;
    libtkedenURL = CFBundleCopyResourceURL(mainBundleRef,
					   CFSTR("lib-tkeden"),
					   NULL, NULL);
    if (libtkedenURL != NULL) {
      char *libtkedenPath = malloc(MAX_PATH_LEN + 1);

      /*
      char *cstr = malloc(1024);
      CFStringGetCString(CFURLGetString(libtkedenURL),
			 cstr, 1024, kCFStringEncodingISOLatin2);
      fprintf(stderr, "libtkedenPath=%s\n", cstr);
      */

      if (CFURLGetFileSystemRepresentation(libtkedenURL, true,
					   libtkedenPath, MAX_PATH_LEN)) {
	setLibLocation(libtkedenPath);
      } else {
	/* gcc needs the -fpascal-strings option to allow \p (which
           means form a Pascal string: max 255 chars, the first byte
           states the length) */
        /* ideally errors like this would appear in a Mac dialog box, eg
           via StandardAlert(), but I can't get this to link any more, so
           doing it this way instead.  I think that if they occur, these errors
           will be visible in Console.app.  [Ash] */
        fprintf(stderr, "Ooops: couldn't GetFileSystemRepresentation of libtkedenURL");
        exit(1);
      }

      free(libtkedenPath);

    } else {
      fprintf(stderr, "Ooops: Couldn't find libtkedenURL");

    }

  } else {
    fprintf(stderr, "Ooops: Couldn't find mainBundleRef");

  }

}