Exemple #1
3
//----------------------------------------------------------------------
int FFileDialog::changeDir (const FString& dirname)
{
  FString lastdir = directory;
  FString newdir = dirname;

  if ( newdir.includes('~') )
    newdir = newdir.replace('~', getHomeDir());

  if ( newdir[0] == '/' )
    setPath(newdir);
  else
    setPath(directory + newdir);

  switch ( readDir() )
  {
    case -1:
      setPath(lastdir);
      return -1;

    case -2:
      setPath(lastdir);
      readDir();
      return -2;

    case 0:
      if ( newdir == FString("..") )
      {
        if ( lastdir == FString('/') )
          filename.setText('/');
        else
        {
          auto baseName = basename(C_STR(lastdir.c_str()));
          selectDirectoryEntry (baseName);
        }
      }
      else
      {
        FString firstname = dir_entries[0].name;

        if ( dir_entries[0].directory )
          filename.setText(firstname + '/');
        else
          filename.setText(firstname);
      }

      printPath(directory);
      filename.redraw();
      filebrowser.redraw();
      // fall through
    default:
      return 0;
  }
}
Exemple #2
0
static const char *
getOldConfigDir( void )
{
    static char * path = NULL;

    if( !path )
    {
#ifdef __BEOS__
        char buf[MAX_PATH_LENGTH];
        find_directory( B_USER_SETTINGS_DIRECTORY,
                       dev_for_path( "/boot" ), true,
                       buf, sizeof( buf ) );
        path = tr_buildPath( buf, "Transmission", NULL );
#elif defined( SYS_DARWIN )
        path = tr_buildPath( getHomeDir( ), "Library",
                              "Application Support",
                              "Transmission", NULL );
#elif defined( __AMIGAOS4__ )
        path = tr_strdup( "PROGDIR:.transmission" );
#elif defined( WIN32 )
        char appdata[MAX_PATH]; /* SHGetFolderPath() requires MAX_PATH */
        SHGetFolderPath( NULL, CSIDL_APPDATA, NULL, 0, appdata );
        path = tr_buildPath( appdata, "Transmission", NULL );
#else
        path = tr_buildPath( getHomeDir( ), ".transmission", NULL );
#endif
    }

    return path;
}
Exemple #3
0
static const char *
getOldConfigDir( void )
{
    static char * path = NULL;

    if( !path )
    {
#ifdef SYS_DARWIN
        path = tr_buildPath( getHomeDir( ), "Library",
                              "Application Support",
                              "Transmission", NULL );
#elif defined( WIN32 )
        char appdata[MAX_PATH]; /* SHGetFolderPath() requires MAX_PATH */
        SHGetFolderPath( NULL, CSIDL_APPDATA, NULL, 0, appdata );
        path = tr_buildPath( appdata, "Transmission", NULL );
#elif defined( __HAIKU__ )
        char buf[TR_PATH_MAX];
        find_directory( B_USER_SETTINGS_DIRECTORY, -1, true, buf, sizeof(buf) );
        path = tr_buildPath( buf, "Transmission", NULL );
#else
        path = tr_buildPath( getHomeDir( ), ".transmission", NULL );
#endif
    }

    return path;
}
Exemple #4
0
const char*
tr_getDefaultConfigDir( void )
{
    static char * s = NULL;

    if( !s )
    {
        if( ( s = getenv( "TRANSMISSION_HOME" ) ) )
        {
            s = tr_strdup( s );
        }
        else
        {
#ifdef SYS_DARWIN
            s = tr_buildPath( getHomeDir( ), "Library",
                              "Application Support", "Transmission", NULL );
#elif defined( WIN32 )
            char appdata[MAX_PATH]; /* SHGetFolderPath() requires MAX_PATH */
            SHGetFolderPath( NULL, CSIDL_APPDATA, NULL, 0, appdata );
            s = tr_buildPath( appdata, "Transmission", NULL );
#else
            if( ( s = getenv( "XDG_CONFIG_HOME" ) ) )
                s = tr_buildPath( s, "transmission", NULL );
            else
                s = tr_buildPath( getHomeDir( ), ".config", "transmission", NULL );
#endif
        }
    }

    return s;
}
Exemple #5
0
void QJDMainWindow::creatNewArea(QString areaName)
{
    QString lowerCaseAreaName;
    lowerCaseAreaName=areaName.toLower();
    lowerCaseAreaName.simplified();
    lowerCaseAreaName.remove(" ");
    qDebug()<<"creatNewArea::"<<areaName<<lowerCaseAreaName;  // 所有大写阿,带空格的之类的统一小写,并且去空格

    //1. 创建文件夹
    QDir newDir;
    newDir.setPath(getHomeDir());
    if(newDir.exists(lowerCaseAreaName))
    {
        QMessageBox::warning(this,"Warning!","Do not creat the same AREA again!");
        return;
    }

    if(!newDir.mkdir(lowerCaseAreaName))
        qDebug()<<"Creat New Area Dir failed";

    //2. 创建.Desc
    QFile newDesc;
    newDesc.setFileName(newDir.path()+"/"+lowerCaseAreaName+"/DescName");
    if(!newDesc.open(QFile::WriteOnly))
    {
        qDebug()<<"creat new desc open failed";
    }
    QTextStream ts(&newDesc);
    ts<<areaName<<"\n";
    newDesc.close();

    setHomeDir(getHomeDir());
    areaWidget->expandToDepth(1);
}
Exemple #6
0
const char*
tr_getDefaultDownloadDir (void)
{
    static char * user_dir = NULL;

    if (user_dir == NULL)
    {
        const char * config_home;
        char * config_file;
        char * content;
        size_t content_len;

        /* figure out where to look for user-dirs.dirs */
        config_home = getenv ("XDG_CONFIG_HOME");
        if (config_home && *config_home)
            config_file = tr_buildPath (config_home, "user-dirs.dirs", NULL);
        else
            config_file = tr_buildPath (getHomeDir (), ".config", "user-dirs.dirs", NULL);

        /* read in user-dirs.dirs and look for the download dir entry */
        content = (char *) tr_loadFile (config_file, &content_len);
        if (content && content_len>0)
        {
            const char * key = "XDG_DOWNLOAD_DIR=\"";
            char * line = strstr (content, key);
            if (line != NULL)
            {
                char * value = line + strlen (key);
                char * end = strchr (value, '"');

                if (end)
                {
                    *end = '\0';

                    if (!memcmp (value, "$HOME/", 6))
                        user_dir = tr_buildPath (getHomeDir (), value+6, NULL);
                    else if (!strcmp (value, "$HOME"))
                        user_dir = tr_strdup (getHomeDir ());
                    else
                        user_dir = tr_strdup (value);
                }
            }
        }

        if (user_dir == NULL)
#ifdef __HAIKU__
            user_dir = tr_buildPath (getHomeDir (), "Desktop", NULL);
#else
            user_dir = tr_buildPath (getHomeDir (), "Downloads", NULL);
#endif

        tr_free (content);
        tr_free (config_file);
    }

    return user_dir;
}
Exemple #7
0
static int
FindXDPSNXInXrmDatabase(
     Display *dpy,
     char **host,
     int *transport,
     int *port)
{
  XrmDatabase rDB = NULL;	/* for merged database */
  XrmDatabase serverDB;
  char filenamebuf[1024];
  char *filename = &filenamebuf[0];
  char *env, *str_type;
  char name[255];
  XrmValue value;
  int retVal = !Success;

  XrmInitialize();
  (void) strcpy(name, "/usr/lib/X11/app-defaults/");
  (void) strcat(name, XDPSNX_X_CLASS_NAME);
  
  /* try to get application defaults file, if there is any */
  XrmMergeDatabases(XrmGetFileDatabase(name), &rDB);

  /* try to merge the server defaults.  if not defined then use .Xdefaults */
  if (XResourceManagerString(dpy) != NULL) {
    serverDB = XrmGetStringDatabase(XResourceManagerString(dpy));
  } else {			/* use the .Xdefaults */
    (void) getHomeDir(filename);
    (void) strcat(filename, "/.Xdefaults");
    
    serverDB = XrmGetFileDatabase(filename);
  }
  XrmMergeDatabases(serverDB, &rDB);
 
  /* try the XENVIRONMENT file, or if not defined, then .Xdefaults */
  if ((env = getenv("XENVIRONMENT")) == NULL) {
    int len;
    env = getHomeDir(filename);
    (void) strcat(filename, "/.Xdefaults-");
    len = strlen(env);
    (void) gethostname(env+len, 1024-len);
  }
  XrmMergeDatabases(XrmGetFileDatabase(env), &rDB);

  /* Now that the database is built, try to extract the values we want. */

  if (XrmGetResource(rDB, XDPSNX_X_RESOURCE, XDPSNX_X_CLASS_NAME, &str_type,
		     &value) == True) {
    retVal = ParseAgentString((char *) value.addr, host, transport, port);
  }
  (void) XrmDestroyDatabase(rDB);
  return(retVal);
}
bool InvokeJavascript_NoArgs(NPObject *npobj, const char *methodName, NPVariant *&result) {
  bool success = false;
  if (!strcmp(methodName, "getPlatform")) {
    //getPlatform() : string
#if defined(OS_WIN)
    success = SetReturnValue("windows", 7, *result);
#elif defined(OS_LINUX)
    success = SetReturnValue("linux", 5, *result);
#endif 
  } else if (!strcmp(methodName, "getTempPath") || !strcmp(methodName, "getTmpPath")) {
    char *value = NULL;
    size_t len = 0;
    if (getTempPath(value, len)) {
      success = SetReturnValue(value, len, *result);
      delete[] value;
    }
  }
  else if (!strcmp(methodName,"getHomeDir")) {
    char *value = NULL;
    size_t len=0;
    getHomeDir(value, len);
    success = SetReturnValue(value, len, *result);
  }
  return success;
}
Exemple #9
0
Glib::ustring CSystem::getAsString(void){
	std::stringstream l_str;
	/*
	 id;"name";"description";"icon_file";"dat_file";"bios_file";"home_dir";""rom_dir";
	"snap_dir";"tittle_dir";"front_dir";"back_dir";"media_dir";emulator_id;
	"datname";"datDescription";"datcategory";datversion";"datauthor";datgames;
	*/

	l_str << getId() << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getName()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getDescription()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getIconFile()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getDatFile()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getBiosFile()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getHomeDir()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getRomsDir()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getSnapDir()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getTitleDir()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getFrontDir()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getBackDir()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getMediaDir()) << "\"" << CSV_SEPARATOR
		<< getEmulatorId() << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getDatName()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getDatDescription()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getDatCategory()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getDatVersion()) << "\"" << CSV_SEPARATOR
		<< "\"" << Glib::strescape(getDatAuthor()) << "\"" << CSV_SEPARATOR
		<< getDatGames() << CSV_SEPARATOR
		<< std::endl;
	return l_str.str();
}
Exemple #10
0
PRIVATE char*   expandTilde (
                            const char*    destBuff,
                                  char**   srcPtrPtr,
                            const size_t   destBuffSize
                            )
   {
   register char*   dstPtr = (char*)destBuff;
   register char*   srcPtr;

   ASSERT_RTN (destBuff != NULL,  "expandTilde: no destBuff",     NULL);
   ASSERT_RTN (srcPtrPtr != NULL, "expandTilde: no srcPtrPtr",    NULL);
   ASSERT_RTN (destBuffSize > 0,  "expandTilde: no destBuffSize", NULL);

   if ((destBuff == NULL) || (srcPtrPtr == NULL) || (destBuffSize == 0))
      {
      return (NULL);
      }

   srcPtr = *srcPtrPtr;

   ASSERT_RTN (srcPtr != NULL, "expandTilde: no srcPtr", NULL);

   if (srcPtr == NULL) return (NULL);

   if ((*srcPtr == '~') && (destBuffSize > 0))
      {

      ++srcPtr;
      if ((*srcPtr == '/') || (*srcPtr == '\0'))
         {
         /* expand `~' to this user's home directory. */
         dstPtr = getHomeDir (dstPtr, destBuffSize);
         }
      else
         {
         /* Buggy: we assume we have a username at srcPtr. */
         /* expand `~<username>' to some <username>'s home directory. */
                  int     index;
                  char*   userName;
         register char*   tmpDst;
         if ((userName=(char*)CSC_MALLOC_FUNC(1,80)) != NULL) /* bug #1 */
            {
            tmpDst = userName;
            index = 79;
            while ((*srcPtr != '/') && (*srcPtr != '\0') && (index-- > 0))
               {
               *tmpDst++ = *srcPtr++;
               }
            *tmpDst = '\0';
            dstPtr = getUserHomeDir (dstPtr, userName, destBuffSize);
            (void)CSC_FREE_FUNC (userName);
            }
         }

      }

   *srcPtrPtr = srcPtr;

   return (dstPtr);
   }
