コード例 #1
0
stringVector * FileDialog::doOpenMultiFilesDlg()
{
	TCHAR dir[MAX_PATH];
	::GetCurrentDirectory(MAX_PATH, dir);

	NppParameters * params = NppParameters::getInstance();
	_ofn.lpstrInitialDir = params->getWorkingDir();

	_ofn.Flags |= OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_ENABLESIZING;

	if (!params->useNewStyleSaveDlg())
	{
		_ofn.Flags |= OFN_ENABLEHOOK | OFN_NOVALIDATE;
		_ofn.lpfnHook = OFNHookProc;
	}

	BOOL res = ::GetOpenFileName(&_ofn);
	if (params->getNppGUI()._openSaveDir == dir_last)
	{
		::GetCurrentDirectory(MAX_PATH, dir);
		params->setWorkingDir(dir);
	}
	::SetCurrentDirectory(dir);

	if (res)
	{
		TCHAR* pFn = _fileName + lstrlen(_fileName) + 1;
		TCHAR fn[MAX_PATH*8];
		memset(fn, 0x0, sizeof(fn));

		if (!(*pFn))
		{
			_fileNames.push_back(generic_string(_fileName));
		}
		else
		{
			lstrcpy(fn, _fileName);
			if (fn[lstrlen(fn) - 1] != '\\')
				lstrcat(fn, TEXT("\\"));
		}

		int term = lstrlen(fn);

		while (*pFn)
		{
			fn[term] = '\0';
			lstrcat(fn, pFn);
			_fileNames.push_back(generic_string(fn));
			pFn += lstrlen(pFn) + 1;
		}

		return &_fileNames;
	}
	return nullptr;
}
コード例 #2
0
ファイル: chainbase.cpp プロジェクト: dbarobin/steem
   void database::open( const bfs::path& dir, uint32_t flags, size_t shared_file_size, const boost::any& database_cfg )
   {
      assert( dir.is_absolute() );
      bfs::create_directories( dir );
      if( _data_dir != dir ) close();

      _data_dir = dir;
      _database_cfg = database_cfg;

#ifndef ENABLE_MIRA
      auto abs_path = bfs::absolute( dir / "shared_memory.bin" );

      if( bfs::exists( abs_path ) )
      {
         _file_size = bfs::file_size( abs_path );
         if( shared_file_size > _file_size )
         {
            if( !bip::managed_mapped_file::grow( abs_path.generic_string().c_str(), shared_file_size - _file_size ) )
               BOOST_THROW_EXCEPTION( std::runtime_error( "could not grow database file to requested size." ) );

            _file_size = shared_file_size;
         }

         _segment.reset( new bip::managed_mapped_file( bip::open_only,
                                                       abs_path.generic_string().c_str()
                                                       ) );

         auto env = _segment->find< environment_check >( "environment" );
         if( !env.first || !( *env.first == environment_check()) ) {
            BOOST_THROW_EXCEPTION( std::runtime_error( "database created by a different compiler, build, or operating system" ) );
         }
      } else {
         _file_size = shared_file_size;
         _segment.reset( new bip::managed_mapped_file( bip::create_only,
                                                       abs_path.generic_string().c_str(), shared_file_size
                                                       ) );
         _segment->find_or_construct< environment_check >( "environment" )();
      }

      _flock = bip::file_lock( abs_path.generic_string().c_str() );
      if( !_flock.try_lock() )
         BOOST_THROW_EXCEPTION( std::runtime_error( "could not gain write access to the shared memory file" ) );
#else
      for( auto& item : _index_list )
      {
         item->open( _data_dir, _database_cfg );
      }
#endif
      _is_open = true;
   }
