Example #1
0
// check for equivalence (point to the same file-system entity)
bool FilePath::isEquivalentTo(const FilePath& filePath) const
{
   if (!exists() || !filePath.exists())
      return false;

   try
   {
      return boost::filesystem::equivalent(pImpl_->path, filePath.pImpl_->path);
   }
   catch(const boost::filesystem::filesystem_error& e)
   {
      Error error(e.code(), ERROR_LOCATION) ;
      addErrorProperties(pImpl_->path, &error) ;
      error.addProperty("equivilant-to", filePath);
      return error ;
   }

   // keep compiler happy
   return false;
}
Example #2
0
FilePath FilePath::resolveAliasedPath(const std::string& aliasedPath,
                            const FilePath& userHomePath)
{
   // Special case for  empty string or "~"
   if (aliasedPath.empty() || (aliasedPath.compare(kHomePathLeafAlias) == 0))
      return userHomePath;

   // if the path starts with the home alias then substitute the home path
   if (aliasedPath.find(kHomePathAlias) == 0)
   {
      std::string resolvedPath = userHomePath.absolutePath() +
      aliasedPath.substr(1);
      return FilePath(resolvedPath);
   }
   else  // no aliasing, this is either an absolute path or path
         // relative to the current directory
   {
      return FilePath::safeCurrentPath(userHomePath).complete(aliasedPath);
   }
}
Error PlotManager::savePlotAsPostscript(const FilePath& targetPath,
                                        int width,
                                        int height)
{
   // calculate size in inches
   double widthInches = pixelsToInches(width);
   double heightInches = pixelsToInches(height);

   // generate code for creating postscript device
   boost::format fmt("{ require(grDevices, quietly=TRUE); "
                     "  postscript(file=\"%1%\", width=%2%, height=%3%, "
                     "             onefile = FALSE, "
                     "             paper = \"special\", "
                     "             horizontal = FALSE); }");
   std::string deviceCreationCode = boost::str(fmt % string_utils::utf8ToSystem(targetPath.absolutePath()) %
                                                     widthInches %
                                                     heightInches);

   return savePlotAsFile(deviceCreationCode);
}
Example #4
0
core::Error createConsoleProc(const ShellArgs& args,
                              const FilePath& outputFile,
                              const boost::optional<FilePath>& workingDir,
                              const std::string& caption,
                              bool requiresSsh,
                              bool dialog,
                              bool enqueueRefreshOnExit,
                              boost::shared_ptr<ConsoleProcess>* ppCP)
{
    core::system::ProcessOptions options = procOptions(requiresSsh);
    if (!workingDir)
        options.workingDir = s_workingDir;
    else if (!workingDir.get().empty())
        options.workingDir = workingDir.get();

    // NOTE: we use runCommand style process creation on both windows and posix
    // so that we can redirect standard output to a file -- this works on
    // windows because we are not specifying options.detachProcess (not
    // necessary because ConsoleProcess specifies options.createNewConsole
    // which overrides options.detachProcess)

    // build command
    std::string command = svn() << args.args();

    // redirect stdout to a file
    if (!outputFile.empty())
        options.stdOutFile = outputFile;

    // create the process
    *ppCP = ConsoleProcess::create(command,
                                   options,
                                   caption,
                                   dialog,
                                   console_process::InteractionPossible,
                                   console_process::kDefaultMaxOutputLines);

    if (enqueueRefreshOnExit)
        (*ppCP)->onExit().connect(boost::bind(&enqueueRefreshEvent));

    return Success();
}
Example #5
0
String File::GetModificationDate(const FilePath & filePathname)
{
    String realPathname = filePathname.GetAbsolutePathname();
    
    struct stat fileInfo = {0};
    int32 ret = stat(realPathname.c_str(), &fileInfo);
    if(0 == ret)
    {
#if defined (__DAVAENGINE_WIN32__)
		tm* utcTime = gmtime(&fileInfo.st_mtime);
#elif defined (__DAVAENGINE_ANDROID__)
		tm* utcTime = gmtime((const time_t *)&fileInfo.st_mtime);
#elif defined (__DAVAENGINE_MACOS__) || defined (__DAVAENGINE_IPHONE__)
        tm* utcTime = gmtime(&fileInfo.st_mtimespec.tv_sec);
#endif
        return String(Format("%04d.%02d.%02d %02d:%02d:%02d",
                       utcTime->tm_year + 1900, utcTime->tm_mon + 1, utcTime->tm_mday,
                       utcTime->tm_hour, utcTime->tm_min, utcTime->tm_sec));
    }
    return String("");
}
Example #6
0
Error parseDcfFile(const FilePath& dcfFilePath,
                   bool preserveKeyCase,
                   DcfFieldRecorder recordField,
                   std::string* pUserErrMsg)
{
   // read the file
   std::string dcfFileContents;
   Error error = readStringFromFile(dcfFilePath,
                                    &dcfFileContents);
   if (error)
   {
      error.addProperty("dcf-file", dcfFilePath.absolutePath());
      *pUserErrMsg = error.summary();
      return error;
   }

   return parseDcfFile(dcfFileContents,
                       preserveKeyCase,
                       recordField,
                       pUserErrMsg);
}
Example #7
0
bool isReadOnly(const FilePath& filePath)
{
   if (::access(filePath.absolutePath().c_str(), W_OK) == -1)
   {
      if (errno == EACCES)
      {
         return true;
      }
      else
      {
         Error error = systemError(errno, ERROR_LOCATION);
         error.addProperty("path", filePath);
         LOG_ERROR(error);
         return false;
      }
   }
   else
   {
      return false;
   }
}
Example #8
0
	bool VideoWriter::CVideoWriter::open(const FilePath& path, const Size& size, const double fps)
	{
		if (isOpened())
		{
			close();
		}
		
		if (FileSystem::Exists(path))
		{
			FileSystem::Remove(path);
		}

		const bool result = m_writer.open(path.narrow(), cv::VideoWriter::fourcc('H', '2', '6', '4'), fps, cv::Size(size.x, size.y), true);

		if (result)
		{
			m_frameSize = size;
		}

		return result;
	}