Exemple #11
0
void TwitPicView::setImagePath()
{
  m_ui->imagePathEdit->setText( QFileDialog::getOpenFileName(
      this, tr( "Select photo to upload" ),
      settings.value("TwitPic/lastPath", getHomeDir()).toString(),
      tr( "Image files" ).append( " (*.jpg *.jpeg *.png *.bmp *.gif *.JPG *.JPEG *.PNG *.GIF)" ) ) );
}
Exemple #12
0
// 除了创建窗口输入名称之外,输入完毕之后还需要创建一个submdi
void QJDMainWindow::on_actionNewFlow_triggered()
{
    QJDNewFlow *newFlow=new QJDNewFlow;
    qDebug()<<"New Flow"<<newFlow;  // it will have different new area
    /// 万一重复了呢?不需要执行以下的语句了嗄
    connect(newFlow,SIGNAL(sigFlowName(QString)),this,SLOT(creatNewFlow(QString)));
    newFlow->exec();
    // ---------------------------------------------------------------------- //
    // 模态,以下语句将在已返回的情况下执行,除了需要名称之外,路径也需要
    qDebug()<<"can?::"<<canCreatNewFlow
            <<"|after new flow->exec!"<<newFlow->getFlowName()<<areaWidget->returnPathStr;
    qDebug()<<"level::"<<areaWidget->level();
    if(canCreatNewFlow==true)
    {
        if(areaWidget->level()==2)
        {
            QString linePath=areaWidget->getAbsolutePath();
            mdiWidget->newSubWindow(newFlow->getFlowName(),linePath);
        }

        tabWidget->setCurrentIndex(1);
        setHomeDir(getHomeDir());
        areaWidget->expandToDepth(1);
    }
}
Exemple #13
0
/**
 * Provides a config file from the given location
 * @param loc:
 * 0 - the current directory. If none found, then:
 * 1 - the users HOME directory
 */
