Example #1
0
bool remove(const path & p) {
	int ret = ::remove(p.string().c_str());
	return !ret || ret == ENOENT || ret == ENOTDIR;
}
Example #2
0
 bool operator<(const path& lhs, const path& rhs) noexcept
 {
   return lhs.compare(rhs) < 0;
 }
long ExtractCurrentFile ( path parent, unzFile uf )
{
    long error = UNZ_OK;

    char filename_inzip[PATH_MAX];
    unz_file_info64 file_info;
	
    error = unzGetCurrentFileInfo64 ( uf, &file_info, filename_inzip, sizeof ( filename_inzip ), NULL, 0, NULL, 0 );
	
	path file = filename_inzip;

	file.make_preferred();
	parent.make_preferred();

	if ( error == UNZ_OK ) {

		std::string macos = "__MACOSX";
		if ( file.string().compare ( 0, macos.length(), macos ) == 0 ) {
			return kNoError;
		}
		
		path to_write = parent / file;
		create_directories ( to_write.parent_path() );

		if ( file.filename().string() == "." ) {
			
			create_directory ( to_write );
			
		} else {
			
			error = unzOpenCurrentFilePassword ( uf, NULL );

			if ( error == UNZ_OK ) {

				char * buffer = new char [ WRITEBUFFERSIZE ];
				
				boost::filesystem::ofstream output_file ( to_write, std::ios_base::binary );
				output_file.exceptions ( boost::filesystem::ofstream::badbit | boost::filesystem::ofstream::failbit );			
				
				long bytes_read = 0;
				do {
					bytes_read = unzReadCurrentFile ( uf, (void *)buffer, WRITEBUFFERSIZE );
					
					if ( bytes_read > 0 ) {
						output_file.write ( buffer, bytes_read );
					} else if ( bytes_read < 0 ) {
						error = bytes_read;
					}
				} while ( bytes_read > 0 );
								
				output_file.close();
                ChangeFileDate ( to_write, file_info.tmu_date );
				delete [] buffer;

			}
			
			// don't lose the error
			int close_error = unzCloseCurrentFile ( uf );
			if ( error == UNZ_OK ) {
				error = close_error;
			}
		}
	}
	    
	return error;

} // ExtractCurrentFile
Example #4
0
 void pushFlowThrowPath(const path& p, const F& pFlow) {
     for (typename path::const_iterator v = p.begin(); v != p.end() - 1; ++v) {
         flows.at(*v).at(*(v + 1)) += pFlow;
         flows.at(*(v + 1)).at(*v) -= pFlow;
     }
 }
Example #5
0
 void swap(path& lhs, path& rhs) noexcept
 {
   lhs.swap(rhs);
 }