Example #9
0
void TextureDescriptor::Export(const FilePath &filePathname)
{
    File *file = File::Create(filePathname, File::WRITE | File::OPEN | File::CREATE);
    if(!file)
    {
        Logger::Error("[TextureDescriptor::Export] Can't open file: %s", filePathname.GetAbsolutePathname().c_str());
        return;
    }

    int32 signature = COMPRESSED_FILE;
    file->Write(&signature, sizeof(signature));

    int8 version = CURRENT_VERSION;
    file->Write(&version, sizeof(version));

    WriteGeneralSettings(file);
    file->Write(&exportedAsGpuFamily, sizeof(exportedAsGpuFamily));
    file->Write(&exportedAsPixelFormat, sizeof(exportedAsPixelFormat));

    SafeRelease(file);
}
Example #10
0
FilePath getDefaultWorkingDirectory()
{
   // calculate using user settings
   FilePath defaultWorkingDir = userSettings().initialWorkingDirectory();
   FilePath sessionDefaultWorkingDir = FilePath(session::options().defaultWorkingDir());

   // return it if it exists, otherwise use the
   // session specified value if it exists
   // otherwise, use the default user home path
   if (defaultWorkingDir.exists() && defaultWorkingDir.isDirectory())
      return defaultWorkingDir;
   else if (sessionDefaultWorkingDir.exists() && sessionDefaultWorkingDir.isDirectory())
      return sessionDefaultWorkingDir;
   else
      return session::options().userHomePath();
}
Example #11
0
Error readStringFromFile(const FilePath& filePath,
                         std::string* pStr,
                         string_utils::LineEnding lineEnding)
{
   using namespace boost::system::errc ;
   
   // open file
   std::string file = filePath.absolutePath();
   std::ifstream ifs(file.c_str(), std::ios_base::in | std::ios_base::binary) ;
   if (!ifs)
   {
      Error error = systemError(no_such_file_or_directory,ERROR_LOCATION);
      error.addProperty("path", file);
      return error;
   }
   

   try
   {
      // set exception mask (required for proper reporting of errors)
      ifs.exceptions(std::istream::failbit | std::istream::badbit);
      
      // copy file to string stream
      std::ostringstream ostr;
      boost::iostreams::copy(ifs, ostr);
      *pStr = ostr.str();
      string_utils::convertLineEndings(pStr, lineEnding);

      // return success
      return Success();
   }
   catch(const std::exception& e)
   {
      Error error = systemError(boost::system::errc::io_error, 
                                ERROR_LOCATION);
      error.addProperty("what", e.what());
      error.addProperty("path", file);
      return error;
   }
}
Example #12
0
	bool Win32FileGroupDirectory::openMappedFile( const FilePath & _fileName, const FileMappedInterfacePtr & _stream )
	{
		if( _stream == nullptr )
		{
			LOGGER_ERROR(m_serviceProvider)("Win32FileGroupDirectory::openMappedFile failed _stream == NULL"
				);

			return false;
		}

		if( _stream->open( m_path, _fileName ) == false )
		{
			LOGGER_ERROR(m_serviceProvider)("Win32FileGroupDirectory::openMappedFile failed open file '%s':'%s'"
				, m_path.c_str()
				, _fileName.c_str()
				);

			return false;
		}

		return true;
	}