コード例 #3
0
ファイル: FileSystem.cpp プロジェクト: serengeor/TheEngine
bool FileSystem::SetWriteDirectory(const Path & path)
{
	auto posixPath = MakePosix(path);
	auto genericString = posixPath.generic_string();
	int32_t status = PHYSFS_setWriteDir(genericString.c_str());

	if (status == 0)
	{
		return false;
	}

	m_writeDirectory = posixPath.generic_string();
	return true;
}
コード例 #4
0
ファイル: Application.cpp プロジェクト: serengeor/TheEngine
bool Application::InitFileSystem()
{
	///set working directory to where the binary is.
	auto workingDirectory = GetContext().GetFileSystem()->GetWorkingDirectory();
	GetContext().GetFileSystem()->SetWriteDirectory(workingDirectory);

	///create directory for application
	auto applicationDirectory = Path(GetApplicationId());

	if (!GetContext().GetFileSystem()->CreateDirectory(applicationDirectory))
	{
		printf("%s\n", "Failed to create directory for current application.");
		exit(-1);
	}

	Path appendedPath = Path(workingDirectory).append(applicationDirectory.generic_string());
	GetContext().GetFileSystem()->SetWriteDirectory(appendedPath);
	GetContext().GetFileSystem()->AddSearchDirectory(appendedPath);


	auto & fileSystemVars = GetContext().GetApplicationSettingsManager()->GetGroup("filesystem");

	Path logPath(fileSystemVars.GetVar("log_path").ValueS());
	Path configPath(fileSystemVars.GetVar("config_path").ValueS());

	GetContext().GetFileSystem()->CreateDirectory(logPath);
	GetContext().GetFileSystem()->CreateDirectory(configPath);

	return true;
}
コード例 #5
0
config load_config( const fc::path& datadir )
{ try {
      auto config_file = datadir/"config.json";
      config cfg;
      if( fc::exists( config_file ) )
      {
         std::cout << "Loading config \"" << config_file.generic_string()  << "\"\n";
         cfg = fc::json::from_file( config_file ).as<config>();
      }
      else
      {
         std::cerr<<"Creating default config file \""<<config_file.generic_string()<<"\"\n";
         fc::json::save_to_file( cfg, config_file );
      }
      return cfg;
} FC_RETHROW_EXCEPTIONS( warn, "unable to load config file ${cfg}", ("cfg",datadir/"config.json")) }
コード例 #6
0
std::pair<std::string, std::string> ShaderManager::FindShaderCode(const std::string& name) const {
	std::string keyName = StripShaderName(name);
	std::string fileName = StripShaderName(name, false);

	// try it in direct source cache
	auto codeIt = m_codes.find(keyName);
	if (codeIt != m_codes.end()) {
		return { keyName, codeIt->second };
	}

	// try it in directories
	for (const auto& directory : m_directories) {
		auto filepath = directory / (fileName + ".hlsl");
		std::ifstream fs(filepath.c_str());
		if (fs.is_open()) {
			fs.seekg(0, std::ios::end);
			size_t s = fs.tellg();
			fs.seekg(0, std::ios::beg);
			std::unique_ptr<char[]> content = std::make_unique<char[]>(s + 1);
			fs.read(content.get(), s);
			content[s] = '\0';
			return { filepath.generic_string(), content.get() };
		}
	}

	throw FileNotFoundException("Shader was not found.", keyName + "(" + name + " as requested)");
}
コード例 #7
0
stringVector * FileDialog::doOpenMultiFilesDlg()
{
	TCHAR dir[MAX_PATH];
	::GetCurrentDirectory(MAX_PATH, dir);
	//_ofn.lpstrInitialDir = dir;

	NppParameters * params = NppParameters::getInstance();
	_ofn.lpstrInitialDir = params->getWorkingDir();

	_ofn.Flags |= OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT;

	BOOL res = ::GetOpenFileName(&_ofn);
	if (params->getNppGUI()._openSaveDir == dir_last)
	{
		::GetCurrentDirectory(MAX_PATH, dir);
		params->setWorkingDir(dir);
	}
	::SetCurrentDirectory(dir); 

	if (res)
	{
		TCHAR fn[MAX_PATH];
		TCHAR *pFn = _fileName + lstrlen(_fileName) + 1;
		if (!(*pFn))
			_fileNames.push_back(generic_string(_fileName));
		else
		{
			lstrcpy(fn, _fileName);
			if (fn[lstrlen(fn)-1] != '\\')
				lstrcat(fn, TEXT("\\"));
		}
		int term = int(lstrlen(fn));

		while (*pFn)
		{
			fn[term] = '\0';
			lstrcat(fn, pFn);
			_fileNames.push_back(generic_string(fn));
			pFn += lstrlen(pFn) + 1;
		}

		return &_fileNames;
	}
	else
		return NULL;
}
コード例 #8
0
ファイル: Common.cpp プロジェクト: JuneZhao/notepad-plus-plus
generic_string uintToString(unsigned int val)
{
	std::vector<TCHAR> vt;

	vt.push_back('0' + (TCHAR)(val % 10));
	val /= 10;
	while (val != 0) {
		vt.push_back('0' + (TCHAR)(val % 10));
		val /= 10;
	}

	return generic_string(vt.rbegin(), vt.rend());
}
コード例 #9
0
generic_string Buffer::getFileTime(fileTimeType ftt) const
{
	if (_currentStatus == DOC_UNNAMED)
		return generic_string();

	struct _stat buf;

	if (PathFileExists(_fullPathName.c_str()))
	{
		if (!generic_stat(_fullPathName.c_str(), &buf))
		{
			time_t rawtime = (ftt == ft_created ? buf.st_ctime : (ftt == ft_modified ? buf.st_mtime : buf.st_atime));
			tm *timeinfo = localtime(&rawtime);
			const int temBufLen = 64;
			TCHAR tmpbuf[temBufLen];

			generic_strftime(tmpbuf, temBufLen, TEXT("%Y-%m-%d %H:%M:%S"), timeinfo);
			return tmpbuf;
		}
	}

	return generic_string();
}
コード例 #10
0
ファイル: FileSystem.cpp プロジェクト: serengeor/TheEngine
bool FileSystem::AddSearchDirectory(const Path & path)
{
	auto posixPath = MakePosix(path);
	auto genericString = posixPath.generic_string();
	int32_t status = PHYSFS_mount(genericString.c_str(), NULL, 0);

	if (status == 0)
	{
		return false;
	}

	m_searchDirectories.push_back(path);
	return true;
}
コード例 #11
0
BufferID Notepad_plus::doOpen(const TCHAR *fileName, bool isReadOnly, int encoding)
{
	NotepadFile notepadFile(fileName, encoding);

	if (encoding == -1)
		notepadFile.setEncoding(getHtmlXmlEncoding(notepadFile.getLongFileName()));

	bool isNewDocument = generic_string(fileName).find_first_of(PREFIX_FOR_NEW_DOCUMENT_NAMES) == 0;
	BufferID existingBuffer = MainFileManager->getBufferFromName(isNewDocument ? fileName : notepadFile.getLongFileName());
	if (existingBuffer != BUFFER_INVALID) {
		updateTray();
		return existingBuffer;
	}

	return openFileThatIsntOpenedYet(notepadFile, isReadOnly);
}
コード例 #12
0
ファイル: file_manager.cpp プロジェクト: AnkyrinRepeat/mongo
std::vector<boost::filesystem::path> FTDCFileManager::scanDirectory() {
    std::vector<boost::filesystem::path> files;

    boost::filesystem::directory_iterator di(_path);
    for (; di != boost::filesystem::directory_iterator(); di++) {
        boost::filesystem::directory_entry& de = *di;
        auto filename = de.path().filename();

        std::string str = filename.generic_string();
        if (str.compare(0, strlen(kFTDCArchiveFile), kFTDCArchiveFile) == 0 &&
            str != kFTDCInterimFile) {
            files.emplace_back(_path / filename);
        }
    }

    std::sort(files.begin(), files.end());

    return files;
}
コード例 #13
0
ファイル: Common.cpp プロジェクト: JuneZhao/notepad-plus-plus
generic_string intToString(int val)
{
	std::vector<TCHAR> vt;
	bool isNegative = val < 0;
	// can't use abs here because std::numeric_limits<int>::min() has no positive representation
	//val = std::abs(val);

	vt.push_back('0' + (TCHAR)(std::abs(val % 10)));
	val /= 10;
	while (val != 0) {
		vt.push_back('0' + (TCHAR)(std::abs(val % 10)));
		val /= 10;
	}

	if (isNegative)
		vt.push_back('-');

	return generic_string(vt.rbegin(), vt.rend());
}
コード例 #14
0
ファイル: NppIO.cpp プロジェクト: Oldes/npp-community
const TCHAR * Notepad_plus::fileSaveSession(size_t nbFile, TCHAR ** fileNames, const TCHAR *sessionFile2save)
{
	if (sessionFile2save)
	{
		Session currentSession;
		if ((nbFile) && (fileNames))
		{
			for (size_t i = 0 ; i < nbFile ; i++)
			{
				if (PathFileExists(fileNames[i]))
					currentSession._mainViewFiles.push_back(generic_string(fileNames[i]));
			}
		}
		else
			getCurrentOpenedFiles(currentSession);

		(NppParameters::getInstance())->writeSession(&currentSession, sessionFile2save);
		return sessionFile2save;
	}
	return NULL;
}
コード例 #15
0
bool ReadWithStbi(const std::string& path, const filesystem::path& base_path,
                  std::vector<std::unique_ptr<unsigned char, TextureDeleter>>* textures,
                  std::vector<Rendering::Texture::ImageData>* data) {
  auto full_path = base_path / path;

  int current_image_width;
  int current_image_height;
  int current_image_components;
  auto image = stbi_load(full_path.generic_string().c_str(), &current_image_width, &current_image_height, &current_image_components, STBI_default);
  textures->emplace_back(image);

  auto dxgi_format = StbiComponentsToDxgiFormat(current_image_components);
  if (dxgi_format == DXGI_FORMAT_UNKNOWN) {
    DXFW_TRACE(__FILE__, __LINE__, false, "Unsupported number of components from STBI: %d", current_image_components);
    return false;
  }

  data->emplace_back(current_image_width, current_image_height, current_image_components, dxgi_format, image);

  return true;
}
コード例 #16
0
bool FileManager::deleteCurrentBufferBackup()
{
	HANDLE writeEvent = ::OpenEvent(EVENT_ALL_ACCESS, TRUE, TEXT("nppWrittingEvent"));
	if (!writeEvent)
	{
		// no thread yet, create a event with non-signaled, to block all threads
		writeEvent = ::CreateEvent(NULL, TRUE, FALSE, TEXT("nppWrittingEvent"));
	}
	else
	{
		if (::WaitForSingleObject(writeEvent, INFINITE) != WAIT_OBJECT_0)
		{
			// problem!!!
			printStr(TEXT("WaitForSingleObject problem in deleteCurrentBufferBackup()!"));
			return false;
		}

		// unlocled here, set to non-signaled state, to block all threads
		::ResetEvent(writeEvent);
	}

	EventReset reset(writeEvent); // Will reset event in destructor.

	Buffer* buffer = _pNotepadPlus->getCurrentBuffer();
	bool result = true;
	generic_string backupFilePath = buffer->getBackupFileName();
	if (not backupFilePath.empty())
	{
		// delete backup file
		buffer->setBackupFileName(generic_string());
		result = (::DeleteFile(backupFilePath.c_str()) != 0);
	}

	// set to signaled state via destructor EventReset.
	return result;
}
コード例 #17
0
/*
Specs and Algorithm of session snapshot & periodic backup system:
Notepad++ quits without asking for saving unsaved file.
It restores all the unsaved files and document as the states they left.

For existing file (c:\tmp\foo.h)
	- Open
	In the next session, Notepad++
	1. load backup\FILENAME@CREATION_TIMESTAMP (backup\foo.h@198776) if exist, otherwise load FILENAME (c:\tmp\foo.h).
	2. if backup\FILENAME@CREATION_TIMESTAMP (backup\foo.h@198776) is loaded, set it dirty (red).
	3. if backup\FILENAME@CREATION_TIMESTAMP (backup\foo.h@198776) is loaded, last modif timestamp of FILENAME (c:\tmp\foo.h), compare with tracked timestamp (in session.xml).
	4. in the case of unequal result, tell user the FILENAME (c:\tmp\foo.h) was modified. ask user if he want to reload FILENAME(c:\tmp\foo.h)

	- Editing
	when a file starts being modified, a file will be created with name: FILENAME@CREATION_TIMESTAMP (backup\foo.h@198776)
	the Buffer object will associate with this FILENAME@CREATION_TIMESTAMP file (backup\foo.h@198776).
	1. sync: (each 3-5 second) backup file will be saved, if buffer is dirty, and modification is present (a bool on modified notificatin).
	2. sync: each save file, or close file, the backup file will be deleted (if buffer is not dirty).
	3. before switch off to another tab (or close files on exit), check 1 & 2 (sync with backup).

	- Close
	In the current session, Notepad++
	1. track FILENAME@CREATION_TIMESTAMP (backup\foo.h@198776) if exist (in session.xml).
	2. track last modified timestamp of FILENAME (c:\tmp\foo.h) if FILENAME@CREATION_TIMESTAMP (backup\foo.h@198776) was tracked  (in session.xml).

For untitled document (new  4)
	- Open
	In the next session, Notepad++
	1. open file UNTITLED_NAME@CREATION_TIMESTAMP (backup\new  4@198776)
	2. set label as UNTITLED_NAME (new  4) and disk icon as red.

	- Editing
	when a untitled document starts being modified, a backup file will be created with name: UNTITLED_NAME@CREATION_TIMESTAMP (backup\new  4@198776)
	the Buffer object will associate with this UNTITLED_NAME@CREATION_TIMESTAMP file (backup\new  4@198776).
	1. sync: (each 3-5 second) backup file will be saved, if buffer is dirty, and modification is present (a bool on modified notificatin).
	2. sync: if untitled document is saved, or closed, the backup file will be deleted.
	3. before switch off to another tab (or close documents on exit), check 1 & 2 (sync with backup).

	- CLOSE
	In the current session, Notepad++
	1. track UNTITLED_NAME@CREATION_TIMESTAMP (backup\new  4@198776) in session.xml.
*/
bool FileManager::backupCurrentBuffer()
{
	LongRunningOperation op;

	Buffer* buffer = _pNotepadPlus->getCurrentBuffer();
	bool result = false;
	bool hasModifForSession = false;

	if (buffer->isDirty())
	{
		if (buffer->isModified()) // buffer dirty and modified, write the backup file
		{
			// Synchronization
			// This method is called from 2 differents place, so synchronization is important
			HANDLE writeEvent = ::OpenEvent(EVENT_ALL_ACCESS, TRUE, TEXT("nppWrittingEvent"));
			if (!writeEvent)
			{
				// no thread yet, create a event with non-signaled, to block all threads
				writeEvent = ::CreateEvent(NULL, TRUE, FALSE, TEXT("nppWrittingEvent"));
			}
			else
			{
				if (::WaitForSingleObject(writeEvent, INFINITE) != WAIT_OBJECT_0)
				{
					// problem!!!
					printStr(TEXT("WaitForSingleObject problem in backupCurrentBuffer()!"));
					return false;
				}

				// unlocled here, set to non-signaled state, to block all threads
				::ResetEvent(writeEvent);
			}

			UniMode mode = buffer->getUnicodeMode();
			if (mode == uniCookie)
				mode = uni8Bit;	//set the mode to ANSI to prevent converter from adding BOM and performing conversions, Scintilla's data can be copied directly

			Utf8_16_Write UnicodeConvertor;
			UnicodeConvertor.setEncoding(mode);
			int encoding = buffer->getEncoding();

			generic_string backupFilePath = buffer->getBackupFileName();
			if (backupFilePath.empty())
			{
				// Create file
				backupFilePath = NppParameters::getInstance()->getUserPath();
				backupFilePath += TEXT("\\backup\\");

				// if "backup" folder doesn't exist, create it.
				if (!PathFileExists(backupFilePath.c_str()))
				{
					::CreateDirectory(backupFilePath.c_str(), NULL);
				}

				backupFilePath += buffer->getFileName();

				const int temBufLen = 32;
				TCHAR tmpbuf[temBufLen];
				time_t ltime = time(0);
				struct tm* today = localtime(&ltime);
				generic_strftime(tmpbuf, temBufLen, TEXT("%Y-%m-%d_%H%M%S"), today);

				backupFilePath += TEXT("@");
				backupFilePath += tmpbuf;

				// Set created file name in buffer
				buffer->setBackupFileName(backupFilePath);

				// Session changes, save it
				hasModifForSession = true;
			}

			TCHAR fullpath[MAX_PATH];
			::GetFullPathName(backupFilePath.c_str(), MAX_PATH, fullpath, NULL);
			::GetLongPathName(fullpath, fullpath, MAX_PATH);

			// Make sure the backup file is not read only
			DWORD dwFileAttribs = ::GetFileAttributes(fullpath);
			if (dwFileAttribs & FILE_ATTRIBUTE_READONLY) // if file is read only, remove read only attribute
			{
				dwFileAttribs ^= FILE_ATTRIBUTE_READONLY;
				::SetFileAttributes(fullpath, dwFileAttribs);
			}

			FILE *fp = UnicodeConvertor.fopen(fullpath, TEXT("wb"));
			if (fp)
			{
				int lengthDoc = _pNotepadPlus->_pEditView->getCurrentDocLen();
				char* buf = (char*)_pNotepadPlus->_pEditView->execute(SCI_GETCHARACTERPOINTER);	//to get characters directly from Scintilla buffer
				size_t items_written = 0;
				if (encoding == -1) //no special encoding; can be handled directly by Utf8_16_Write
				{
					items_written = UnicodeConvertor.fwrite(buf, lengthDoc);
					if (lengthDoc == 0)
						items_written = 1;
				}
				else
				{
					WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
					int grabSize;
					for (int i = 0; i < lengthDoc; i += grabSize)
					{
						grabSize = lengthDoc - i;
						if (grabSize > blockSize)
							grabSize = blockSize;

						int newDataLen = 0;
						int incompleteMultibyteChar = 0;
						const char *newData = wmc->encode(SC_CP_UTF8, encoding, buf+i, grabSize, &newDataLen, &incompleteMultibyteChar);
						grabSize -= incompleteMultibyteChar;
						items_written = UnicodeConvertor.fwrite(newData, newDataLen);
					}
					if (lengthDoc == 0)
						items_written = 1;
				}
				UnicodeConvertor.fclose();

				// Note that fwrite() doesn't return the number of bytes written, but rather the number of ITEMS.
				if(items_written == 1) // backup file has been saved
				{
					buffer->setModifiedStatus(false);
					result = true;	//all done
				}
			}
			// set to signaled state
			if (::SetEvent(writeEvent) == NULL)
			{
				printStr(TEXT("oups!"));
			}
			// printStr(TEXT("Event released!"));
			::CloseHandle(writeEvent);
		}
		else // buffer dirty but unmodified
		{
			result = true;
		}
	}
	else // buffer not dirty, sync: delete the backup file
	{
		generic_string backupFilePath = buffer->getBackupFileName();
		if (not backupFilePath.empty())
		{
			// delete backup file
			generic_string file2Delete = buffer->getBackupFileName();
			buffer->setBackupFileName(generic_string());
			result = (::DeleteFile(file2Delete.c_str()) != 0);

			// Session changes, save it
			hasModifForSession = true;
		}
		//printStr(TEXT("backup deleted in backupCurrentBuffer"));
		result = true; // no backup file to delete
	}
	//printStr(TEXT("backup sync"));

	if (result && hasModifForSession)
	{
		//printStr(buffer->getBackupFileName().c_str());
		_pNotepadPlus->saveCurrentSession();
	}
	return result;
}
コード例 #18
0
ファイル: path.hpp プロジェクト: JieHUUU317/IN55
 const std::string   generic_string() const { return generic_string(codecvt()); } 
