Exemple #1
0
beast::File Config::getValidatorsFile () const
{
    beast::String const s (VALIDATORS_FILE.native().c_str());
    if (s.isNotEmpty() && getConfigDir() != beast::File::nonexistent())
        return getConfigDir().getChildFile (s);
    return beast::File::nonexistent ();
}
Exemple #2
0
void getResourceName( std::string &_out_str, const char *rname ) {
    std::stringstream ss;
    ss << getConfigDir() << "_" << rname;
    _out_str = ss.str();
    std::replace( _out_str.begin(), _out_str.end(), '\\', '_' );
    std::replace( _out_str.begin(), _out_str.end(), '/', '_' );
}
Exemple #3
0
//Sets ptrs 0 and load settings, only called once
void initSettings()
{
  settings.packDir=0;
  settings.playerName=0;
  printf( "Loading settings from: %s/settings.ini\n", getConfigDir() );

  loadSettings();
}
Exemple #4
0
bool Brewtarget::ensureDirectoriesExist()
{
   bool success;
   QDir dir;

   QString errTitle(QObject::tr("Directory Problem"));
   QString errText(QObject::tr("\"%1\" cannot be read."));

   // Check data dir
   dir.setPath(getDataDir());
   if( ! dir.exists() || ! dir.isReadable() )
   {
      QMessageBox::information(
         0,
         errTitle,
         errText.arg(dir.path())
      );
      return false;
   }

   // Check doc dir
   dir.setPath(getDocDir());
   if( ! dir.exists() || ! dir.isReadable() )
   {
      QMessageBox::information(
         0,
         errTitle,
         errText.arg(dir.path())
      );
      return false;
   }

   // Check config dir
   dir.setPath(getConfigDir(&success));
   if( !success || ! dir.exists() || ! dir.isReadable() )
   {
      QMessageBox::information(
         0,
         errTitle,
         errText.arg(dir.path())
      );
      return false;
   }

   // Check/create user data directory
   dir.setPath(getUserDataDir());
   if( !dir.exists() && !dir.mkpath(".") )
   {
      QMessageBox::information(
         0,
         errTitle,
         errText.arg(dir.path())
      );
      return false;
   }

   return true;
}
CLoginDlg::CLoginDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CLoginDlg::IDD, pParent)
{
	TCHAR  g_ConfigVedioDir[260];
	getConfigDir(g_ConfigVedioDir);
	m_EsOutCfgHigh     = new CEsOutCfg(g_ConfigVedioDir);
	m_EsOutCfgCommon   = new CEsOutCfg(g_ConfigVedioDir,_T("out2.xml"));
	m_EsMainCfg        = new CEsMainCfg(g_ConfigVedioDir);
}
Exemple #6
0
void getResourceName( char buf[1024], char *rname ) {
    snprintf( buf, 1024, "%s/%s", getConfigDir(), rname );
    char *ch = buf;
    while ( *ch != '\0' ) {
        if ( *ch == '\\' || *ch == '/' ) {
            *ch = '_';
        }
        ch++;
    }

}
Exemple #7
0
void saveSettings()
{
  char* buf = malloc(sizeof(char)*1024);
  sprintf( buf, "%s/settings.ini", getConfigDir() );

  FILE *f = fopen(buf, "w");
  if(f)
  {
    fprintf(f, "# Sound volume (0-128)\nsoundvol=%i\n\n"
               "# Music volume (0-128)\nmusicvol=%i\n\n"
               "# For the GP2X Wiz handheld: CPU Mhz.\nwizclock=%i\n\n"
               "# For the GP2X Wiz handheld: System-volume.\nwizvolume=%i\n\n"
               "# Show the FPS counter? 0 = No,  1 = Yes.\nshowfps=%i\n\n"
               "# Use particle effects? 0 = No,  1 = Yes.\nparticles=%i\n\n"
               "# 0 = Normal mode, progress through levels.\n# 1 = Arcade mode: Start on first level at game-over.\narcademode=%i\n\n"
               "# The currently selected content pack.\npackdir=%s\n\n"
               "# Name of the player.\nplayername=%s\n\n"
               "# If usermusic is on, play music from this directory.\nmusicdir=%s\n\n"
               "# 0 = Play the music that comes with the game. 1 = Use user-selected music. \nusermusic=%i\n\n"
               "# 0 = Play music. 1 = Don't load any music (faster loading)\ndisablemusic=%i\n\n"
               "# Allow Wizznic to access the Internet (http://wizznic.org)\n# 0 = No, 1 = Yes.\n# Helps Jimmy create more balanced gameplay in future versions.\n# Enables DLC downloading.\nallowonline=%i\n\n"
               "# 0 = No OpenGL Scaling. 1 = Use OpenGL to scale the image.\nglenable=%i\n\n"
               "# How to scale graphics ( 0 = Blocky/Sharp, 1 = Smooth/Blurry)\nglfilter=%i\n\n"
               "# If using glenable, the width of the window in pixels.\nglwidth=%i\n\n"
               "# If using glenable, the height of the window in pixels.\n# If this is -1, then select window size automatically.\nglheight=%i\n\n"
               "# Go to full-screen mode.\nfullscreen=%i\n\n"
               "# printf network traffic (when uploadstats=1)\nshowweb=%i\n",
               settings.soundVol,
               settings.musicVol,
               settings.wizClock,
               settings.wizVol,
               settings.showFps,
               settings.particles,
               settings.arcadeMode,
               settings.packDir,
               settings.playerName,
               settings.musicDir,
               settings.userMusic,
               settings.disableMusic,
               settings.uploadStats,
               settings.glEnable,
               settings.glFilter,
               settings.glWidth,
               settings.glHeight,
               settings.fullScreen,
               settings.showWeb);
    fclose( f );
  } else {
    printf("saveSettings(); Error: Couldn't open 'settings.ini' for writing.\n");
  }
  free(buf);
}
Exemple #8
0
void saveSettings()
{
  char* buf = malloc(sizeof(char)*1024);
  sprintf( buf, "%s/settings.ini", getConfigDir() );
  FILE *f = fopen(buf, "w");
  if(f)
  {
    fprintf(f, "soundvol=%i\n"
               "musicvol=%i\n"
               "# wizclock/vol is ignored on PC.\n"
               "wizclock=%i\n"
               "wizvolume=%i\n"
               "showfps=%i\n"
               "particles=%i\n"
               "arcademode=%i\n"
               "packdir=%s\n"
               "playername=%s\n"
               "musicdir=%s\n"
               "usermusic=%i\n"
               "disablemusic=%i\n"
               "uploadstats=%i\n"
               "glenable=%i\n"
               "glfilter=%i\n"
               "glwidth=%i\n"
               "glheight=%i\n"
               "fullscreen=%i\n",
               settings.soundVol,
               settings.musicVol,
               settings.wizClock,
               settings.wizVol,
               settings.showFps,
               settings.particles,
               settings.arcadeMode,
               settings.packDir,
               settings.playerName,
               settings.musicDir,
               settings.userMusic,
               settings.disableMusic,
               settings.uploadStats,
               settings.glEnable,
               settings.glFilter,
               settings.glWidth,
               settings.glHeight,
               settings.fullScreen);
    fclose( f );
  } else {
    printf("saveSettings(); Error: Couldn't open 'settings.ini' for writing.\n");
  }
  free(buf);
}
Exemple #9
0
std::string AppConfig::getConfigFileName(bool ignoreName) {
    std::string cfgFileDir = getConfigDir();

    wxFileName cfgFile;
    if (configName.length() && !ignoreName) {
        std::string tempFn("config-");
        tempFn.append(configName);
        tempFn.append(".xml");
        cfgFile = wxFileName(cfgFileDir, tempFn);
    } else {
        cfgFile = wxFileName(cfgFileDir, "config.xml");
    }

    std::string cfgFileName = cfgFile.GetFullPath(wxPATH_NATIVE).ToStdString();

    return cfgFileName;
}
Exemple #10
0
int
getReiFilePath( char *reiFilePath, char *userName ) {
    char *myUserName;

    if ( reiFilePath == NULL ) {
        return SYS_INTERNAL_NULL_INPUT_ERR;
    }

    if ( userName == NULL || strlen( userName ) == 0 ) {
        myUserName = DEF_REI_USER_NAME;
    }
    else {
        myUserName = userName;
    }

    snprintf( reiFilePath, MAX_NAME_LEN,
              "%-s/%-s/%-s.%-s.%-d", getConfigDir(), PACKED_REI_DIR,
              REI_FILE_NAME, myUserName, ( uint ) random() );

    return 0;
}
Exemple #11
0
void loadSettings()
{
  char* buf = malloc(sizeof(char)*2048);
  char* set = malloc(sizeof(char)*1024);
  char* val = malloc(sizeof(char)*1024);

  settings.bgPos.x = HSCREENW-160;
  settings.bgPos.y = HSCREENH-120;

  //Set defaults
  settings.soundVol=64;
  settings.musicVol=72;
  settings.wizClock=450;
  settings.showFps=0;
  settings.arcadeMode=0;
  settings.particles=1;
  settings.userMusic=0;
  settings.disableMusic=0;
  settings.wizVol=52;
  settings.glWidth=-1;
  settings.glHeight=-1;
  settings.glEnable=1;
  settings.glFilter=0;
  settings.fullScreen=0;
  settings.showWeb=0;

  //Not written to file
  settings.rift=0;
  settings.scaleFactor=1.0;
  settings.session=0;
  settings.solvedWorldWide=0;
  settings.firstRun=1;
  settings.uploadStats=-1;
  settings.online=0; //This is what will be checked for in the rest of the code
                     //regardless of "uploadStats", it will only be 1 if
                     //"uploadStats" is 1, because the check that can set it 1 is only
                     //executed if it's enabled.


  //Free ptrs.
  if(settings.packDir)
    free(settings.packDir);

  if(settings.playerName)
    free(settings.playerName);

  settings.packDir = malloc(sizeof(char)*(strlen(DATADIR"packs/000_wizznic")+1) );
  strcpy(settings.packDir, DATADIR"packs/000_wizznic");

  settings.playerName = malloc(sizeof(char)*11 );
  strcpy(settings.playerName, "player");

  settings.musicDir = cwd( NULL, 0 );
  if( !settings.musicDir )
    printf("Out of memory, will crash soon.\n");

  sprintf( buf, "%s/settings.ini", getConfigDir() );

  FILE *f = fopen(buf, "r");
  if(f)
  {
    while( fgets(buf, 128, f) )
    {
      stripNewLine(buf);

      if(splitVals('=',buf, set, val))
      {
        if( strcmp("soundvol", set)==0 )
        {
          settings.soundVol = atoi(val);
        } else
        if( strcmp("musicvol", set)==0 )
        {
          settings.musicVol = atoi(val);
        } else
        if( strcmp("wizclock", set)==0 )
        {
          settings.wizClock = atoi(val);
        } else
        if( strcmp("wizvolume", set)==0 )
        {
          settings.wizVol = atoi(val);
        } else
        if( strcmp("showfps", set)==0 )
        {
          settings.showFps = atoi(val);
        } else
        if( strcmp("arcademode", set)==0 )
        {
          settings.arcadeMode = atoi(val);
        } else
        if( strcmp("particles", set)==0 )
        {
          settings.particles = atoi(val);
        } else
        if( strcmp("packdir", set)==0 )
        {
          free(settings.packDir);
          settings.packDir = malloc(sizeof(char)*(strlen(val)+1) );
          strcpy(settings.packDir,val);
        } else
        if( strcmp("playername", set)==0 )
        {
          if( strlen(set) < 11 )
          {
            strcpy(settings.playerName,val);
          } else {
            printf("Error, name: '%s' too long, max length is 10.\n",set);
          }
        } else
        if( strcmp("musicdir", set)==0 )
        {
          //We check if it starts with . it now has to be a full path.
          if( val[0] != '.' )
          {
            free(settings.musicDir);
            settings.musicDir = malloc(sizeof(char)*(strlen(val)+1) );
            strcpy(settings.musicDir, val);
          } else {
            printf("Using '%s' as music directory instead of '%s'.\n", settings.musicDir, val);
          }
        } else
        if( strcmp("usermusic", set)==0 )
        {
          settings.userMusic=atoi(val);
        } else
        if( strcmp("disablemusic",set)==0 )
        {
          settings.disableMusic=atoi(val);
        } else
        if( strcmp("allowonline",set)==0 )
        {
          //Only if the option is in the file, are we sure they had the choice.
          settings.uploadStats=atoi(val);
          if( settings.uploadStats!=-1 )
          {
            settings.firstRun=0;
          }
        } else
        if( strcmp("glwidth",set)==0 )
        {
          settings.glWidth=atoi(val);
        } else
        if( strcmp("glheight",set)==0 )
        {
          settings.glHeight=atoi(val);
        } else
        if( strcmp("glenable",set)==0 )
        {
          settings.glEnable=atoi(val);
        } else
        if( strcmp("glfilter",set)==0 )
        {
          settings.glFilter=atoi(val);
        } else
        if( strcmp("fullscreen",set)==0 )
        {
          settings.fullScreen=atoi(val);
        } else
        if( strcmp("showweb",set)==0 )
        {
          settings.showWeb=atoi(val);
        }


      }
    }
    //Close file
    fclose( f );
  }

  //Free the textbuffers
  free(buf);
  free(set);
  free(val);
}
int readRuleStructAndRuleSetFromFile(char *ruleBaseName, ruleStruct_t *inRuleStrct)
{
/*  int i; */
/*  char l0[MAX_RULE_LENGTH]; */
/*  char l1[MAX_RULE_LENGTH]; */
/*  char l2[MAX_RULE_LENGTH]; */
/*  char l3[MAX_RULE_LENGTH]; */
   char rulesFileName[MAX_NAME_LEN];
/*   FILE *file; */
/*   char buf[MAX_RULE_LENGTH]; */
   char *configDir;
/*   char *t; */
/*   i = inRuleStrct->MaxNumOfRules; */

   if (ruleBaseName[0] == '/' || ruleBaseName[0] == '\\' ||
       ruleBaseName[1] == ':') {
     snprintf (rulesFileName,MAX_NAME_LEN, "%s",ruleBaseName);
   }
   else {
     configDir = getConfigDir ();
     snprintf (rulesFileName,MAX_NAME_LEN, "%s/reConfigs/%s.re", configDir,ruleBaseName);
   }
   /*file = fopen(rulesFileName, "r");
   if (file == NULL) {
#ifndef DEBUG
       rodsLog(LOG_NOTICE,
	     "readRuleStructFromFile() could not open rules file %s\n",
	     rulesFileName);
#endif
     return(RULES_FILE_READ_ERROR);
   }
   buf[MAX_RULE_LENGTH-1]='\0';
   while (fgets (buf, MAX_RULE_LENGTH-1, file) != NULL) {
     if (buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = '\0';
     if (buf[0] == '#' || strlen(buf) < 4)
       continue;
		char *l0, *l2, *l3;
		// rSplitStr(buf, l1, MAX_RULE_LENGTH, l0, MAX_RULE_LENGTH, '|');
		l0 = nextRuleSection(buf, l1);
     inRuleStrct->action[i] = strdup(l1);
     inRuleStrct->ruleHead[i] = strdup(l1);
     if ((t = strstr(inRuleStrct->action[i],"(")) != NULL) {
       *t = '\0';
     }
     inRuleStrct->ruleBase[i] = strdup(ruleBaseName);
		// rSplitStr(l0, l1, MAX_RULE_LENGTH, l3, MAX_RULE_LENGTH,'|');
		l3 = nextRuleSection(l0, l1);
     inRuleStrct->ruleCondition[i] = strdup(l1);
		// rSplitStr(l3, l1, MAX_RULE_LENGTH, l2, MAX_RULE_LENGTH, '|');
		l2 = nextRuleSection(l3, l1);
     inRuleStrct->ruleAction[i] = strdup(l1);
     inRuleStrct->ruleRecovery[i] = strdup(l2);
     i++;
   }
   fclose (file);
   inRuleStrct->MaxNumOfRules = i;*/
	int errloc;
	rError_t errmsgBuf;
        errmsgBuf.errMsg = NULL;
        errmsgBuf.len = 0;

        char *buf = (char *) malloc(ERR_MSG_LEN*1024*sizeof(char));
        int res = 0;
	if(inRuleStrct == &coreRuleStrct) {
		if((res = readRuleSetFromFile(ruleBaseName,ruleEngineConfig.coreRuleSet,ruleEngineConfig.coreFuncDescIndex,&errloc,&errmsgBuf, ruleEngineConfig.coreRegion))==0) {
		} else {
			errMsgToString(&errmsgBuf, buf, ERR_MSG_LEN*1024);
			rodsLog(LOG_ERROR, "%s", buf);
		}
	} else if(inRuleStrct == &appRuleStrct) {
		if((res = readRuleSetFromFile(ruleBaseName,ruleEngineConfig.appRuleSet, ruleEngineConfig.appFuncDescIndex,&errloc,&errmsgBuf, ruleEngineConfig.appRegion))==0) {
		} else {
			errMsgToString(&errmsgBuf, buf, ERR_MSG_LEN*1024);
			rodsLog(LOG_ERROR, "%s", buf);
		}
	}
	free(buf);
	freeRErrorContent(&errmsgBuf);
	return res;
}
Exemple #13
0
int
main( int argc, char ** argv )
{
    int c;
    const char * optarg;
    tr_benc settings;
    tr_bool boolVal;
    tr_bool loaded;
    tr_bool foreground = FALSE;
    tr_bool dumpSettings = FALSE;
    const char * configDir = NULL;
    const char * pid_filename;
    dtr_watchdir * watchdir = NULL;
    FILE * logfile = NULL;
    tr_bool pidfile_created = FALSE;

    signal( SIGINT, gotsig );
    signal( SIGTERM, gotsig );
#ifndef WIN32
    signal( SIGHUP, gotsig );
#endif

    /* load settings from defaults + config file */
    tr_bencInitDict( &settings, 0 );
    tr_bencDictAddBool( &settings, TR_PREFS_KEY_RPC_ENABLED, TRUE );
    configDir = getConfigDir( argc, (const char**)argv );
    loaded = tr_sessionLoadSettings( &settings, configDir, MY_NAME );

    /* overwrite settings from the comamndline */
    tr_optind = 1;
    while(( c = tr_getopt( getUsage(), argc, (const char**)argv, options, &optarg ))) {
        switch( c ) {
            case 'a': tr_bencDictAddStr( &settings, TR_PREFS_KEY_RPC_WHITELIST, optarg );
                      tr_bencDictAddBool( &settings, TR_PREFS_KEY_RPC_WHITELIST_ENABLED, TRUE );
                      break;
            case 'b': tr_bencDictAddBool( &settings, TR_PREFS_KEY_BLOCKLIST_ENABLED, TRUE );
                      break;
            case 'B': tr_bencDictAddBool( &settings, TR_PREFS_KEY_BLOCKLIST_ENABLED, FALSE );
                      break;
            case 'c': tr_bencDictAddStr( &settings, PREF_KEY_DIR_WATCH, optarg );
                      tr_bencDictAddBool( &settings, PREF_KEY_DIR_WATCH_ENABLED, TRUE );
                      break;
            case 'C': tr_bencDictAddBool( &settings, PREF_KEY_DIR_WATCH_ENABLED, FALSE );
                      break;
            case 941: tr_bencDictAddStr( &settings, TR_PREFS_KEY_INCOMPLETE_DIR, optarg );
                      tr_bencDictAddBool( &settings, TR_PREFS_KEY_INCOMPLETE_DIR_ENABLED, TRUE );
                      break;
            case 942: tr_bencDictAddBool( &settings, TR_PREFS_KEY_INCOMPLETE_DIR_ENABLED, FALSE );
                      break;
            case 'd': dumpSettings = TRUE;
                      break;
            case 'e': logfile = fopen( optarg, "a+" );
                      if( logfile == NULL )
                          fprintf( stderr, "Couldn't open \"%s\": %s\n", optarg, tr_strerror( errno ) );
                      break;
            case 'f': foreground = TRUE;
                      break;
            case 'g': /* handled above */
                      break;
            case 'V': /* version */
                      fprintf(stderr, "%s %s\n", MY_NAME, LONG_VERSION_STRING);
                      exit( 0 );
            case 'o': tr_bencDictAddBool( &settings, TR_PREFS_KEY_DHT_ENABLED, TRUE );
                      break;
            case 'O': tr_bencDictAddBool( &settings, TR_PREFS_KEY_DHT_ENABLED, FALSE );
                      break;
            case 'p': tr_bencDictAddInt( &settings, TR_PREFS_KEY_RPC_PORT, atoi( optarg ) );
                      break;
            case 't': tr_bencDictAddBool( &settings, TR_PREFS_KEY_RPC_AUTH_REQUIRED, TRUE );
                      break;
            case 'T': tr_bencDictAddBool( &settings, TR_PREFS_KEY_RPC_AUTH_REQUIRED, FALSE );
                      break;
            case 'u': tr_bencDictAddStr( &settings, TR_PREFS_KEY_RPC_USERNAME, optarg );
                      break;
            case 'v': tr_bencDictAddStr( &settings, TR_PREFS_KEY_RPC_PASSWORD, optarg );
                      break;
            case 'w': tr_bencDictAddStr( &settings, TR_PREFS_KEY_DOWNLOAD_DIR, optarg );
                      break;
            case 'P': tr_bencDictAddInt( &settings, TR_PREFS_KEY_PEER_PORT, atoi( optarg ) );
                      break;
            case 'm': tr_bencDictAddBool( &settings, TR_PREFS_KEY_PORT_FORWARDING, TRUE );
                      break;
            case 'M': tr_bencDictAddBool( &settings, TR_PREFS_KEY_PORT_FORWARDING, FALSE );
                      break;
            case 'L': tr_bencDictAddInt( &settings, TR_PREFS_KEY_PEER_LIMIT_GLOBAL, atoi( optarg ) );
                      break;
            case 'l': tr_bencDictAddInt( &settings, TR_PREFS_KEY_PEER_LIMIT_TORRENT, atoi( optarg ) );
                      break;
            case 800: paused = TRUE;
                      break;
            case 910: tr_bencDictAddInt( &settings, TR_PREFS_KEY_ENCRYPTION, TR_ENCRYPTION_REQUIRED );
                      break;
            case 911: tr_bencDictAddInt( &settings, TR_PREFS_KEY_ENCRYPTION, TR_ENCRYPTION_PREFERRED );
                      break;
            case 912: tr_bencDictAddInt( &settings, TR_PREFS_KEY_ENCRYPTION, TR_CLEAR_PREFERRED );
                      break;
            case 'i': tr_bencDictAddStr( &settings, TR_PREFS_KEY_BIND_ADDRESS_IPV4, optarg );
                      break;
            case 'I': tr_bencDictAddStr( &settings, TR_PREFS_KEY_BIND_ADDRESS_IPV6, optarg );
                      break;
            case 'r': tr_bencDictAddStr( &settings, TR_PREFS_KEY_RPC_BIND_ADDRESS, optarg );
                      break;
            case 953: tr_bencDictAddReal( &settings, TR_PREFS_KEY_RATIO, atof(optarg) );
                      tr_bencDictAddBool( &settings, TR_PREFS_KEY_RATIO_ENABLED, TRUE );
                      break;
            case 954: tr_bencDictAddBool( &settings, TR_PREFS_KEY_RATIO_ENABLED, FALSE );
                      break;
            case 'x': tr_bencDictAddStr( &settings, PREF_KEY_PIDFILE, optarg );
                      break;
            case 'y': tr_bencDictAddBool( &settings, TR_PREFS_KEY_LPD_ENABLED, TRUE );
                      break;
            case 'Y': tr_bencDictAddBool( &settings, TR_PREFS_KEY_LPD_ENABLED, FALSE );
                      break;
            case 810: tr_bencDictAddInt( &settings,  TR_PREFS_KEY_MSGLEVEL, TR_MSG_ERR );
                      break;
            case 811: tr_bencDictAddInt( &settings,  TR_PREFS_KEY_MSGLEVEL, TR_MSG_INF );
                      break;
            case 812: tr_bencDictAddInt( &settings,  TR_PREFS_KEY_MSGLEVEL, TR_MSG_DBG );
                      break;
            default:  showUsage( );
                      break;
        }
    }

    if( foreground && !logfile )
        logfile = stderr;

    if( !loaded )
    {
        printMessage( logfile, TR_MSG_ERR, MY_NAME, "Error loading config file -- exiting.", __FILE__, __LINE__ );
        return -1;
    }

    if( dumpSettings )
    {
        char * str = tr_bencToStr( &settings, TR_FMT_JSON, NULL );
        fprintf( stderr, "%s", str );
        tr_free( str );
        return 0;
    }

    if( !foreground && tr_daemon( TRUE, FALSE ) < 0 )
    {
        char buf[256];
        tr_snprintf( buf, sizeof( buf ), "Failed to daemonize: %s", tr_strerror( errno ) );
        printMessage( logfile, TR_MSG_ERR, MY_NAME, buf, __FILE__, __LINE__ );
        exit( 1 );
    }

    /* start the session */
    tr_formatter_mem_init( MEM_K, MEM_K_STR, MEM_M_STR, MEM_G_STR, MEM_T_STR );
    tr_formatter_size_init( DISK_K, DISK_K_STR, DISK_M_STR, DISK_G_STR, DISK_T_STR );
    tr_formatter_speed_init( SPEED_K, SPEED_K_STR, SPEED_M_STR, SPEED_G_STR, SPEED_T_STR );
    mySession = tr_sessionInit( "daemon", configDir, TRUE, &settings );
    tr_ninf( NULL, "Using settings from \"%s\"", configDir );
    tr_sessionSaveSettings( mySession, configDir, &settings );

    pid_filename = NULL;
    tr_bencDictFindStr( &settings, PREF_KEY_PIDFILE, &pid_filename );
    if( pid_filename && *pid_filename )
    {
        FILE * fp = fopen( pid_filename, "w+" );
        if( fp != NULL )
        {
            fprintf( fp, "%d", (int)getpid() );
            fclose( fp );
            tr_inf( "Saved pidfile \"%s\"", pid_filename );
            pidfile_created = TRUE;
        }
        else
            tr_err( "Unable to save pidfile \"%s\": %s", pid_filename, strerror( errno ) );
    }

    if( tr_bencDictFindBool( &settings, TR_PREFS_KEY_RPC_AUTH_REQUIRED, &boolVal ) && boolVal )
        tr_ninf( MY_NAME, "requiring authentication" );

    /* maybe add a watchdir */
    {
        const char * dir;

        if( tr_bencDictFindBool( &settings, PREF_KEY_DIR_WATCH_ENABLED, &boolVal )
            && boolVal
            && tr_bencDictFindStr( &settings, PREF_KEY_DIR_WATCH, &dir )
            && dir
            && *dir )
        {
            tr_inf( "Watching \"%s\" for new .torrent files", dir );
            watchdir = dtr_watchdir_new( mySession, dir, onFileAdded );
        }
    }

    /* load the torrents */
    {
        tr_torrent ** torrents;
        tr_ctor * ctor = tr_ctorNew( mySession );
        if( paused )
            tr_ctorSetPaused( ctor, TR_FORCE, TRUE );
        torrents = tr_sessionLoadTorrents( mySession, ctor, NULL );
        tr_free( torrents );
        tr_ctorFree( ctor );
    }

#ifdef HAVE_SYSLOG
    if( !foreground )
        openlog( MY_NAME, LOG_CONS|LOG_PID, LOG_DAEMON );
#endif

    while( !closing ) {
        tr_wait_msec( 1000 ); /* sleep one second */
        dtr_watchdir_update( watchdir );
        pumpLogMessages( logfile );
    }

    /* shutdown */
#if HAVE_SYSLOG
    if( !foreground )
    {
        syslog( LOG_INFO, "%s", "Closing session" );
        closelog( );
    }
#endif

    printf( "Closing transmission session..." );
    tr_sessionSaveSettings( mySession, configDir, &settings );
    dtr_watchdir_free( watchdir );
    tr_sessionClose( mySession );
    printf( " done.\n" );

    /* cleanup */
    if( pidfile_created )
        remove( pid_filename );
    tr_bencFree( &settings );
    return 0;
}
Exemple #14
0
bool AppConfig::load() {
    DataTree cfg;
    std::string cfgFileDir = getConfigDir();

    std::string cfgFileName = getConfigFileName();
    wxFileName cfgFile = wxFileName(cfgFileName);

    if (!cfgFile.Exists()) {
        if (configName.length()) {
            wxFileName baseConfig = wxFileName(getConfigFileName(true));
            if (baseConfig.Exists()) {
                std::string baseConfigFileName = baseConfig.GetFullPath(wxPATH_NATIVE).ToStdString();
                std::cout << "Creating new configuration file '" << cfgFileName << "' by copying '" << baseConfigFileName << "'..";
                wxCopyFile(baseConfigFileName, cfgFileName);
                if (!cfgFile.Exists()) {
                    std::cout << "failed." << std::endl;
                    return true;
                }
                std::cout << "ok." << std::endl;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    if (cfgFile.IsFileReadable()) {
        std::cout << "Loading:: configuration file '" << cfgFileName << "'" << std::endl;

        cfg.LoadFromFileXML(cfgFileName);
    } else {
        std::cout << "Error loading:: configuration file '" << cfgFileName << "' is not readable!" << std::endl;
        return false;
    }

    if (cfg.rootNode()->hasAnother("window")) {
        int x = 0 ,y = 0 ,w = 0 ,h = 0;
        int max = 0 ,tips = 0 ,perf_mode = 0 ,mpc = 0;
        
        DataNode *win_node = cfg.rootNode()->getNext("window");
        
        if (win_node->hasAnother("w") && win_node->hasAnother("h") && win_node->hasAnother("x") && win_node->hasAnother("y")) {

            win_node->getNext("x")->element()->get(x);
            win_node->getNext("y")->element()->get(y);
            win_node->getNext("w")->element()->get(w);
            win_node->getNext("h")->element()->get(h);
            
            winX.store(x);
            winY.store(y);
            winW.store(w);
            winH.store(h);
        }
        
        if (win_node->hasAnother("max")) {
            win_node->getNext("max")->element()->get(max);
            winMax.store(max?true:false);
        }

        if (win_node->hasAnother("tips")) {
            win_node->getNext("tips")->element()->get(tips);
            showTips.store(tips?true:false);
        }

        // default:
        perfMode.store(PERF_NORMAL);

        if (win_node->hasAnother("perf_mode")) {
            win_node->getNext("perf_mode")->element()->get(perf_mode);

            if (perf_mode == (int)PERF_LOW) {
                perfMode.store(PERF_LOW);
            } else if (perf_mode == (int)PERF_HIGH) {
                perfMode.store(PERF_HIGH);
            }
        }
       
        if (win_node->hasAnother("theme")) {
            int theme;
            win_node->getNext("theme")->element()->get(theme);
            themeId.store(theme);
        }

        if (win_node->hasAnother("font_scale")) {
            int fscale;
            win_node->getNext("font_scale")->element()->get(fscale);
            fontScale.store(fscale);
        }

        if (win_node->hasAnother("snap")) {
			long long snapVal;
			win_node->getNext("snap")->element()->get(snapVal);
			snap.store(snapVal);
		}

        if (win_node->hasAnother("center_freq")) {
            long long freqVal;
            win_node->getNext("center_freq")->element()->get(freqVal);
            centerFreq.store(freqVal);
        }

        if (win_node->hasAnother("waterfall_lps")) {
            int lpsVal;
            win_node->getNext("waterfall_lps")->element()->get(lpsVal);
            waterfallLinesPerSec.store(lpsVal);
        }
        
        if (win_node->hasAnother("spectrum_avg")) {
            float avgVal;
            win_node->getNext("spectrum_avg")->element()->get(avgVal);
            spectrumAvgSpeed.store(avgVal);
        }

        if (win_node->hasAnother("modemprops_collapsed")) {
            win_node->getNext("modemprops_collapsed")->element()->get(mpc);
            modemPropsCollapsed.store(mpc?true:false);
        }
        
        if (win_node->hasAnother("db_offset")) {
            DataNode *offset_node = win_node->getNext("db_offset");
            int offsetValue = 0;
            offset_node->element()->get(offsetValue);
            setDBOffset(offsetValue);
        }

        if (win_node->hasAnother("main_split")) {
            float gVal;
            win_node->getNext("main_split")->element()->get(gVal);
            mainSplit.store(gVal);
        }
        
        if (win_node->hasAnother("vis_split")) {
            float gVal;
            win_node->getNext("vis_split")->element()->get(gVal);
            visSplit.store(gVal);
        }
        
        if (win_node->hasAnother("bookmark_split")) {
            float gVal;
            win_node->getNext("bookmark_split")->element()->get(gVal);
            bookmarkSplit.store(gVal);
        }

        if (win_node->hasAnother("bookmark_visible")) {
            int bVal;
            win_node->getNext("bookmark_visible")->element()->get(bVal);
            bookmarksVisible.store(bVal);
        }
    }
    
	//Recording settings:
    if (cfg.rootNode()->hasAnother("recording")) {
        DataNode *rec_node = cfg.rootNode()->getNext("recording");

        if (rec_node->hasAnother("path")) {
            DataNode *rec_path = rec_node->getNext("path");
            recordingPath = rec_path->element()->toString();
        }

		if (rec_node->hasAnother("squelch")) {
			DataNode *rec_squelch = rec_node->getNext("squelch");
			rec_squelch->element()->get(recordingSquelchOption);
		}

		if (rec_node->hasAnother("file_time_limit")) {
			DataNode *rec_file_time_limit = rec_node->getNext("file_time_limit");
			rec_file_time_limit->element()->get(recordingFileTimeLimitSeconds);
		}
    }
    
    if (cfg.rootNode()->hasAnother("devices")) {
        DataNode *devices_node = cfg.rootNode()->getNext("devices");

        while (devices_node->hasAnother("device")) {
            DataNode *device_node = devices_node->getNext("device");
            if (device_node->hasAnother("id")) {
                std::string deviceId = device_node->getNext("id")->element()->toString();

                getDevice(deviceId)->load(device_node);
            }
        }
    }
    
    if (cfg.rootNode()->hasAnother("manual_devices")) {
        DataNode *manuals_node = cfg.rootNode()->getNext("manual_devices");
        
        while (manuals_node->hasAnother("device")) {
            DataNode *manual_node = manuals_node->getNext("device");
            if (manual_node->hasAnother("factory") && manual_node->hasAnother("params")) {
                SDRManualDef mdef;
                
                mdef.factory = manual_node->getNext("factory")->element()->toString();
                mdef.params = manual_node->getNext("params")->element()->toString();

                manualDevices.push_back(mdef);
            }
        }
    }
    
#ifdef USE_HAMLIB
    if (cfg.rootNode()->hasAnother("rig")) {
        DataNode *rig_node = cfg.rootNode()->getNext("rig");

        if (rig_node->hasAnother("enabled")) {
            int loadEnabled;
            rig_node->getNext("enabled")->element()->get(loadEnabled);
            rigEnabled.store(loadEnabled?true:false);
        }
        if (rig_node->hasAnother("model")) {
            int loadModel;
            rig_node->getNext("model")->element()->get(loadModel);
            rigModel.store(loadModel?loadModel:1);
        }
        if (rig_node->hasAnother("rate")) {
            int loadRate;
            rig_node->getNext("rate")->element()->get(loadRate);
            rigRate.store(loadRate?loadRate:57600);
        }
        if (rig_node->hasAnother("port")) {
            rigPort = rig_node->getNext("port")->element()->toString();
        }
        if (rig_node->hasAnother("control")) {
            int loadControl;
            rig_node->getNext("control")->element()->get(loadControl);
            rigControlMode.store(loadControl?true:false);
        }
        if (rig_node->hasAnother("follow")) {
            int loadFollow;
            rig_node->getNext("follow")->element()->get(loadFollow);
            rigFollowMode.store(loadFollow?true:false);
        }
        if (rig_node->hasAnother("center_lock")) {
            int loadCenterLock;
            rig_node->getNext("center_lock")->element()->get(loadCenterLock);
            rigCenterLock.store(loadCenterLock?true:false);
        }
        if (rig_node->hasAnother("follow_modem")) {
            int loadFollow;
            rig_node->getNext("follow_modem")->element()->get(loadFollow);
            rigFollowModem.store(loadFollow?true:false);
        }
    }
#endif


    return true;
}
Exemple #15
0
#include "mash.h"
#include "instruction.h"
#include "water.h"

MainWindow* Brewtarget::_mainWindow = 0;
QDomDocument* Brewtarget::optionsDoc;
QTranslator* Brewtarget::defaultTrans = new QTranslator();
QTranslator* Brewtarget::btTrans = new QTranslator();
QTextStream* Brewtarget::logStream = 0;
QFile* Brewtarget::logFile = 0;
bool Brewtarget::userDatabaseDidNotExist = false;
QFile Brewtarget::pidFile;
QDateTime Brewtarget::lastDbMergeRequest = QDateTime::fromString("1986-02-24T06:00:00", Qt::ISODate);

QString Brewtarget::currentLanguage = "en";
QString Brewtarget::userDataDir = getConfigDir();

bool Brewtarget::checkVersion = true;

iUnitSystem Brewtarget::weightUnitSystem = SI;
iUnitSystem Brewtarget::volumeUnitSystem = SI;

TempScale Brewtarget::tempScale = Celsius;
Unit::unitDisplay Brewtarget::dateFormat = Unit::displaySI;

Brewtarget::ColorType Brewtarget::colorFormula = Brewtarget::MOREY;
Brewtarget::IbuType Brewtarget::ibuFormula = Brewtarget::TINSETH;
Brewtarget::ColorUnitType Brewtarget::colorUnit = Brewtarget::SRM;
Brewtarget::DensityUnitType Brewtarget::densityUnit = Brewtarget::SG;

QHash<int, UnitSystem*> Brewtarget::thingToUnitSystem;
Exemple #16
0
bool AppConfig::load() {
    DataTree cfg;
    std::string cfgFileDir = getConfigDir();

    std::string cfgFileName = getConfigFileName();
    wxFileName cfgFile = wxFileName(cfgFileName);

    if (!cfgFile.Exists()) {
        if (configName.length()) {
            wxFileName baseConfig = wxFileName(getConfigFileName(true));
            if (baseConfig.Exists()) {
                std::string baseConfigFileName = baseConfig.GetFullPath(wxPATH_NATIVE).ToStdString();
                std::cout << "Creating new configuration file '" << cfgFileName << "' by copying '" << baseConfigFileName << "'..";
                wxCopyFile(baseConfigFileName, cfgFileName);
                if (!cfgFile.Exists()) {
                    std::cout << "failed." << std::endl;
                    return true;
                }
                std::cout << "ok." << std::endl;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    if (cfgFile.IsFileReadable()) {
        std::cout << "Loading:: configuration file '" << cfgFileName << "'" << std::endl;

        cfg.LoadFromFileXML(cfgFileName);
    } else {
        std::cout << "Error loading:: configuration file '" << cfgFileName << "' is not readable!" << std::endl;
        return false;
    }

    if (cfg.rootNode()->hasAnother("window")) {
        int x,y,w,h;
        int max;
        
        DataNode *win_node = cfg.rootNode()->getNext("window");
        
        if (win_node->hasAnother("w") && win_node->hasAnother("h") && win_node->hasAnother("x") && win_node->hasAnother("y")) {
            win_node->getNext("x")->element()->get(x);
            win_node->getNext("y")->element()->get(y);
            win_node->getNext("w")->element()->get(w);
            win_node->getNext("h")->element()->get(h);
            
            winX.store(x);
            winY.store(y);
            winW.store(w);
            winH.store(h);
        }
        
        if (win_node->hasAnother("max")) {
            win_node->getNext("max")->element()->get(max);
            winMax.store(max?true:false);
        }

        if (win_node->hasAnother("theme")) {
            int theme;
            win_node->getNext("theme")->element()->get(theme);
            themeId.store(theme);
        }

        if (win_node->hasAnother("snap")) {
			long long snapVal;
			win_node->getNext("snap")->element()->get(snapVal);
			snap.store(snapVal);
		}

        if (win_node->hasAnother("center_freq")) {
            long long freqVal;
            win_node->getNext("center_freq")->element()->get(freqVal);
            centerFreq.store(freqVal);
        }

        if (win_node->hasAnother("waterfall_lps")) {
            int lpsVal;
            win_node->getNext("waterfall_lps")->element()->get(lpsVal);
            waterfallLinesPerSec.store(lpsVal);
        }
        
        if (win_node->hasAnother("spectrum_avg")) {
            float avgVal;
            win_node->getNext("spectrum_avg")->element()->get(avgVal);
            spectrumAvgSpeed.store(avgVal);
        }
    }
    
    if (cfg.rootNode()->hasAnother("devices")) {
        DataNode *devices_node = cfg.rootNode()->getNext("devices");

        while (devices_node->hasAnother("device")) {
            DataNode *device_node = devices_node->getNext("device");
            if (device_node->hasAnother("id")) {
                std::string deviceId = device_node->getNext("id")->element()->toString();

                getDevice(deviceId)->load(device_node);
            }
        }
    }
    
    if (cfg.rootNode()->hasAnother("manual_devices")) {
        DataNode *manuals_node = cfg.rootNode()->getNext("manual_devices");
        
        while (manuals_node->hasAnother("device")) {
            DataNode *manual_node = manuals_node->getNext("device");
            if (manual_node->hasAnother("factory") && manual_node->hasAnother("params")) {
                SDRManualDef mdef;
                
                mdef.factory = manual_node->getNext("factory")->element()->toString();
                mdef.params = manual_node->getNext("params")->element()->toString();

                manualDevices.push_back(mdef);
            }
        }
    }
    
#ifdef USE_HAMLIB
    if (cfg.rootNode()->hasAnother("rig")) {
        DataNode *rig_node = cfg.rootNode()->getNext("rig");

        if (rig_node->hasAnother("model")) {
            int loadModel;
            rig_node->getNext("model")->element()->get(loadModel);
            rigModel.store(loadModel?loadModel:1);
        }
        if (rig_node->hasAnother("rate")) {
            int loadRate;
            rig_node->getNext("rate")->element()->get(loadRate);
            rigRate.store(loadRate?loadRate:57600);
        }
        if (rig_node->hasAnother("port")) {
            rigPort = rig_node->getNext("port")->element()->toString();
        }
    }
#endif


    return true;
}
Exemple #17
0
int
chkAndResetRule (rsComm_t *rsComm)
{
    char *configDir;
    char rulesFileName[MAX_NAME_LEN];
#ifndef USE_BOOST_FS
    struct stat statbuf;
#endif
    int status;
    ruleExecInfo_t rei;
    uint mtime;

    configDir = getConfigDir ();
#ifdef RULE_ENGINE_N
    snprintf (rulesFileName, MAX_NAME_LEN, "%s/reConfigs/core.re",
      configDir);
#else
    snprintf (rulesFileName, MAX_NAME_LEN, "%s/reConfigs/core.irb", 
      configDir); 
#endif
#ifdef USE_BOOST_FS
        path p (rulesFileName);
        if (!exists (p)) {
#else
    status = stat (rulesFileName, &statbuf);

    if (status != 0) {
#endif
	status = UNIX_FILE_STAT_ERR - errno;
        rodsLog (LOG_ERROR,
          "chkAndResetRule: unable to read rule config file %s, status = %d",
	  rulesFileName, status);
	return (status);
    }

#ifdef USE_BOOST_FS
    mtime = (uint) last_write_time (p);
#else
    mtime = (uint) statbuf.st_mtime;
#endif

    if (CoreIrbTimeStamp == 0) {
	/* first time */
	CoreIrbTimeStamp = mtime;
	return (0);
    }

    if (mtime > CoreIrbTimeStamp) {
	/* file has been changed */
        rodsLog (LOG_NOTICE,
          "chkAndResetRule: reconf file %s has been changed. re-initializing",
	  rulesFileName);
	CoreIrbTimeStamp = mtime;
	rei.rsComm = rsComm;
	clearCoreRule();
#ifdef RULE_ENGINE_N
	/* The shared memory cache may have already been updated, do not force reload */
	status = initRuleEngine(RULE_ENGINE_TRY_CACHE, NULL, reRuleStr, reFuncMapStr, reVariableMapStr);
#else
	msiAdmClearAppRuleStruct (&rei);
	status = initRuleEngine(NULL, reRuleStr, reFuncMapStr, reVariableMapStr);
#endif
        if (status < 0) {
            rodsLog (LOG_ERROR,
              "chkAndResetRule: initRuleEngine error, status = %d", status);
        }
    }
    return status;
}
Exemple #18
0
/**
 * \fn msiExtractNaraMetadata (ruleExecInfo_t *rei)
 *
 * \brief  This microservice extracts NARA style metadata from a local configuration file.
 *
 * \module core
 *
 * \since pre-2.1
 *
 * \author  DICE
 * \date    2007
 *
 * \usage See clients/icommands/test/rules3.0/
 *
 * \param[in,out] rei - The RuleExecInfo structure that is automatically
 *    handled by the rule engine. The user does not include rei as a
 *    parameter in the rule invocation.
 *
 * \DolVarDependence none
 * \DolVarModified none
 * \iCatAttrDependence none
 * \iCatAttrModified none
 * \sideeffect none
 *
 * \return integer
 * \retval 0 on success
 * \pre none
 * \post none
 * \sa none
**/
int
msiExtractNaraMetadata( ruleExecInfo_t *rei ) {
    FILE *fp;
    char str[500];
    char *substring;
    int counter;
    int flag;
    char attr[100];
    char value[500];
    modAVUMetadataInp_t modAVUMetadataInp;
    int status;
    /* specify the location of the metadata file here */
    char metafile[MAX_NAME_LEN];

    snprintf( metafile, MAX_NAME_LEN, "%-s/reConfigs/%-s", getConfigDir(),
              NARA_META_DATA_FILE );

    if ( ( fp = fopen( metafile, "r" ) ) == NULL ) {
        rodsLog( LOG_ERROR,
                 "msiExtractNaraMetadata: Cannot open the metadata file %s.", metafile );
        return UNIX_FILE_OPEN_ERR;
    }

    memset( &modAVUMetadataInp, 0, sizeof( modAVUMetadataInp ) );
    modAVUMetadataInp.arg0 = "add";

    while ( !feof( fp ) ) {
        counter = 0;
        flag = 0;
        if ( fgets( str, 500, fp ) ) {
            substring = strtok( str, "|" );
            while ( substring != NULL ) {
                if ( flag == 0 && strcmp( substring, rei->doi->objPath ) == 0 ) {
                    flag = 2;
                }

                if ( counter == 1 ) {
                    if ( strlen( substring ) >= sizeof( attr ) ) {
                        rodsLog( LOG_ERROR,
                                 "attr: [%s] is too long for attr, which may only be %ju characters in length.",
                                 ( uintmax_t )sizeof( attr ) );
                    }
                    snprintf( attr, sizeof( attr ), "%s", substring );
                }
                if ( flag == 2 && counter == 2 ) {
                    if ( strlen( substring ) >= sizeof( value ) ) {
                        rodsLog( LOG_ERROR,
                                 "value: [%s] is too long for value, which may only be %ju characters in length.",
                                 ( uintmax_t )sizeof( value ) );
                    }
                    snprintf( value, sizeof( value ), "%s", substring );
                    /*Call the function to insert metadata here.*/
                    modAVUMetadataInp.arg1 = "-d";
                    modAVUMetadataInp.arg2 = rei->doi->objPath;
                    modAVUMetadataInp.arg3 = attr;
                    modAVUMetadataInp.arg4 = value;
                    modAVUMetadataInp.arg5 = "";
                    status = rsModAVUMetadata( rei->rsComm, &modAVUMetadataInp );
                    if ( status < 0 ) {
                        irods::log( ERROR( status, "rsModAVUMetadata failed." ) );
                    }
                    rodsLog( LOG_DEBUG, "msiExtractNaraMetadata: %s:%s", attr, value );
                }
                substring = strtok( NULL, "|" );
                counter++;
            }
        }
    }
    fclose( fp );
    return 0;
}
Exemple #19
0
void loadSettings()
{
  char* buf = malloc(sizeof(char)*2048);
  char* set = malloc(sizeof(char)*1024);
  char* val = malloc(sizeof(char)*1024);

  settings.bgPos.x = HSCREENW-160;
  settings.bgPos.y = HSCREENH-120;

  //Set defaults
  settings.soundVol=64;
  settings.musicVol=72;
  settings.wizClock=533;
  settings.showFps=0;
  settings.arcadeMode=0;
  settings.particles=1;
  settings.userMusic=0;
  settings.disableMusic=0;
  settings.wizVol=52;
  settings.glWidth=-1;
  settings.glHeight=-1;
  settings.glEnable=1;
  settings.glFilter=0;

  //Not written to file
  settings.scaleFactor=1.0;
  settings.session=0;
  settings.solvedWorldWide=0;
  settings.firstRun=1;
  settings.uploadStats=0;
  settings.online=0; //This is what will be checked for in the rest of the code
                     //regardless of "uploadStats", it will only be 1 if
                     //"uploadStats" is 1, because the check that can set it 1 is only
                     //éxecuted if it's enabled.


  //Free ptrs.
  if(settings.packDir)
    free(settings.packDir);

  if(settings.playerName)
    free(settings.playerName);

  settings.packDir = malloc(sizeof(char)*(strlen("packs/wizznic")+1) );
  strcpy(settings.packDir, "packs/wizznic");

  settings.playerName = malloc(sizeof(char)*11 );
  strcpy(settings.playerName, "player");

  settings.musicDir = (char*)malloc(sizeof(char)*(strlen(".")+1) );
  strcpy(settings.musicDir, ".");

  sprintf( buf, "%s/settings.ini", getConfigDir() );
  FILE *f = fopen(buf, "r");
  if(f)
  {
    while( fgets(buf, 128, f) )
    {
      stripNewLine(buf);

      if(splitVals('=',buf, set, val))
      {
        if( strcmp("soundvol", set)==0 )
        {
          settings.soundVol = atoi(val);
        } else
        if( strcmp("musicvol", set)==0 )
        {
          settings.musicVol = atoi(val);
        } else
        if( strcmp("wizclock", set)==0 )
        {
          settings.wizClock = atoi(val);
        } else
        if( strcmp("wizvolume", set)==0 )
        {
          settings.wizVol = atoi(val);
        } else
        if( strcmp("showfps", set)==0 )
        {
          settings.showFps = atoi(val);
        } else
        if( strcmp("arcademode", set)==0 )
        {
          settings.arcadeMode = atoi(val);
        } else
        if( strcmp("particles", set)==0 )
        {
          settings.particles = atoi(val);
        } else
        if( strcmp("packdir", set)==0 )
        {
          free(settings.packDir);
          settings.packDir = malloc(sizeof(char)*(strlen(val)+1) );
          strcpy(settings.packDir,val);
        } else
        if( strcmp("playername", set)==0 )
        {
          free(settings.playerName);
          settings.playerName = malloc(sizeof(char)*(strlen(val)+1) );
          strcpy(settings.playerName,val);
          settings.playerName[10] = '\0'; //In case user edits file and make a longer than 10 chars name.
        } else
        if( strcmp("musicdir", set)==0 )
        {
          free(settings.musicDir);
          settings.musicDir = malloc(sizeof(char)*(strlen(val)+1) );
          strcpy(settings.musicDir, val);
        } else
        if( strcmp("usermusic", set)==0 )
        {
          settings.userMusic=atoi(val);
        } else
        if( strcmp("disablemusic",set)==0 )
        {
          settings.disableMusic=atoi(val);
        } else
        if( strcmp("uploadstats",set)==0 )
        {
          //Only if the option is in the file, are we sure they had the choice.
          settings.firstRun=0;
          settings.uploadStats=atoi(val);
        } else
        if( strcmp("glwidth",set)==0 )
        {
          settings.glWidth=atoi(val);
        } else
        if( strcmp("glheight",set)==0 )
        {
          settings.glHeight=atoi(val);
        } else
        if( strcmp("glenable",set)==0 )
        {
          settings.glEnable=atoi(val);
        } else
        if( strcmp("glfilter",set)==0 )
        {
          settings.glFilter=atoi(val);
        }

      }
    }
    //Close file
    fclose( f );
  }

  //Free the textbuffers
  free(buf);
  free(set);
  free(val);
}
Exemple #20
0
int main(int argc, char *argv[])
{
  int doScale=0; // 0=Undefined, 1=320x240, -1=OpenGL, >1=SwScale
  char* dumpPack=NULL;
  int state=1; //Game, Menu, Editor, Quit
  int sdlVideoModeFlags = SDL_SWSURFACE;

  #ifdef PSP
    //Note to PSP porter, please test if HW is actually faster, Wizznic does a lot of memory-manipulation in the screen-surface, each call might initiate a full copy back/forth from video memory. Remove comment when read. :)
    sdlVideoModeFlags = (SDL_HWSURFACE | SDL_DOUBLEBUF |SDL_HWACCEL);
    SetupCallbacks();//Callbacks actifs
    scePowerSetClockFrequency(333,333,166);
  #endif

//  #ifdef WIN32
//Redirect stdout to console on windows, so we can see what's going in.
//  FILE *stream;
//  stream = freopen("CON", "w", stdout);
//  #endif

  //Print welcome message
  printf( "Wizznic "VERSION_STRING". GPLv3 or newer Copyleft 2010-2013\n\n");

  //initialize path strings
  initUserPaths();

  //Tell where stuff's at.
  printf("Directories:\n    Settings: %s\n    DLC: %s\n    Highscores: %s\n    Editorlevels: %s\n    Datafiles: %s\n\n", \
                            getConfigDir(), getUsrPackDir(), getHighscoreDir(), getUserLevelDir(), (!strlen(DATADIR))?".":DATADIR);

  //Print the command line parameters
  printf("Command-line parameters:\n"STR_VID_OPTIONS);

  //Quit if user wants help
  if( argc > 1 && ( strcmp(argv[1], "-h")==0 || strcmp(argv[1], "--help")==0 || strcmp(argv[1], "-help")==0 ))
  {
    printf("Please see readme.txt or http://wizznic.org/ for more help.\n");
    return(0);
  }

  //Read settings
  printf("Loading settings...\n");
  initSettings();

  #if defined(WITH_OPENGL)
  //We start by enabling glScaling if it was enabled in settings, it can then be overwritten by command line options.
  if( setting()->glEnable && doScale==0 )
    doScale=-1;
  #endif

  //Set scaling
  setting()->scaleFactor=1.0;

  atexit(SDL_Quit);

  //Init SDL
  if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_TIMER ) <0 )
  {
    printf("SDL_Init failed: %s\n",SDL_GetError());
    return(-1);
  }

  //Setup display
  #if defined (GP2X) || defined (PSP) || defined (WIZ)
  SDL_Surface* screen = SDL_SetVideoMode(SCREENW,SCREENH,16, sdlVideoModeFlags);
  #else
  SDL_Surface* screen=NULL;

  int i;
  for( i=0; i < argc; i++ )
  {
    if( strcmp( argv[i], "-sw" ) == 0 )
    {
      setting()->glEnable=0;
      doScale=0;
      saveSettings();
    } else
    if( strcmp( argv[i], "-gl" ) == 0 )
    {
      setting()->glEnable=1;
      doScale=-1;
      saveSettings();
    } else
    if( strcmp( argv[i], "-z" ) == 0 )
    {
      if( i+1 < argc )
      {
        doScale = atoi( argv[i+1] );
        setting()->glEnable=0;
        i++;
        saveSettings();
      } else {
        printf(" -z requires zoom level ( -z 2 for example ).\n");
        return(1);
      }
    } else
    if( strcmp( argv[i], "-f" ) == 0 )
    {
        setting()->fullScreen=1;
        saveSettings();
    } else
    if( strcmp( argv[i], "-w" ) == 0 )
      {
        setting()->fullScreen=0;
        saveSettings();
    } else if( strcmp( argv[i], "-glheight" ) == 0 )
    {
      if( i+1 < argc )
      {
        setting()->glHeight = atoi( argv[i+1] );
        setting()->glEnable=1;
        doScale=-1;
        i++;
        printf("Setting OpenGL window height to %i.\n", setting()->glHeight);
        saveSettings();
      } else {
        printf(" -glheight requires an argument (-1 or size in pixels).\n");
        return(1);
      }
    } else if( strcmp( argv[i], "-glwidth" ) == 0 )
    {
      if( i+1 < argc )
      {
        setting()->glWidth = atoi( argv[i+1] );
        setting()->glEnable=1;
        doScale=-1;
        i++;
        printf("Setting OpenGL window width to %i.\n", setting()->glWidth);
        saveSettings();
      } else {
        printf(" -glwidth requires an argument (-1 or size in pixels).\n");
        return(1);
      }
    } else if( strcmp( argv[i], "-glfilter" ) == 0 )
    {
      if( i+1 < argc )
      {
        setting()->glFilter=atoi(argv[i+1]);
        printf("OpenGL texture filtering set to %s.\n", (setting()->glFilter)?"Smooth":"Off");
        i++;
        saveSettings();
      } else {
        printf("-glfilter requires 0 or 1 as argument.\n");
        return(1);
      }
    } else if( strcmp( argv[i] , "-d" ) == 0 )
    {
      if( argc == 3 && i < argc+1 )
      {
        dumpPack = malloc( sizeof(char)*strlen(argv[i+1])+1 );
        strcpy( dumpPack, argv[i+1] );
        doScale=0;
        setting()->glEnable=0;
        i++;
      } else {
        printf("-d requires a packname, and must not be used with other parameters.\n");
        return(1);
      }
    } else if( strcmp( argv[i], "-rift") == 0 )
    {
      setting()->glWidth = 1280;
      setting()->glHeight = 800;
      setting()->glEnable=1;
      setting()->rift=1;
      doScale=-1;
    } else if( i > 0 )
    {
      printf("\nError: Invalid argument '%s', quitting.\n", argv[i]);
      return(1);
    }

  }

  if( setting()->fullScreen )
  {
    sdlVideoModeFlags |= SDL_FULLSCREEN;
  }

  if(doScale)
  {
    //Hardware accelerated scaling
    if( doScale == -1 )
    {
    #ifdef HAVE_ACCELERATION
      printf("Enabling platform specific accelerated scaling.\n");
      screen = platformInitAccel(sdlVideoModeFlags);
      if( !screen )
      {
        printf("Failed to set platform accelerated scaling, falling back to software window.\n");
        screen=swScreen(SDL_SWSURFACE);
        doScale=0;
      }
    #else
      printf("\nError:\n  Not compiled with hardware-scaling support, don't give me -z -1\n  Exiting...\n");
      return(-1);
    #endif
    } else if( doScale > 0 )
    {
    #ifdef WANT_SWSCALE
      //Set up software scaling
      printf("Enabling slow software-based scaling to %ix%i.\n",320*doScale, 240*doScale);
      screen = swScaleInit(sdlVideoModeFlags,doScale);
    #else
      printf("\nError:\n  I don't support software scaling, don't give me any -z options\n  Exiting...\n");
      return(-1);
    #endif
    }
  } else {
    screen=swScreen(sdlVideoModeFlags);
    doScale=0;
  }

  printf("Scaling factor: %f\n", setting()->scaleFactor);

  if( screen == NULL )
  {
    printf("ERROR: Couldn't init video.\n");
    return(-1);
  }


  //Set window title
  SDL_WM_SetCaption("Wizznic!", "Wizznic!");
  //Set window icon
  SDL_Surface* icon = IMG_Load( DATADIR"data/wmicon.png");
  SDL_WM_SetIcon(icon, NULL);
  SDL_FreeSurface(icon);

  #endif

  setting()->bpp = screen->format->BytesPerPixel;
  setAlphaCol( setting()->bpp );

  printf("Screen surface using %i bytes per pixel.\n",setting()->bpp);

  //Open Joysticks (for wiz)
  if (SDL_NumJoysticks() > 0) SDL_JoystickOpen(0);

  //Hide mouse cursor
  SDL_ShowCursor(SDL_DISABLE);

  //Load fonts
  txtInit();

  //Load sounds
  if(!initSound())
  {
    printf("Couldn't init sound.\n");
    return(-1);
  }

  //Menu Graphics
  if(!initMenu(screen))
  {
    printf("Couldn't load menu graphics.\n");
    return(-1);
  }

  //Init controls
  initControls();

  //Init stats
  statsInit();

  //Init packs
  packInit();

  //Scan userlevels dir
  makeUserLevelList(screen);

  //Init particles
  initParticles(screen);

  //Seed the pseudo random number generator (for particles 'n' stuff)
  srand( (int)time(NULL) );

  #if defined(PC)
  //Need to dump level-screenshots?
  if(dumpPack)
  {
    printf("Dumping level-images for pack: %s\n", dumpPack);
    dumplevelimages(screen, dumpPack, 0);
    return(0);
  }
  #endif

  //init starfield
  initStars(screen);

  //Init pointer
  initPointer(screen);

  printf("Applying settings..\n");
  //Apply settings (has to be done after packs are inited)
  applySettings();
  //Set Pack
  packSetByPath( setting()->packDir );

  #if defined( PLATFORM_SUPPORTS_STATSUPLOAD )
  if( (setting()->uploadStats) && !(setting()->firstRun) )
  {
    statsUpload(0,0,0,0,0,"check",1, &(setting()->session) );
    statsUpload(0,0,0,0,0,"q_solved",1, &(setting()->solvedWorldWide) );

    //DLC only works when stats-uploading is enabled so we can use the same nag-screen.
    dlcCheckOnline();
  }
  #endif

  printf("Setting Music...\n");
  //Start playing music (has to be done after readong settings)
  soundSetMusic();

  //Initialize credits
  initCredits(screen);

  initTransition();


#if SCREENW != 320 || SCREENH != 240
  SDL_Rect *borderSrcRect = malloc(sizeof(SDL_Rect));
  SDL_Surface* border = loadImg( BORDER_IMAGE );
  if( border )
  {
    printf("Border image loaded.\n");
    borderSrcRect->x=(border->w-SCREENW)/2;
    borderSrcRect->y=(border->h-SCREENH)/2;
    borderSrcRect->w=SCREENW;
    borderSrcRect->h=SCREENH;
    SDL_BlitSurface( border, borderSrcRect, screen, NULL );
    SDL_FreeSurface(border);
  } else {
    printf("Could not load border image: %s\n", BORDER_IMAGE);
    SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0,0,0));
  }
  free(borderSrcRect);
  borderSrcRect=NULL;

#endif

  int lastTick;
  while(state!=STATEQUIT)
  {
    lastTick=SDL_GetTicks();

    frameStart();

    if(runControls()) state=STATEQUIT;
    switch(state)
    {
      case STATEPLAY:
        state = runGame(screen);
      break;

      case STATEMENU:
        state = runMenu(screen);
      break;

      case STATEEDIT:
        state=runEditor(screen);
      break;
    }

    drawPointer(screen);

    soundRun(screen,state);

    runTransition(screen);

    if(setting()->showFps)
      drawFPS(screen);

    switch( doScale )
    {
      #if defined(HAVE_ACCELERATION)
      case -1:
        platformDrawScaled(screen);
        break;
      #endif
      case 0:
        SDL_Flip(screen);
        break;
      #if defined(WANT_SWSCALE)
      default:
        swScale(screen,doScale);
        break;
      #else
      default:
        state=STATEQUIT;
      break;
      #endif
    }

    #if defined(CRUDE_TIMING)
    //Oh how I loathe this, is there no better way?
    while(SDL_GetTicks()-lastTick <= PLATFORM_CRUDE_TIMING_TICKS)
    {
      //Burn, burn baby burn!
    }
    #else
    int t=SDL_GetTicks()-lastTick;
    if(t < 20)
    {
      SDL_Delay( 20 -t);
    }
    #endif
  }

  #if defined(PLATFORM_NEEDS_EXIT)
  platformExit();
  #endif

  SDL_Quit();

  return(0);
}
Exemple #21
0
bool AppConfig::load() {
    DataTree cfg;
    std::string cfgFileDir = getConfigDir();

    std::string cfgFileName = getConfigFileName();
    wxFileName cfgFile = wxFileName(cfgFileName);

    if (!cfgFile.Exists()) {
        if (configName.length()) {
            wxFileName baseConfig = wxFileName(getConfigFileName(true));
            if (baseConfig.Exists()) {
                std::string baseConfigFileName = baseConfig.GetFullPath(wxPATH_NATIVE).ToStdString();
                std::cout << "Creating new configuration file '" << cfgFileName << "' by copying '" << baseConfigFileName << "'..";
                wxCopyFile(baseConfigFileName, cfgFileName);
                if (!cfgFile.Exists()) {
                    std::cout << "failed." << std::endl;
                    return true;
                }
                std::cout << "ok." << std::endl;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    if (cfgFile.IsFileReadable()) {
        std::cout << "Loading:: configuration file '" << cfgFileName << "'" << std::endl;

        cfg.LoadFromFileXML(cfgFileName);
    } else {
        std::cout << "Error loading:: configuration file '" << cfgFileName << "' is not readable!" << std::endl;
        return false;
    }

    if (cfg.rootNode()->hasAnother("window")) {
        int x,y,w,h;
        int max;

        DataNode *win_node = cfg.rootNode()->getNext("window");

        if (win_node->hasAnother("w") && win_node->hasAnother("h") && win_node->hasAnother("x") && win_node->hasAnother("y")) {
            win_node->getNext("x")->element()->get(x);
            win_node->getNext("y")->element()->get(y);
            win_node->getNext("w")->element()->get(w);
            win_node->getNext("h")->element()->get(h);

            winX.store(x);
            winY.store(y);
            winW.store(w);
            winH.store(h);
        }

        if (win_node->hasAnother("max")) {
            win_node->getNext("max")->element()->get(max);
            winMax.store(max?true:false);
        }

        if (win_node->hasAnother("theme")) {
            int theme;
            win_node->getNext("theme")->element()->get(theme);
            themeId.store(theme);
        }

        if (win_node->hasAnother("snap")) {
            long long snapVal;
            win_node->getNext("snap")->element()->get(snapVal);
            snap.store(snapVal);
        }

        if (win_node->hasAnother("center_freq")) {
            long long freqVal;
            win_node->getNext("center_freq")->element()->get(freqVal);
            centerFreq.store(freqVal);
        }
    }

    if (cfg.rootNode()->hasAnother("devices")) {
        DataNode *devices_node = cfg.rootNode()->getNext("devices");

        while (devices_node->hasAnother("device")) {
            DataNode *device_node = devices_node->getNext("device");
            if (device_node->hasAnother("id")) {
                std::string deviceId;
                device_node->getNext("id")->element()->get(deviceId);

                getDevice(deviceId)->load(device_node);
            }
        }
    }

    return true;
}
int
myS3Init (void)
{
    int status = -1;
    char *tmpPtr;

    if (S3Initialized) return 0;

    S3Initialized = 1;

#ifdef libs3_3_1_4
    if ((status = S3_initialize ("s3", S3_INIT_ALL)) != S3StatusOK) {
#else
    if ((status = S3_initialize ("s3", S3_INIT_ALL, NULL)) != S3StatusOK) {
#endif
        status = myS3Error (status, S3_INIT_ERROR);
    }

    bzero (&S3Auth, sizeof (S3Auth));

    if ((tmpPtr = getenv("S3_ACCESS_KEY_ID")) != NULL) {
	rstrcpy (S3Auth.accessKeyId, tmpPtr, MAX_NAME_LEN);
        if ((tmpPtr = getenv("S3_SECRET_ACCESS_KEY")) != NULL) {
	    rstrcpy (S3Auth.secretAccessKey, tmpPtr, MAX_NAME_LEN);
	    return 0;
	}
    }

    if ((status = readS3AuthInfo ()) < 0) {
        rodsLog (LOG_ERROR,
          "initHpssAuth: readHpssAuthInfo error. status = %d", status);
        return status;
    }

    return status;
}

int
readS3AuthInfo (void)
{
    FILE *fptr;
    char s3AuthFile[MAX_NAME_LEN];
    char inbuf[MAX_NAME_LEN];
    int lineLen, bytesCopied;
    int linecnt = 0;

    snprintf (s3AuthFile, MAX_NAME_LEN, "%-s/%-s",
      getConfigDir(), S3_AUTH_FILE);

    fptr = fopen (s3AuthFile, "r");

    if (fptr == NULL) {
        rodsLog (LOG_ERROR,
          "readS3AuthInfo: open S3_AUTH_FILE file %s err. ernro = %d",
          s3AuthFile, errno);
        return (SYS_CONFIG_FILE_ERR);
    }
    while ((lineLen = getLine (fptr, inbuf, MAX_NAME_LEN)) > 0) {
        char *inPtr = inbuf;
        if (linecnt == 0) {
            while ((bytesCopied = getStrInBuf (&inPtr, 
	      S3Auth.accessKeyId, &lineLen, LONG_NAME_LEN)) > 0) {
                linecnt ++;
                break;
            }
        } else if (linecnt == 1) {
            while ((bytesCopied = getStrInBuf (&inPtr, 
	      S3Auth.secretAccessKey, &lineLen, LONG_NAME_LEN)) > 0) {
                linecnt ++;
                break;
            }
        }
    }
    if (linecnt != 2)  {
        rodsLog (LOG_ERROR,
          "readS3AuthInfo: read %d lines in S3_AUTH_FILE file",
          linecnt);
        return (SYS_CONFIG_FILE_ERR);
    }
    return 0;
}
Exemple #23
0
/**
 * Run the event loop.
 * @param options Options.
 * @return Exit code.
 */
int EmuLoop::run(const Options *options)
{
	// Save options.
	// TODO: Make EmuLoop::run() non-virtual, save options there,
	// and then call protected virtual run_int()?
	EmuLoopPrivate *const d = d_func();
	d->options = options;
	
	// Load the ROM image.
	// NOTE: On gcc-5.x, if we store rom_filename().c_str(),
	// random corruption happens with filenames longer than
	// the short string buffer.
	string rom_filename = options->rom_filename();
	d->rom = new Rom(rom_filename.c_str());
	if (!d->rom->isOpen()) {
		// Error opening the ROM.
		// TODO: Error code?
		fprintf(stderr, "Error opening ROM file %s: (TODO get error code)\n",
			rom_filename.c_str());
		delete d->rom;
		d->rom = nullptr;
		return EXIT_FAILURE;
	}

	if (d->rom->isMultiFile()) {
		// Select the first file.
		d->rom->select_z_entry(d->rom->get_z_entry_list());
	}

	// Is the ROM format supported?
	if (!EmuContextFactory::isRomFormatSupported(d->rom)) {
		// ROM format is not supported.
		const char *rom_format = romFormatToString(d->rom->romFormat());
		fprintf(stderr, "Error loading ROM file %s: ROM is in %s format.\n"
			"Only plain binary and SMD-format ROMs are supported.\n",
			rom_filename.c_str(), rom_format);
		return EXIT_FAILURE;
	}

	// Check the ROM's system ID.
	if (!EmuContextFactory::isRomSystemSupported(d->rom)) {
		// System is not supported.
		const char *rom_sysId = sysIdToString(d->rom->sysId());
		fprintf(stderr, "Error loading ROM file %s: ROM is for %s.\n"
			"Only Mega Drive and Pico ROMs are supported.\n",
			rom_filename.c_str(), rom_sysId);
		return EXIT_FAILURE;
	}

	// Check for Pico controller.
	d->isPico = false;
	if (d->rom->sysId() == Rom::MDP_SYSTEM_PICO) {
		d->isPico = true;
	}

	// Set the SRAM/EEPROM path.
	EmuContext::SetPathSRam(getConfigDir("SRAM").c_str());

	// Set some static EmuContext properties.
	// TODO: Make these non-static?
	EmuContext::SetAutoFixChecksum(options->auto_fix_checksum());
	if (options->is_tmss_enabled()) {
		EmuContext::SetTmssRomFilename(options->tmss_rom_filename());
		EmuContext::SetTmssEnabled(true);
	}

	// Detect the ROM region.
	SysVersion::RegionCode_t region = options->region();
	SysVersion::RegionCode_t region_auto = SysVersion::REGION_AUTO;
	if (region == SysVersion::REGION_AUTO) {
		// Auto-detect the region code.
		// Using region code order 0x4812.
		// (US, Europe, Japan, Asia)
		region = SysVersion::DetectRegion(d->rom->regionCode(), 0x4812);
		if (region == SysVersion::REGION_AUTO) {
			// Detection failed.
			// Default to US/NTSC.
			region = SysVersion::REGION_US_NTSC;
		}

		region_auto = region;
	}

	// Create the emulation context.
	d->emuContext = EmuContextFactory::createContext(d->rom, region);
	if (!d->emuContext || !d->emuContext->isRomOpened()) {
		// Error loading the ROM into EmuMD.
		// TODO: Error code?
		fprintf(stderr, "Error initializing EmuContext for %s: (TODO get error code)\n",
			rom_filename.c_str());
		return EXIT_FAILURE;
	}

	// Set VDP properties.
	// TODO: More properties?
	Vdp *vdp = d->emuContext->m_vdp;
	vdp->options.spriteLimits = options->sprite_limits();

	// Initialize the SDL handlers.
	d->sdlHandler = new SdlHandler();
	if (d->sdlHandler->init_video() < 0)
		return EXIT_FAILURE;
	if (d->sdlHandler->init_audio(options->sound_freq(), options->stereo()) < 0)
		return EXIT_FAILURE;
	d->vBackend = d->sdlHandler->vBackend();

	// Check for startup messages.
	checkForStartupMessages();

	// If the ROM region was auto-detected, print a message.
	if (region_auto != SysVersion::REGION_AUTO) {
		static const char *const region_tbl[4] = {
			"Japan (NTSC)",
			"Asia (PAL)",
			"USA (NTSC)",
			"Europe (PAL)"
		};

		const char *region_str = region_tbl[region_auto & 3];
		d->vBackend->osd_printf(1500, "ROM region detected as %s.", region_str);
	}

	// Set frame timing.
	// TODO: SysVersion convenience function to check if a RegionCode_t is PAL.
	bool isPal;
	switch (region) {
		case SysVersion::REGION_US_NTSC:
		case SysVersion::REGION_JP_NTSC:
		default:
			isPal = false;
			break;

		case SysVersion::REGION_EU_PAL:
		case SysVersion::REGION_ASIA_PAL:
			isPal = true;
			break;
	}
	d->setFrameTiming(isPal ? 50 : 60);

	// Update the window title information.
	// FIXME: On my XP VM, there's a slight pause while
	// loading where it shows "Gens/GS II [SDL]", then
	// it gets changed to the ROM name.
	d->updateWinTitleInfo();

	// TODO: Close the ROM, or let EmuContext do it?

	// Set the color depth.
	MdFb *fb = d->emuContext->m_vdp->MD_Screen->ref();
	fb->setBpp(options->bpp());

	// Set the SDL video source.
	d->sdlHandler->set_video_source(fb);

	// Start audio.
	d->sdlHandler->pause_audio(false);

	// Initialize the I/O Manager with a default key layout.
	d->keyManager = new KeyManager();
	if (!d->isPico) {
		// Standard Mega Drive controllers.
		d->keyManager->setIoType(IoManager::VIRTPORT_1, IoManager::IOT_6BTN);
		d->keyManager->setKeyMap(IoManager::VIRTPORT_1, d->keyMap_md, ARRAY_SIZE(d->keyMap_md));
		d->keyManager->setIoType(IoManager::VIRTPORT_2, IoManager::IOT_NONE);
	} else {
		// Sega Pico controller.
		d->keyManager->setIoType(IoManager::VIRTPORT_1, IoManager::IOT_PICO);
		d->keyManager->setKeyMap(IoManager::VIRTPORT_1, d->keyMap_pico, ARRAY_SIZE(d->keyMap_pico));
		d->keyManager->setIoType(IoManager::VIRTPORT_2, IoManager::IOT_NONE);
	}

	// TODO: Move some more common stuff back to gens-sdl.cpp.
	d->running = true;
	d->paused.data = 0;
	d->last_paused.data = 0;
	while (d->running) {
		// Process the SDL event queue.
		processSdlEventQueue();
		if (!d->running) {
			// Emulation has stopped.
			break;
		}

		// Check if the 'paused' state was changed.
		// If it was, autosave SRAM/EEPROM.
		if (d->last_paused.data != d->paused.data) {
			// 'paused' state was changed.
			// (TODO: Only if paused == true?)
			// TODO: Evaluate both fields as boolean,
			// so switching from manual to manual+auto
			// or vice-versa doesn't trigger an autosave?
			d->emuContext->autoSaveData(-1);
			d->last_paused.data = d->paused.data;
		}

		if (d->paused.data) {
			// Emulation is paused.
			// Don't run any frames.
			// TODO: Wait for what would be the next frame?
			// Otherwise, we'll end up "spinning" if e.g.
			// there are OSD messages being processed.
			continue;
		}

		// Run a frame.
		// EventLoop::runFrame() handles frameskip timing.
		runFrame();

		// Autosave SRAM/EEPROM.
		// TODO: EmuContext::execFrame() should probably do this itself...
		d->emuContext->autoSaveData(1);

		// Update the I/O manager.
		d->keyManager->updateIoManager(d->emuContext->m_ioManager);
	}

	// Unreference the framebuffer.
	fb->unref();

	// Save SRAM/EEPROM, if necessary.
	// TODO: Move to EmuContext::~EmuContext()?
	d->emuContext->saveData();

	// Shut down LibGens.
	delete d->keyManager;
	d->keyManager = nullptr;
	delete d->emuContext;
	d->emuContext = nullptr;
	delete d->rom;
	d->rom = nullptr;

	// Pause audio and wait 50ms for SDL to catch up.
	d->sdlHandler->pause_audio(true);
	usleep(50000);

	// NOTE: Deleting sdlHandler can cause crashes on Windows
	// due to the timer callback trying to post the semaphore
	// after it's been deleted.
	// Shut down the SDL functions manually.
	d->sdlHandler->end_audio();
	d->sdlHandler->end_video();
	d->vBackend = nullptr;

	// Done running the emulation loop.
	return 0;
}
QString Config::getConfigFile()
{
    return getConfigDir() + QDir::separator() + CONFIG_FILE_NAME;
}
/** Returns the full path of the challenge file. */
std::string FileManager::getChallengeFile(const std::string &fname) const
{
    return getConfigDir()+"/"+fname;
}   // getChallengeFile