Example #6
0
boost::intmax_t getFileSize(path &myPath){
	if ( !exists(myPath) )
		throw std::string("file "+myPath.string()+" doesn't exist");

	return file_size(myPath);
}
/***************************
Find liblightsparkBACKENDplugin libraries
****************************/
void PluginManager::findPlugins()
{
	//Search for all files under the plugins directory
	//Verify if they are audio plugins
	//If true, add to list of audio plugins
#ifdef _WIN32
	const path plugins_folder = getExectuablePath();
#else
	const path plugins_folder = string(PRIVATELIBDIR) + "/plugins/";
#endif
	const string pattern ( "liblightspark+[A-Za-z]+plugin.*" );

	//Stuff used by/for pcre
	const char* patternError;
	int patternErrorOffset;
	pcre* file_pattern = pcre_compile ( pattern.c_str(), 0, &patternError, &patternErrorOffset, NULL );
	if(patternError)
		throw RunTimeException("PluginManager::findPlugins(): can't compile file_pattern");
	//We don't expect any captured substrings, so 3 ints should be enough

#if defined DEBUG
	LOG(LOG_INFO, "Looking for plugins under " << plugins_folder << " for pattern " << pattern);
#endif

	if ( !is_directory ( plugins_folder ) )
	{
		LOG ( LOG_ERROR, _ ( ( ( string ) ( "The plugins folder doesn't exists under " + plugins_folder.string() ) ).c_str() ) );
	}
	else
	{
		for ( directory_iterator itr ( plugins_folder ), end_itr; itr != end_itr; ++itr )
		{
			if ( is_regular_file ( *itr ) )   //Is it a real file? This will remove symlink
			{
#if BOOST_VERSION >= 104600
				string leaf_name = itr->path().filename().string();
#else
				string leaf_name = itr->path().filename();
#endif
				int patternOvector[3];
				int rc=pcre_exec(file_pattern, NULL, leaf_name.c_str(), leaf_name.length(), 0, 0, patternOvector, 3);
				if ( rc > 0 )   // Does it answer to the desired pattern?
				{
#if BOOST_VERSION >= 104600
					path fullpath = plugins_folder.string();
#else
					path fullpath = plugins_folder.directory_string();
#endif
					fullpath /= leaf_name;
					//Try to load the file and see if it's an audio plugin
					if ( GModule* h_plugin = g_module_open( fullpath.string().c_str(), G_MODULE_BIND_LAZY) )
					{
						PLUGIN_FACTORY p_factory_function;
						PLUGIN_CLEANUP p_cleanup_function;

						if ( g_module_symbol(h_plugin, "create", (void**)&p_factory_function)
							&& g_module_symbol(h_plugin, "release", (void**)&p_cleanup_function) )
						{  //Does it contain the LS IPlugin?
							IPlugin *p_plugin = p_factory_function (); //Instanciate the plugin
							LOG ( LOG_INFO, _ ( "A plugin was found. Adding it to the list." ) );
							addPluginToList ( p_plugin, fullpath.string() ); //Add the plugin info to the audio plugins list

							p_cleanup_function ( p_plugin );
							g_module_close ( h_plugin );
						}
						else   //If doesn't implement our IPlugin interface entry points, close it
						{
							g_module_close( h_plugin );
						}
					}
				}
			}
		}
	}
	pcre_free(file_pattern);
}
Example #8
0
size_type filesys::file_size(const path & p)
{
    struct stat stats;
    if (stat(p.c_str(), &stats) != 0) return 0;
    return stats.st_size;
}
/// \brief Attempt to parse the specified options
///
/// \pre All previously added options_blocks must still exist
///
/// \pre The two parameters must be in the standard argc/argv configuration
///
/// Note that the two input parameters are taken const
/// (including the argv being (a pointer to) an array of const pointers *to const*)
/// so they will remain untouched.
///
/// \post The options will be parsed and ready for querying
void executable_options::parse_options(const int          &argc,  ///< The argc from command line parameters
                                       const char * const  argv[] ///< The argv from command line parameters
                                       ) {
	// Check the options haven't already been processed
	if (processed_options) {
		BOOST_THROW_EXCEPTION(invalid_argument_exception("Cannot process options once they have already been processed"));
	}

	// Create two options_description, one complete and another containing all visible options
	options_description full_po_desc   ( DEFAULT_PROG_OPS_LINE_LENGTH );
	options_description visible_po_desc( DEFAULT_PROG_OPS_LINE_LENGTH );

	// Frustratingly, Boost 1.41 (as used by orengobuild64) won't accept a const argv, so
	// it's necessary to construct a fake argc/argv here
	argc_argv_faker fake_argc_argv(argc, argv);
	int new_argc      = fake_argc_argv.get_argc();
	char * * new_argv = fake_argc_argv.get_argv();

	// Add each of the options_blocks to po_desc
	for (options_block * const options_block_ptr : all_options_blocks) {
		const options_description hidden_opts  = options_block_ptr->get_hidden_options_description(  DEFAULT_PROG_OPS_LINE_LENGTH );
		const options_description visible_opts = options_block_ptr->get_visible_options_description( DEFAULT_PROG_OPS_LINE_LENGTH );
		full_po_desc.add(    hidden_opts  );
		full_po_desc.add(    visible_opts );
		visible_po_desc.add( visible_opts );
	}

	// Attempt the parses and catch any exceptions
	//
	// The parses are performed in decreasing order of precedence
	// (ie options specified via the command line should take precedence over those
	//  specified via environment variables so it comes first)
	//
	// \todo If this gets any more complicated then consider putting each of these
	//       different parses into different objects (presumably of classes deriving from
	//       a single ABC).
	string parsing_approach = "";
	try {
		// Parse options from the command line
		parsing_approach = "from the command line";
		const positional_options_description positionals = get_positional_options();
		processed_options = true;
		store(
			command_line_parser(
				new_argc,
				new_argv
			).options(
				full_po_desc
			).positional(
				positionals
			).run(),
			vm
		);

		// Parse any environment variables prefixed with "CATH_TOOLS_"
		// and just silently ignore any unknown options
		parsing_approach = "from global environment variables with prefix " + CATH_TOOLS_ENVIRONMENT_VARIABLE_PREFIX;
		//! [Using env_var_option_name_handler]
		store(
			parse_environment(
				full_po_desc,
				env_var_option_name_handler(
					CATH_TOOLS_ENVIRONMENT_VARIABLE_PREFIX,
					true,
					full_po_desc
				)
			),
			vm
		);
		//! [Using env_var_option_name_handler]

		// Parse any configuration file called cath_tools.conf
		const path located_cath_tools_conf_file = find_file(CATH_TOOLS_CONF_FILE_SEARCH_PATH, CATH_TOOLS_CONF_FILE.string());
		if (!located_cath_tools_conf_file.empty()) {
//			cerr << "Parsing configuration from file " << CATH_TOOLS_CONF_FILE << endl;
			parsing_approach = "from the global configuration file " + located_cath_tools_conf_file.string();
			ifstream config_file_stream;
			open_ifstream(config_file_stream, CATH_TOOLS_CONF_FILE);
			store(parse_config_file(config_file_stream, full_po_desc, true), vm);
			config_file_stream.close();
		}

		// All parsing is complete so call notify, which will trigger any
		// post-parsing hooks to get called
		notify(vm);
	}
	catch (std::exception &e) {
		error_or_help_string = get_program_name() + ": Error in parsing program options (" + parsing_approach + "): " + e.what();
	}
	catch (...) {
		error_or_help_string = get_program_name() + ": Caught an unrecognised exception whilst parsing program options (" + parsing_approach + ").\n";
	}

	// If no error has yet been encountered
	// and if any of the blocks return non-empty invalid_string() results,
	// then set error_or_help_string to the first
	if (error_or_help_string.empty()) {
		for (options_block * const options_block_ptr : all_options_blocks) {
			const opt_str block_invalid_string = options_block_ptr->invalid_string();
			if ( block_invalid_string ) {
				error_or_help_string = *block_invalid_string;
				break;
			}
		}
	}

	// If an error string has already arisen from the parsing or from an options block being invalid...
	if (!error_or_help_string.empty()) {
		// ...and if doesn't already end with the standard usage error string
		// (eg "Try 'cath-ssap --help' for usage information.")
		// then append it now.
		if (!ends_with(error_or_help_string, get_standard_usage_error_string())) {
			error_or_help_string += ("\n" + get_standard_usage_error_string());
		}
	}
	// Else there is no error string yet, so now let the derived class consider then
	// set it to whatever the derived class decides
	else {
		error_or_help_string = do_update_error_or_help_string( visible_po_desc );
	}
}
Example #10
0
// ----------------------------------------------------------------------------
Track::Track(path file)
{
    m_valid = true;
    FILE* pFile;
    pFile = fopen(file.c_str(), "rb");

    if (!pFile)
    {
        m_valid = false;
        stringw emsg = _("Editor failed to open file:\n \"");
        emsg += file;
        emsg += "\"";

        MsgWndw::get()->showMsg(emsg);
        return;
    }

    // SIGN
    u64 sign;
    fread(&sign, sizeof(u64), 1, pFile);
    if (sign != TOP_SECRET_SIGNATURE_NUMBER)
    {
        MsgWndw::get()->showMsg(_("File can not be opened: signature failed."));
        m_valid = false;
        fclose(pFile);
        return;
    }

    // TRACK NAME
    u8 size;
    wchar_t* c;
    fread(&size, sizeof(u8), 1, pFile);
    if (!Editor::isValidSize(size))
    {
        fclose(pFile); m_valid = false;
        MsgWndw::get()->showMsg(_("File loading failed!"));
        return;
    }
    c = new wchar_t[size];
    fread(c, sizeof(wchar_t), size, pFile);
    m_track_name = c;
    delete[] c;

    // DESIGNER NAME
    fread(&size, sizeof(u8), 1, pFile);
    if (!Editor::isValidSize(size))
    {
        fclose(pFile); m_valid = false;
        MsgWndw::get()->showMsg(_("File loading failed!"));
        return;
    }
    c = new wchar_t[size];
    fread(c, sizeof(wchar_t), size, pFile);
    m_designer = c;
    delete[] c;

    // FILE NAME
    c8* cc;
    fread(&size, sizeof(u8), 1, pFile);
    if (!Editor::isValidSize(size))
    {
        fclose(pFile); m_valid = false;
        MsgWndw::get()->showMsg(_("File loading failed!"));
        return;
    }
    cc = new c8[size];
    fread(cc, sizeof(c8), size, pFile);
    m_file_name = cc;
    delete[] cc;

    // MUSIC
    fread(&size, sizeof(u8), 1, pFile);
    if (!Editor::isValidSize(size))
    {
        fclose(pFile); m_valid = false;
        MsgWndw::get()->showMsg(_("File loading failed!"));
        return;
    }
    cc = new c8[size];
    fread(cc, sizeof(c8), size, pFile);
    m_music = cc;
    delete[] cc;

    // TERRAIN
    ISceneManager* sm = Editor::getEditor()->getSceneManager();
    m_terrain = new Terrain(sm->getRootSceneNode(), sm, 1, pFile);

    if (!m_terrain->isValid())
    {
        fclose(pFile);
        MsgWndw::get()->showMsg(_("Loading failed :invalid terrain!"));
        m_valid = false;
        return;
    }

    // SKY

    Sky* s = Viewport::get()->getSky();
    delete s;

    s = new Sky(pFile);
    Viewport::get()->setSky(s);

    // GRAVITY ROAD FLAG
    fread(&m_gravity_road, sizeof(bool), 1, pFile);

    // ROADS

    fread(&size, sizeof(u8), 1, pFile);
    if (size < 0 || size > MAX_ROAD_NUM)
    {
        MsgWndw::get()->showMsg(_("Loading failed: invalid terrain!"));
    }
    else
    {
        if (size > 0)
        {
            m_driveline = new DriveLine(sm->getRootSceneNode(), sm, 0, pFile);
            if (!m_driveline->isValid())
            {
                std::cerr << _("Warning: invalid driveline!\n");
                ISpline* spline = new TCR(sm->getRootSceneNode(), sm, 0);
                m_driveline = new DriveLine(sm->getRootSceneNode(), sm, 0, spline, L"DriveLine");
            }
            m_roads.push_back(m_driveline);
            m_driveline->refresh();
        } // driveline
        for (u8 i = 1; i < size; i++)
        {
            std::unique_ptr<IRoad> r(new Road(sm->getRootSceneNode(), sm, 0, pFile));
            if (r->isValid())
            {
                m_roads.push_back(r.get());
                r->refresh();
                r->setWireFrame(false);
                Viewport::get()->setSplineMode(false);
		// Explicitly release r to prevent it from being deleted.
                r.release();
            }
            else std::cerr << "Warning: invalid road - skipped :(\n";
        } // roads
    } // valid roadnum

    // CHECKLINES

    Viewport::get()->loadCheckLines(pFile);

    // OBJECTS
    u32 num;
    fread(&num, sizeof(u32), 1, pFile);
    Viewport::setLastEntityID(num + MAGIC_NUMBER);

    for (u32 i = 0; i < num; i++)
    {
        ISceneNode* node = 0;
        vector3df pos, rot, sca;
        fread(&pos, sizeof(vector3df), 1, pFile);
        fread(&rot, sizeof(vector3df), 1, pFile);
        fread(&sca, sizeof(vector3df), 1, pFile);

        u8 size;
        fread(&size, sizeof(u8), 1, pFile);
        if (!Editor::isValidSize(size))
        {
            m_valid = false;
            MsgWndw::get()->showMsg(_("Loading failed!"));
            fclose(pFile);
            return;
        }
        c8 *name = new c8[size];
        fread(name, sizeof(c8), size, pFile);

        path p = name;
        if (p == path("banana") || p == path("item")
            || p == path("small-nitro") || p == path("big-nitro"))
        {
            node = loadItem(name);
        } // item
        else
        {
            node = sm->addAnimatedMeshSceneNode(sm->getMesh(p));
            node->setName(name);
        } // object
        if (node)
        {
            node->setPosition(pos);
            node->setRotation(rot);
            node->setScale(sca);
            node->setID(MAGIC_NUMBER + i + 1);
        }  // valid node
        else
        {
            std::cerr << "Warning: couldn't load object < " << name << " >!\n";
            num -= 1;
            i -= 1;
        } // invalid node
        delete[] name;
    }

    fclose(pFile);
} // Track - from file
Example #11
0
/***************************
Find liblightsparkBACKENDplugin libraries
****************************/
void PluginManager::findPlugins()
{
	//Search for all files under ${PRIVATELIBDIR}/plugins
	//Verify if they are audio plugins
	//If true, add to list of audio plugins
	string froot ( PRIVATELIBDIR ), fplugins ( "/plugins/" ); //LS should always look in the plugins folder, nowhere else
	const path plugins_folder = froot + fplugins;
	const string pattern ( "liblightspark+[A-Za-z]+plugin.so" );

	//Stuff used by/for pcre
	const char* patternError;
	int patternErrorOffset;
	pcre* file_pattern = pcre_compile ( pattern.c_str(), 0, &patternError, &patternErrorOffset, NULL );
	if(patternError)
		throw RunTimeException("PluginManager::findPlugins(): can't compile file_pattern");
	//We don't expect any captured substrings, so 3 ints should be enough
	int patternOvector[3];

#if defined DEBUG
	cout << "Looking for plugins under " << plugins_folder << " for pattern " << pattern << endl;
#endif

	if ( !is_directory ( plugins_folder ) )
	{
		LOG ( LOG_ERROR, _ ( ( ( string ) ( "The plugins folder doesn't exists under " + plugins_folder.string() ) ).c_str() ) );
	}
	else
	{
		for ( recursive_directory_iterator itr ( plugins_folder ), end_itr; itr != end_itr; ++itr )
		{
			if ( is_regular_file ( itr.status() ) )   //Is it a real file? This will remove symlink
			{
				string leaf_name = itr->path().filename();
				int rc=pcre_exec(file_pattern, NULL, leaf_name.c_str(), leaf_name.length(), 0, 0, patternOvector, 3);
				if ( rc > 0 )   // Does it answer to the desired pattern?
				{
					string fullpath = plugins_folder.directory_string() + leaf_name;
					//Try to load the file and see if it's an audio plugin
					if ( HMODULE h_plugin = LoadLib ( fullpath ) )
					{
						PLUGIN_FACTORY p_factory_function = ( PLUGIN_FACTORY ) ExtractLibContent ( h_plugin, "create" );
						PLUGIN_CLEANUP p_cleanup_function = ( PLUGIN_CLEANUP ) ExtractLibContent ( h_plugin, "release" );

						if ( p_factory_function != NULL && p_cleanup_function != NULL )   //Does it contain the LS IPlugin?
						{
							IPlugin *p_plugin = ( *p_factory_function ) (); //Instanciate the plugin
							LOG ( LOG_NO_INFO, _ ( "A plugin was found. Adding it to the list." ) );
							addPluginToList ( p_plugin, fullpath ); //Add the plugin info to the audio plugins list

							( *p_cleanup_function ) ( p_plugin );
							CloseLib ( h_plugin );
						}
						else   //If doesn't implement our IPlugin interface entry points, close it
						{
							CloseLib ( h_plugin );
						}
					}
				}
			}
		}
	}
	pcre_free(file_pattern);
}
Example #12
0
	void encrypt(path &filesPlace, path &keysPlace) {

		if (!groupes.size()) {
			std::cout << "Files are not grouped" << std::endl;
			return;
		}

		for (auto it : groupes) {

			std::ostringstream dataToEncode;
			auto group = it.second;

			for (auto currentFile : group) {

				std::ifstream input(filesPlace.string() + currentFile, std::ios::binary);
				if (!input.is_open()) {
					std::cout << "Wrong directory: " << filesPlace.string();
					exit(0);
				}

				//Obtaining file data
				std::string buffer((
					std::istreambuf_iterator<char >(input)),
					(std::istreambuf_iterator<char >()));


				
				//Encode to hex if file is an image
				if (it.first.second == IMAGE) {

					std::string encoded_image;
					bn::encode_b16(buffer.begin(), buffer.end(), std::back_inserter(encoded_image));
					dataToEncode << currentFile << std::endl << encoded_image.size() << std::endl << encoded_image;
				}
				else {

					dataToEncode << currentFile << std::endl << buffer.size() << std::endl << buffer;
				}

				input.close();
			}

			//Size of files to decode
			int size = dataToEncode.tellp();

			DES_cblock key;
			DES_random_key(&key);

			DES_key_schedule key_schedule;
			DES_set_key_checked(&key, &key_schedule);

			//ncbc block magic
			size_t len = (size + 7) / 8 * 8;
			char *output = new char[len + 1];

			DES_cblock ivec;
			memset((char*)&ivec, 0, sizeof(ivec));

			DES_ncbc_encrypt((unsigned char *)&dataToEncode.str()[0], 
				             (unsigned char *)output, size, &key_schedule, &ivec, DES_ENCRYPT);


			std::string Day = std::to_string(it.first.first);
			std::string Type = it.first.second == TEXT ? "txt" : "image";
			std::string encodedFileName = Type + "_" + Day;

			std::ofstream outputFile(filesPlace.string() + encodedFileName, 
				                     std::ofstream::in | std::ofstream::trunc | std::ofstream::binary);

			std::ofstream outputKey(keysPlace.string() + encodedFileName + "_key", 
				                     std::ofstream::in | std::ofstream::trunc | std::ofstream::binary);
			

			if (!outputFile.is_open()) {
				std::cout << "Cannot create output file: " << encodedFileName;
				exit(0);
			}
			outputFile.write(output, len);

			

			if (!outputKey.is_open()) {
				std::cout << "Cannot create output key for file: " << encodedFileName;
				exit(0);
			}
			outputKey.write((char *)key, sizeof(key));

			outputFile.close();
			outputKey.close();

		}
	}