コード例 #19
0
 fc::variant execute_interactive_command(const std::string& command, const fc::variants& arguments)
 {
   if (command == "wallet_create" || command == "wallet_change_passphrase")
   {
       if( command == "wallet_create" )
       {
           auto wallet_name = arguments[0].as_string();
           if( fc::exists( _client->get_wallet()->get_data_directory() / wallet_name ) )
           {
             std::cout << "Wallet \"" << wallet_name << "\" already exists\n";
             FC_THROW_EXCEPTION(invalid_arg_exception, "");
           }
       }
       return execute_wallet_command_with_passphrase_query( command, arguments, "new passphrase", true );
   }
   else if ( command == "unlock" || 
             command == "open"   || 
             command == "wallet_open" || 
             command == "wallet_open_file" || command == "wallet_unlock")
   {
       if( command == "wallet_open" || command == "open" )
       {
           auto wallet_name = arguments[0].as_string();
           if( !fc::exists( _client->get_wallet()->get_data_directory() / wallet_name ) )
           {
             std::cout << "Wallet \"" << wallet_name << "\" not found\n";
             FC_THROW_EXCEPTION(invalid_arg_exception, "");
           }
       }
       else if( command == "wallet_open_file" )
       {
           auto filename = arguments[0].as<fc::path>();
           if( !fc::exists( filename ) )
           {
              std::cout << "File \"" << filename.generic_string() << "\" not found\n";
              FC_THROW_EXCEPTION(invalid_arg_exception, "");
           }
       }
       return execute_wallet_command_with_passphrase_query( command, arguments, "passphrase" );
   }
   else if (command == "wallet_import_bitcoin")
   {
       auto filename = arguments[0].as<fc::path>();
       if( !fc::exists( filename ) )
       {
          std::cout << "File \"" << filename.generic_string() << "\" not found\n";
          FC_THROW_EXCEPTION(invalid_arg_exception, "");
       }
       try /* Try empty password first */
       {
           auto new_arguments = arguments;
           new_arguments.push_back( fc::variant( "" ) );
           return _rpc_server->direct_invoke_method( command, new_arguments );
       }
       catch( const fc::exception& e )
       {
          ilog( "failed with empty password: ${e}", ("e",e.to_detail_string() ) );
       }
       return execute_wallet_command_with_passphrase_query( command, arguments, "imported wallet passphrase" );
   }
   else if (command == "wallet_export_to_json")
   {
       auto filename = arguments[0].as<fc::path>();
       if( fc::exists( filename ) )
       {
          std::cout << "File \"" << filename.generic_string() << "\" already exists\n";
          FC_THROW_EXCEPTION(invalid_arg_exception, "");
       }
   }
   else if (command == "wallet_create_from_json")
   {
       auto filename = arguments[0].as<fc::path>();
       auto wallet_name = arguments[1].as_string();
       if( !fc::exists( filename ) )
       {
          std::cout << "File \"" << filename.generic_string() << "\" not found\n";
          FC_THROW_EXCEPTION(invalid_arg_exception, "");
       }
       if( fc::exists( _client->get_wallet()->get_data_directory() / wallet_name ) )
       {
         std::cout << "Wallet \"" << wallet_name << "\" already exists\n";
         FC_THROW_EXCEPTION(invalid_arg_exception, "");
       }
       return execute_wallet_command_with_passphrase_query( command, arguments, "imported wallet passphrase" );
   }
   else if(command == "wallet_rescan_blockchain")
   {
       if ( ! _client->get_wallet()->is_open() )
           interactive_open_wallet();
       std::cout << "Rescanning blockchain...\n";
       uint32_t start;
       if (arguments.size() == 0)
           start = 1;
       else
           start = arguments[0].as<uint32_t>();
       while(true)
       {
           try {
               for(int i = 0; i < 100; i++)
                   std::cout << "-";
               std::cout << "\n";
               uint32_t next_step = 0;
               auto cb = [start, next_step](uint32_t cur,
                                            uint32_t last,
                                            uint32_t cur_trx,
                                            uint32_t last_trx) mutable
               {
                   if (((100*(cur - start)) / (last - start)) > next_step)
                   {
                       std::cout << "=";
                       next_step++;
                   }
               };
               _client->get_wallet()->scan_chain(start, cb);
               std::cout << "\n";
               return fc::variant("Scan complete.");
           }
           catch( const rpc_wallet_open_needed_exception& )
           {
               interactive_open_wallet();
           }
       }
   }
   else if(command == "quit")
   {
     FC_THROW_EXCEPTION(canceled_exception, "quit command issued");
   }
   
   return execute_command(command, arguments);
 }