Example #13
0
Error writeStringToFile(const FilePath& filePath,
                        const std::string& str,
                        string_utils::LineEnding lineEnding)
{
   using namespace boost::system::errc ;
   
   // open file
   std::string file = filePath.absolutePath();
   std::ofstream ofs(file.c_str(), std::ios_base::out | std::ios_base::binary);
   if (!ofs)
   {
      Error error = systemError(no_such_file_or_directory,ERROR_LOCATION);
      error.addProperty("path", file);
      return error;
   }
   
   try
   {
      // set exception mask (required for proper reporting of errors)
      ofs.exceptions(std::istream::failbit | std::istream::badbit);
      
      // copy string to file
      std::string normalized = str;
      string_utils::convertLineEndings(&normalized, lineEnding);
      std::istringstream istr(normalized);
      boost::iostreams::copy(istr, ofs);
      
      // return success
      return Success();
   }
   catch(const std::exception& e)
   {
      Error error = systemError(boost::system::errc::io_error, 
                                ERROR_LOCATION);
      error.addProperty("what", e.what());
      error.addProperty("path", file);
      return error;
   }
}
Example #14
0
		bool Problem::CProblem::trainAndSaveModel(const FilePath& path, const Paramter& param) const
		{
			if (!m_hasData)
			{
				return false;
			}

			svm_model* model = svm_train(&m_problem, &param);

			const FilePath parentFilePath = FileSystem::ParentPath(path);

			if (!FileSystem::Exists(parentFilePath) && !FileSystem::CreateDirectories(parentFilePath))
			{
				return false;
			}

			const int32 result = svm_save_model(path.narrow().c_str(), model);

			svm_free_and_destroy_model(&model);

			return (result == 0);
		}