string ConfigReader::provideConfigFile ( int loc )
{
    string homeDir;
    char dir [1024];
    string res = "";
    switch ( loc )
    {
    case 0: // config file from the current directory
        getcwd ( dir, 1024 );
        res = dir;
#ifdef _WIN32
        res += "\\";
#else
        res += "/";
#endif
        res += configFile;
        fullPath = res;
        return res;

    case 1: // config file from the users home directory
        homeDir = getHomeDir();
#ifdef _WIN32
        homeDir += "\\";
#else
        homeDir += "/";
#endif
        homeDir += configFile;
        fullPath = homeDir;
        return homeDir;
    default:
        return "";
    }
}
Exemple #14
0
/**
 * Creates a new config dynamically searching for config file locations.
 */
ConfigReader::ConfigReader ( const string& file ) : configFile ( file ), doc ( NULL ), initSuccesful ( true )
{
    std::string s = getHomeDir();
    std::string s1 = getHomeDir();

    if(s != s1)
    {
        LOG("ff");
    }
    if ( loadConfig ( provideConfigFile ( 0 ) ) )
    {
        return;
    }
    if ( loadConfig ( provideConfigFile ( 1 ) ) )
    {
        return;
    }
    initSuccesful = false;
}
Exemple #15
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    std::string homeDir = *getHomeDir() + "/.djon";
    std::string workspaceFile = homeDir + "/default.dwk";
    _workspace = loadWorkspace(workspaceFile);
    _plugin = new Coreplugin();
}
Exemple #16
0
boost::filesystem::path Helper::Paths::getAppDataDir() const
{
  boost::filesystem::path ret;
  if(_executablePath.empty())
    _executablePath = getExecutablePath();
  if(_homedir.empty())
    _homedir = getHomeDir();

  ret = _homedir;
  ret += _executablePath.stem();
  return ret;
}
string gt::Platform::getDefaultConfigPath()
{
    const char *c = getenv("XDG_CONFIG_HOME");
    string config_home;

    if (c == nullptr)
        config_home = getHomeDir() + ".config";
    else
        config_home = c;

    config_home += "/gtorrent/";
    return config_home;
}
Exemple #18
0
const char*
tr_getDefaultConfigDir( const char * appname )
{
    static char * s = NULL;

    if( !appname || !*appname )
        appname = "Transmission";

    if( !s )
    {
        if( ( s = getenv( "TRANSMISSION_HOME" ) ) )
        {
            s = tr_strdup( s );
        }
        else
        {
#ifdef SYS_DARWIN
            s = tr_buildPath( getHomeDir( ), "Library", "Application Support",
                              appname, NULL );
#elif defined( WIN32 )
            char appdata[MAX_PATH]; /* SHGetFolderPath() requires MAX_PATH */
            SHGetFolderPath( NULL, CSIDL_APPDATA, NULL, 0, appdata );
            s = tr_buildPath( appdata, appname, NULL );
#elif defined( __HAIKU__ )
            char buf[MAX_PATH_LENGTH];
            find_directory( B_USER_SETTINGS_DIRECTORY, -1, true, buf, sizeof(buf) );
            s = tr_buildPath( buf, appname, NULL );
#else
            if( ( s = getenv( "XDG_CONFIG_HOME" ) ) )
                s = tr_buildPath( s, appname, NULL );
            else
                s = tr_buildPath( getHomeDir( ), ".config", appname, NULL );
#endif
        }
    }

    return s;
}
Exemple #19
0
void Environment::init(int argc, char* argv[])
{
	_homePath = getHomeDir();

#ifdef PKGDATADIR
	_appPath = std::string(PKGDATADIR) + "/" + RADIANT_DIRECTORY;
	if (!(g_file_test(_appPath.c_str(), (GFileTest)G_FILE_TEST_IS_DIR) && g_path_is_absolute(_appPath.c_str())))
#endif
	{
		gchar *currentDir = g_get_current_dir();
		_appPath = DirectoryCleaned(currentDir);
		g_free(currentDir);
	}
	initPaths();
}
Exemple #20
0
char* readPreference(const std::string& key, const char* def) {
    std::string* home = getHomeDir();
    std::string fileName = home->append("/.djon/djon.user");

    string cont = readFile(const_cast<char*>(fileName.c_str()));

    char* value = readValue(cont, key);

    if (strlen(value) == 0) {
        free(value);
        value = strcpy(def);
    }

    delete (home);

    return value;
}
Exemple #21
0
int writePreference(const std::string& key, const std::string& value) {
    std::string* home = getHomeDir();
    std::string fileName = home->append("/.djon/djon.user");

    qDebug("writePreference key: %s, value: %s", key.c_str(), value.c_str());
    std::string currentData = std::string(readFile(const_cast<char*> (fileName.c_str())));

    qDebug("currentData %s", currentData.c_str());
    currentData = replaceValue(currentData, key, value);
    qDebug("newData %s", currentData.c_str());

    int res = writeFile(fileName, currentData, false);

    delete(home);

    return res;
}
char* proxy_cache(char* input_url, char* h_path, int semid)
{
        umask(000);             //set permission umask(000)
        char homedir[30];
	char hash_url[41];      //hashed URL
        int check = 0;          //check variable

        struct dirent *pFile;   //declare dirent
        DIR *pDir;              //declare DIR 
	
	strcpy(h_path, getHomeDir(homedir));
        strcat(h_path, "/proxy_cache");                 //attach "/proxy_cache" after home directory
        mkdir(h_path, S_IRWXU | S_IRWXG | S_IRWXO);     //make proxy_cache directory

        sha1_hash(input_url, hash_url);                 //convert input_url to hashed URL
        strncat(h_path, "/",1);                         //attach "/" to h_path
        strncat(h_path, hash_url,1);                    //attach hash_url[0] to h_path
        //current h_path = "home directory/proxy_cache/hash_url[0]"

        mkdir(h_path, S_IRWXU | S_IRWXG | S_IRWXO);     //make h_path directory
	
        strncat(h_path, "/",1);                         //attach "/' to h_path
        strncat(h_path,&hash_url[1], 1);                //attach hash_url[1] to h_path
        //current h_path = "home directory/proxy_cache/hash_url[0]/hash_url[1]"
        check=mkdir(h_path, S_IRWXU | S_IRWXG | S_IRWXO);       //make h_path directory
        if(check==-1){                                          //only in case h_path aleady exist, to read file is executed.   
                pDir=opendir(h_path);                           //pDir = h_path directory

                for(pFile=readdir(pDir); pFile; pFile=readdir(pDir)){           //check same name file to already exist(
                        if(strcmp(pFile->d_name, &hash_url[2])==0){             //compare files in h_pat with hash_url[2]~end
                                //!HIT!
                                //print hash_url, local time in "logfile"
				print_logfile(1, semid, hash_url);			
                                check=1;        //if same check ==1? HIT
                                break;
                        }
                }
                closedir(pDir);                 //close directory
        }


        strncat(h_path, "/",1);                 //attach "/" to h_path
        strcat(h_path, &hash_url[2]);                        //current h_path="home directory/proxy_cache/hash_url[0]/hash_url[1]/hash_url[2]~end"
	
        return h_path;
}
Exemple #23
0
static const char *
getOldCacheDir( void )
{
    static char * path = NULL;

    if( !path )
    {
#if defined( __BEOS__ ) || defined( WIN32 )
        path = tr_buildPath( getOldConfigDir( ), "Cache", NULL );
#elif defined( SYS_DARWIN )
        path = tr_buildPath( getHomeDir( ), "Library", "Caches", "Transmission", NULL );
#else
        path = tr_buildPath( getOldConfigDir( ), "cache", NULL );
#endif
    }

    return path;
}
void ZLUnixFSManager::normalizeRealPath(std::string &path) const {
	static std::string HomeDir = getHomeDir();
	static std::string PwdDir = getPwdDir();

	if (path.empty()) {
		path = PwdDir;
	} else if (path[0] == '~') {
		if ((path.length() == 1) || (path[1] == '/')) {
			path = HomeDir + path.substr(1);
		}
	} else if (path[0] != '/') {
		path = PwdDir + '/' + path;
	}
	int last = path.length() - 1;
	while ((last > 0) && (path[last] == '/')) {
		--last;
	}
	if (last < (int)path.length() - 1) {
		path = path.substr(0, last + 1);
	}

	int index;
	while ((index = path.find("/../")) != -1) {
		int prevIndex = std::max((int)path.rfind('/', index - 1), 0);
		path.erase(prevIndex, index + 3 - prevIndex);
	}
	int len = path.length();
	if ((len >= 3) && (path.substr(len - 3) == "/..")) {
		int prevIndex = std::max((int)path.rfind('/', len - 4), 0);
		path.erase(prevIndex);
	}
	while ((index = path.find("/./")) != -1) {
		path.erase(index, 2);
	}
	while (path.length() >= 2 &&
				 path.substr(path.length() - 2) == "/.") {
		path.erase(path.length() - 2);
	}
	while ((index = path.find("//")) != -1) {
		path.erase(index, 1);
	}
}
Exemple #25
0
PUBLIC char*   (CSCfileGetHomeDir) (
                                   const size_t                 pathSize,
                                         CSCmemListType   const memList,
                                         int                    memTag
                                   )
   {
   char*   homeDirPath = NULL;

   ASSERT_RTN (pathSize > 0,    "CSCfileGetHomeDir: no pathSize",  NULL);
   ASSERT_RTN (memList != NULL, "CSCfileGetHomeDir: NULL memList", NULL);

   if ((pathSize == 0) || (memList == NULL)) return (NULL);

   if (CSCmemAlloc(memList,(void**)&homeDirPath,1,pathSize,memTag) == CSC_OK)
      {
      homeDirPath = getHomeDir (homeDirPath, pathSize);
      }

   return (homeDirPath);
   }