コード例 #20
0
bool FileManager::saveBuffer(BufferID id, const TCHAR * filename, bool isCopy, generic_string * error_msg)
{
	HANDLE writeEvent = ::OpenEvent(EVENT_ALL_ACCESS, TRUE, TEXT("nppWrittingEvent"));
	if (!writeEvent)
	{
		// no thread yet, create a event with non-signaled, to block all threads
		writeEvent = ::CreateEvent(NULL, TRUE, FALSE, TEXT("nppWrittingEvent"));
	}
	else
	{		//printStr(TEXT("Locked. I wait."));
		if (::WaitForSingleObject(writeEvent, INFINITE) != WAIT_OBJECT_0)
		{
			// problem!!!
			printStr(TEXT("WaitForSingleObject problem in saveBuffer()!"));
			return false;
		}

		// unlocled here, set to non-signaled state, to block all threads
		::ResetEvent(writeEvent);
	}

	EventReset reset(writeEvent); // Will reset event in destructor.
	Buffer* buffer = getBufferByID(id);
	bool isHidden = false;
	bool isSys = false;
	DWORD attrib = 0;

	TCHAR fullpath[MAX_PATH];
	::GetFullPathName(filename, MAX_PATH, fullpath, NULL);
	::GetLongPathName(fullpath, fullpath, MAX_PATH);
	if (PathFileExists(fullpath))
	{
		attrib = ::GetFileAttributes(fullpath);

		if (attrib != INVALID_FILE_ATTRIBUTES)
		{
			isHidden = (attrib & FILE_ATTRIBUTE_HIDDEN) != 0;
			if (isHidden)
				::SetFileAttributes(filename, attrib & ~FILE_ATTRIBUTE_HIDDEN);

			isSys = (attrib & FILE_ATTRIBUTE_SYSTEM) != 0;
			if (isSys)
				::SetFileAttributes(filename, attrib & ~FILE_ATTRIBUTE_SYSTEM);
		}
	}

	UniMode mode = buffer->getUnicodeMode();
	if (mode == uniCookie)
		mode = uni8Bit;	//set the mode to ANSI to prevent converter from adding BOM and performing conversions, Scintilla's data can be copied directly

	Utf8_16_Write UnicodeConvertor;
	UnicodeConvertor.setEncoding(mode);

	int encoding = buffer->getEncoding();

	FILE *fp = UnicodeConvertor.fopen(fullpath, TEXT("wb"));
	if (fp)
	{
		_pscratchTilla->execute(SCI_SETDOCPOINTER, 0, buffer->_doc);	//generate new document

		int lengthDoc = _pscratchTilla->getCurrentDocLen();
		char* buf = (char*)_pscratchTilla->execute(SCI_GETCHARACTERPOINTER);	//to get characters directly from Scintilla buffer
		size_t items_written = 0;
		if (encoding == -1) //no special encoding; can be handled directly by Utf8_16_Write
		{
			items_written = UnicodeConvertor.fwrite(buf, lengthDoc);
			if (lengthDoc == 0)
				items_written = 1;
		}
		else
		{
			WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
			int grabSize;
			for (int i = 0; i < lengthDoc; i += grabSize)
			{
				grabSize = lengthDoc - i;
				if (grabSize > blockSize)
					grabSize = blockSize;

				int newDataLen = 0;
				int incompleteMultibyteChar = 0;
				const char *newData = wmc->encode(SC_CP_UTF8, encoding, buf+i, grabSize, &newDataLen, &incompleteMultibyteChar);
				grabSize -= incompleteMultibyteChar;
				items_written = UnicodeConvertor.fwrite(newData, newDataLen);
			}
			if (lengthDoc == 0)
				items_written = 1;
		}

		UnicodeConvertor.fclose();

		// Error, we didn't write the entire document to disk.
		// Note that fwrite() doesn't return the number of bytes written, but rather the number of ITEMS.
		if(items_written != 1)
		{
			if(error_msg != NULL)
				*error_msg = TEXT("Failed to save file.\nNot enough space on disk to save file?");

			// set to signaled state via destructor EventReset.
			return false;
		}

		if (isHidden)
			::SetFileAttributes(fullpath, attrib | FILE_ATTRIBUTE_HIDDEN);

		if (isSys)
			::SetFileAttributes(fullpath, attrib | FILE_ATTRIBUTE_SYSTEM);

		if (isCopy)
		{
			_pscratchTilla->execute(SCI_SETDOCPOINTER, 0, _scratchDocDefault);

			/* for saveAs it's not necessary since this action is for the "current" directory, so we let manage in SAVEPOINTREACHED event
			generic_string backupFilePath = buffer->getBackupFileName();
			if (not backupFilePath.empty())
			{
				// delete backup file
				generic_string file2Delete = buffer->getBackupFileName();
				buffer->setBackupFileName(generic_string());
				::DeleteFile(file2Delete.c_str());
			}
			*/

			// set to signaled state via destructor EventReset.
			return true;	//all done
		}

		buffer->setFileName(fullpath);
		buffer->setDirty(false);
		buffer->setStatus(DOC_REGULAR);
		buffer->checkFileState();
		_pscratchTilla->execute(SCI_SETSAVEPOINT);
		//_pscratchTilla->markSavedLines();
		_pscratchTilla->execute(SCI_SETDOCPOINTER, 0, _scratchDocDefault);

		generic_string backupFilePath = buffer->getBackupFileName();
		if (not backupFilePath.empty())
		{
			// delete backup file
			buffer->setBackupFileName(generic_string());
			::DeleteFile(backupFilePath.c_str());
		}

		// set to signaled state via destructor EventReset.
		return true;
	}
	// set to signaled state via destructor EventReset.
	return false;
}
コード例 #21
0
bool isCertificateValidated(const generic_string & fullFilePath, const generic_string & subjectName2check)
{
	bool isOK = false;
	HCERTSTORE hStore = NULL;
	HCRYPTMSG hMsg = NULL;
	PCCERT_CONTEXT pCertContext = NULL;
	BOOL result;
	DWORD dwEncoding, dwContentType, dwFormatType;
	PCMSG_SIGNER_INFO pSignerInfo = NULL;
	DWORD dwSignerInfo;
	CERT_INFO CertInfo;
	LPTSTR szName = NULL;

	generic_string subjectName;

	try {
		// Get message handle and store handle from the signed file.
		result = CryptQueryObject(CERT_QUERY_OBJECT_FILE,
			fullFilePath.c_str(),
			CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
			CERT_QUERY_FORMAT_FLAG_BINARY,
			0,
			&dwEncoding,
			&dwContentType,
			&dwFormatType,
			&hStore,
			&hMsg,
			NULL);

		if (!result)
		{
			generic_string errorMessage = TEXT("Check certificate of ") + fullFilePath + TEXT(" : ");
			errorMessage += GetLastErrorAsString(GetLastError());
			throw errorMessage;
		}

		// Get signer information size.
		result = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwSignerInfo);
		if (!result)
		{
			generic_string errorMessage = TEXT("CryptMsgGetParam first call: ");
			errorMessage += GetLastErrorAsString(GetLastError());
			throw errorMessage;
		}

		// Allocate memory for signer information.
		pSignerInfo = (PCMSG_SIGNER_INFO)LocalAlloc(LPTR, dwSignerInfo);
		if (!pSignerInfo)
		{
			generic_string errorMessage = TEXT("CryptMsgGetParam memory allocation problem: ");
			errorMessage += GetLastErrorAsString(GetLastError());
			throw errorMessage;
		}

		// Get Signer Information.
		result = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, (PVOID)pSignerInfo, &dwSignerInfo);
		if (!result)
		{
			generic_string errorMessage = TEXT("CryptMsgGetParam: ");
			errorMessage += GetLastErrorAsString(GetLastError());
			throw errorMessage;
		}

		// Search for the signer certificate in the temporary 
		// certificate store.
		CertInfo.Issuer = pSignerInfo->Issuer;
		CertInfo.SerialNumber = pSignerInfo->SerialNumber;

		pCertContext = CertFindCertificateInStore(hStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_SUBJECT_CERT, (PVOID)&CertInfo, NULL);
		if (not pCertContext)
		{
			generic_string errorMessage = TEXT("Certificate context: ");
			errorMessage += GetLastErrorAsString(GetLastError());
			throw errorMessage;
		}

		DWORD dwData;

		// Get Subject name size.
		dwData = CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, NULL, 0);
		if (dwData <= 1)
		{
			throw generic_string(TEXT("Certificate checking error: getting data size problem."));
		}

		// Allocate memory for subject name.
		szName = (LPTSTR)LocalAlloc(LPTR, dwData * sizeof(TCHAR));
		if (!szName)
		{
			throw generic_string(TEXT("Certificate checking error: memory allocation problem."));
		}

		// Get subject name.
		if (CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, szName, dwData) <= 1)
		{
			throw generic_string(TEXT("Cannot get certificate info."));
		}

		// check Subject name.
		subjectName = szName;
		if (subjectName != subjectName2check)
		{
			throw generic_string(TEXT("Certificate checking error: the certificate is not matched."));
		}

		isOK = true;
	}
	catch (generic_string s)
	{
		// display error message
		MessageBox(NULL, s.c_str(), TEXT("Certificate checking"), MB_OK);
	}
	catch (...)
	{
		// Unknown error
		generic_string errorMessage = TEXT("Unknown exception occured. ");
		errorMessage += GetLastErrorAsString(GetLastError());
		MessageBox(NULL, errorMessage.c_str(), TEXT("Certificate checking"), MB_OK);
	}

	// Clean up.
	if (pSignerInfo != NULL) LocalFree(pSignerInfo);
	if (pCertContext != NULL) CertFreeCertificateContext(pCertContext);
	if (hStore != NULL) CertCloseStore(hStore, 0);
	if (hMsg != NULL) CryptMsgClose(hMsg);
	if (szName != NULL) LocalFree(szName);

	return isOK;
}
コード例 #22
0
int PluginsManager::loadPlugin(const generic_string& pluginFilePath, std::vector<generic_string> & dll2Remove)
{
	PluginInfo *pi = new PluginInfo;
	try {
		pi->_moduleName = PathFindFileName(pluginFilePath.c_str());

		pi->_hLib = ::LoadLibrary(pluginFilePath.c_str());
		if (!pi->_hLib)
			throw generic_string(TEXT("Load Library is failed.\nMake \"Runtime Library\" setting of this project as \"Multi-threaded(/MT)\" may cure this problem."));

		pi->_pFuncIsUnicode = (PFUNCISUNICODE)GetProcAddress(pi->_hLib, "isUnicode");
#ifdef UNICODE
		if (!pi->_pFuncIsUnicode || !pi->_pFuncIsUnicode())
			throw generic_string(TEXT("This ANSI plugin is not compatible with your Unicode Notepad++."));
#else
		if (pi->_pFuncIsUnicode)
			throw generic_string(TEXT("This Unicode plugin is not compatible with your ANSI mode Notepad++."));
#endif

		pi->_pFuncSetInfo = (PFUNCSETINFO)GetProcAddress(pi->_hLib, "setInfo");

		if (!pi->_pFuncSetInfo)
			throw generic_string(TEXT("Missing \"setInfo\" function"));

		pi->_pFuncGetName = (PFUNCGETNAME)GetProcAddress(pi->_hLib, "getName");
		if (!pi->_pFuncGetName)
			throw generic_string(TEXT("Missing \"getName\" function"));

		pi->_pBeNotified = (PBENOTIFIED)GetProcAddress(pi->_hLib, "beNotified");
		if (!pi->_pBeNotified)
			throw generic_string(TEXT("Missing \"beNotified\" function"));

		pi->_pMessageProc = (PMESSAGEPROC)GetProcAddress(pi->_hLib, "messageProc");
		if (!pi->_pMessageProc)
			throw generic_string(TEXT("Missing \"messageProc\" function"));

		pi->_pFuncSetInfo(_nppData);

		pi->_pFuncGetFuncsArray = (PFUNCGETFUNCSARRAY)GetProcAddress(pi->_hLib, "getFuncsArray");
		if (!pi->_pFuncGetFuncsArray)
			throw generic_string(TEXT("Missing \"getFuncsArray\" function"));

		pi->_funcItems = pi->_pFuncGetFuncsArray(&pi->_nbFuncItem);

		if ((!pi->_funcItems) || (pi->_nbFuncItem <= 0))
			throw generic_string(TEXT("Missing \"FuncItems\" array, or the nb of Function Item is not set correctly"));

		pi->_pluginMenu = ::CreateMenu();

		GetLexerCountFn GetLexerCount = (GetLexerCountFn)::GetProcAddress(pi->_hLib, "GetLexerCount");
		// it's a lexer plugin
		if (GetLexerCount)
		{
			GetLexerNameFn GetLexerName = (GetLexerNameFn)::GetProcAddress(pi->_hLib, "GetLexerName");
			if (!GetLexerName)
				throw generic_string(TEXT("Loading GetLexerName function failed."));

			GetLexerStatusTextFn GetLexerStatusText = (GetLexerStatusTextFn)::GetProcAddress(pi->_hLib, "GetLexerStatusText");

			if (!GetLexerStatusText)
				throw generic_string(TEXT("Loading GetLexerStatusText function failed."));

			// Assign a buffer for the lexer name.
			char lexName[MAX_EXTERNAL_LEXER_NAME_LEN];
			lexName[0] = '\0';
			TCHAR lexDesc[MAX_EXTERNAL_LEXER_DESC_LEN];
			lexDesc[0] = '\0';

			int numLexers = GetLexerCount();

			NppParameters * nppParams = NppParameters::getInstance();

			ExternalLangContainer *containers[30];
#ifdef UNICODE
			WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
#endif
			for (int x = 0; x < numLexers; x++)
			{
				GetLexerName(x, lexName, MAX_EXTERNAL_LEXER_NAME_LEN);
				GetLexerStatusText(x, lexDesc, MAX_EXTERNAL_LEXER_DESC_LEN);
#ifdef UNICODE
				const TCHAR *pLexerName = wmc->char2wchar(lexName, CP_ACP);
#else
				const TCHAR *pLexerName = lexName;
#endif
				if (!nppParams->isExistingExternalLangName(pLexerName) && nppParams->ExternalLangHasRoom())
					containers[x] = new ExternalLangContainer(pLexerName, lexDesc);
				else
					containers[x] = NULL;
			}

			TCHAR xmlPath[MAX_PATH];
            lstrcpy(xmlPath, nppParams->getNppPath().c_str());
			PathAppend(xmlPath, TEXT("plugins\\Config"));
            PathAppend(xmlPath, pi->_moduleName.c_str());
			PathRemoveExtension(xmlPath);
			PathAddExtension(xmlPath, TEXT(".xml"));

			if (!PathFileExists(xmlPath))
			{
				memset(xmlPath, 0, MAX_PATH * sizeof(TCHAR));
				lstrcpy(xmlPath, nppParams->getAppDataNppDir() );
				PathAppend(xmlPath, TEXT("plugins\\Config"));
                PathAppend(xmlPath, pi->_moduleName.c_str());
				PathRemoveExtension( xmlPath );
				PathAddExtension( xmlPath, TEXT(".xml") );

				if (! PathFileExists( xmlPath ) )
				{
					throw generic_string(generic_string(xmlPath) + TEXT(" is missing."));
				}
			}

			TiXmlDocument *_pXmlDoc = new TiXmlDocument(xmlPath);

			if (!_pXmlDoc->LoadFile())
			{
				delete _pXmlDoc;
				_pXmlDoc = NULL;
				throw generic_string(generic_string(xmlPath) + TEXT(" failed to load."));
			}

			for (int x = 0; x < numLexers; x++) // postpone adding in case the xml is missing/corrupt
				if (containers[x] != NULL)
					nppParams->addExternalLangToEnd(containers[x]);

			nppParams->getExternalLexerFromXmlTree(_pXmlDoc);
			nppParams->getExternalLexerDoc()->push_back(_pXmlDoc);
#ifdef UNICODE
			const char *pDllName = wmc->wchar2char(pluginFilePath.c_str(), CP_ACP);
#else
			const char *pDllName = pluginFilePath.c_str();
#endif
			::SendMessage(_nppData._scintillaMainHandle, SCI_LOADLEXERLIBRARY, 0, (LPARAM)pDllName);
		}

		_pluginInfos.push_back(pi);
        return (_pluginInfos.size() - 1);
	}
	catch(generic_string s)
	{
		s += TEXT("\n\n");
		s += USERMSG;
		if (::MessageBox(NULL, s.c_str(), pluginFilePath.c_str(), MB_YESNO) == IDYES)
		{
			dll2Remove.push_back(pluginFilePath);
		}
		delete pi;
        return -1;
	}
	catch(...)
	{
		generic_string msg = TEXT("Fail loaded");
		msg += TEXT("\n\n");
		msg += USERMSG;
		if (::MessageBox(NULL, msg.c_str(), pluginFilePath.c_str(), MB_YESNO) == IDYES)
		{
			dll2Remove.push_back(pluginFilePath);
		}
		delete pi;
        return -1;
	}
}
コード例 #23
0
             void handle_request( const fc::http::request& r, const fc::http::server::response& s )
             {
                 //ilog( "handle request ${r}", ("r",r.path) );
                 s.add_header( "Connection", "close" );

                 try {
                    auto pos = r.path.find( "/", 1 );
                    auto first_dir = r.path.substr(1,pos);
                    //ilog( "command: ${command}", ("command",first_dir) );
                    if( first_dir == "pending" )
                    {
                       s.set_status( fc::http::reply::OK );
                       auto pending_json = fc::json::to_string( _pending );
                       s.set_length( pending_json.size() );
                       s.write( pending_json.c_str(), pending_json.size() );
                    }
                    else if( first_dir == "update_record" )
                    {
                       FC_ASSERT( r.body.size() );
                       std::string str(r.body.data(),r.body.size());
                       auto rec = fc::json::from_string( str ).as<signed_name_record>();

                       _self->update_record( rec );

                       s.set_status( fc::http::reply::RecordCreated );
                       s.set_length( 12 );
                       s.write( "Record Created", 12 );
                    }
                    else if( first_dir == "fetch_by_name/" )
                    {
                       auto name = r.path.substr( pos+1, std::string::npos );
                       auto record  = _self->fetch_record( name );
                       s.set_status( fc::http::reply::Found );
                       auto blkjson = fc::json::to_string( record );
                       s.set_length( blkjson.size() );
                       s.write( blkjson.c_str(), blkjson.size() );
                    }
                    else if( first_dir == "fetch_by_key/" )
                    {
                       auto key = r.path.substr( pos+1, std::string::npos );
                       auto record  = _self->fetch_record_by_key( key );
                       s.set_status( fc::http::reply::Found );

                       auto blkjson = fc::json::to_string( record );
                       s.set_length( blkjson.size() );
                       s.write( blkjson.c_str(), blkjson.size() );
                    }
                    else if( first_dir == "store_key/" )
                    {
                       auto name = r.path.substr( pos+1, std::string::npos );
                       std::string str(r.body.data(),r.body.size());
                       auto rec = fc::json::from_string( str ).as<stored_key>();

                       _self->store_key( name, rec );
                       s.set_status( fc::http::reply::RecordCreated );
                       s.set_length( 12 );
                       s.write( "Record Created", 12 );
                    }
                    else if( first_dir == "fetch_key/" )
                    {
                       auto user_name = r.path.substr( pos+1, std::string::npos );
                       auto key_data  = _self->fetch_key(  user_name );
                       s.set_status( fc::http::reply::Found );

                       auto blkjson = fc::json::to_string( key_data );
                       s.set_length( blkjson.size() );
                       s.write( blkjson.c_str(), blkjson.size() );
                    }
                    else if( first_dir == "fetch_block/" )
                    {
                       auto block_num = r.path.substr( pos+1, std::string::npos );
                       auto blk = _self->fetch_block(  fc::to_uint64( block_num ) );
                       s.set_status( fc::http::reply::Found );
                       auto blkjson = fc::json::to_string( blk );
                       s.set_length( blkjson.size() );
                       s.write( blkjson.c_str(), blkjson.size() );
                    }
                    else
                    {
                       auto dotpos = r.path.find( ".." );
                       FC_ASSERT( dotpos == std::string::npos );
                       auto filename = _data_dir / r.path.substr(1,std::string::npos);
                       if( fc::exists( filename ) )
                       {
                          FC_ASSERT( !fc::is_directory( filename ) );
                          auto file_size = fc::file_size( filename );
                          FC_ASSERT( file_size != 0 );

                          fc::file_mapping fm( filename.generic_string().c_str(), fc::read_only );
                          fc::mapped_region mr( fm, fc::read_only, 0, fc::file_size( filename ) );

                          s.set_status( fc::http::reply::OK );
                          s.set_length( file_size );
                          s.write( (const char*)mr.get_address(), mr.get_size() );
                          return;
                       }
                       s.set_status( fc::http::reply::NotFound );
                       s.set_length( 9 );
                       s.write( "Not Found", 9 );
                    }
                 } 
                 catch ( const fc::exception& e )
                 {
                    s.set_status( fc::http::reply::BadRequest );
                    auto msg = e.to_detail_string();
                    s.set_length( msg.size() );
                    if( msg.size() )
                    {
                      s.write( msg.c_str(), msg.size() );
                    }
                 }
             }