Example #15
0
// IN: String sourcePath, String targetPath
Error copyFile(const core::json::JsonRpcRequest& request,
               json::JsonRpcResponse* pResponse)
{
   // read params
   std::string sourcePath, targetPath;
   Error error = json::readParams(request.params, &sourcePath, &targetPath);
   if (error)
      return error ;
   
   // make sure the target path doesn't exist
   FilePath targetFilePath = module_context::resolveAliasedPath(targetPath);
   if (targetFilePath.exists())
      return fileExistsError(ERROR_LOCATION);

   // compute the source file path
   FilePath sourceFilePath = module_context::resolveAliasedPath(sourcePath);
   
   // copy directories recursively
   Error copyError ;
   if (sourceFilePath.isDirectory())
   {
      // create the target directory
      Error error = targetFilePath.ensureDirectory();
      if (error)
         return error ;
      
      // iterate over the source
      copyError = sourceFilePath.childrenRecursive(
        boost::bind(copySourceFile, sourceFilePath, targetFilePath, _1, _2));
   }
   else
   {
      copyError = sourceFilePath.copy(targetFilePath);
   }
   
   // check quota after copies
   quotas::checkQuotaStatus();
   
   // return error status
   return copyError;
}
void LandscapeEditorCustomColors::LoadTextureAction(const FilePath &pathToFile)
{
	if(pathToFile.IsEmpty())
		return;

	Vector<Image*> images = ImageLoader::CreateFromFile(pathToFile);
	if(images.empty())
		return;

	Image* image = images.front();
	if(image)
	{
		Texture* texture = Texture::CreateFromData(image->GetPixelFormat(),
												   image->GetData(),
												   image->GetWidth(),
												   image->GetHeight(),
												   false);

		SafeRelease(colorSprite);
		colorSprite = Sprite::CreateAsRenderTarget(texSurf->GetWidth(), texSurf->GetHeight(), FORMAT_RGBA8888);
		Sprite* sprite = Sprite::CreateFromTexture(texture, 0, 0, texture->GetWidth(), texture->GetHeight());

		StoreOriginalState();

		RenderManager::Instance()->SetRenderTarget(colorSprite);
		sprite->Draw();
		RenderManager::Instance()->RestoreRenderTarget();
		PerformLandscapeDraw();

		SafeRelease(sprite);
		SafeRelease(texture);
		for_each(images.begin(), images.end(), SafeRelease<Image>);

		StoreSaveFileName(pathToFile);

		CreateUndoPoint();
	}
}
Example #17
0
void FilePath::Join(const FilePath& rhs)
{
	Normalise();
	rhs.Normalise();

	size_t len = m_storage.length();
	bool trailingSlash = len > 0 && m_storage[len - 1] == '/';
	size_t rhsLen = rhs.m_storage.length();
	bool leadingSlash = rhsLen > 0 && rhs.m_storage[rhsLen - 1] == '/';

	//Copy only one slash if both leading and trailing
	if (leadingSlash && trailingSlash)
	{
		char buf[MB_MAX_PATH];
		memcpy(buf, m_storage.c_str(), len - 1);
		memcpy(buf + len, rhs.m_storage.c_str(), rhsLen);
	}
	//Join together without adding new slash
	else if (leadingSlash || trailingSlash)
	{
		m_storage += rhs.m_storage;
	}
	else
	{
		//No slash needed if our length is 0
		if (len == 0)
		{
			m_storage = rhs.m_storage;
		}
		else
		{
			//Add new slash
			char buf[MB_MAX_PATH];
			sprintf(buf, "%s/%s", m_storage.c_str(), rhs.m_storage.c_str());
			m_storage = buf;
		}
	}
}
void ConfigManager::readXml(const icl_core::String& prefix, TiXmlNode *node, FilePath fp, bool extend_prefix)
{
  icl_core::String node_name(node->Value());
  icl_core::String fq_node_name = prefix;
  if (extend_prefix)
  {
    fq_node_name = prefix + "/" + node_name;
  }

  TiXmlNode *child = node->IterateChildren(NULL);
  while (child != 0)
  {
    if (child->Type() == TiXmlNode::TINYXML_ELEMENT)
    {
      if (strcmp(child->Value(), "INCLUDE") == 0)
      {
        TiXmlElement *child_element = dynamic_cast<TiXmlElement*>(child);
        assert(child_element != NULL);
        const char *included_file = child_element->GetText();
        if (included_file != NULL)
        {
          load(fp.path() + included_file);
        }
      }
      else
      {
        readXml(fq_node_name, child, fp);
      }
    }
    else if (child->Type() == TiXmlNode::TINYXML_TEXT)
    {
      insert(fq_node_name, child->Value());
      notify(fq_node_name);
    }

    child = node->IterateChildren(child);
  }
}
Example #19
0
Error ConsoleHistory::loadFromFile(const FilePath& filePath,
                                   bool verifyFile)
{
   historyBuffer_.clear();
   
   // tolerate file not found -- the user may not have any prior history
   if (filePath.exists())
   {
      return ::core::readCollectionFromFile<boost::circular_buffer<std::string> >(
                                                      filePath,
                                                      &historyBuffer_,
                                                      ::core::parseString);
   }
   else if (verifyFile)
   {
      return systemError(boost::system::errc::no_such_file_or_directory,
                         ERROR_LOCATION);
   }
   else
   {
      return Success();
   }
}
Example #20
0
//! adds a file or folder
unsigned int FileList::addItem( const FilePath& fullPath, unsigned int offset, unsigned int size, bool isDirectory, unsigned int id )
{
	FileListItem entry;
	entry.iD   = id ? id : _d->files.size();
	entry.Offset = offset;
	entry.size = size;
  entry.name = StringHelper::replace( fullPath.toString(), "\\", "/" );
	entry.isDirectory = isDirectory;

	// remove trailing slash
	if( *(entry.name.toString().rbegin()) == '/')
	{
		entry.isDirectory = true;
		entry.name = entry.name.removeEndSlash();
		//entry.name.validate();
	}

	if( _d->ignoreCase)
  {
    entry.name = StringHelper::localeLower( entry.name.toString() );
  }

	entry.fullName = entry.name;

	entry.name = entry.name.getBasename();

	if(_d->ignorePaths )
  {
		entry.fullName = entry.name;
  }

	//os::Printer::log(Path.c_str(), entry.fullName);

	_d->files.push_back(entry);

	return _d->files.size() - 1;
}
Example #21
0
void SceneSaver::SaveScene(Scene *scene, const FilePath &fileName, Set<String> &errorLog)
{
    DVASSERT(0 == texturesForSave.size())
    
    String relativeFilename = fileName.GetRelativePathname(sceneUtils.dataSourceFolder);
    sceneUtils.workingFolder = fileName.GetDirectory().GetRelativePathname(sceneUtils.dataSourceFolder);
    
    FileSystem::Instance()->CreateDirectory(sceneUtils.dataFolder + sceneUtils.workingFolder, true);

    scene->Update(0.1f);

    FilePath oldPath = SceneValidator::Instance()->SetPathForChecking(sceneUtils.dataSourceFolder);
    SceneValidator::Instance()->ValidateScene(scene, fileName, errorLog);

    texturesForSave.clear();
    SceneHelper::EnumerateTextures(scene, texturesForSave);

    CopyTextures(scene, errorLog);
	ReleaseTextures();

	Landscape *landscape = FindLandscape(scene);
    if (landscape)
    {
        sceneUtils.CopyFile(landscape->GetHeightmapPathname(), errorLog);
    }

	CopyReferencedObject(scene, errorLog);
	CopyEffects(scene, errorLog);
	CopyCustomColorTexture(scene, fileName.GetDirectory(), errorLog);

    //save scene to new place
    FilePath tempSceneName = sceneUtils.dataSourceFolder + relativeFilename;
    tempSceneName.ReplaceExtension(".saved.sc2");
    
    scene->Save(tempSceneName, true);

    bool moved = FileSystem::Instance()->MoveFile(tempSceneName, sceneUtils.dataFolder + relativeFilename, true);
	if(!moved)
	{
		errorLog.insert(Format("Can't move file %s", fileName.GetAbsolutePathname().c_str()));
	}
    
    SceneValidator::Instance()->SetPathForChecking(oldPath);
}
Example #22
0
void Options::Generate_Configuration_File( const FilePath& config_path )
{
    // Open the File
    std::ofstream fout;
    fout.open(config_path.ToString().c_str());
    fout << std::endl;
    
    
    // Write the Program Configuration
    fout << "#  Map-Services Configuration Information" << std::endl;
    fout << "SERVICES_REGEX_PATTERN=.*\\.cfg" << std::endl;
    fout << "SERVICES_DEFAULT_PROJECTION=EPSG:4326" << std::endl;
    fout << std::endl;


    // Write the GUI Configuration
    fout << "#  GUI Configuration Information" << std::endl;
    fout << "GUI_TITLE=Map Service Connector Viewer" << std::endl;
    fout << "GUI_H1_FONT_FAMILY=" << m_gui_config_settings["GUI_H1_FONT_FAMILY"] << std::endl;
    fout << "GUI_H1_FONT_SIZE=" << m_gui_config_settings["GUI_H1_FONT_SIZE"] << std::endl;
    fout << "GUI_H1_FONT_WEIGHT=" << m_gui_config_settings["GUI_H1_FONT_WEIGHT"] << std::endl;
    
    fout << "GUI_H2_FONT_FAMILY=" << m_gui_config_settings["GUI_H2_FONT_FAMILY"] << std::endl;
    fout << "GUI_H2_FONT_SIZE=" << m_gui_config_settings["GUI_H2_FONT_SIZE"] << std::endl;
    fout << "GUI_H2_FONT_WEIGHT=" << m_gui_config_settings["GUI_H2_FONT_WEIGHT"] << std::endl;
    
    fout << "GUI_H3_FONT_FAMILY=" << m_gui_config_settings["GUI_H3_FONT_FAMILY"] << std::endl;
    fout << "GUI_H3_FONT_SIZE=" << m_gui_config_settings["GUI_H3_FONT_SIZE"] << std::endl;
    fout << "GUI_H3_FONT_WEIGHT=" << m_gui_config_settings["GUI_H3_FONT_WEIGHT"] << std::endl;
    fout << "SERVICE_LIST_COLUMN_0_WIDTH=" << m_gui_config_settings["SERVICE_LIST_COLUMN_0_WIDTH"] << std::endl;
    fout << std::endl;

    // Close the File
    fout.close();

}
Example #23
0
void Options::Load_Configuration_File( const FilePath& config_path )
{

    // open the file
    std::ifstream fin;
    fin.open( config_path.ToString().c_str());

    // read the first line
    std::string line;
    std::getline( fin, line);

    // split the string
    std::vector<std::string> components = String_Split(line,"="); 
    
    // pass components to set function
    if( components.size() > 1 ){
        m_gui_config_settings[components[0]] = components[1];
    }

    // iterate until empty
    while( !fin.eof() )
    {
        // grab the next line
        std::getline( fin, line);
        std::vector<std::string> components = String_Split(line,"="); 

        // set the item        
        if( components.size() > 1 ){
            m_gui_config_settings[components[0]] = components[1];
        }
    }

    // close the file
    fin.close();

}
Example #24
0
void AnimInfo::load(const FilePath& path) {
    TextFile file(path);
    if (!file.open()) {
        printf("cannot open for read \"%s\"\n", path.str());
        return;
    }
    clear();

    _tex_name = strip(file.read_line());
    std::string current_frame = file.read_line();

    while (!current_frame.empty()) {
        std::string result;
        std::vector<int> results;
        for (int i = 0; i < current_frame.size(); i++) {
            char c = current_frame[i];
            if (c == ' ' || c == '\n') {
                results.push_back(atoi(result.c_str()));
                result = "";
                continue;
            }
            result.push_back(c);
        }
        if (!result.empty()) {
            results.push_back(atoi(result.c_str()));
        }
        int xx = results[0];
        int yy = results[1];
        int w = results[2];
        int h = results[3];
        int dx = results[4];
        int dy = results[5];
        _frames.push_back(Frame(xx, yy, w, h, dx, dy));
        current_frame = file.read_line();
    }
}
Example #25
0
	bool Win32FileGroupDirectory::openOutputFile( const FilePath & _fileName, const OutputStreamInterfacePtr & _stream )
	{
        if( _stream == nullptr )
        {
            LOGGER_ERROR(m_serviceProvider)("Win32FileGroupDirectory::openOutputFile failed _stream == NULL"
                );

            return false;
        }

        FileOutputStreamInterface * file = stdex::intrusive_get<FileOutputStreamInterface *>(_stream);

        if( file->open( m_path, _fileName ) == false )
        {
            LOGGER_ERROR(m_serviceProvider)("Win32FileGroupDirectory::openOutputFile failed open file '%s':'%s'"
                , m_path.c_str()
                , _fileName.c_str()
                );

            return false;
        }
        		
		return true;
	}
