예제 #1
0
파일: Shortcuts.cpp 프로젝트: 9tong/YDWE
bool CreateOrUpdateShortcutLink(fs::path const& shortcut_path, fs::path const& target_path)
{
    bool shortcut_existed = fs::exists(shortcut_path);

    {
        base::com::unique_ptr<IShellLinkW> pShellLink;
        HRESULT hr = pShellLink.CreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER);
        if (FAILED(hr))
            return false;

        pShellLink->SetPath(target_path.c_str());

        base::com::unique_ptr<IPersistFile> pPf;
        hr = pPf.QueryFrom(pShellLink.get());
        if (FAILED(hr))
            return false;

        hr = pPf->Save(shortcut_path.c_str(), TRUE);
        if (FAILED(hr))
            return false;

    }

    if (shortcut_existed)
    {
        ::SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
    }
    else
    {
        ::SHChangeNotify(SHCNE_CREATE, SHCNF_PATH, shortcut_path.c_str(), NULL);
    }

    return true;
}
예제 #2
0
std::string Shader::parseShader( const fs::path &path, bool optional, int level )
{
	std::stringstream output;

	if( level > 32 ) {
		throw std::runtime_error( "Reached the maximum inclusion depth." );
		return std::string();
	}

	static const std::regex includeRegexp( "^[ ]*#[ ]*include[ ]+[\"<](.*)[\">].*" );

	std::ifstream input( path.c_str() );
	if( !input.is_open() ) {
		if( optional )
			return std::string();

		if( level == 0 ) {
			char msg[512];
			snprintf( msg, 512, "Failed to open shader file '%s'.", path.c_str() );
			throw std::runtime_error( msg );
		}
		else {
			char msg[512];
			snprintf( msg, 512, "Failed to open shader include file '%s'.", path.c_str() );
			throw std::runtime_error( msg );
		}

		return std::string();
	}

	// go through each line and process includes
	std::string line;
	std::smatch matches;

	while( std::getline( input, line ) ) {
		if( std::regex_search( line, matches, includeRegexp ) )
			output << parseShader( path.parent_path() / matches[1].str(), false, level + 1 );
		else
			output << line;

		output << std::endl;
	}

	input.close();

	// make sure #version is the first line of the shader
	if( level == 0 )
		return parseVersion( output.str() );
	else
		return output.str();
}
예제 #3
0
/// Applies a set of templates to an input file and writes an output file.
///
/// \param templates The templates to use.
/// \param input_file The path to the input to process.
/// \param output_file The path to the file into which to write the output.
///
/// \throw text::error If the input or output files cannot be opened.
/// \throw text::syntax_error If there is any problem processing the input.
void
text::instantiate(const templates_def& templates,
                  const fs::path& input_file, const fs::path& output_file)
{
    std::ifstream input(input_file.c_str());
    if (!input)
        throw text::error(F("Failed to open %s for read") % input_file);

    std::ofstream output(output_file.c_str());
    if (!output)
        throw text::error(F("Failed to open %s for write") % output_file);

    instantiate(templates, input, output);
}
예제 #4
0
/*
This function is still a proof of concept, it's probably rife with bugs, below
is a short (and incomplete) todo
 * "Basic" checks (Read/Write/File/Dir) checks for FAT32 filesystems which
   requires detecting the filesystem being used.
*/
void Check(fs::path const& file, acs::Type type) {
	DWORD file_attr = GetFileAttributes(file.c_str());
	if ((file_attr & INVALID_FILE_ATTRIBUTES) == INVALID_FILE_ATTRIBUTES) {
		switch (GetLastError()) {
			case ERROR_FILE_NOT_FOUND:
			case ERROR_PATH_NOT_FOUND:
				throw fs::FileNotFound(file);
			case ERROR_ACCESS_DENIED:
				throw fs::ReadDenied(file);
			default:
				throw fs::FileSystemUnknownError(str(boost::format("Unexpected error when getting attributes for \"%s\": %s") % file % util::ErrorString(GetLastError())));
		}
	}

	switch (type) {
		case FileRead:
		case FileWrite:
			if ((file_attr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
				throw fs::NotAFile(file);
			break;
		case DirRead:
		case DirWrite:
			if ((file_attr & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY)
				throw fs::NotADirectory(file);
			break;
	}

	SECURITY_INFORMATION info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION;
	DWORD len = 0;
	GetFileSecurity(file.c_str(), info, nullptr, 0, &len);
	if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
		LOG_W("acs/check") << "GetFileSecurity: fatal: " << util::ErrorString(GetLastError());

	std::vector<uint8_t> sd_buff(len);
	SECURITY_DESCRIPTOR *sd = (SECURITY_DESCRIPTOR *)&sd_buff[0];

	if (!GetFileSecurity(file.c_str(), info, sd, len, &len))
		LOG_W("acs/check") << "GetFileSecurity failed: " << util::ErrorString(GetLastError());

	ImpersonateSelf(SecurityImpersonation);
	HANDLE client_token;
	if (!OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, TRUE, &client_token))
		LOG_W("acs/check") << "OpenThreadToken failed: " << util::ErrorString(GetLastError());

	if (!check_permission(true, sd, client_token))
		throw fs::ReadDenied(file);
	if ((type == DirWrite || type == FileWrite) && !check_permission(false, sd, client_token))
		throw fs::WriteDenied(file);
}
예제 #5
0
파일: Output.cpp 프로젝트: Baron59/boss
	void BossLog::Save(const fs::path file, const bool overwrite) {
		if (fs::exists(file))
			recognisedHasChanged = HasRecognisedListChanged(file);

		ofstream outFile;
		if (overwrite)
			outFile.open(file.c_str());
		else
			outFile.open(file.c_str(), ios_base::out|ios_base::app);
		if (outFile.fail())
			throw boss_error(BOSS_ERROR_FILE_WRITE_FAIL, file.string());

		outFile << PrintLog();
		outFile.close();
	}
예제 #6
0
void trm::Database::createEntry(fs::path path, fs::path trashPath, std::size_t size)
{
    sqlite3_stmt *stmt;
    std::string objectName = trashPath.filename().string();
    const char *cPath = path.remove_filename().c_str();

    char sql[] =  "INSERT INTO trash (OBJECTNAME, FILESIZE, TRASHPATH, OLDPATH, DELETEDAT) "
                        "VALUES (?, ?, ?, ?, datetime('NOW', 'localtime'));";
    dbStatus = sqlite3_prepare(db, sql, -1, &stmt, 0);
    if (dbStatus != SQLITE_OK)
    {
        std::cout << "Database Error: " << errMsg << std::endl;
        exit(0);
    }

    if (sqlite3_bind_text(stmt, 1, objectName.c_str(), -1, SQLITE_STATIC) != SQLITE_OK)
        std::cout << "Database Bind Error: " << sqlite3_errmsg(db) << std::endl;
    if (sqlite3_bind_int(stmt, 2, static_cast<int>(size)) != SQLITE_OK)
        std::cout << "Database Bind Error: " << sqlite3_errmsg(db) << std::endl;
    if (sqlite3_bind_text(stmt, 3, trashPath.c_str(), -1, SQLITE_STATIC) != SQLITE_OK)
        std::cout << "Database Bind Error: " << sqlite3_errmsg(db) << std::endl;
    if (sqlite3_bind_text(stmt, 4, cPath, -1, SQLITE_STATIC))
        std::cout << "Database Bind Error: " << sqlite3_errmsg(db) << std::endl;

    if (sqlite3_step(stmt) != SQLITE_DONE)
        std::cout << "Database Execute Error: " << sqlite3_errmsg(db) << std::endl;
}
예제 #7
0
파일: Shortcuts.cpp 프로젝트: 9tong/YDWE
bool ResolveShortcut(fs::path const& shortcut_path, fs::path* target_path)
{
    HRESULT hr;
    base::com::unique_ptr<IShellLinkW> pShellLink;

    hr = pShellLink.CreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER);
    if (FAILED(hr))
        return false;

    base::com::unique_ptr<IPersistFile> pPf;

    hr = pPf.QueryFrom(pShellLink.get());
    if (FAILED(hr))
        return false;

    hr = pPf->Load(shortcut_path.c_str(), STGM_READ);
    if (FAILED(hr))
        return false;

    wchar_t temp[MAX_PATH];
    if (target_path)
    {
        hr = pShellLink->Resolve(0, SLR_NO_UI | SLR_NOSEARCH);
        if (FAILED(hr))
            return false;

        hr = pShellLink->GetPath(temp, MAX_PATH, NULL, SLGP_UNCPRIORITY);
        if (FAILED(hr))
            return false;

        *target_path = fs::path(temp);
    }

    return true;
}
예제 #8
0
bool ciWMFVideoPlayer::loadMovie( const fs::path &filePath, const string &audioDevice )
{
    if (!_player)
    {
        //ofLogError("ciWMFVideoPlayer") << "Player not created. Can't open the movie.";
        return false;
    }

    DWORD fileAttr = GetFileAttributesW( filePath.c_str() );
    if (fileAttr == INVALID_FILE_ATTRIBUTES)
    {
        CI_LOG_E( "The video file could not be found: '" << filePath );
        //ofLog(OF_LOG_ERROR,"ciWMFVideoPlayer:" + s.str());
        return false;
    }

    //CI_LOG_I( "Videoplayer[" << _id << "] loading " << name );
    HRESULT hr = S_OK;
    string s = filePath.string();
    std::wstring w(s.length(), L' ');
    std::copy(s.begin(), s.end(), w.begin());

    std::wstring a(audioDevice.length(), L' ');
    std::copy(audioDevice.begin(), audioDevice.end(), a.begin());

    hr = _player->OpenURL( w.c_str(), a.c_str() );
    if (!_sharedTextureCreated)
    {
        _width = _player->getWidth();
        _height = _player->getHeight();

        gl::Texture::Format format;
        format.setInternalFormat(GL_RGBA);
        format.setTargetRect();
        _tex = gl::Texture::create(_width,_height, format);
        //_tex.allocate(_width,_height,GL_RGBA,true);
        _player->m_pEVRPresenter->createSharedTexture(_width, _height, _tex->getId());
        _sharedTextureCreated = true;
    }
    else
    {
        if ((_width != _player->getWidth()) || (_height != _player->getHeight()))
        {
            _player->m_pEVRPresenter->releaseSharedTexture();

            _width = _player->getWidth();
            _height = _player->getHeight();

            gl::Texture::Format format;
            format.setInternalFormat(GL_RGBA);
            format.setTargetRect();
            _tex = gl::Texture::create(_width,_height, format);
            //_tex.allocate(_width,_height,GL_RGBA,true);
            _player->m_pEVRPresenter->createSharedTexture(_width, _height, _tex->getId());
        }
    }

    _waitForLoadedToPlay = false;
    return true;
}
예제 #9
0
void transform(fs::path xslt, std::string inputfile, std::string outputfile)
{
    auto stylesheet = xsltParseStylesheetFile(BAD_CAST xslt.c_str());
    auto doc = xmlParseFile(inputfile.c_str());

    const char *params = NULL;
    auto result = xsltApplyStylesheet(stylesheet, doc, &params);
    xsltSaveResultToFilename(outputfile.c_str(), result, stylesheet, 0);

    xmlFreeDoc(doc);
    xmlFreeDoc(result);
    xsltFreeStylesheet(stylesheet);
}
예제 #10
0
파일: file.cpp 프로젝트: chanchancl/YDWE
	std::string get_name(const fs::path& fil_path)
	{
		try
		{
			base::file::memory_mapped_file mmap(fil_path.c_str());
			const char* memory_ptr = static_cast<const char*>(mmap.memory());
			if (memory_ptr)
			{
				return get_name(memory_ptr);
			}
		}
		catch (std::exception const&) {}

		return std::move(std::string());
	}
예제 #11
0
파일: torch.cpp 프로젝트: aaalgo/xnn
    TorchModel (fs::path const &lua_config, fs::path const& model_path, int batch, int H, int W, int C)
        : state(luaL_newstate())
    // we are taking in input tensor shape here
    // will have to change code to get the shape from the lua_config
    {
        BOOST_VERIFY(batch >= 1);
        if (!state) throw std::runtime_error("failed to initialize Lua");
        luaL_openlibs(state);
        int result = luaL_loadfile(state, lua_config.c_str());
        if (result != 0) throw std::runtime_error("failed to load openface server");
        result = lua_pcall(state, 0, LUA_MULTRET, 0);
        if (result != 0) throw std::runtime_error("failed to run openface server");
        // call lua's setup with model path
        lua_getglobal(state, "setup");
        lua_pushstring(state, model_path.c_str());
        if (lua_pcall(state, 1, 0, 0) != 0) {
            throw std::runtime_error("fail to extract");
        }

        shape[0] = batch;
        shape[1] = C;
        shape[2] = H;
        shape[3] = W;
    }
예제 #12
0
void AssetReloader::reloadAsset( fs::path assetPath )
{
    
    //    console() << "reload :: " << mKeyList[ assetPath.c_str() ] << endl;
    
    string key = "";
    key = mKeyList[ assetPath.c_str() ];
    
    if( key != "" ){
        console() << "AssetReloader :: reloading asset :: " << assetPath.filename() << endl;
        load( assetPath.filename(), key );
        // fire signal
        sAssetReloaded();
    }else{
        console() << "AssetReloader :: can't reload " << assetPath.filename() << endl;
    }
}
예제 #13
0
std::string Database::getSHA(fs::path filepath) {
	LOG4CPLUS_DEBUG(logger, "Getting SHA for path " << filepath);

	boost::mutex::scoped_lock lock(dbMutex);
	sqlite3_bind_text(getSHAqueryStmt, 1, filepath.c_str(), filepath.string().size(), SQLITE_STATIC );

	int response = sqlite3_step(getSHAqueryStmt);
	std::string sha;

	if (SQLITE_ROW == response) {
		std::string resultPath;
		sha = (reinterpret_cast<const char*>(sqlite3_column_text(getSHAqueryStmt, 0)));
		LOG4CPLUS_DEBUG(logger, "Found SHA " << sha << " for file " << filepath);
	}

	sqlite3_reset(getSHAqueryStmt);

	return sha;
}
예제 #14
0
ProcessWithThread Process::launch(const fs::path& app, const wstring& args,
	optional<const vector<string>&> env,
	optional<const wstring&> cwd,
	bool inheritHandles, DWORD creationFlags,
	SECURITY_ATTRIBUTES* processAttributes, SECURITY_ATTRIBUTES* threadAttributes,
	STARTUPINFOW startupInfo)
{
	startupInfo.cb = sizeof(STARTUPINFOW); // needed
	PROCESS_INFORMATION pi = {};
	wstring commandLine = app.wstring() + L" " + args;

	if (!CreateProcessW(app.c_str(), &commandLine[0], processAttributes, threadAttributes, inheritHandles,
			creationFlags, nullptr, nullptr, &startupInfo, &pi))
	{
		DWORD errcode = GetLastError();
		BOOST_THROW_EXCEPTION(ex_injection() << e_api_function("CreateProcess") << e_last_error(errcode) << e_file(app));
	}
	else
		return ProcessWithThread(Process(pi.dwProcessId, pi.hProcess), Thread(pi.dwThreadId, pi.hThread));
}
예제 #15
0
bool Database::hasSHA(fs::path filepath) {
	boost::mutex::scoped_lock lock(dbMutex);

	LOG4CPLUS_DEBUG(logger, "Looking if " << filepath << " has SHA");

	sqlite3_bind_text(checkSHAStmt, 1, filepath.c_str(), filepath.string().size(), SQLITE_STATIC);


	sqlite3_step(checkSHAStmt);
		int response = sqlite3_column_int(checkSHAStmt, 0);
		sqlite3_reset(checkSHAStmt);

		if (response == 1) {
			return true;
		} else {
			return false;
		}

	return false;
}
예제 #16
0
bool Database::entryExists(fs::path filePath) {
boost::mutex::scoped_lock lock(dbMutex);
	const char* path = filePath.c_str();
	int pathSize = filePath.string().size();

	LOG4CPLUS_DEBUG(logger, "Looking for file " << path);

	sqlite3_bind_text(checkExistsStmt, 1, path, pathSize, SQLITE_STATIC);
	sqlite3_bind_text(checkExistsStmt, 2, path, pathSize, SQLITE_STATIC);

	sqlite3_step(checkExistsStmt);
	int response = sqlite3_column_int(checkExistsStmt, 0);
	sqlite3_reset(checkExistsStmt);

	if (response == 1) {
		return true;
	} else {
		return false;
	}
}
예제 #17
0
/// Opens a named on-disk SQLite database.
///
/// \param file The path to the database file to be opened.  This does not
///     accept the values "" and ":memory:"; use temporary() and in_memory()
///     instead.
/// \param open_flags The flags to be passed to the open routine.
///
/// \return A file-backed database instance.
///
/// \throw std::bad_alloc If there is not enough memory to open the database.
/// \throw api_error If there is any problem opening the database.
sqlite::database
sqlite::database::open(const fs::path& file, int open_flags)
{
    PRE_MSG(!file.str().empty(), "Use database::temporary() instead");
    PRE_MSG(file.str() != ":memory:", "Use database::in_memory() instead");

    int flags = 0;
    if (open_flags & open_readonly) {
        flags |= SQLITE_OPEN_READONLY;
        open_flags &= ~open_readonly;
    }
    if (open_flags & open_readwrite) {
        flags |= SQLITE_OPEN_READWRITE;
        open_flags &= ~open_readwrite;
    }
    if (open_flags & open_create) {
        flags |= SQLITE_OPEN_CREATE;
        open_flags &= ~open_create;
    }
    PRE(open_flags == 0);

    return database(impl::safe_open(file.c_str(), flags), true);
}
예제 #18
0
파일: UIFile.cpp 프로젝트: Geshishouhu/YDWE
	CUIBuffer CUIFile::LoadFile(fs::path const& name)
	{
		CUIBuffer buf;

		HANDLE hFile = ::CreateFileW(name.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		if (hFile == INVALID_HANDLE_VALUE) 
			return std::move(buf);

		DWORD dwSize = ::GetFileSize(hFile, NULL);
		if (dwSize == 0) 
			return std::move(buf);

		buf.reset(dwSize);
		DWORD dwRead = 0;
		BOOL r = ::ReadFile(hFile, buf.ptrData.get(), dwSize, &dwRead, NULL);
		::CloseHandle(hFile);

		if (!r || (dwRead != dwSize))
		{
			buf.reset();
		}

		return std::move(buf);
	}
예제 #19
0
파일: Shortcuts.cpp 프로젝트: 9tong/YDWE
bool TaskbarUnpinShortcutLink(fs::path const& shortcut_path)
{
    int result = reinterpret_cast<int>(::ShellExecute(NULL, L"taskbarunpin", shortcut_path.c_str(), NULL, NULL, 0));
    return result > 32;
}
예제 #20
0
void AssetReloader::load( const fs::path assetPath )
{
    load( assetPath, assetPath.c_str() );
}
예제 #21
0
  bool MemoryBuffer::lock(const fs::path &relativePath)
  {
    unlock();

    #if defined(CHR_FS_RC)
      if (!locked)
      {
        auto basePath = fs::path("res") / relativePath;
        auto found = win::RESOURCES.find(basePath.generic_string());

        if (found != win::RESOURCES.end())
        {
          int resId = found->second;
          HRSRC infoHandle = ::FindResource(NULL, MAKEINTRESOURCE(resId), RT_RCDATA);

          if (infoHandle)
          {
            HGLOBAL handle = ::LoadResource(NULL, infoHandle);

            if (handle)
            {
              _size = ::SizeofResource(NULL, infoHandle);
              _data = ::LockResource(handle);

              locked = true;
              return true;
            }
          }
        }
      }
    #elif defined(CHR_FS_APK)
      asset = AAssetManager_open(android::assetManager, relativePath.c_str(), AASSET_MODE_BUFFER);

      if (asset)
      {
        _size = AAsset_getLength(asset);
        _data = AAsset_getBuffer(asset);

        locked = true;
        return true;
      }
    #elif defined(FS_JS_EMBED) || defined(FS_JS_PRELOAD)
      auto fd = open(relativePath.c_str(), O_RDONLY);

      if (fd != -1)
      {
        struct stat stats;
        
        if ((fstat(fd, &stats) != -1) && (stats.st_size > 0))
        {
          _size = stats.st_size;
          _data = mmap(nullptr, size, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0);
          
          close(fd);
          
          if (_data != MAP_FAILED)
          {
            locked = true;
            return true;
          }
          
          _size = 0;
          _data = nullptr;
        }
      }
    #endif

    return false;
  }
void FollowablePath::write(const fs::path &path)
{
    ofstream out(path.c_str(), ifstream::binary);
    writeToStream(out);
    out.close();
}