コード例 #24
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;
  }
コード例 #25
0
void AutoCompletion::showPathCompletion()
{
    // Get current line (at most MAX_PATH characters "backwards" from current caret).
    generic_string currentLine;
    {
        const long bufSize = MAX_PATH;
        TCHAR buf[bufSize + 1];
        const int currentPos = _pEditView->execute(SCI_GETCURRENTPOS);
        const int startPos = max(0, currentPos - bufSize);
        _pEditView->getGenericText(buf, bufSize + 1, startPos, currentPos);
        currentLine = buf;
    }

    /* Try to figure out which path the user wants us to complete.
       We need to know the "raw path", which is what the user actually wrote.
       But we also need to know which directory to look in (pathToMatch), which might
       not be the same as what the user wrote. This happens when the user types an
       incomplete name.
       For instance: the user wants to autocomplete "C:\Wind", and assuming that no such directory
       exists, this means we should list all files and directories in C:.
    */
    generic_string rawPath, pathToMatch;
    if(! getPathsForPathCompletion(currentLine, rawPath, pathToMatch))
        return;

    // Get all files and directories in the path.
    generic_string autoCompleteEntries;
    {
        HANDLE hFind;
        WIN32_FIND_DATA data;
        generic_string pathToMatchPlusSlash = addTrailingSlash(pathToMatch);
        generic_string searchString = pathToMatchPlusSlash + TEXT("*.*");
        hFind = ::FindFirstFile(searchString.c_str(), &data);
        if(hFind != INVALID_HANDLE_VALUE)
        {
            // Maximum number of entries to show. Without this it appears to the user like N++ hangs when autocompleting
            // some really large directories (c:\windows\winxsys on my system for instance).
            const unsigned int maxEntries = 2000;
            unsigned int counter = 0;
            do
            {
                if(++counter > maxEntries)
                    break;

                if(generic_string(data.cFileName) == TEXT(".") || generic_string(data.cFileName) == TEXT(".."))
                    continue;

                if(! autoCompleteEntries.empty())
                    autoCompleteEntries += TEXT("\n");

                autoCompleteEntries += pathToMatchPlusSlash;
                autoCompleteEntries += data.cFileName;
                if(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // If directory, add trailing slash.
                    autoCompleteEntries += TEXT("\\");

            } while(::FindNextFile(hFind, &data));
            ::FindClose(hFind);
        }
        else
        {
            return;
        }
    }

    // Show autocompletion box.
    _pEditView->execute(SCI_AUTOCSETSEPARATOR, WPARAM('\n'));
    _pEditView->execute(SCI_AUTOCSETIGNORECASE, true);
    _pEditView->showAutoComletion(rawPath.length(), autoCompleteEntries.c_str());
    _activeCompletion = CompletionPath;
    return;
}