Example #26
0
Error SourceManager::source(const FilePath& filePath, bool local)
{
   std::string localPrefix = local ? "local(" : "";
   std::string localParam = local ? "TRUE" : "FALSE" ;
   std::string localSuffix = local ? ")" : "";
      
   // do \ escaping (for windows)
   std::string path = filePath.absolutePath();
   boost::algorithm::replace_all(path, "\\", "\\\\");

   // build the code 
   std::string rCode = localPrefix + "source(\"" 
                           + path + "\", " +
                           "local=" + localParam + ", " + 
                           "echo=FALSE, " +
                           "verbose=FALSE, " + 
                           "encoding='UTF-8')" + localSuffix;
      
   // record that we sourced the file. 
   recordSourcedFile(filePath, local);
   
   // source the file
   return r::exec::executeString(rCode); 
}
Example #27
0
Error getTerminalOptions(const json::JsonRpcRequest& request,
                         json::JsonRpcResponse* pResponse)
{
   json::Object optionsJson;

   FilePath terminalPath;

#if defined(_WIN32)

   // if we are using git bash then return its path
   if (git::isGitEnabled() && userSettings().vcsUseGitBash())
   {
      FilePath gitExePath = git::detectedGitExePath();
      if (!gitExePath.empty())
         terminalPath = gitExePath.parent().childPath("sh.exe");
   }

#elif defined(__APPLE__)

   // do nothing (we always launch Terminal.app)

#else

   // auto-detection (+ overridable by a setting)
   terminalPath = userSettings().vcsTerminalPath();
   if (terminalPath.empty())
      terminalPath = detectedTerminalPath();

#endif

   // append shell paths as appropriate
   std::string extraPathEntries;
   ammendShellPaths(&extraPathEntries);

   optionsJson["terminal_path"] = terminalPath.absolutePath();
   optionsJson["working_directory"] =
                  module_context::shellWorkingDirectory().absolutePath();
   optionsJson["extra_path_entries"] = extraPathEntries;
   pResponse->setResult(optionsJson);

   return Success();
}
Example #28
0
void copySourceFile(const FilePath& sourceDir, 
                    const FilePath& destDir,
                    int level,
                    const FilePath& sourceFilePath)
{
   // compute the target path
   std::string relativePath = sourceFilePath.relativePath(sourceDir);
   FilePath targetPath = destDir.complete(relativePath);
   
   // if the copy item is a directory just create it
   if (sourceFilePath.isDirectory())
   {
      Error error = targetPath.ensureDirectory();
      if (error)
         LOG_ERROR(error);
   }
   // otherwise copy it
   else
   {
      Error error = sourceFilePath.copy(targetPath);
      if (error)
         LOG_ERROR(error);
   }
}
Example #29
0
    PlatformFile CreatePlatformFile(const FilePath& name,
        int flags, bool* created, PlatformFileError* error_code)
    {
        ThreadRestrictions::AssertIOAllowed();

        DWORD disposition = 0;
        if(created)
        {
            *created = false;
        }

        if(flags & PLATFORM_FILE_OPEN)
        {
            disposition = OPEN_EXISTING;
        }

        if(flags & PLATFORM_FILE_CREATE)
        {
            DCHECK(!disposition);
            disposition = CREATE_NEW;
        }

        if(flags & PLATFORM_FILE_OPEN_ALWAYS)
        {
            DCHECK(!disposition);
            disposition = OPEN_ALWAYS;
        }

        if(flags & PLATFORM_FILE_CREATE_ALWAYS)
        {
            DCHECK(!disposition);
            disposition = CREATE_ALWAYS;
        }

        if(flags & PLATFORM_FILE_TRUNCATE)
        {
            DCHECK(!disposition);
            DCHECK(flags & PLATFORM_FILE_WRITE);
            disposition = TRUNCATE_EXISTING;
        }

        if(!disposition)
        {
            NOTREACHED();
            return NULL;
        }

        DWORD access = (flags & PLATFORM_FILE_READ) ? GENERIC_READ : 0;
        if(flags & PLATFORM_FILE_WRITE)
        {
            access |= GENERIC_WRITE;
        }
        if(flags & PLATFORM_FILE_WRITE_ATTRIBUTES)
        {
            access |= FILE_WRITE_ATTRIBUTES;
        }

        DWORD sharing = (flags & PLATFORM_FILE_EXCLUSIVE_READ) ? 0
            : FILE_SHARE_READ;
        if(!(flags & PLATFORM_FILE_EXCLUSIVE_WRITE))
        {
            sharing |= FILE_SHARE_WRITE;
        }
        if(flags & PLATFORM_FILE_SHARE_DELETE)
        {
            sharing |= FILE_SHARE_DELETE;
        }

        DWORD create_flags = 0;
        if(flags & PLATFORM_FILE_ASYNC)
        {
            create_flags |= FILE_FLAG_OVERLAPPED;
        }
        if(flags & PLATFORM_FILE_TEMPORARY)
        {
            create_flags |= FILE_ATTRIBUTE_TEMPORARY;
        }
        if(flags & PLATFORM_FILE_HIDDEN)
        {
            create_flags |= FILE_ATTRIBUTE_HIDDEN;
        }
        if(flags & PLATFORM_FILE_DELETE_ON_CLOSE)
        {
            create_flags |= FILE_FLAG_DELETE_ON_CLOSE;
        }

        HANDLE file = CreateFile(name.value().c_str(), access, sharing,
            NULL, disposition, create_flags, NULL);

        if(created && (INVALID_HANDLE_VALUE != file))
        {
            if(flags & (PLATFORM_FILE_OPEN_ALWAYS))
            {
                *created = (ERROR_ALREADY_EXISTS != GetLastError());
            }
            else if(flags & (PLATFORM_FILE_CREATE_ALWAYS|PLATFORM_FILE_CREATE))
            {
                *created = true;
            }
        }

        if(error_code)
        {
            if(file != kInvalidPlatformFileValue)
            {
                *error_code = PLATFORM_FILE_OK;
            }
            else
            {
                DWORD last_error = GetLastError();
                switch(last_error)
                {
                case ERROR_SHARING_VIOLATION:
                    *error_code = PLATFORM_FILE_ERROR_IN_USE;
                    break;
                case ERROR_FILE_EXISTS:
                    *error_code = PLATFORM_FILE_ERROR_EXISTS;
                    break;
                case ERROR_FILE_NOT_FOUND:
                    *error_code = PLATFORM_FILE_ERROR_NOT_FOUND;
                    break;
                case ERROR_ACCESS_DENIED:
                    *error_code = PLATFORM_FILE_ERROR_ACCESS_DENIED;
                    break;
                default:
                    *error_code = PLATFORM_FILE_ERROR_FAILED;
                }
            }
        }

        return file;
    }