Example #13
0
	void decrypt(path &filePlace, path &keyPlace) {
		
		std::ifstream fileToDecode(filePlace.string(), std::ios::binary);
		std::ifstream fileWithKey(keyPlace.string(), std::ios::binary);

		if (!fileToDecode.is_open()) {
			std::cout << "Cannot open file to decode: " << filePlace.filename().string();
			exit(0);
		}
		if (!fileWithKey.is_open()) {
			std::cout << "Cannot open file with key: " << keyPlace.filename().string();
			exit(0);
		}

		DES_cblock key;
		fileWithKey.read((char *)key, file_size(keyPlace));

		DES_key_schedule key_schedule;
		DES_set_key_checked(&key, &key_schedule);

		DES_cblock ivec;
		memset((char*)&ivec, 0, sizeof(ivec));

		char *inputData = new char[file_size(filePlace)];
		char *outputData = new char[file_size(filePlace)];
		memset(inputData, 0, file_size(filePlace));
		memset(outputData, 0, file_size(filePlace));
		fileToDecode.read(inputData, file_size(filePlace));

		DES_ncbc_encrypt((unsigned char *)inputData, (unsigned char *)outputData, 
			             file_size(filePlace), &key_schedule, &ivec, DES_DECRYPT);

		std::stringstream outputDataStream(outputData);
		std::string newFileName;
		std::string size;


		//Loop for file data
		while (std::getline(outputDataStream, newFileName)) {

			std::getline(outputDataStream, size);
			int fileSize = std::stoi(size);

			std::string newData;
			newData.resize(fileSize + 1);
			outputDataStream.read(&newData[0], fileSize);


			std::ofstream outputFile;

			//if on Linux
			if (filePlace.parent_path().string()[0] == '/') {
				outputFile.open(filePlace.parent_path().string() + "/" + newFileName,
				    			std::ofstream::out | std::ofstream::trunc | std::ofstream::binary);
			}
			else {
				outputFile.open(filePlace.parent_path().string() + "\\" + newFileName,
				             	std::ofstream::out | std::ofstream::trunc | std::ofstream::binary);
			}

			if (!outputFile.is_open()) {
				std::cout << "Cannot create new file: " << newFileName;
				exit(0);
			}


			//If it`s an image then decode back
			path p(newFileName);
			if (p.extension() != ".txt") {

				char *decoded_image = new char[fileSize + 1];
				bn::decode_b16(newData.begin(), newData.end(), decoded_image);

				outputFile.write(decoded_image, fileSize);
			}
			else {

				outputFile.write(&newData[0], fileSize);
			}

			outputFile.close();
		}


		fileToDecode.close();
		fileWithKey.close();

		delete[] inputData;
		delete[] outputData;
	}