int EclCMDShell::run()
{
    try
    {
        if (!parseCommandLineOptions(args))
            return 1;

        if (!optIniFilename)
        {
            StringBuffer fn;
            if (checkFileExists(INIFILE))
                optIniFilename.set(INIFILE);
            else if (getHomeDir(fn) && checkFileExists(addPathSepChar(fn).append(INIFILE)))
                optIniFilename.set(fn);
            else if (fn.set(SYSTEMCONFDIR).append(PATHSEPSTR).append(DEFAULTINIFILE))
                optIniFilename.set(fn);
        }

        globals.setown(createProperties(optIniFilename, true));
        finalizeOptions(globals);

        return processCMD(args);
    }
    catch (IException *E)
    {
        StringBuffer m;
        fputs(E->errorMessage(m.newline()).newline().str(), stderr);
        E->Release();
        return 2;
    }
#ifndef _DEBUG
    catch (...)
    {
        ERRLOG("Unexpected exception\n");
        return 4;
    }
#endif
    return 0;
}
Exemple #27
0
std::string getConfigFileName() {
    std::string* homeDir = getHomeDir();
    std::string confFileName = *homeDir + "/.djon/djon.conf";
    delete (homeDir);
    return confFileName;
}
Exemple #28
0
signed char SWMgr::Load() {
	signed char ret = 0;

	if (!config) {	// If we weren't passed a config object at construction, find a config file
		if (!configPath) {	// If we weren't passed a config path at construction...
			SWLog::getSystemLog()->logDebug("LOOKING UP MODULE CONFIGURATION...");
			SWConfig *externalSysConf = sysConfig;	// if we have a sysConf before findConfig, then we were provided one from an external source.
			findConfig(&configType, &prefixPath, &configPath, &augPaths, &sysConfig);
			if (!externalSysConf) mysysconfig = sysConfig;	// remind us to delete our own sysConfig in d-tor
			SWLog::getSystemLog()->logDebug("LOOKING UP MODULE CONFIGURATION COMPLETE.");
		}
		if (configPath) {
			if (configType)
				loadConfigDir(configPath);
			else	config = myconfig = new SWConfig(configPath);
		}
	}

	if (config) {
		SectionMap::iterator Sectloop, Sectend;
		ConfigEntMap::iterator Entryloop, Entryend;

		DeleteMods();

		for (Sectloop = config->Sections.lower_bound("Globals"), Sectend = config->Sections.upper_bound("Globals"); Sectloop != Sectend; Sectloop++) {		// scan thru all 'Globals' sections
			for (Entryloop = (*Sectloop).second.lower_bound("AutoInstall"), Entryend = (*Sectloop).second.upper_bound("AutoInstall"); Entryloop != Entryend; Entryloop++)	// scan thru all AutoInstall entries
				InstallScan((*Entryloop).second.c_str());		// Scan AutoInstall entry directory for new modules and install
		}		
		if (configType) {	// force reload on config object because we may have installed new modules
			delete myconfig;
			config = myconfig = 0;
			loadConfigDir(configPath);
		}
		else	config->Load();

		CreateMods(mgrModeMultiMod);

		for (std::list<SWBuf>::iterator pathIt = augPaths.begin(); pathIt != augPaths.end(); pathIt++) {
			augmentModules(pathIt->c_str(), mgrModeMultiMod);
		}
		if (augmentHome) {
			// augment config with ~/.sword/mods.d if it exists ---------------------
			SWBuf homeDir = getHomeDir();
			if (homeDir.length() && configType != 2) { // 2 = user only
				SWBuf path = homeDir;
				path += ".sword/";
				augmentModules(path.c_str(), mgrModeMultiMod);
				path = homeDir;
				path += "sword/";
				augmentModules(path.c_str(), mgrModeMultiMod);
			}
		}
// -------------------------------------------------------------------------
		if (!Modules.size()) // config exists, but no modules
			ret = 1;

	}
	else {
		SWLog::getSystemLog()->logError("SWMgr: Can't find 'mods.conf' or 'mods.d'.  Try setting:\n\tSWORD_PATH=<directory containing mods.conf>\n\tOr see the README file for a full description of setup options (%s)", (configPath) ? configPath : "<configPath is null>");
		ret = -1;
	}

	return ret;
}
Exemple #29
0
void SWMgr::findConfig(char *configType, char **prefixPath, char **configPath, std::list<SWBuf> *augPaths, SWConfig **providedSysConf) {
	SWBuf path;
	SWBuf sysConfPath;
	ConfigEntMap::iterator entry;
	ConfigEntMap::iterator lastEntry;

	SWConfig *sysConf = 0;
	SWBuf sysConfDataPath = "";

	*configType = 0;

	SWBuf homeDir = getHomeDir();

	// check for a sysConf passed in to us
	SWLog::getSystemLog()->logDebug("Checking for provided SWConfig(\"sword.conf\")...");
	if (providedSysConf && *providedSysConf) {
		sysConf = *providedSysConf;
		SWLog::getSystemLog()->logDebug("found.");
	}

	// if we haven't been given our datapath in a sysconf, we need to track it down
	if (!sysConf) {
		// check working directory
		SWLog::getSystemLog()->logDebug("Checking working directory for sword.conf...");
		if (FileMgr::existsFile(".", "sword.conf")) {
			SWLog::getSystemLog()->logDebug("Overriding any systemwide or ~/.sword/ sword.conf with one found in current directory.");
			sysConfPath = "./sword.conf";
			sysConf = new SWConfig(sysConfPath);
			if ((entry = sysConf->Sections["Install"].find("DataPath")) != sysConf->Sections["Install"].end()) {
				sysConfDataPath = (*entry).second;
			}
			if (providedSysConf) {
				*providedSysConf = sysConf;
			}
			else {
				delete sysConf;
				sysConf = 0;
			}
		}
		if (!sysConfDataPath.size()) {
			SWLog::getSystemLog()->logDebug("Checking working directory for mods.conf...");
			if (FileMgr::existsFile(".", "mods.conf")) {
				SWLog::getSystemLog()->logDebug("found.");
				stdstr(prefixPath, "./");
				stdstr(configPath, "./mods.conf");
				return;
			}

			SWLog::getSystemLog()->logDebug("Checking working directory for mods.d...");
			if (FileMgr::existsDir(".", "mods.d")) {
				SWLog::getSystemLog()->logDebug("found.");
				stdstr(prefixPath, "./");
				stdstr(configPath, "./mods.d");
				*configType = 1;
				return;
			}

			// check working directory ../library/
			SWLog::getSystemLog()->logDebug("Checking working directory ../library/ for mods.d...");
			if (FileMgr::existsDir("../library", "mods.d")) {
				SWLog::getSystemLog()->logDebug("found.");
				stdstr(prefixPath, "../library/");
				stdstr(configPath, "../library/mods.d");
				*configType = 1;
				return;
			}

			// check environment variable SWORD_PATH
			SWLog::getSystemLog()->logDebug("Checking $SWORD_PATH...");

			SWBuf envsworddir = getenv("SWORD_PATH");
			if (envsworddir.length()) {
				
				SWLog::getSystemLog()->logDebug("found (%s).", envsworddir.c_str());
				path = envsworddir;
				if ((envsworddir[envsworddir.length()-1] != '\\') && (envsworddir[envsworddir.length()-1] != '/'))
					path += "/";

				SWLog::getSystemLog()->logDebug("Checking $SWORD_PATH for mods.conf...");
				if (FileMgr::existsFile(path.c_str(), "mods.conf")) {
					SWLog::getSystemLog()->logDebug("found.");
					stdstr(prefixPath, path.c_str());
					path += "mods.conf";
					stdstr(configPath, path.c_str());
					return;
				}

				SWLog::getSystemLog()->logDebug("Checking $SWORD_PATH for mods.d...");
				if (FileMgr::existsDir(path.c_str(), "mods.d")) {
					SWLog::getSystemLog()->logDebug("found.");
					stdstr(prefixPath, path.c_str());
					path += "mods.d";
					stdstr(configPath, path.c_str());
					*configType = 1;
					return;
				}
			}


			// check for systemwide globalConfPath

			SWLog::getSystemLog()->logDebug("Parsing %s...", globalConfPath);
			char *globPaths = 0;
			char *gfp;
			stdstr(&globPaths, globalConfPath);
			for (gfp = strtok(globPaths, ":"); gfp; gfp = strtok(0, ":")) {
				SWLog::getSystemLog()->logDebug("Checking for %s...", gfp);
				if (FileMgr::existsFile(gfp)) {
					SWLog::getSystemLog()->logDebug("found.");
					break;
				}
			}
			if (gfp)
				sysConfPath = gfp;
			delete [] globPaths;

			if (homeDir.length()) {
				SWBuf tryPath = homeDir;
				tryPath += ".sword/sword.conf";
				if (FileMgr::existsFile(tryPath)) {
					SWLog::getSystemLog()->logDebug("Overriding any systemwide sword.conf with one found in users home directory (%s)", tryPath.c_str());
					sysConfPath = tryPath;
				}
				else {
					SWBuf tryPath = homeDir;
					tryPath += "sword/sword.conf";
					if (FileMgr::existsFile(tryPath)) {
						SWLog::getSystemLog()->logDebug("Overriding any systemwide sword.conf with one found in users home directory (%s)", tryPath.c_str());
						sysConfPath = tryPath;
					}
				}
			}
		}
	}

	if (!sysConf && sysConfPath.size()) {
		sysConf = new SWConfig(sysConfPath);
	}

	if (sysConf) {
		if ((entry = sysConf->Sections["Install"].find("DataPath")) != sysConf->Sections["Install"].end()) {
			sysConfDataPath = (*entry).second;
		}
		if (sysConfDataPath.size()) {
			if ((!sysConfDataPath.endsWith("\\")) && (!sysConfDataPath.endsWith("/")))
				sysConfDataPath += "/";

			path = sysConfDataPath;
			SWLog::getSystemLog()->logDebug("DataPath in %s is set to %s.", sysConfPath.c_str(), path.c_str());
			SWLog::getSystemLog()->logDebug("Checking for mods.conf in DataPath...");
			
			if (FileMgr::existsFile(path.c_str(), "mods.conf")) {
				SWLog::getSystemLog()->logDebug("found.");
				stdstr(prefixPath, path.c_str());
				path += "mods.conf";
				stdstr(configPath, path.c_str());
				*configType = 1;
			}

			SWLog::getSystemLog()->logDebug("Checking for mods.d in DataPath...");

			if (FileMgr::existsDir(path.c_str(), "mods.d")) {
				SWLog::getSystemLog()->logDebug("found.");
				stdstr(prefixPath, path.c_str());
				path += "mods.d";
				stdstr(configPath, path.c_str());
				*configType = 1;
			}
		}
	}

	// do some extra processing of sysConf if we have one
	if (sysConf) {
		if (augPaths) {
			augPaths->clear();
			entry     = sysConf->Sections["Install"].lower_bound("AugmentPath");
			lastEntry = sysConf->Sections["Install"].upper_bound("AugmentPath");
			for (;entry != lastEntry; entry++) {
				path = entry->second;
				if ((entry->second.c_str()[strlen(entry->second.c_str())-1] != '\\') && (entry->second.c_str()[strlen(entry->second.c_str())-1] != '/'))
					path += "/";
				augPaths->push_back(path);
			}
		}
		if (providedSysConf) {
			*providedSysConf = sysConf;
		}
		else delete sysConf;
	}

	if (*configType)
		return;

	// WE STILL HAVEN'T FOUND A CONFIGURATION.  LET'S LOOK IN SOME OS SPECIFIC
	// LOCATIONS
	//
	// for various flavors of windoze...
	// check %ALLUSERSPROFILE%/Application Data/sword/

	SWLog::getSystemLog()->logDebug("Checking $ALLUSERSPROFILE/Application Data/sword/...");

	SWBuf envallusersdir  = getenv("ALLUSERSPROFILE");
	if (envallusersdir.length()) {
		SWLog::getSystemLog()->logDebug("found (%s).", envallusersdir.c_str());
		path = envallusersdir;
		if ((!path.endsWith("\\")) && (!path.endsWith("/")))
			path += "/";

		path += "Application Data/sword/";
		SWLog::getSystemLog()->logDebug("Checking %s for mods.d...", path.c_str());
		if (FileMgr::existsDir(path.c_str(), "mods.d")) {
			SWLog::getSystemLog()->logDebug("found.");
			stdstr(prefixPath, path.c_str());
			path += "mods.d";
			stdstr(configPath, path.c_str());
			*configType = 1;
			return;
		}
	}

	// for Mac OSX...
	// check $HOME/Library/Application Support/Sword/

	SWLog::getSystemLog()->logDebug("Checking $HOME/Library/Application Support/Sword/...");

	SWBuf pathCheck = getHomeDir();
	if (pathCheck.length()) {
		SWLog::getSystemLog()->logDebug("found (%s).", pathCheck.c_str());
		path = pathCheck;
		if ((!path.endsWith("\\")) && (!path.endsWith("/")))
			path += "/";

		SWLog::getSystemLog()->logDebug("Checking %s for mods.d...", path.c_str());
		if (FileMgr::existsDir(path.c_str(), "mods.d")) {
			SWLog::getSystemLog()->logDebug("found.");
			stdstr(prefixPath, path.c_str());
			path += "mods.d";
			stdstr(configPath, path.c_str());
			*configType = 1;
			return;
		}
	}

	// FINALLY CHECK PERSONAL HOME DIRECTORY LOCATIONS
	// check ~/.sword/

	SWLog::getSystemLog()->logDebug("Checking home directory for ~/.sword...");

	if (homeDir.length()) {
		path = homeDir;
		path += ".sword/";
		SWLog::getSystemLog()->logDebug("  Checking for %smods.conf...", path.c_str());
		if (FileMgr::existsFile(path.c_str(), "mods.conf")) {
			SWLog::getSystemLog()->logDebug("found.");
			stdstr(prefixPath, path.c_str());
			path += "mods.conf";
			stdstr(configPath, path.c_str());
			return;
		}

		SWLog::getSystemLog()->logDebug("  Checking for %smods.d...", path.c_str());
		if (FileMgr::existsDir(path.c_str(), "mods.d")) {
			SWLog::getSystemLog()->logDebug("found.");
			stdstr(prefixPath, path.c_str());
			path += "mods.d";
			stdstr(configPath, path.c_str());
			*configType = 2;
			return;
		}

		path = homeDir;
		path += "sword/";
		SWLog::getSystemLog()->logDebug("  Checking for %smods.d...", path.c_str());
		if (FileMgr::existsDir(path.c_str(), "mods.d")) {
			SWLog::getSystemLog()->logDebug("found.");
			stdstr(prefixPath, path.c_str());
			path += "mods.d";
			stdstr(configPath, path.c_str());
			*configType = 2;
			return;
		}
	}
}
Exemple #30
0
int main(int argc, char* argv[])
{
  signal(SIGTERM, sighandler);
  signal(SIGINT, sighandler);

#ifndef WIN32
  signal(SIGPIPE, pipehandler);
#else
  signal(SIGBREAK, sighandler);
#endif

  std::srand((uint32_t)std::time(NULL));
  initPRNG();

  std::string cfg;
  std::vector<std::string> overrides;

  for (int i = 1; i < argc; i++)
  {
    const std::string arg(argv[i]);

    switch (arg[0])
    {
    case '-':   // option
      // we have only '-h' and '--help' now, so just return with help
      return printHelp(EXIT_SUCCESS);

    case '+':   // override
      overrides.push_back(arg.substr(1));
      break;

    default:    // otherwise, it is config file
      if (!cfg.empty())
      {
        LOG2(ERROR, "Only single CONFIG_FILE argument is allowed!");
        return EXIT_FAILURE;
      }
      cfg = arg;
      break;
    }
  }

  const std::string path_exe = pathOfExecutable();
  unsigned int search_count = 0;

  std::cout << "Executable is in directory \"" << path_exe << "\".\n"
            << "Home/App directory is \"" << getHomeDir() << "\".\n"
            << "Searching for configuration file..." << std::endl;

  if (!cfg.empty())
  {
    std::cout << ++search_count << ". in specified file (\"" << cfg << "\"): ";
    if (fileExists(cfg))
    {
      const std::pair<std::string, std::string> fullpath = pathOfFile(cfg);
      cfg = fullpath.first + PATH_SEPARATOR + fullpath.second;
      Mineserver::get()->config()->config_path = fullpath.first;
      std::cout << "FOUND at \"" << cfg << "\"!\n";
    }
    else
    {
      std::cout << "not found\n";
      cfg.clear();
    }
  }
  if (cfg.empty())
  {
#ifdef DEBUG
    std::cout << ++search_count << ". in executable directory: ";
    if (fileExists(path_exe + PATH_SEPARATOR + CONFIG_FILE))
    {
      cfg = path_exe + PATH_SEPARATOR + CONFIG_FILE;
      Mineserver::get()->config()->config_path = path_exe;
      std::cout << "FOUND at \"" << cfg << "\"!\n";
    }
    else
    {
#endif
      std::cout << "not found\n"
                << ++search_count << ". in home/app directory: ";

      cfg = getHomeDir() + PATH_SEPARATOR + CONFIG_FILE;
      Mineserver::get()->config()->config_path = getHomeDir();

      if (fileExists(getHomeDir() + PATH_SEPARATOR + CONFIG_FILE))
      {
        std::cout << "FOUND at \"" << cfg << "\"!\n";
      }
      else
      {
        std::cout << "not found\n"
                  << "No config file found! We will place the factory default in \"" << cfg << "\"." << std::endl;
      }
#ifdef DEBUG
    }
#endif
  }
  std::cout << "Configuration directory is \"" << Mineserver::get()->config()->config_path << "\"." << std::endl;

  // create home and copy files if necessary
  Mineserver::get()->configDirectoryPrepare(Mineserver::get()->config()->config_path);

  // load config
  Config & config = *Mineserver::get()->config();
  if (!config.load(cfg))
  {
    return EXIT_FAILURE;
  }

  LOG2(INFO, "Using config: " + cfg);

  if (overrides.size())
  {
    std::stringstream override_config;
    for (size_t i = 0; i < overrides.size(); i++)
    {
      LOG2(INFO, "Overriden: " + overrides[i]);
      override_config << overrides[i] << ';' << std::endl;
    }
    // override config
    if (!config.load(override_config))
    {
      LOG2(ERROR, "Error when parsing overrides: maybe you forgot to doublequote string values?");
      return EXIT_FAILURE;
    }
  }

  bool ret = Mineserver::get()->init();

  if (!ret)
  {
    LOG2(ERROR, "Failed to start Mineserver!");
  }
  else
  {
    ret = Mineserver::get()->run();
  }

  Mineserver::get()->free();

  return ret ? EXIT_SUCCESS : EXIT_FAILURE;
}