Example #30
0
	u32 num = reader->ReadInt32(Endian::BigEndian);
	BRICKS_FEATURE_ASSERT(num == 0x1337BAAD);
	String str = reader->ReadString();
	BRICKS_FEATURE_ASSERT(str == "ohai");
	u16 num2 = reader->ReadInt16();
	BRICKS_FEATURE_ASSERT(num2 == 0xF33D);
	BRICKS_FEATURE_ASSERT(reader->IsEndOfFile()); // Not implemented yet, fail.
	rstream.Release();

	Console::GetDefault()->Out->WriteLine(String::Format("Success! Read back 0x%08x, \"%s\", and 0x%04x from file.", num, str.CString(), num2));

	// rstream and reader are both Released() when this returns thanks to AutoPointer.

	Console::GetDefault()->Out->WriteLine(" --- File Path Test --- ");
	Console::GetDefault()->Out->WriteLine("Creating FilePath, should be /test/lol/sup");
	FilePath path("lol");
	path = path.Combine("sup");
	path = path.RootPath("/test");
#if !BRICKS_ENV_WINDOWS
	BRICKS_FEATURE_ASSERT(path == "/test/lol/sup");
#endif
	Console::GetDefault()->Out->WriteLine(String::Format("Result: %s, filename is %s", path.CString(), path.GetFileName().CString()));
	Console::GetDefault()->Out->WriteLine(String::Format("Directory is: %s", path.GetDirectory().CString()));

	Console::GetDefault()->Out->WriteLine(" --- Directory Iteration Test --- ");
	Console::GetDefault()->Out->WriteLine("Listing contents of current directory...");
	AutoPointer<FileNode> node = autonew FilesystemNode("."); // current dir
#if BRICKS_CONFIG_CPP0X
	node->Iterate([](FileNode* subnode) -> bool {
		Console::GetDefault()->Out->WriteLine(String::Format("Subfile: %s", subnode->GetName().CString()));
		return true; // returning false is like break;ing out of the loop.