Example #14
0
//! Like IGPUProgrammingServices::addShaderMaterial() (look there for a detailed description),
//! but tries to load the programs from files.
s32 CNullDriver::addHighLevelShaderMaterialFromFiles(
		const path& vertexShaderProgramFileName,
		const c8* vertexShaderEntryPointName,
		E_VERTEX_SHADER_TYPE vsCompileTarget,
		const path& pixelShaderProgramFileName,
		const c8* pixelShaderEntryPointName,
		E_PIXEL_SHADER_TYPE psCompileTarget,
		const path& geometryShaderProgramFileName,
		const c8* geometryShaderEntryPointName,
		E_GEOMETRY_SHADER_TYPE gsCompileTarget,
		E_PRIMITIVE_TYPE inType, E_PRIMITIVE_TYPE outType,
		u32 verticesOut,
		IShaderConstantSetCallBack* callback,
		E_MATERIAL_TYPE baseMaterial,
		s32 userData, E_GPU_SHADING_LANGUAGE shadingLang)
{
	IReadFile* vsfile = 0;
	IReadFile* psfile = 0;
	IReadFile* gsfile = 0;

	if (vertexShaderProgramFileName.size() )
	{
		vsfile = FileSystem->createAndOpenFile(vertexShaderProgramFileName);
		if (!vsfile)
		{
			Printer::log("Could not open vertex shader program file",
				vertexShaderProgramFileName, ELL_WARNING);
		}
	}

	if (pixelShaderProgramFileName.size() )
	{
		psfile = FileSystem->createAndOpenFile(pixelShaderProgramFileName);
		if (!psfile)
		{
			Printer::log("Could not open pixel shader program file",
				pixelShaderProgramFileName, ELL_WARNING);
		}
	}

	if (geometryShaderProgramFileName.size() )
	{
		gsfile = FileSystem->createAndOpenFile(geometryShaderProgramFileName);
		if (!gsfile)
		{
			Printer::log("Could not open geometry shader program file",
				geometryShaderProgramFileName, ELL_WARNING);
		}
	}

	s32 result = addHighLevelShaderMaterialFromFiles(
		vsfile, vertexShaderEntryPointName, vsCompileTarget,
		psfile, pixelShaderEntryPointName, psCompileTarget,
		gsfile, geometryShaderEntryPointName, gsCompileTarget,
		inType, outType, verticesOut,
		callback, baseMaterial, userData, shadingLang);

	if (psfile)
		psfile->releaseRef();

	if (vsfile)
		vsfile->releaseRef();

	if (gsfile)
		gsfile->releaseRef();

	return result;
}
Example #15
0
void __rename(const path& from, const path& to, std::error_code *ec) {
    if (::rename(from.c_str(), to.c_str()) == -1)
        set_or_throw(ec, "rename", from, to);
    else if (ec)
        ec->clear();
}
Example #16
0
    void file_name_check::inspect(
      const string & library_name,
      const path & full_path )
    {
      string::size_type pos;

      //  called for each file and directory, so only the leaf need be tested
      string const leaf( full_path.leaf().string() );

      //  includes only allowable characters
      if ( (pos = leaf.find_first_not_of( allowable )) != string::npos )
      {
        ++m_name_errors;
        error( library_name, full_path, loclink(full_path, string(name()))
            + " file or directory name contains unacceptable character '"
            + leaf[pos] + "'" );
      }

      //  allowable initial character
      if ( std::strchr( initial_char, leaf[0] ) == nullptr )
      {
        ++m_name_errors;
        error( library_name, full_path, loclink(full_path, string(name()))
            + " file or directory name begins with an unacceptable character" );
      }

      //  rules for dot characters differ slightly for directories and files
      if ( filesystem::is_directory( full_path ) )
      {
        if ( std::strchr( leaf.c_str(), '.' ) )
        {
          ++m_name_errors;
          error( library_name, full_path, loclink(full_path, string(name()))
              + " directory name contains a dot character ('.')" );
        }
      }
      //else // not a directory
      //{
      //  //  includes at most one dot character
      //  const char * first_dot = std::strchr( leaf.c_str(), '.' );
      //  if ( first_dot && std::strchr( first_dot+1, '.' ) )
      //  {
      //    ++m_name_errors;
      //    error( library_name, full_path, string(name())
      //        + " file name with more than one dot character ('.')" );
      //  }
      //}

      //  the path, including a presumed root, does not exceed the maximum size
      path const relative_path( relative_to( full_path, search_root_path() ) );
      const unsigned max_relative_path = 207; // ISO 9660:1999 sets this limit
      const string generic_root( "boost_X_XX_X/" );
      if ( relative_path.string().size() >
          ( max_relative_path - generic_root.size() ) )
      {
        ++m_name_errors;
        error( library_name, full_path,
            loclink(full_path, string(name()))
            + " path will exceed "
            + boost::lexical_cast<string>(max_relative_path)
            + " characters in a directory tree with a root in the form "
            + generic_root + ", and this exceeds ISO 9660:1999 limit of 207"  )
            ;
      }
    }
Example #17
0
void __resize_file(const path& p, std::uintmax_t size, std::error_code *ec) {
    if (::truncate(p.c_str(), static_cast<long>(size)) == -1)
        set_or_throw(ec, "resize_file", p);
    else if (ec)
        ec->clear();
}
Example #18
0
 void open( const path & file_ph,
   std::ios_base::openmode mode = std::ios_base::out )
 {
   std::basic_ofstream<charT,traits>::open(
     file_ph.native_file_string().c_str(), mode );
 }
Example #19
0
void get_files_in_dir(const std::string &dir,
                      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(path(dir).is_relative() && !game_config::path.empty()) {
		path absolute_dir(game_config::path);
		absolute_dir /= dir;
		if(is_directory_internal(absolute_dir)) {
			get_files_in_dir(absolute_dir.string(), files, dirs, mode, filter, reorder, checksum);
			return;
		}
	}

	const path dirpath(dir);

	if (reorder == DO_REORDER) {
		LOG_FS << "searching for _main.cfg in directory " << dir << '\n';
		const path maincfg = dirpath / maincfg_filename;

		if (file_exists(maincfg)) {
			LOG_FS << "_main.cfg found : " << maincfg << '\n';
			push_if_exists(files, maincfg, mode == ENTIRE_FILE_PATH);
			return;
		}
	}

	error_code ec;
	bfs::directory_iterator di(dirpath, ec);
	bfs::directory_iterator end;
	if (ec) {
		// Probably not a directory, let the caller deal with it.
		return;
	}
	for(; di != end; ++di) {
		bfs::file_status st = di->status(ec);
		if (ec) {
			LOG_FS << "Failed to get file status of " << di->path().string() << ": " << ec.message() << '\n';
			continue;
		}
		if (st.type() == bfs::regular_file) {
			{
				std::string basename = di->path().filename().string();
				if (filter == SKIP_PBL_FILES && looks_like_pbl(basename))
					continue;
				if(!basename.empty() && basename[0] == '.' )
					continue;
			}
			push_if_exists(files, di->path(), mode == ENTIRE_FILE_PATH);

			if (checksum != NULL) {
				std::time_t mtime = bfs::last_write_time(di->path(), ec);
				if (ec) {
					LOG_FS << "Failed to read modification time of " << di->path().string() << ": " << ec.message() << '\n';
				} else if (mtime > checksum->modified) {
					checksum->modified = mtime;
				}

				uintmax_t size = bfs::file_size(di->path(), ec);
				if (ec) {
					LOG_FS << "Failed to read filesize of " << di->path().string() << ": " << ec.message() << '\n';
				} else {
					checksum->sum_size += size;
				}
				checksum->nfiles++;
			}
		} else if (st.type() == bfs::directory_file) {
			std::string basename = di->path().filename().string();

			if(!basename.empty() && basename[0] == '.' )
				continue;
			if (filter == SKIP_MEDIA_DIR
				&& (basename == "images" || basename == "sounds"))
				continue;

			const path inner_main(di->path() / maincfg_filename);
			bfs::file_status main_st = bfs::status(inner_main, ec);
			if (error_except_not_found(ec)) {
				LOG_FS << "Failed to get file status of " << inner_main.string() << ": " << ec.message() << '\n';
			} else if (reorder == DO_REORDER && main_st.type() == bfs::regular_file) {
				LOG_FS << "_main.cfg found : " << (mode == ENTIRE_FILE_PATH ? inner_main.string() : inner_main.filename().string()) << '\n';
				push_if_exists(files, inner_main, mode == ENTIRE_FILE_PATH);
			} else {
				push_if_exists(dirs, di->path(), mode == ENTIRE_FILE_PATH);
			}
		}
	}

	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
		int foundit = -1;
		for (unsigned int i = 0; i < files->size(); i++)
			if (ends_with((*files)[i], "/" + initialcfg_filename)) {
				foundit = i;
				break;
			}
		if (foundit > 0) {
			std::string initialcfg = (*files)[foundit];
			for (unsigned int i = foundit; i > 0; i--)
				(*files)[i] = (*files)[i-1];
			(*files)[0] = initialcfg;
		}
	}
}
Example #20
0
 explicit basic_fstream( const path & file_ph,
   std::ios_base::openmode mode = std::ios_base::in|std::ios_base::out )
   : std::basic_fstream<charT,traits>(
   file_ph.native_file_string().c_str(), mode ) {}
Example #21
0
/** path to UTF-8 encoding. */
std::string toString(const path& p) 
{
  return p.generic_string();
}
Example #22
0
path path::combine(const path &p) const
{
    TCHAR combined[MAX_PATH];
    PathCombine(combined, p_.c_str(), p.to_string().c_str());
    return path(combined);
}
Example #23
0
 int path::compare(const path& p) const noexcept
 {
   return native() < p.native();
 }
Example #24
0
void __copy(const path& from, const path& to, copy_options options,
            std::error_code *ec)
{
    const bool sym_status = bool(options &
        (copy_options::create_symlinks | copy_options::skip_symlinks));

    const bool sym_status2 = bool(options &
        copy_options::copy_symlinks);

    std::error_code m_ec;
    struct ::stat f_st = {};
    const file_status f = sym_status || sym_status2
                                     ? detail::posix_lstat(from, f_st, &m_ec)
                                     : detail::posix_stat(from,  f_st, &m_ec);
    if (m_ec)
        return set_or_throw(m_ec, ec, "copy", from, to);

    struct ::stat t_st = {};
    const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec)
                                     : detail::posix_stat(to, t_st, &m_ec);

    if (not status_known(t))
        return set_or_throw(m_ec, ec, "copy", from, to);

    if (!exists(f) || is_other(f) || is_other(t)
        || (is_directory(f) && is_regular_file(t))
        || detail::stat_equivalent(f_st, t_st))
    {
        return set_or_throw(make_error_code(errc::function_not_supported),
                            ec, "copy", from, to);
    }

    if (ec) ec->clear();

    if (is_symlink(f)) {
        if (bool(copy_options::skip_symlinks & options)) {
            // do nothing
        } else if (not exists(t)) {
            __copy_symlink(from, to, ec);
        } else {
            set_or_throw(make_error_code(errc::file_exists),
                         ec, "copy", from, to);
        }
        return;
    }
    else if (is_regular_file(f)) {
        if (bool(copy_options::directories_only & options)) {
            // do nothing
        }
        else if (bool(copy_options::create_symlinks & options)) {
            __create_symlink(from, to, ec);
        }
        else if (bool(copy_options::create_hard_links & options)) {
            __create_hard_link(from, to, ec);
        }
        else if (is_directory(t)) {
            __copy_file(from, to / from.filename(), options, ec);
        } else {
            __copy_file(from, to, options, ec);
        }
        return;
    }
    else if (is_directory(f)) {
        if (not bool(copy_options::recursive & options) &&
            bool(copy_options::__in_recursive_copy & options))
        {
            return;
        }

        if (!exists(t)) {
            // create directory to with attributes from 'from'.
            __create_directory(to, from, ec);
            if (ec && *ec) { return; }
        }
        directory_iterator it = ec ? directory_iterator(from, *ec)
                                   : directory_iterator(from);
        if (ec && *ec) { return; }
        std::error_code m_ec;
        for (; it != directory_iterator(); it.increment(m_ec)) {
            if (m_ec) return set_or_throw(m_ec, ec, "copy", from, to);
            __copy(it->path(), to / it->path().filename(),
                   options | copy_options::__in_recursive_copy, ec);
            if (ec && *ec) { return; }
        }
    }
}
Example #25
0
 size_t hash_value(const path& p) noexcept
 {
   return std::hash<path::string_type>()(p.generic_string());
 }
Example #26
0
void __create_hard_link(const path& from, const path& to, std::error_code *ec){
    if (::link(from.c_str(), to.c_str()) == -1)
        set_or_throw(ec, "create_hard_link", from, to);
    else if (ec)
        ec->clear();
}
Example #27
0
string replace_ending(path file, string new_ending){
	string filename=file.string();
	filename.erase(filename.rfind(".")+1);
	return filename+new_ending;
}
Example #28
0
void __current_path(const path& p, std::error_code *ec) {
    if (::chdir(p.c_str()) == -1)
        set_or_throw(ec, "current_path", p);
    else if (ec)
        ec->clear();
}
Example #29
0
path canonical_parent(const path& pth, const path& base) {
  return canonical(pth.parent_path(), base) / pth.filename();
}
Example #30
0
u64 file_size(const path & p) {
	struct stat buf;
	return stat(p.string().c_str(), &buf) ? (u64)-1 : (u64)buf.st_size;
}