Exemplo n.º 1
0
	void Get(ConfigFile& conf) {
		switch(type)
		{
			case CIT_BOOL:
			case CIT_BOOLONOFF:
				if(size	== 1) *(uint8 *)addr = (uint8) conf.GetBool(name, def!=0);
				if(size	== 2) *(uint16*)addr = (uint16)conf.GetBool(name, def!=0);
				if(size	== 4) *(uint32*)addr = (uint32)conf.GetBool(name, def!=0);
				if(size	== 8) *(uint64*)addr = (uint64)conf.GetBool(name, def!=0);
				break;
			case CIT_INT:
				if(size	== 1) *(uint8 *)addr = (uint8) conf.GetInt(name, reinterpret_cast<int32>(def));
				if(size	== 2) *(uint16*)addr = (uint16)conf.GetInt(name, reinterpret_cast<int32>(def));
				if(size	== 4) *(uint32*)addr = (uint32)conf.GetInt(name, reinterpret_cast<int32>(def));
				if(size	== 8) *(uint64*)addr = (uint64)conf.GetInt(name, reinterpret_cast<int32>(def));
				break;
			case CIT_UINT:
				if(size	== 1) *(uint8 *)addr = (uint8) conf.GetUInt(name, reinterpret_cast<uint32>(def));
				if(size	== 2) *(uint16*)addr = (uint16)conf.GetUInt(name, reinterpret_cast<uint32>(def));
				if(size	== 4) *(uint32*)addr = (uint32)conf.GetUInt(name, reinterpret_cast<uint32>(def));
				if(size	== 8) *(uint64*)addr = (uint64)conf.GetUInt(name, reinterpret_cast<uint32>(def));
				break;
			case CIT_STRING:
				lstrcpyn((TCHAR*)addr, _tFromChar(conf.GetString(name, reinterpret_cast<const char*>(def))), size-1);
				((TCHAR*)addr)[size-1] = TEXT('\0');
				break;
			case CIT_INVBOOL:
			case CIT_INVBOOLONOFF:
				if(size	== 1) *(uint8 *)addr = (uint8) !conf.GetBool(name, def!=0);
				if(size	== 2) *(uint16*)addr = (uint16)!conf.GetBool(name, def!=0);
				if(size	== 4) *(uint32*)addr = (uint32)!conf.GetBool(name, def!=0);
				if(size	== 8) *(uint64*)addr = (uint64)!conf.GetBool(name, def!=0);
				break;
			case CIT_VKEY:
				{
					uint16 keyNum = (uint16)conf.GetUInt(name, reinterpret_cast<uint32>(def));
					const char* keyStr = conf.GetString(name);
					if(keyStr)
					{
						for(int i=0;i<512;i++)
						{
							if(i<256) // keys
							{
								if(!strcasecmp(keyStr,keyToString[i]) ||
								(*keyToAlternateString[i] && !strcasecmp(keyStr,keyToAlternateString[i])))
								{
									keyNum = i;
									break;
								}
							}
							else // joystick:
							{
								char temp [128];
								extern void TranslateKey(WORD keyz,char *out);
								TranslateKey(0x8000|(i-256),temp);
								if(strlen(keyStr)>3 && !strcasecmp(keyStr+3,temp+3))
								{
									for(int j = 0 ; j < 16 ; j++)
									{
										if(keyStr[2]-'0' == j || keyStr[2]-'a' == j-10)
										{
											keyNum = 0x8000|(i-256)|(j<<8);
											i = 512;
											break;
										}
									}
								}
							}
						}
					}
					if(size	== 1) *(uint8 *)addr = (uint8) keyNum;
					if(size	== 2) *(uint16*)addr = (uint16)keyNum;
					if(size	== 4) *(uint32*)addr = (uint32)keyNum;
					if(size	== 8) *(uint64*)addr = (uint64)keyNum;
				}
				break;
			case CIT_VKEYMOD:
				{
					uint16 modNum = 0;
					const char* modStr = conf.GetString(name);
					if(modStr) {
						if(strstr(modStr, "ft") || strstr(modStr, "FT")) modNum |= CUSTKEY_SHIFT_MASK;
						if(strstr(modStr, "tr") || strstr(modStr, "TR")) modNum |= CUSTKEY_CTRL_MASK;
						if(strstr(modStr, "lt") || strstr(modStr, "LT")) modNum |= CUSTKEY_ALT_MASK;
					}
					if(!modNum && (!modStr || strcasecmp(modStr, "none")))
						modNum = conf.GetUInt(name, reinterpret_cast<uint32>(def));
					if(size	== 1) *(uint8 *)addr = (uint8) modNum;
					if(size	== 2) *(uint16*)addr = (uint16)modNum;
					if(size	== 4) *(uint32*)addr = (uint32)modNum;
					if(size	== 8) *(uint64*)addr = (uint64)modNum;
				}
				break;
		}

		// if it had a comment, override our own with it
		const char* newComment = conf.GetComment(name);
		if(newComment && *newComment)
			comment = newComment;
	}
bool OBSBasic::AddProfile(bool create_new, const char *title, const char *text,
		const char *init_text)
{
	std::string newName;
	std::string newDir;
	ConfigFile config;

	if (!GetProfileName(this, newName, newDir, title, text, init_text))
		return false;

	std::string curDir = config_get_string(App()->GlobalConfig(),
			"Basic", "ProfileDir");

	char newPath[512];
	int ret = GetConfigPath(newPath, 512, "obs-studio/basic/profiles/");
	if (ret <= 0) {
		blog(LOG_WARNING, "Failed to get profiles config path");
		return false;
	}

	strcat(newPath, newDir.c_str());

	if (os_mkdir(newPath) < 0) {
		blog(LOG_WARNING, "Failed to create profile directory '%s'",
				newDir.c_str());
		return false;
	}

	if (!create_new)
		CopyProfile(curDir.c_str(), newPath);

	strcat(newPath, "/basic.ini");

	if (config.Open(newPath, CONFIG_OPEN_ALWAYS) != 0) {
		blog(LOG_ERROR, "Failed to open new config file '%s'",
				newDir.c_str());
		return false;
	}

	config_set_string(App()->GlobalConfig(), "Basic", "Profile",
			newName.c_str());
	config_set_string(App()->GlobalConfig(), "Basic", "ProfileDir",
			newDir.c_str());

	config_set_string(config, "General", "Name", newName.c_str());
	config.SaveSafe("tmp");
	config.Swap(basicConfig);
	InitBasicConfigDefaults();
	RefreshProfiles();

	if (create_new)
		ResetProfileData();

	blog(LOG_INFO, "Created profile '%s' (%s, %s)", newName.c_str(),
			create_new ? "clean" : "duplicate", newDir.c_str());
	blog(LOG_INFO, "------------------------------------------------");

	config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
	UpdateTitleBar();
	return true;
}
Exemplo n.º 3
0
void  cfgLoadStr(const wchar * Section, const wchar * Key, wchar * Return,const wchar* Default)
{
	string value = cfgdb.get(Section, Key, Default);
	// FIXME: Buffer overflow possible
	strcpy(Return, value.c_str());
}
Exemplo n.º 4
0
void S9xLoadConfigFiles (char **argv, int argc)
{
	static ConfigFile	conf; // static because some of its functions return pointers
	conf.Clear();

	bool	skip = false;
	for (int i = 0; i < argc; i++)
	{
		if (!strcasecmp(argv[i], "-nostdconf"))
		{
			skip = true;
			break;
		}
	}

	if (!skip)
	{
	#ifdef SYS_CONFIG_FILE
		try_load_config_file(SYS_CONFIG_FILE, conf);
		S9xParsePortConfig(conf, 0);
	#endif

		std::string	fname;

		fname = S9xGetDirectory(DEFAULT_DIR);
		fname += SLASH_STR S9X_CONF_FILE_NAME;
		try_load_config_file(fname.c_str(), conf);
	}
	else
		fprintf(stderr, "Skipping standard config files.\n");

	for (int i = 0; i < argc - 1; i++)
		if (!strcasecmp(argv[i], "-conf"))
			try_load_config_file(argv[++i], conf);

	// Parse config file here

	// ROM

	Settings.ForceInterleaved2          =  conf.GetBool("ROM::Interleaved2",                   false);
	Settings.ForceInterleaveGD24        =  conf.GetBool("ROM::InterleaveGD24",                 false);
	Settings.ApplyCheats                =  conf.GetBool("ROM::Cheat",                          false);
	Settings.NoPatch                    = !conf.GetBool("ROM::Patch",                          true);

	Settings.ForceLoROM = conf.GetBool("ROM::LoROM", false);
	Settings.ForceHiROM = conf.GetBool("ROM::HiROM", false);
	if (Settings.ForceLoROM)
		Settings.ForceHiROM = false;

	Settings.ForcePAL   = conf.GetBool("ROM::PAL",  false);
	Settings.ForceNTSC  = conf.GetBool("ROM::NTSC", false);
	if (Settings.ForcePAL)
		Settings.ForceNTSC = false;

	if (conf.Exists("ROM::Header"))
	{
		Settings.ForceHeader = conf.GetBool("ROM::Header", false);
		Settings.ForceNoHeader = !Settings.ForceHeader;
	}

	if (conf.Exists("ROM::Interleaved"))
	{
		Settings.ForceInterleaved = conf.GetBool("ROM::Interleaved", false);
		Settings.ForceNotInterleaved = !Settings.ForceInterleaved;
	}

	rom_filename = conf.GetStringDup("ROM::Filename", NULL);

	// Sound

	Settings.SoundSync                  =  conf.GetBool("Sound::Sync",                         true);
	Settings.SixteenBitSound            =  conf.GetBool("Sound::16BitSound",                   true);
	Settings.Stereo                     =  conf.GetBool("Sound::Stereo",                       true);
	Settings.ReverseStereo              =  conf.GetBool("Sound::ReverseStereo",                false);
	Settings.SoundPlaybackRate          =  conf.GetUInt("Sound::Rate",                         32000);
	Settings.SoundInputRate             =  conf.GetUInt("Sound::InputRate",                    32000);
	Settings.Mute                       =  conf.GetBool("Sound::Mute",                         false);

	// Display

	Settings.SupportHiRes               =  conf.GetBool("Display::HiRes",                      true);
	Settings.Transparency               =  conf.GetBool("Display::Transparency",               true);
	Settings.DisableGraphicWindows      = !conf.GetBool("Display::GraphicWindows",             true);
	Settings.DisplayFrameRate           =  conf.GetBool("Display::DisplayFrameRate",           false);
	Settings.DisplayWatchedAddresses    =  conf.GetBool("Display::DisplayWatchedAddresses",    false);
	Settings.DisplayPressedKeys         =  conf.GetBool("Display::DisplayInput",               false);
	Settings.DisplayMovieFrame          =  conf.GetBool("Display::DisplayFrameCount",          false);
	Settings.AutoDisplayMessages        =  conf.GetBool("Display::MessagesInImage",            true);
	Settings.InitialInfoStringTimeout   =  conf.GetInt ("Display::MessageDisplayTime",         120);

	// Settings

	Settings.BSXBootup                  =  conf.GetBool("Settings::BSXBootup",                 false);
	Settings.TurboMode                  =  conf.GetBool("Settings::TurboMode",                 false);
	Settings.TurboSkipFrames            =  conf.GetUInt("Settings::TurboFrameSkip",            15);
	Settings.MovieTruncate              =  conf.GetBool("Settings::MovieTruncateAtEnd",        false);
	Settings.MovieNotifyIgnored         =  conf.GetBool("Settings::MovieNotifyIgnored",        false);
	Settings.WrongMovieStateProtection  =  conf.GetBool("Settings::WrongMovieStateProtection", true);
	Settings.StretchScreenshots         =  conf.GetInt ("Settings::StretchScreenshots",        1);
	Settings.SnapshotScreenshots        =  conf.GetBool("Settings::SnapshotScreenshots",       true);
	Settings.DontSaveOopsSnapshot       =  conf.GetBool("Settings::DontSaveOopsSnapshot",      false);
	Settings.AutoSaveDelay              =  conf.GetUInt("Settings::AutoSaveDelay",             0);

	if (conf.Exists("Settings::FrameTime"))
		Settings.FrameTimePAL = Settings.FrameTimeNTSC = conf.GetUInt("Settings::FrameTime", 16667);

	if (!strcasecmp(conf.GetString("Settings::FrameSkip", "Auto"), "Auto"))
		Settings.SkipFrames = AUTO_FRAMERATE;
	else
		Settings.SkipFrames = conf.GetUInt("Settings::FrameSkip", 0) + 1;

	// Controls

	Settings.MouseMaster                =  conf.GetBool("Controls::MouseMaster",               true);
	Settings.SuperScopeMaster           =  conf.GetBool("Controls::SuperscopeMaster",          true);
	Settings.JustifierMaster            =  conf.GetBool("Controls::JustifierMaster",           true);
	Settings.MultiPlayer5Master         =  conf.GetBool("Controls::MP5Master",                 true);
	Settings.UpAndDown                  =  conf.GetBool("Controls::AllowLeftRight",            false);

	if (conf.Exists("Controls::Port1"))
		parse_controller_spec(0, conf.GetString("Controls::Port1"));
	if (conf.Exists("Controls::Port2"))
		parse_controller_spec(1, conf.GetString("Controls::Port2"));

	if (conf.Exists("Controls::Mouse1Crosshair"))
		parse_crosshair_spec(X_MOUSE1,     conf.GetString("Controls::Mouse1Crosshair"));
	if (conf.Exists("Controls::Mouse2Crosshair"))
		parse_crosshair_spec(X_MOUSE2,     conf.GetString("Controls::Mouse2Crosshair"));
	if (conf.Exists("Controls::SuperscopeCrosshair"))
		parse_crosshair_spec(X_SUPERSCOPE, conf.GetString("Controls::SuperscopeCrosshair"));
	if (conf.Exists("Controls::Justifier1Crosshair"))
		parse_crosshair_spec(X_JUSTIFIER1, conf.GetString("Controls::Justifier1Crosshair"));
	if (conf.Exists("Controls::Justifier2Crosshair"))
		parse_crosshair_spec(X_JUSTIFIER2, conf.GetString("Controls::Justifier2Crosshair"));

	// Hack

	Settings.DisableGameSpecificHacks       = !conf.GetBool("Hack::EnableGameSpecificHacks",       true);
	Settings.BlockInvalidVRAMAccessMaster   = !conf.GetBool("Hack::AllowInvalidVRAMAccess",        false);
	Settings.HDMATimingHack                 =  conf.GetInt ("Hack::HDMATiming",                    100);

	// Netplay

#ifdef NETPLAY_SUPPORT
	Settings.NetPlay = conf.GetBool("Netplay::Enable");

	Settings.Port = NP_DEFAULT_PORT;
	if (conf.Exists("Netplay::Port"))
		Settings.Port = -(int) conf.GetUInt("Netplay::Port");

	Settings.ServerName[0] = '\0';
	if (conf.Exists("Netplay::Server"))
		conf.GetString("Netplay::Server", Settings.ServerName, 128);
#endif

	// Debug

#ifdef DEBUGGER
	if (conf.GetBool("DEBUG::Debugger", false))
		CPU.Flags |= DEBUG_MODE_FLAG;

	if (conf.GetBool("DEBUG::Trace", false))
	{
		ENSURE_TRACE_OPEN(trace,"trace.log","wb")
		CPU.Flags |= TRACE_FLAG;
	}
#endif

	S9xParsePortConfig(conf, 1);
	S9xVerifyControllers();
}
Exemplo n.º 5
0
void EventReceiver::loadKeyMapping()
{
    // Load resource paths from config file
    clearKeyMapping();

    ConfigFile cf;
    cf.load(keyMappingFilename);

    dprintf(MY_DEBUG_NOTE, "Read keymapping file:\n");
    // Go through all sections & settings in the file
    ConfigFile::SectionIterator seci = cf.getSectionIterator();

    std::string secName, keyName, valueName;
    while (seci.hasMoreElements())
    {
        bool primary = false;
        bool secondary = false;
        unsigned int p_type = 0;
        unsigned int p_key = (unsigned int)-1;
        unsigned int p_key2 = (unsigned int)-1;
        int p_from = 0;
        int p_to = 0;
        unsigned int s_type = 0;
        unsigned int s_key = (unsigned int)-1;
        unsigned int s_key2 = (unsigned int)-1;
        int s_from = 0;
        int s_to = 0;

        secName = seci.peekNextKey();
        dprintf(MY_DEBUG_NOTE, "\tKey: %s\n", secName.c_str());
        ConfigFile::SettingsMultiMap *settings = seci.getNext();
        for (ConfigFile::SettingsMultiMap::iterator i = settings->begin(); i != settings->end(); ++i)
        {
            keyName = i->first;
            valueName = i->second;

            if (keyName == "primary_type")
            {
                primary = true;
                p_type = StringConverter::parseUnsignedInt(valueName, 0);
            } else
            if (keyName == "secondary_type")
            {
                secondary = true;
                s_type = StringConverter::parseUnsignedInt(valueName, 0);
            } else
            if (keyName == "primary_key")
            {
                primary = true;
                p_key = StringConverter::parseUnsignedInt(valueName, (unsigned int)-1);
            } else
            if (keyName == "secondary_key")
            {
                secondary = true;
                s_key = StringConverter::parseUnsignedInt(valueName, (unsigned int)-1);
            } else
            if (keyName == "primary_key2")
            {
                primary = true;
                p_key2 = StringConverter::parseUnsignedInt(valueName, (unsigned int)-1);
            } else
            if (keyName == "secondary_key2")
            {
                secondary = true;
                s_key2 = StringConverter::parseUnsignedInt(valueName, (unsigned int)-1);
            } else
            if (keyName == "primary_from")
            {
                primary = true;
                p_from = StringConverter::parseInt(valueName, 0);
            } else
            if (keyName == "secondary_from")
            {
                secondary = true;
                s_from = StringConverter::parseInt(valueName, 0);
            } else
            if (keyName == "primary_to")
            {
                primary = true;
                p_to = StringConverter::parseInt(valueName, 0);
            } else
            if (keyName == "secondary_to")
            {
                secondary = true;
                s_to = StringConverter::parseInt(valueName, 0);
            }
        }
        keyNameMap_t::iterator kit = keyNameMap.find(secName);
        if (kit != keyNameMap.end())
        {
            KeyName kn = kit->second;
            assert(kn < NUMBER_OF_KEYNAMES);
            if (primary)
            {
                keyMap[kn].primaryKeyConfig = KeyConfig::getKeyConfig((KeyConfig::type_t)p_type, p_key, p_key2, p_from, p_to, keyMap[kn].continous);
            }
            if (secondary)
            {
                keyMap[kn].secondaryKeyConfig = KeyConfig::getKeyConfig((KeyConfig::type_t)s_type, s_key, s_key2, s_from, s_to, keyMap[kn].continous);
            }
        }
    }
}
Exemplo n.º 6
0
int main(int argc, char **argv) try
{
    ConfigFile params;
    if (BasicSetup(argc,argv,params,"findstars")) return EXIT_FAILURE;

    // Setup Log
    std::string logFile = ""; // Default is to stdout
    if (params.keyExists("log_file") || params.keyExists("log_ext"))
        logFile = MakeName(params,"log",false,false);
    std::string starsFile=MakeName(params,"stars",false,false);
    std::auto_ptr<FindStarsLog> log(
        new FindStarsLog(params,logFile,starsFile));

    try {
        bool timing = params.read("timing",false);
        timeval tp;
        double t1=0.,t2=0.;

        if (timing) {
            gettimeofday(&tp,0);
            t1 = tp.tv_sec + tp.tv_usec/1.e6;
        }

        // Read image, transformation
        std::auto_ptr<Image<double> > weight_image;
        Image<double> im(params,weight_image);

        if (timing) {
            gettimeofday(&tp,0);
            t2 = tp.tv_sec + tp.tv_usec/1.e6;
            std::cout<<"Time: Open imgae = "<<t2-t1<<std::endl;
            t1 = t2;
        }

        // Read distortion function
        Transformation trans(params);

        if (timing) {
            gettimeofday(&tp,0);
            t2 = tp.tv_sec + tp.tv_usec/1.e6;
            std::cout<<"Time: Read Transformation = "<<t2-t1<<std::endl;
            t1 = t2;
        }

        // Read input catalog
        InputCatalog incat(params,&im);
        incat.read();

        if (timing) {
            gettimeofday(&tp,0);
            t2 = tp.tv_sec + tp.tv_usec/1.e6;
            std::cout<<"Time: Read InputCatalog = "<<t2-t1<<std::endl;
            t1 = t2;
        }

        std::auto_ptr<StarCatalog> starcat;
        DoFindStars(params,*log,im,weight_image.get(),trans,incat,starcat);
    }
#if 0
    // Change to 1 to let gdb see where the program bombed out.
    catch(int) {}
#else
    CATCHALL;
#endif

    if (dbgout && dbgout != &std::cout) {
        delete dbgout;
        dbgout=0;
    }
    return EXIT_SUCCESS;
} catch (std::exception& e) {
    std::cerr<<"Fatal error: Caught \n"<<e.what()<<std::endl;
    std::cout<<"STATUS5BEG Fatal error: "<<e.what()<<" STATUS5END\n";
    return EXIT_FAILURE;
} catch (...) {
    std::cerr<<"Fatal error: Cought an exception.\n";
    std::cout<<"STATUS5BEG Fatal error: unknown exception STATUS5END\n";
    return EXIT_FAILURE;
}
Exemplo n.º 7
0
bool Annotation::initSection(const std::string &entry, const std::string &cfgname)
{
    AnnotationCfgEntry e, *ne;

    ConfigFile *cfg = s2e()->getConfig();
    llvm::raw_ostream &os  = s2e()->getWarningsStream();
    std::vector<std::string> cfgkeys = s2e()->getConfig()->getListKeys(entry);

    e.cfgname = cfgname;

    bool ok;


    e.isActive = cfg->getBool(entry + ".active", false, &ok);
    if (!ok) {
        os << "You must specify whether the entry is active in " << entry << ".active!" << '\n';
        return false;
    }

    e.module = cfg->getString(entry + ".module", "", &ok);
    if (!ok) {
        os << "You must specify a valid module for " << entry << ".module!" << '\n';
        return false;
    }else {
        if (!m_moduleExecutionDetector->isModuleConfigured(e.module)) {
            os << "The module " << e.module << " is not configured in ModuleExecutionDetector!" << '\n';
            return false;
        }
    }


    e.address = cfg->getInt(entry + ".address", 0, &ok);
    if (!ok) {
        os << "You must specify a valid address for " << entry << ".address!" << '\n';
        return false;
    }

    if (!m_functionMonitor || !m_moduleExecutionDetector || !m_osMonitor) {
        os << "You must enable FunctionMonitor, ModuleExecutionDetector, and an OS monitor plugin\n";
        return false;
    }

    // Check if this is a call or an instruction annotation
    e.annotation = "";
    if (std::find(cfgkeys.begin(), cfgkeys.end(), "callAnnotation") != cfgkeys.end())	{
        e.annotation = cfg->getString(entry + ".callAnnotation", e.annotation, &ok);
        e.isCallAnnotation = true;
    } else if (std::find(cfgkeys.begin(), cfgkeys.end(), "instructionAnnotation") != cfgkeys.end())	{
        e.annotation = cfg->getString(entry + ".instructionAnnotation", e.annotation, &ok);
        e.isCallAnnotation = false;
    }

    // Assert that this is a properly attached annotation
    if (!ok || e.annotation=="") {
        os << "You must specify either " << entry << ".callAnnotation or .instructionAnnotation!" << '\n';
        return false;
    }

    // Get additional annotation-specific options
    e.paramCount = 0;
    e.beforeInstruction = false;
    e.switchInstructionToSymbolic = false;
    if (e.isCallAnnotation) {
        // Get the number of arguments of the annotated subroutine
        e.paramCount = cfg->getInt(entry + ".paramcount", e.paramCount, &ok);
        if (!ok) {
            os << "You must specify a valid number of function parameters for " << entry << ".paramcount!" << '\n';
            return false;
        }
    } else {
        // Whether to call the annotation before or after the instruction
        e.beforeInstruction = cfg->getBool(entry + ".beforeInstruction", e.beforeInstruction, &ok);
        e.switchInstructionToSymbolic = cfg->getBool(entry + ".switchInstructionToSymbolic", e.switchInstructionToSymbolic, &ok);
    }

    ne = new AnnotationCfgEntry(e);
    m_entries.insert(ne);

    return true;
}
Exemplo n.º 8
0
void DoMeasurePsf(
    ConfigFile& params, PsfLog& log,
    const Image<double>& im, const Image<double>* weight_image,
    const Transformation& trans, 
    const StarCatalog& starcat,
    std::auto_ptr<PsfCatalog>& psfcat, std::auto_ptr<FittedPsf>& fitpsf,
    double& sigma_p)
{
    dbg<<"Starting MeasurePsf script\n";

    bool isTiming = params.read("timing",false);
    timeval tp;
    double t1=0.,t2=0.;

    if (isTiming) {
        gettimeofday(&tp,0);
        t1 = tp.tv_sec + tp.tv_usec/1.e6;
    }

    if (params.read("psf_skip_measurements",false)) {
        // Option to read existing PsfCatalog rather than remeasure.
        // (Useful if you only want to redo the fitting step.)
        psfcat.reset(new PsfCatalog(params));
        psfcat->read();

        if (isTiming) {
            gettimeofday(&tp,0);
            t2 = tp.tv_sec + tp.tv_usec/1.e6;
            std::cout<<"Time: Read PSFCatalog = "<<t2-t1<<std::endl;
            t1 = t2;
        }
    } else {
        // Create PsfCatalog from StarCatalog
        psfcat.reset(new PsfCatalog(starcat,params));

        if (isTiming) {
            gettimeofday(&tp,0);
            t2 = tp.tv_sec + tp.tv_usec/1.e6;
            std::cout<<"Time: Create PSFCatalog = "<<t2-t1<<std::endl;
            t1 = t2;
        }

        // Estimate the scale size to use for shapelet decompositions
        if (sigma_p == 0.)
            sigma_p = psfcat->estimateSigma(im,weight_image,trans);

        if (isTiming) {
            gettimeofday(&tp,0);
            t2 = tp.tv_sec + tp.tv_usec/1.e6;
            std::cout<<"Time: Estimate Sigma = "<<t2-t1<<std::endl;
            t1 = t2;
        }

        // Do the actual PSF measurements
        int npsf = psfcat->measurePsf(im,weight_image,trans,sigma_p,log);

        if (isTiming) {
            gettimeofday(&tp,0);
            t2 = tp.tv_sec + tp.tv_usec/1.e6;
            std::cout<<"Time: Measure PSF = "<<t2-t1<<std::endl;
            t1 = t2;
        }

        // Write PSF catalog to file
        psfcat->write();

        if (isTiming) {
            gettimeofday(&tp,0);
            t2 = tp.tv_sec + tp.tv_usec/1.e6;
            std::cout<<"Time: Write PSFCatalog = "<<t2-t1<<std::endl;
            t1 = t2;
        }

        if (npsf == 0) {
            throw ProcessingException(
                "No successful PSF measurements");
        }
    }


    // Fit the PSF with a polynomial:
    fitpsf.reset(new FittedPsf(*psfcat,params,log));

    if (isTiming) {
        gettimeofday(&tp,0);
        t2 = tp.tv_sec + tp.tv_usec/1.e6;
        std::cout<<"Time: Fit PSF = "<<t2-t1<<std::endl;
        t1 = t2;
    }

    // Write fitted psf to file
    fitpsf->write();

    // Re-write the PSF catalog, since the interpolation may have changed
    // the flags.
    // TODO: It may be worth having a new routine that just updates the 
    // flags.  More efficient, since don't need to re-write everything.
    psfcat->write();

    if (isTiming) {
        gettimeofday(&tp,0);
        t2 = tp.tv_sec + tp.tv_usec/1.e6;
        std::cout<<"Time: Write FittedPSF = "<<t2-t1<<std::endl;
        t1 = t2;
    }

    xdbg<<"PSF Log: \n"<<log<<std::endl;
}
ObeyGameManager::ObeyGameManager(ConfigFile & configFile, Log & _log)
  : INITIAL_CHEST_COLOR  (configFile.getInt("rules/initialChestColor",   0x000000)),
    READY_CHEST_COLOR    (configFile.getInt("rules/readyChestColor",     0x0000FF)),
    SET_CHEST_COLOR      (configFile.getInt("rules/setChestColor",       0xFFFF00)),
    PLAYING_CHEST_COLOR  (configFile.getInt("rules/playingChestColor",   0x00FF00)),
    FINISHED_CHEST_COLOR (configFile.getInt("rules/finishedChestColor",  0x000000)),
    PENALIZED_CHEST_COLOR(configFile.getInt("rules/penalisedChestColor", 0xFF0000)),
    BLUE_TEAM_FOOT_COLOR (configFile.getInt("rules/blueTeamFootColor",   0x0000FF)),
    RED_TEAM_FOOT_COLOR  (configFile.getInt("rules/redTeamFootColor",    0xFF0000)),
    KICKOFF_FOOT_COLOR   (configFile.getInt("rules/kickoffFootColor",    0xFFFFFF)),
    NO_KICKOFF_FOOT_COLOR(configFile.getInt("rules/noKickoffFootColor",  0x000000)),
    READY_SPEECH            (configFile.getString("behaviors/2010/tactics/obeyGameManager/readySpeech",           "I will get ready for the game.")),
    SET_SPEECH              (configFile.getString("behaviors/2010/tactics/obeyGameManager/setSpeech",             "I am all set!")),
    PLAYING_SPEECH          (configFile.getString("behaviors/2010/tactics/obeyGameManager/playingSpeech",         "It's time to play.")),
    PENALIZED_SPEECH        (configFile.getString("behaviors/2010/tactics/obeyGameManager/penalizedSpeech",       "Please don't penalize me!")),
    BACK_FROM_PENALTY_SPEECH(configFile.getString("behaviors/2010/tactics/obeyGameManager/backFromPenaltySpeech", "The taste of freedom is sweet.")),
    BLUE_TEAM_SPEECH        (configFile.getString("behaviors/2010/tactics/obeyGameManager/blueTeamSpeech",        "I am now on the blue team.")),
    RED_TEAM_SPEECH         (configFile.getString("behaviors/2010/tactics/obeyGameManager/redTeamSpeech",         "I am now on the red team.")),
    KICKOFF_SPEECH          (configFile.getString("behaviors/2010/tactics/obeyGameManager/kickoffSpeech",         "We have kickoff.")),
    NO_KICKOFF_SPEECH       (configFile.getString("behaviors/2010/tactics/obeyGameManager/noKickoffSpeech",       "We don't have kickoff.")),
    PLAYER_NUMBER(configFile.getInt("team/playerNumber", 2)),
    HEAD_SPEED(configFile.getFloat("motion/defaultHeadSpeed", 0.8f)),
    log(_log),
    fsm(_log),
    previousState(Uninitialized),
    currentState(Uninitialized),
    wasIBlue(false),
    wasOurKickoff(false),
    wasIPenalized(false) {
  init(_log.getTimestamp());
}
bool AtlasResourceCompiler::Compile()
{
	Platform* platform = Platform::Get();

	// Load configuration if we haven't already.
	if (m_config_file == NULL)
	{
		if (!Load_Config())
		{
			return false;
		}
	}

	// Compile time.
	DBG_LOG("Compiling atlas resource '%s'.", m_input_path.c_str());

	// Create new atlas, and start adding rectangles.
	Atlas* atlas = new Atlas(m_config_file);
	atlas->Lock_Textures();

	// Add each of the source-images.
	std::vector<ConfigFileNode> images = m_config_file->Get<std::vector<ConfigFileNode>>("images/image");
	for (std::vector<ConfigFileNode>::iterator iter = images.begin(); iter != images.end(); iter++)
	{
		ConfigFileNode node = *iter;		

		const char* type = m_config_file->Get<const char*>("type", node, true);
		const char* file = m_config_file->Get<const char*>("file", node, true);

		Point origin = Point(0, 0);

		if (m_config_file->Contains("origin", node, true))
		{
			origin = m_config_file->Get<Point>("origin", node, true);
		}

		if (stricmp(type, "single") == 0)
		{
			const char* name = m_config_file->Get<const char*>("name", node, true);

			Texture* texture = TextureFactory::Load_Without_Handle(file, TextureFlags::None);
			DBG_ASSERT_STR(texture != NULL, "Could not load dependent texture '%s'.", file);
			
			atlas->Add_Frame(name, texture, Rect(0, 0, texture->Get_Width(), texture->Get_Height()), origin);
		}		
		else if (stricmp(type, "multiple") == 0)
		{
			const char* name = m_config_file->Get<const char*>("name", node, true);

			// Grab all the file paths.
			std::string name_str = name;
			std::vector<std::string> files;
			Expand_Multiple_Path(file, files);

			// Grab hash mark.
			int hash_mark = name_str.find('#');
			DBG_ASSERT_STR(hash_mark != std::string::npos, "Image marked as type 'multiple' does not contain replacement hash mark.");
			std::string split_left  = name_str.substr(0, hash_mark);
			std::string split_right = name_str.substr(hash_mark + 1);

			// Add each file.
			int counter = 0;
			for (std::vector<std::string>::iterator subiter = files.begin(); subiter != files.end(); subiter++)
			{
				std::string sub_path = *subiter;
				std::string sub_name = split_left + StringHelper::To_String(counter++) + split_right;
				
				Texture* texture = TextureFactory::Load_Without_Handle(sub_path.c_str(), TextureFlags::None);
				DBG_ASSERT_STR(texture != NULL, "Could not load dependent texture '%s'.", sub_path);

				atlas->Add_Frame(sub_name.c_str(), texture, Rect(0, 0, texture->Get_Width(), texture->Get_Height()), origin);
			}
		}
		else if (stricmp(type, "grid") == 0)
		{
			const char* name = m_config_file->Get<const char*>("name", node, true);

			Texture* texture = TextureFactory::Load_Without_Handle(file, TextureFlags::None);
			DBG_ASSERT_STR(texture != NULL, "Could not load dependent texture '%s'.", file);
		
			// Grab hash mark.
			std::string name_str = name;
			int hash_mark = name_str.find('#');
			DBG_ASSERT_STR(hash_mark != std::string::npos, "Image marked as type 'grid' does not contain replacement hash mark.");
			std::string split_left  = name_str.substr(0, hash_mark);
			std::string split_right = name_str.substr(hash_mark + 1);

			// Iterate over each sub-image.			
			int   frame_width		= m_config_file->Get<int>("width", node, true);
			int   frame_height		= m_config_file->Get<int>("height", node, true);
			int   frame_hspace		= m_config_file->Get<int>("hspace", node, true);
			int   frame_vspace		= m_config_file->Get<int>("vspace", node, true);			
			float texture_width		= (float)texture->Get_Width();
			float texture_height	= (float)texture->Get_Height();
			int	  cell_count_u		= texture_width  / (frame_width + frame_hspace);
			int	  cell_count_v		= texture_height / (frame_height + frame_vspace);
			int	  cell_count		= cell_count_u * cell_count_v;

			for (int i = 0; i < cell_count; i++)
			{
				int u = i % cell_count_u;
				int v = i / cell_count_u;

				int u_offset = floor(u * (frame_width + frame_hspace));
				int v_offset = floor(v * (frame_height + frame_vspace));
				
				std::string sub_name = split_left + StringHelper::To_String(i) + split_right;
				atlas->Add_Frame(sub_name.c_str(), texture, Rect(u_offset, v_offset, frame_width, frame_height), origin);
			}
		}
		else if (stricmp(type, "atlas") == 0)
		{
			Texture* texture = TextureFactory::Load_Without_Handle(file, TextureFlags::None);
			DBG_ASSERT_STR(texture != NULL, "Could not load dependent texture '%s'.", file);

			// Calculate frame positions for atlas.
			int frame_width			= m_config_file->Get<int>("width", node, true);
			int frame_height		= m_config_file->Get<int>("height", node, true);
			int frame_hspace		= m_config_file->Get<int>("hspace", node, true);
			int frame_vspace		= m_config_file->Get<int>("vspace", node, true);	
			float texture_width		= (float)texture->Get_Width();
			float texture_height	= (float)texture->Get_Height();
			int	  cell_count_u		= texture_width  / (frame_width + frame_hspace);
			int	  cell_count_v		= texture_height / (frame_height + frame_vspace);
			int	  cell_count		= cell_count_u * cell_count_v;

			// Iterate over each sub-image.	
			std::vector<ConfigFileNode> sub_images = m_config_file->Get<std::vector<ConfigFileNode>>("subimage", node);
			for (std::vector<ConfigFileNode>::iterator subiter = sub_images.begin(); subiter != sub_images.end(); subiter++)
			{
				ConfigFileNode sub_node = *subiter;	
				
				const char* sub_type = m_config_file->Get<const char*>("type", sub_node, true);
				const char* sub_name = m_config_file->Get<const char*>("name", sub_node, true);
				
				if (stricmp(sub_type, "single") == 0)
				{
					int frame		= m_config_file->Get<int>("frame", sub_node, true);
					int u			= frame % cell_count_u;
					int v			= frame / cell_count_u;
					int u_offset	= floor(u * (frame_width + frame_hspace));
					int v_offset	= floor(v * (frame_height + frame_vspace));
						
					atlas->Add_Frame(sub_name, texture, Rect(u_offset, v_offset, frame_width, frame_height), origin);
				}
				else if (stricmp(sub_type, "strip") == 0)
				{
					int to_frame   = m_config_file->Get<int>("to_frame", sub_node, true);
					int from_frame = m_config_file->Get<int>("from_frame", sub_node, true);
					DBG_ASSERT_STR(to_frame >= from_frame, "Invalid strip range %i to %i.", from_frame, to_frame);
					
					std::string sub_name_str	= sub_name;
					int			hash_mark		= sub_name_str.find('#');
					DBG_ASSERT_STR(hash_mark != std::string::npos, "Sub-image marked as type 'strip' does not contain replacement hash mark.");

					std::string split_left  = sub_name_str.substr(0, hash_mark);
					std::string split_right = sub_name_str.substr(hash_mark + 1);

					for(int frame = from_frame; frame <= to_frame; frame++)
					{
						int u			= frame % cell_count_u;
						int v			= frame / cell_count_u;
						int u_offset	= floor(u * (frame_width + frame_hspace));
						int v_offset	= floor(v * (frame_height + frame_vspace));
						
						std::string sub_sub_name = split_left + StringHelper::To_String(frame) + split_right;
						atlas->Add_Frame(sub_sub_name.c_str(), texture, Rect(u_offset, v_offset, frame_width, frame_height), origin);
					}
				}
				else
				{
					DBG_ASSERT_STR(false, "Unknown or invalid sub-image type '%s'", sub_type);
				}
			}
		}
		else
		{
			DBG_ASSERT_STR(false, "Unknown or invalid source-image type '%s'", type);
		}
	}

	// Add each of the animations.
	std::vector<ConfigFileNode> animations = m_config_file->Get<std::vector<ConfigFileNode>>("animations/animation");
	for (std::vector<ConfigFileNode>::iterator iter = animations.begin(); iter != animations.end(); iter++)
	{
		ConfigFileNode node = *iter;		
		
		const char* name = m_config_file->Get<const char*>("name", node, true);
		const char* mode = m_config_file->Get<const char*>("mode", node, true);
		float	   speed = m_config_file->Get<float>("speed", node, true);
		std::vector<AtlasFrame*> out_frames;
		
		// Decode the animation mode.
		AtlasAnimationMode::Type anim_mode;
		if (stricmp(mode, "once") == 0)
		{
			anim_mode = AtlasAnimationMode::Once;
		}
		else if (stricmp(mode, "loop") == 0)
		{
			anim_mode = AtlasAnimationMode::Loop;
		}
		else
		{
			DBG_ASSERT_STR(false, "Unknown or invalid animation mode '%s'", mode);
		}
		
		// Work out the names of each of the frames.
		std::vector<ConfigFileNode> frames = m_config_file->Get<std::vector<ConfigFileNode>>("frame", node);
		for (std::vector<ConfigFileNode>::iterator frameiter = frames.begin(); frameiter != frames.end(); frameiter++)
		{
			ConfigFileNode frame_node = *frameiter;			
			const char*	   frame_type = m_config_file->Get<const char*>("type", frame_node, true);
			const char*	   frame_name = m_config_file->Get<const char*>("name", frame_node, true);

			if (stricmp(frame_type, "single") == 0)
			{
				AtlasFrame* frame = atlas->Get_Frame(frame_name);
				DBG_ASSERT(frame != NULL, "Invalid frame name '%s' in animation '%s'.", frame_name, name);
				out_frames.push_back(frame);
			}
			else if (stricmp(frame_type, "multiple") == 0)
			{
				LinkedList<AtlasFrame*>& frames = atlas->Get_Frames_List();
				
				std::string name_str = frame_name;

				int hash_mark = name_str.find('#');
				DBG_ASSERT_STR(hash_mark != std::string::npos, "Animation marked as type 'multiple' does not contain replacement hash mark.");

				std::string split_left  = name_str.substr(0, hash_mark);
				std::string split_right = name_str.substr(hash_mark + 1);
				
				for (LinkedList<AtlasFrame*>::Iterator animiter = frames.Begin(); animiter != frames.End(); animiter++)
				{
					AtlasFrame* anim = *animiter;

					if (anim->Name.size() > split_left.size() + split_right.size())
					{
						if (anim->Name.substr(0, split_left.size()) == split_left &&
							anim->Name.substr((anim->Name.size() - split_right.size()), split_right.size()) == split_right)
						{
							AtlasFrame* frame = atlas->Get_Frame(anim->Name.c_str());
							DBG_ASSERT(frame != NULL, "Invalid frame name '%s' in animation '%s'.", anim->Name, name);
							out_frames.push_back(frame);
						}
					}
				}
			}
			else
			{
				DBG_ASSERT_STR(false, "Unknown or invalid frame type '%s'", frame_type);
			}
		}

		// Add the animation.
		atlas->Add_Animation(name, speed, anim_mode, out_frames);
	}

	// Save compiled file.
	atlas->Unlock_Textures();

	// Configuration settings.
	ConfigFile config;
	
	// Store configuration settings.
	config.Set<const char*>("settings/texture-size",		m_config_file->Get<const char*>("settings/texture-size"));
	config.Set<const char*>("settings/max-textures",		m_config_file->Get<const char*>("settings/max-textures"));

	// Save pngs.
	int texture_count = 0;
	AtlasTexture** textures = atlas->Get_Textures(texture_count);

	for (int i = 0; i < texture_count; i++)
	{
		AtlasTexture* texture = textures[i];		

		std::string output_path = (m_output_path + "." + StringHelper::To_String(i) + ".png");

		// Save texture file.
		TextureFactory::Save(output_path.c_str(), texture->Texture, TextureFlags::None);

		// Store texture spec in xml.
		ConfigFileNode node = config.New_Node("textures/texture");
		config.Set(NULL, output_path.c_str(), node, false);
	}

	// Save frame configuration.
	config.New_Node("frames");
	HashTable<AtlasFrame*, unsigned int>& frames = atlas->Get_Frames();
	for (HashTable<AtlasFrame*, unsigned int>::Iterator iter = frames.Begin(); iter != frames.End(); iter++)
	{
		AtlasFrame* frame = iter.Get_Value();
		
		// Store character spec in xml.
		ConfigFileNode node = config.New_Node("frames/frame");
		config.Set("name",			frame->Name.c_str(),				node, true);
		config.Set("namehash",		frame->NameHash,					node, true);
		config.Set("texture",		frame->TextureIndex,				node, true);
		config.Set("rectangle",		frame->Rectangle,					node, true);
		config.Set("uv",			frame->UV,							node, true);
		config.Set("origin",		frame->Origin,						node, true);
	}

	// Save animation configuration.
	config.New_Node("animations");
	HashTable<AtlasAnimation*, unsigned int>& anims = atlas->Get_Animations();
	for (HashTable<AtlasAnimation*, unsigned int>::Iterator iter = anims.Begin(); iter != anims.End(); iter++)
	{
		AtlasAnimation* frame = iter.Get_Value();
		
		// Store character spec in xml.
		ConfigFileNode node = config.New_Node("animations/animation");
		config.Set("name",			frame->Name.c_str(),				node, true);
		config.Set("namehash",		frame->NameHash,					node, true);
		switch (frame->Mode)
		{
			case AtlasAnimationMode::Loop: config.Set("mode", "loop", node, true); break;
			case AtlasAnimationMode::Once: config.Set("mode", "once", node, true); break;
			default: DBG_ASSERT_STR(false, "Invalid animation mode.");
		}
		config.Set("speed",			frame->Speed,						node, true);

		for (std::vector<AtlasFrame*>::iterator iter = frame->Frames.begin(); iter != frame->Frames.end(); iter++)
		{
			AtlasFrame* frame = (*iter);
			ConfigFileNode subnode = config.New_Node("frame", node);

			config.Set("name", frame->Name.c_str(), subnode, true);
			config.Set("namehash", frame->NameHash, subnode, true);
		}
	}

	// Save font xml configuration.
	config.Save(m_output_path.c_str());

	// Update timestamps.
	Update_File_Timestamp(m_input_path);

	// Update timestamps on dependent files.
	for (std::vector<std::string>::iterator iter = m_dependent_files.begin(); iter != m_dependent_files.end(); iter++)
	{
		std::string path = (*iter);
		DBG_ASSERT_STR(Platform::Get()->Is_File(path.c_str()), "Could not find dependent file '%s'.", path.c_str());

		Update_File_Timestamp(path.c_str());
	}

	DBG_LOG("Finished compiling to '%s'.", m_output_path.c_str());

	return true;
}
Exemplo n.º 11
0
void DoFindStars(
    ConfigFile& params, FindStarsLog& log,
    const Image<double>& im, const Image<double>* weight_image,
    const Transformation& trans, 
    const InputCatalog& incat,
    std::auto_ptr<StarCatalog>& starcat)
{
    dbg<<"Starting FindStars script\n";

    bool isTiming = params.read("timing",false);
    timeval tp;
    double t1=0.,t2=0.;

    if (isTiming) {
        gettimeofday(&tp,0);
        t1 = tp.tv_sec + tp.tv_usec/1.e6;
    }

    // Create StarCatalog from InputCatalog
    starcat.reset(new StarCatalog(incat,params));

    if (isTiming) {
        gettimeofday(&tp,0);
        t2 = tp.tv_sec + tp.tv_usec/1.e6;
        std::cout<<"Time: Make StarCatalog = "<<t2-t1<<std::endl;
        t1 = t2;
    }

    // Update the sizes to more robust values
    starcat->calculateSizes(im,weight_image,trans);

    if (isTiming) {
        gettimeofday(&tp,0);
        t2 = tp.tv_sec + tp.tv_usec/1.e6;
        std::cout<<"Time: CalcSizes = "<<t2-t1<<std::endl;
        t1 = t2;
    }

    try {
        starcat->findStars(log);
    } catch(StarFinderException& e) {
        // Need to catch this here, so we can write the output file
        // with the sizes, even though we haven't figured out which 
        // objects are stars.
        dbg<<"Caught StarFinderException: "<<e.what()<<std::endl;  
        starcat->write();
        throw;
    } catch (...) {
        dbg<<"Caught unknown exception\n";
        starcat->write();
        throw;
    }
    dbg<<"After RunFindStars\n";

    if (isTiming) {
        gettimeofday(&tp,0);
        t2 = tp.tv_sec + tp.tv_usec/1.e6;
        std::cout<<"Time: FindStars = "<<t2-t1<<std::endl;
        t1 = t2;
    }

    // Write star catalog to file
    starcat->write();

    if (isTiming) {
        gettimeofday(&tp,0);
        t2 = tp.tv_sec + tp.tv_usec/1.e6;
        std::cout<<"Time: Write StarCatalog = "<<t2-t1<<std::endl;
        t1 = t2;
    }

    xdbg<<"FindStars Log: \n"<<log<<std::endl;
}
Exemplo n.º 12
0
ShibbolethWebView::~ShibbolethWebView()
{
    ConfigFile config;
    QSettings settings(config.configFile());
    settings.setValue(ShibbolethWebViewGeometryC, saveGeometry());
}
Exemplo n.º 13
0
//Constructor
Parameters::Parameters(ConfigFile config)
{
    config.readInto(outflow_model_on, "outflowModelOn");
    config.readInto(lambda, "lambda");
    config.readInto(single_mode, "Mode");
    config.readInto(range_number, "numberOfSpeedValues");
    config.readInto(elements_in_l, "elementsInL");
    config.readInto(adotc0, "aDotc0");

    config.readInto(pipeid, "pipeID");
    config.readInto(diameter, "diameter");
    config.readInto(sdr, "sdr");
    config.readInto(notch_depth, "notchDepth");
    config.readInto(diameter_creep_ratio, "diameterCreepRatio");

    config.readInto(matid, "matID" );
    config.readInto(density, "density" );
    config.readInto(edyn0degc, "eDyn0degC" );
    config.readInto(dedyndt, "dEdyndT" );
    config.readInto(creep_modulus, "creepModulus" );
    config.readInto(poisson, "poisson" );

    config.readInto(fullscale, "fullScale");
    config.readInto(tempdegc, "tempDegC");
    config.readInto(p0bar, "p0bar");
    config.readInto(is_backfilled, "isBackfilled");
    config.readInto(backfill_depth, "backfillDepth");
    config.readInto(backfill_density, "backfillDensity");
    config.readInto(solid_inside_pipe, "solidInsidePipe");
    config.readInto(water_inside_pipe, "waterInsidePipe");
}
Exemplo n.º 14
0
	void Set(ConfigFile& conf) {
		switch(type)
		{
			case CIT_BOOL:
				if(size	== 1) conf.SetBool(name, 0!=(*(uint8 *)addr), "TRUE","FALSE", comment);
				if(size	== 2) conf.SetBool(name, 0!=(*(uint16*)addr), "TRUE","FALSE", comment);
				if(size	== 4) conf.SetBool(name, 0!=(*(uint32*)addr), "TRUE","FALSE", comment);
				if(size	== 8) conf.SetBool(name, 0!=(*(uint64*)addr), "TRUE","FALSE", comment);
				break;
			case CIT_BOOLONOFF:
				if(size	== 1) conf.SetBool(name, 0!=(*(uint8 *)addr), "ON","OFF", comment);
				if(size	== 2) conf.SetBool(name, 0!=(*(uint16*)addr), "ON","OFF", comment);
				if(size	== 4) conf.SetBool(name, 0!=(*(uint32*)addr), "ON","OFF", comment);
				if(size	== 8) conf.SetBool(name, 0!=(*(uint64*)addr), "ON","OFF", comment);
				break;
			case CIT_INT:
				if(size	== 1) conf.SetInt(name,	(int32)(*(uint8	*)addr), comment);
				if(size	== 2) conf.SetInt(name,	(int32)(*(uint16*)addr), comment);
				if(size	== 4) conf.SetInt(name,	(int32)(*(uint32*)addr), comment);
				if(size	== 8) conf.SetInt(name,	(int32)(*(uint64*)addr), comment);
				break;
			case CIT_UINT:
				if(size	== 1) conf.SetUInt(name, (uint32)(*(uint8 *)addr), 10, comment);
				if(size	== 2) conf.SetUInt(name, (uint32)(*(uint16*)addr), 10, comment);
				if(size	== 4) conf.SetUInt(name, (uint32)(*(uint32*)addr), 10, comment);
				if(size	== 8) conf.SetUInt(name, (uint32)(*(uint64*)addr), 10, comment);
				break;
			case CIT_STRING:
				if((TCHAR*)addr)
					conf.SetString(name, std::string(_tToChar((TCHAR*)addr)), comment);
				break;
			case CIT_INVBOOL:
				if(size	== 1) conf.SetBool(name, 0==(*(uint8 *)addr), "TRUE","FALSE", comment);
				if(size	== 2) conf.SetBool(name, 0==(*(uint16*)addr), "TRUE","FALSE", comment);
				if(size	== 4) conf.SetBool(name, 0==(*(uint32*)addr), "TRUE","FALSE", comment);
				if(size	== 8) conf.SetBool(name, 0==(*(uint64*)addr), "TRUE","FALSE", comment);
				break;
			case CIT_INVBOOLONOFF:
				if(size	== 1) conf.SetBool(name, 0==(*(uint8 *)addr), "ON","OFF", comment);
				if(size	== 2) conf.SetBool(name, 0==(*(uint16*)addr), "ON","OFF", comment);
				if(size	== 4) conf.SetBool(name, 0==(*(uint32*)addr), "ON","OFF", comment);
				if(size	== 8) conf.SetBool(name, 0==(*(uint64*)addr), "ON","OFF", comment);
				break;
			case CIT_VKEY:
				{
					uint16 keyNum = 0;
					if(size	== 1) keyNum = (uint8)(*(uint8 *)addr);
					if(size	== 2) keyNum = (uint16)(*(uint16*)addr);
					if(size	== 4) keyNum = (uint16)(*(uint32*)addr);
					if(size	== 8) keyNum = (uint16)(*(uint64*)addr);
					if(keyNum < 256) conf.SetString(name, keyToString[keyNum], comment);
					else if(keyNum & 0x8000) {
						char temp [128];
						extern void TranslateKey(WORD keyz,char *out);
						TranslateKey(keyNum,temp);
						conf.SetString(name, temp, comment);
					}
					else conf.SetUInt(name, keyNum, 16, comment);
				}
				break;
			case CIT_VKEYMOD:
				{
					uint16 modNum = 0;
					if(size	== 1) modNum = (uint8)(*(uint8 *)addr);
					if(size	== 2) modNum = (uint16)(*(uint16*)addr);
					if(size	== 4) modNum = (uint16)(*(uint32*)addr);
					if(size	== 8) modNum = (uint16)(*(uint64*)addr);
					std::string modStr;
					if(modNum & CUSTKEY_CTRL_MASK) modStr += "Ctrl ";
					if(modNum & CUSTKEY_ALT_MASK) modStr += "Alt ";
					if(modNum & CUSTKEY_SHIFT_MASK) modStr += "Shift ";
					if(!(modNum & (CUSTKEY_CTRL_MASK|CUSTKEY_ALT_MASK|CUSTKEY_SHIFT_MASK))) modStr = "none";
					else modStr.erase(modStr.length()-1);
					conf.SetString(name, modStr, comment);
				}
				break;
		}
	}
Exemplo n.º 15
0
bool CCGShader::LoadShader(const char *path)
{
	ConfigFile conf;
	int shaderCount;
	char keyName[100];

	shaderPasses.clear();
	lookupTextures.clear();

	if(strlen(path)<4 || strcasecmp(&path[strlen(path)-4],".cgp")) {
		shaderPass pass;
		pass.scaleParams.scaleTypeX = CG_SCALE_NONE;
		pass.scaleParams.scaleTypeY = CG_SCALE_NONE;
		pass.linearFilter = false;
		pass.filterSet = false;
		strcpy(pass.cgShaderFile,path);
		shaderPasses.push_back(pass);
		return true;
	} else {
		conf.LoadFile(path);
	}	

	shaderCount = conf.GetInt("::shaders",0);

	if(shaderCount<1)
		return false;

	for(int i=0;i<shaderCount;i++) {
		shaderPass pass;
		sprintf(keyName,"::filter_linear%u",i);
		pass.linearFilter = conf.GetBool(keyName);
		pass.filterSet = conf.Exists(keyName);

		sprintf(keyName,"::scale_type%u",i);
		const char *scaleType = conf.GetString(keyName,"");
		if(!strcasecmp(scaleType,"")) {
			sprintf(keyName,"::scale_type_x%u",i);
			const char *scaleTypeX = conf.GetString(keyName,"");
			if(*scaleTypeX=='\0' && (i!=(shaderCount-1)))
				scaleTypeX = "source";
			pass.scaleParams.scaleTypeX = scaleStringToEnum(scaleTypeX);
			sprintf(keyName,"::scale_type_y%u",i);
			const char *scaleTypeY = conf.GetString(keyName,"");
			if(*scaleTypeY=='\0' && (i!=(shaderCount-1)))
				scaleTypeY = "source";
			pass.scaleParams.scaleTypeY = scaleStringToEnum(scaleTypeY);
		} else {
			cgScaleType sType = scaleStringToEnum(scaleType);
			pass.scaleParams.scaleTypeX = sType;
			pass.scaleParams.scaleTypeY = sType;
		}

		sprintf(keyName,"::scale%u",i);
		const char *scaleFloat = conf.GetString(keyName,"");
		int scaleInt = conf.GetInt(keyName,0);
		if(!strcasecmp(scaleFloat,"")) {
			sprintf(keyName,"::scalex%u",i);
			const char *scaleFloatX = conf.GetString(keyName,"1.0");
			pass.scaleParams.scaleX = atof(scaleFloatX);
			pass.scaleParams.absX = conf.GetInt(keyName,1);
			sprintf(keyName,"::scaley%u",i);
			const char *scaleFloatY = conf.GetString(keyName,"1.0");
			pass.scaleParams.scaleY = atof(scaleFloatY);
			pass.scaleParams.absY = conf.GetInt(keyName,1);

		} else {
			float floatval = atof(scaleFloat);
			pass.scaleParams.scaleX = floatval;
			pass.scaleParams.absX = scaleInt;
			pass.scaleParams.scaleY = floatval;
			pass.scaleParams.absY = scaleInt;
		}

		sprintf(keyName,"::shader%u",i);
		strcpy(pass.cgShaderFile,conf.GetString(keyName,""));
		shaderPasses.push_back(pass);
	}

	char *shaderIds = conf.GetStringDup("::textures","");

	char *id = strtok(shaderIds,";");
	while(id!=NULL) {
		lookupTexture tex;
		sprintf(keyName,"::%s",id);
		strcpy(tex.id,id);
		strcpy(tex.texturePath,conf.GetString(keyName,""));
		sprintf(keyName,"::%s_linear",id);
		tex.linearfilter = conf.GetBool(keyName,true);
		lookupTextures.push_back(tex);
		id = strtok(NULL,";");
	}

	free(shaderIds);

	return true;
}
Exemplo n.º 16
0
void GeneralSettings::slotToggleOptionalDesktopNotifications(bool enable)
{
    ConfigFile cfgFile;
    cfgFile.setOptionalDesktopNotifications(enable);
}
void MaterialEditorFrame::createOgrePane()
{
	mRoot = new Ogre::Root();

	// Find Render Systems
	// Testing only, this will be deleted once Projects can tell us
	// which rendering system they want used
	mDirectXRenderSystem = NULL;
	mOpenGLRenderSystem = NULL;
	const RenderSystemList &rl = mRoot.getAvailableRenderers();
	if (rl->empty()) 
	{
		wxMessageBox("No render systems found", "Error");
		return;
	}
	for(RenderSystemList::const_iterator it = rl.begin(); it != rl.end(); ++it)
	{
		Ogre::RenderSystem *rs = (*it);
		rs->setConfigOption("Full Screen", "No");
		rs->setConfigOption("VSync", "No");
		rs->setConfigOption("Video Mode", "512 x 512 @ 32-bit");
		
		if(rs->getName() == "OpenGL Rendering Subsystem") 
			mOpenGLRenderSystem = *it;
		else if(rs->getName() == "Direct3D9 Rendering Subsystem")
			mDirectXRenderSystem = *it;
	}

	// We'll see if there is already and Ogre.cfg, if not we'll
	// default to OpenGL since we know that will work on all
	// platforms
	if(!mRoot->restoreConfig())
	{
		mRoot->setRenderSystem(mOpenGLRenderSystem);
	}

	mOgreControl = new wxOgre(this);

	ConfigFile cf;
	cf.load("resources.cfg");

	ConfigFile::SectionIterator seci = cf.getSectionIterator();

	Ogre::String secName, typeName, archName;
	while(seci.hasMoreElements())
	{
		secName = seci.peekNextKey();
		ConfigFile::SettingsMultiMap *settings = seci.getNext();
		ConfigFile::SettingsMultiMap::iterator i;
		for(i = settings->begin(); i != settings->end(); ++i)
		{
			typeName = i->first;
			archName = i->second;
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
		}
	}

	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	wxString caption;
	String rs = mRoot->getRenderSystem()->getName();
	if(rs == "OpenGL Rendering Subsystem") caption = "OGRE - OpenGL";
	else caption = "OGRE - DirectX";

	wxAuiPaneInfo info;
	info.Caption(caption);
	info.MaximizeButton(true);
	info.MinimizeButton(true);
	info.Floatable(true);
	info.BestSize(512, 512);
	info.Left();

	mAuiManager->AddPane(mOgreControl, info);
}
Exemplo n.º 18
0
void Folder::startSync(const QStringList &pathList)
{
    Q_ASSERT(_accountState);

    Q_UNUSED(pathList)
    if (!_csync_ctx) {
        // no _csync_ctx yet,  initialize it.
        init();

        if (!_csync_ctx) {
            qDebug() << Q_FUNC_INFO << "init failed.";
            // the error should already be set
            QMetaObject::invokeMethod(this, "slotSyncFinished", Qt::QueuedConnection);
            return;
        }
    } else if (proxyDirty()) {
        setProxyDirty(false);
    }
    csync_set_log_level( Logger::instance()->isNoop() ? 0 : 11 );

    if (isBusy()) {
        qCritical() << "* ERROR csync is still running and new sync requested.";
        return;
    }
    _errors.clear();
    _csyncError = false;
    _csyncUnavail = false;

    _timeSinceLastSyncStart.restart();
    _syncResult.clearErrors();
    _syncResult.setStatus( SyncResult::SyncPrepare );
    _syncResult.setSyncFileItemVector(SyncFileItemVector());
    emit syncStateChange();

    qDebug() << "*** Start syncing " << alias() << " - client version"
             << qPrintable(Theme::instance()->version());

    if (! setIgnoredFiles())
    {
        slotSyncError(tr("Could not read system exclude file"));
        QMetaObject::invokeMethod(this, "slotSyncFinished", Qt::QueuedConnection);
        return;
    }

    // pass the setting if hidden files are to be ignored, will be read in csync_update
    _csync_ctx->ignore_hidden_files = _definition.ignoreHiddenFiles;

    _engine.reset(new SyncEngine( _accountState->account(), _csync_ctx, path(), remoteUrl().path(), remotePath(), &_journal));

    qRegisterMetaType<SyncFileItemVector>("SyncFileItemVector");
    qRegisterMetaType<SyncFileItem::Direction>("SyncFileItem::Direction");

    connect(_engine.data(), SIGNAL(rootEtag(QString)), this, SLOT(etagRetreivedFromSyncEngine(QString)));
    connect( _engine.data(), SIGNAL(treeWalkResult(const SyncFileItemVector&)),
              this, SLOT(slotThreadTreeWalkResult(const SyncFileItemVector&)), Qt::QueuedConnection);
    connect( _engine.data(), SIGNAL(aboutToPropagate(SyncFileItemVector&)),
              this, SLOT(slotAboutToPropagate(SyncFileItemVector&)));

    connect(_engine.data(), SIGNAL(started()),  SLOT(slotSyncStarted()), Qt::QueuedConnection);
    connect(_engine.data(), SIGNAL(finished(bool)), SLOT(slotSyncFinished(bool)), Qt::QueuedConnection);
    connect(_engine.data(), SIGNAL(csyncError(QString)), SLOT(slotSyncError(QString)), Qt::QueuedConnection);
    connect(_engine.data(), SIGNAL(csyncUnavailable()), SLOT(slotCsyncUnavailable()), Qt::QueuedConnection);

    //direct connection so the message box is blocking the sync.
    connect(_engine.data(), SIGNAL(aboutToRemoveAllFiles(SyncFileItem::Direction,bool*)),
                    SLOT(slotAboutToRemoveAllFiles(SyncFileItem::Direction,bool*)));
    connect(_engine.data(), SIGNAL(folderDiscovered(bool,QString)), this, SLOT(slotFolderDiscovered(bool,QString)));
    connect(_engine.data(), SIGNAL(transmissionProgress(ProgressInfo)), this, SLOT(slotTransmissionProgress(ProgressInfo)));
    connect(_engine.data(), SIGNAL(itemCompleted(const SyncFileItem &, const PropagatorJob &)),
            this, SLOT(slotItemCompleted(const SyncFileItem &, const PropagatorJob &)));
    connect(_engine.data(), SIGNAL(syncItemDiscovered(const SyncFileItem &)), this, SLOT(slotSyncItemDiscovered(const SyncFileItem &)));
    connect(_engine.data(), SIGNAL(newBigFolder(QString)), this, SLOT(slotNewBigFolderDiscovered(QString)));

    setDirtyNetworkLimits();

    ConfigFile cfgFile;
    auto newFolderLimit = cfgFile.newBigFolderSizeLimit();
    quint64 limit = newFolderLimit.first ? newFolderLimit.second * 1000 * 1000 : -1; // convert from MB to B
    _engine->setNewBigFolderSizeLimit(limit);

    QMetaObject::invokeMethod(_engine.data(), "startSync", Qt::QueuedConnection);

    // disable events until syncing is done
    // _watcher->setEventsEnabled(false);
    emit syncStarted();
}
Exemplo n.º 19
0
void OwncloudPropagator::start(const SyncFileItemVector& items)
{
    Q_ASSERT(std::is_sorted(items.begin(), items.end()));

    /* Check and log the transmission checksum type */
    ConfigFile cfg;
    const QString checksumType = cfg.transmissionChecksum().toUpper();

    /* if the checksum type is empty, it is not send. No error */
    if( !checksumType.isEmpty() ) {
        if( checksumType == checkSumAdlerUpperC ||
                checksumType == checkSumMD5C    ||
                checksumType == checkSumSHA1C ) {
            qDebug() << "Client sends and expects transmission checksum type" << checksumType;
        } else {
            qWarning() << "Unknown transmission checksum type from config" << checksumType;
        }
    }

    /* This builds all the job needed for the propagation.
     * Each directories is a PropagateDirectory job, which contains the files in it.
     * In order to do that we loop over the items. (which are sorted by destination)
     * When we enter adirectory, we can create the directory job and push it on the stack. */

    _rootJob.reset(new PropagateDirectory(this));
    QStack<QPair<QString /* directory name */, PropagateDirectory* /* job */> > directories;
    directories.push(qMakePair(QString(), _rootJob.data()));
    QVector<PropagatorJob*> directoriesToRemove;
    QString removedDirectory;
    foreach(const SyncFileItemPtr &item, items) {

        if (!removedDirectory.isEmpty() && item->_file.startsWith(removedDirectory)) {
            // this is an item in a directory which is going to be removed.
            PropagateDirectory *delDirJob = dynamic_cast<PropagateDirectory*>(directoriesToRemove.last());

            if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
                //already taken care of.  (by the removal of the parent directory)

                // increase the number of subjobs that would be there.
                if( delDirJob ) {
                    delDirJob->increaseAffectedCount();
                }
                continue;
            } else if (item->_instruction == CSYNC_INSTRUCTION_NEW && item->_isDirectory) {
                // create a new directory within a deleted directory? That can happen if the directory
                // etag were not fetched properly on the previous sync because the sync was aborted
                // while uploading this directory (which is now removed).  We can ignore it.
                if( delDirJob ) {
                    delDirJob->increaseAffectedCount();
                }
                continue;
            } else if (item->_instruction == CSYNC_INSTRUCTION_IGNORE) {
                continue;
            }

            qWarning() << "WARNING:  Job within a removed directory?  This should not happen!"
                       << item->_file << item->_instruction;
        }

        while (!item->destination().startsWith(directories.top().first)) {
            directories.pop();
        }

        if (item->_isDirectory) {
            PropagateDirectory *dir = new PropagateDirectory(this, item);
            dir->_firstJob.reset(createJob(item));
            if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
                //We do the removal of directories at the end, because there might be moves from
                // this directories that will happen later.
                directoriesToRemove.append(dir);
                removedDirectory = item->_file + "/";

                // We should not update the etag of parent directories of the removed directory
                // since it would be done before the actual remove (issue #1845)
                // NOTE: Currently this means that we don't update those etag at all in this sync,
                //       but it should not be a problem, they will be updated in the next sync.
                for (int i = 0; i < directories.size(); ++i) {
                    directories[i].second->_item->_should_update_metadata = false;
                }
            } else {
                PropagateDirectory* currentDirJob = directories.top().second;
                currentDirJob->append(dir);
            }
            directories.push(qMakePair(item->destination() + "/" , dir));
        } else if (PropagateItemJob* current = createJob(item)) {
            directories.top().second->append(current);
        }
    }

    foreach(PropagatorJob* it, directoriesToRemove) {
        _rootJob->append(it);
    }
Exemplo n.º 20
0
 static void mapping(IO& inputOutput, ConfigFile& config)
 {
     config.mapping(inputOutput);
 }
Exemplo n.º 21
0
Arquivo: main.cpp Projeto: WST/mawar
int main(int argc, const char **argv)
{
	// Конфигурация
	ConfigFile *config = new ConfigFile(PATH_CONFIG);
	
	// открыть лог файлы до смены пользователя
	open_access_log(PATH_ACCESS_LOG);
	open_error_log(PATH_ERROR_LOG);
	FILE *fpid = fopen(PATH_PID, "w");
	
	// установить лимиты до смены пользователя
	if ( getuid() == 0 )
	{
		struct rlimit rl;
		rl.rlim_cur = config->filesLimit();
		rl.rlim_max = config->filesLimit();
		if ( setrlimit(RLIMIT_NOFILE, &rl) == -1 )
		{
			fprintf(stderr, "setrlimit fault: %s\n", strerror(errno));
		}
	}
	else
	{
		struct rlimit rl;
		if ( getrlimit(RLIMIT_NOFILE, &rl) == -1 )
		{
			fprintf(stderr, "getrlimit fault: %s\n", strerror(errno));
		}
		else
		{
			rl.rlim_cur = config->filesLimit();
			if ( config->filesLimit() > rl.rlim_max )
			{
				fprintf(stderr, "only root can increase over hard limit (RLIMIT_NOFILE)\ntry to increase up to hard limit (%lu)\n", rl.rlim_max);
				rl.rlim_cur = rl.rlim_max;
			}
			if ( setrlimit(RLIMIT_NOFILE, &rl) == -1 )
			{
				fprintf(stderr, "setrlimit fault: %s\n", strerror(errno));
			}
		}
	}
	
	// если запущены под root, то сменить пользователя
	if ( getuid() == 0 )
	{
		fprintf(stdout, "Trying to switch to user: "******"\n");
		struct passwd *pw = getpwnam(config->user());
		if(pw)
		{
			if(setgid(pw->pw_gid) != 0) fprintf(stderr, "Failed to setgid!\n");
			if(setuid(pw->pw_uid) != 0 ) fprintf(stderr, "Failed to setuid!\n");
		}
		else
		{
			fprintf(stderr, "user %s not found\n", config->user());
		}
	}
	
	if ( argc > 1 && strcmp(argv[1], "-d") == 0 )
	{
		printf("try fork\n");
		pid_t parpid;
		if((parpid = fork()) < 0) {
			mawarError("Failed to fork!", 99);
		}
		else if(parpid != 0) {
			exit(0); // успешно создан дочерний процесс, основной можно завершить
		}
		setsid();
	}
	
	// после форка записать pid
	if ( fpid )
	{
		fprintf(fpid, "%d", getpid());
		fclose(fpid);
		fpid = 0;
	}
	
	// демон управляющий воркерами вводом-выводом
	struct rlimit rl;
	if ( getrlimit(RLIMIT_NOFILE, &rl) == -1 )
	{
		fprintf(stderr, "getrlimit fault: %s\n", strerror(errno));
		return 1;
	}
	printf("files limit: %lu\n", rl.rlim_cur);
	NetDaemon daemon(rl.rlim_cur, config->getOutputBuffers());
	
	// устанавливаем скорректированное число воркеров
	daemon.setWorkerCount(config->workers() - 1);
	
	// XMPP-сервер
	server = new XMPPServer(&daemon);
	server->config = config;
	
	// подключемся к c2s-порту из конфига
	server->bind(config->c2s());
	
	// не более 10 ожидающих соединений
	server->listen(10);
	
	// добавляем виртуальные хосты
	printf("[main] loading virtual hosts\n");
	for(XmlTag *vhost = config->firstHost(); vhost; vhost = config->nextHost(vhost)) {
		printf("[main] load vhost: %s\n", vhost->getAttribute("name").c_str());
		server->addHost(vhost->getAttribute("name"), vhost);
	}
	printf("[main] virtual hosts loaded\n");
	
	// асинхронный резолвер
	nanosoft::ptr<AsyncDNS> dns = new AsyncDNS(&daemon);
	daemon.addObject(dns);
	server->adns = dns;
	
	// добавляем сервер в демона
	daemon.addObject(server);
	
	int port = config->xep0114();
	if ( port > 0 ) {
		nanosoft::ptr<XEP0114Listener> xep0114 = new XEP0114Listener(server.getObject());
		xep0114->bind(port);
		xep0114->listen(10);
		daemon.addObject(xep0114);
	}
	
	port = config->s2s();
	if ( port > 0 )
	{
		server->s2s = new S2SListener(server.getObject());
		server->s2s->bind(port);
		server->s2s->listen(10);
		daemon.addObject(server->s2s);
	}
	
	string path = config->status();
	if ( path != "" )
	{
		nanosoft::ptr<ServerStatus> status = new ServerStatus(server.getObject());
		status->bind(path.c_str());
		status->listen(1);
		daemon.addObject(status);
	}
	
	// консоль управления сервером
	//MyConsole console(&daemon, 0);
	//daemon.addObject(&console);
	
	struct sigaction sa;
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = on_signal;
	sigaction(SIGTERM, &sa, 0);
	sigaction(SIGHUP, &sa, 0);
	sigaction(SIGINT, &sa, 0);
	
	// запускаем демона
	fprintf(stderr, "[main] run daemon\n");
	daemon.run();
	fprintf(stderr, "[main] daemon exited\n");
	
	cleanup();
	
	return 0;
}
Exemplo n.º 22
0
void LogBrowser::closeEvent(QCloseEvent *)
{
    ConfigFile cfg;
    cfg.saveGeometry(this);
}
void MeshSerializerTests::setUp()
{
	errorFactor = 0.05;

	OGRE_DELETE LogManager::getSingletonPtr();
	mLogManager = OGRE_NEW LogManager();
	mLogManager->createLog("MeshWithoutIndexDataTests.log", false);
	mLogManager->setLogDetail(LL_LOW);

	mFSLayer = OGRE_NEW_T(Ogre::FileSystemLayer, Ogre::MEMCATEGORY_GENERAL)(OGRE_VERSION_NAME);

	OGRE_NEW ResourceGroupManager();
	OGRE_NEW LodStrategyManager();
	OGRE_NEW DefaultHardwareBufferManager();
	OGRE_NEW MeshManager();
	OGRE_NEW SkeletonManager();
	ArchiveManager* archiveMgr = OGRE_NEW ArchiveManager();
	archiveMgr->addArchiveFactory(OGRE_NEW FileSystemArchiveFactory());

	MaterialManager* matMgr = OGRE_NEW MaterialManager();
	matMgr->initialise();

	// Load resource paths from config file
	ConfigFile cf;
	String resourcesPath;
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_WIN32
	resourcesPath = mFSLayer->getConfigFilePath("resources.cfg");
#else
	resourcesPath = mFSLayer->getConfigFilePath("bin/resources.cfg");
#endif

	// Go through all sections & settings in the file
	cf.load(resourcesPath);
	ConfigFile::SectionIterator seci = cf.getSectionIterator();

	String secName, typeName, archName;
	while (seci.hasMoreElements()) {
		secName = seci.peekNextKey();
		ConfigFile::SettingsMultiMap* settings = seci.getNext();
		ConfigFile::SettingsMultiMap::iterator i;
		for (i = settings->begin(); i != settings->end(); ++i) {
			typeName = i->first;
			archName = i->second;
			if (typeName == "FileSystem") {
				ResourceGroupManager::getSingleton().addResourceLocation(
				    archName, typeName, secName);
			}

		}
	}

	mMesh = MeshManager::getSingleton().load("knot.mesh", ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME);

	getResourceFullPath(mMesh, mMeshFullPath);
	if (!copyFile(mMeshFullPath + ".bak", mMeshFullPath)) {
		// If there is no backup, create one.
		copyFile(mMeshFullPath, mMeshFullPath + ".bak");
	}
	mSkeletonFullPath = "";
	mSkeleton = SkeletonManager::getSingleton().load("jaiqua.skeleton", "Popular").staticCast<Skeleton>();
	getResourceFullPath(mSkeleton, mSkeletonFullPath);
	if (!copyFile(mSkeletonFullPath + ".bak", mSkeletonFullPath)) {
		// If there is no backup, create one.
		copyFile(mSkeletonFullPath, mSkeletonFullPath + ".bak");
	}

	mMesh->reload();
#ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR
	{
		MeshLodGenerator().generateAutoconfiguredLodLevels(mMesh);
	}
#endif /* ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR */
	mOrigMesh = mMesh->clone(mMesh->getName() + ".orig.mesh", mMesh->getGroup());
}
Exemplo n.º 24
0
LogBrowser::LogBrowser(QWidget *parent) :
    QDialog(parent),
    _logWidget( new LogWidget(parent) )
{
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    setObjectName("LogBrowser"); // for save/restoreGeometry()
    setWindowTitle(tr("Log Output"));
    setMinimumWidth(600);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    // mainLayout->setMargin(0);

    mainLayout->addWidget( _logWidget );

    QHBoxLayout *toolLayout = new QHBoxLayout;
    mainLayout->addLayout( toolLayout );

    // Search input field
    QLabel *lab = new QLabel(tr("&Search: "));
    _findTermEdit = new QLineEdit;
    lab->setBuddy( _findTermEdit );
    toolLayout->addWidget(lab);
    toolLayout->addWidget( _findTermEdit );

    // find button
    QPushButton *findBtn = new QPushButton;
    findBtn->setText( tr("&Find") );
    connect( findBtn, SIGNAL(clicked()), this, SLOT(slotFind()));
    toolLayout->addWidget( findBtn );

    // stretch
    toolLayout->addStretch(1);
    _statusLabel = new QLabel;
    toolLayout->addWidget( _statusLabel );
    toolLayout->addStretch(5);

    QDialogButtonBox *btnbox = new QDialogButtonBox;
    QPushButton *closeBtn = btnbox->addButton( QDialogButtonBox::Close );
    connect(closeBtn,SIGNAL(clicked()),this,SLOT(close()));

    mainLayout->addWidget( btnbox );

    // clear button
    _clearBtn = new QPushButton;
    _clearBtn->setText( tr("Clear") );
    _clearBtn->setToolTip( tr("Clear the log display.") );
    btnbox->addButton(_clearBtn, QDialogButtonBox::ActionRole);
    connect( _clearBtn, SIGNAL(clicked()), this, SLOT(slotClearLog()));

    // save Button
    _saveBtn = new QPushButton;
    _saveBtn->setText( tr("S&ave") );
    _saveBtn->setToolTip(tr("Save the log file to a file on disk for debugging."));
    btnbox->addButton(_saveBtn, QDialogButtonBox::ActionRole);
    connect( _saveBtn, SIGNAL(clicked()),this, SLOT(slotSave()));

    setLayout( mainLayout );

    setModal(false);

    // Direct connection for log comming from this thread, and queued for the one in a different thread
    connect(Logger::instance(), SIGNAL(newLog(QString)),this,SLOT(slotNewLog(QString)), Qt::AutoConnection);

    QAction *showLogWindow = new QAction(this);
    showLogWindow->setShortcut(QKeySequence("F12"));
    connect(showLogWindow, SIGNAL(triggered()), SLOT(close()));
    addAction(showLogWindow);

    ConfigFile cfg;
    cfg.restoreGeometry(this);
    int lines = cfg.maxLogLines();
    // qDebug() << "#        ##  Have " << lines << " Loglines!";
    _logWidget->document()->setMaximumBlockCount( lines );

}
Exemplo n.º 25
0
void DirectoryViewer::ShowEntry(const FileList::FileEntry& fileEntry, const ConfigFile& configFile, unsigned int columnNumber, unsigned int numColumns)
{
   unsigned char color = static_cast<unsigned char>(configFile.GetColorByExtension(fileEntry.Extension()));
   color += color < 10 ? '0' : 'a' - 10;

   unsigned int columnWidth = m_console.Width() / numColumns;

   if (columnWidth > 89)
   {
      m_console.Printf("^4³"); // 1
      ShowDate(fileEntry.m_time, false); // 11
      ShowTime(fileEntry.m_time, false); // 9
      ShowAttributes(fileEntry.m_attributes); // 6
      m_console.Printf(" "); // 1
      ShowSize(fileEntry.m_size, fileEntry.m_attributes, false); // 16

      int remainingSpace = columnWidth - 1 - 11 - 9 - 6 - 1 - 16 - 1;
      m_console.Printf("^%c%-*s^7", color, remainingSpace, fileEntry.m_name.c_str());
   }
   else if (columnWidth > 80)
   {
      m_console.Printf("^4³"); // 1
      ShowDate(fileEntry.m_time, false); // 11
      ShowTime(fileEntry.m_time, false); // 9
      ShowAttributes(fileEntry.m_attributes); // 6
      m_console.Printf(" "); // 1
      ShowSize(fileEntry.m_size, fileEntry.m_attributes, true); // 7
      m_console.Printf("^%c%-44.44s^7", color, fileEntry.m_name.c_str()); // 44
   }
   else if (columnWidth > 40)
   {
      m_console.Printf("^4³"); // 1
      ShowDate(fileEntry.m_time, true); // 9
      ShowTime(fileEntry.m_time, true); // 6
      ShowSize(fileEntry.m_size, fileEntry.m_attributes, true); // 7
      m_console.Printf("^%c%-17.17s^7", color, fileEntry.m_name.c_str()); // 17
   }
   else if (columnWidth > 26)
   {
      m_console.Printf("^4³"); // 1
      ShowAttributes(fileEntry.m_attributes); // 6
      ShowSize(fileEntry.m_size, fileEntry.m_attributes, true); // 7
      m_console.Printf("^%c%-12.12s", color, fileEntry.m_name.c_str()); // 12
      if (columnNumber + 1 == numColumns)
         m_console.Printf("^4³"); // 1
   }
   else if (columnWidth > 20)
   {
      m_console.Printf("^4³"); // 1
      ShowSize(fileEntry.m_size, fileEntry.m_attributes, true); // 7
      m_console.Printf("^%c%-12.12s", color, fileEntry.m_name.c_str()); // 12
   }
   else if (columnWidth > 16)
   {
      m_console.Printf("^4³^%c%-15.15s", color, fileEntry.m_name.c_str());
   }
   else if (columnWidth > 13)
   {
      m_console.Printf("^4³^%c%-12.12s^7", color, fileEntry.m_name.c_str());
      if (columnNumber + 1 == numColumns)
         m_console.Printf("^4³");
   }

   if (columnNumber + 1 == numColumns)
      m_console.Printf("\n");
}
Exemplo n.º 26
0
NaoCamera::NaoCamera(ConfigFile & configFile, Log & _log)
  : V4L2_CID_AUTO_EXPOSURE(10094849),
    NUM_FRAME_BUFFERS(configFile.getInt("camera/numFrameBuffers", 4)),
    IMAGE_WIDTH(configFile.getInt("camera/imageWidth", 320)),
    IMAGE_HEIGHT(configFile.getInt("camera/imageHeight", 240)),
    FRAMES_PER_SECOND(configFile.getInt("camera/framesPerSecond", 0)),
    IMAGE_SIZE(IMAGE_WIDTH * IMAGE_HEIGHT * 2),
    BRIGHTNESS_TOP            (configFile.getInt("camera/top/brightness", 55)),
    CONTRAST_TOP              (configFile.getInt("camera/top/contrast", 32)),
    SATURATION_TOP            (configFile.getInt("camera/top/saturation", 128)),
    HUE_TOP                   (configFile.getInt("camera/top/hue", 0)),
    AUTO_WHITE_BALANCE_TOP    (configFile.getInt("camera/top/autoWhiteBalance", 0)),
    WHITE_BALANCE_TOP         (configFile.getInt("camera/top/whiteBalance", 0)),
    AUTO_EXPOSURE_TOP         (configFile.getInt("camera/top/autoExposure", 0)),
    EXPOSURE_TOP              (configFile.getInt("camera/top/exposure", 0)),
    GAIN_TOP                  (configFile.getInt("camera/top/gain", 32)),
    HORIZONTAL_FLIP_TOP       (configFile.getInt("camera/top/horizontalFlip", 0)),
    VERTICAL_FLIP_TOP         (configFile.getInt("camera/top/verticalFlip", 0)),
    SHARPNESS_TOP             (configFile.getInt("camera/top/sharpness", 0)),
    BACKLIGHT_COMPENSATION_TOP(configFile.getInt("camera/top/backlightCompensation", 1)),
    BRIGHTNESS_BOTTOM            (configFile.getInt("camera/bottom/brightness", BRIGHTNESS_TOP)),
    CONTRAST_BOTTOM              (configFile.getInt("camera/bottom/contrast", CONTRAST_TOP)),
    SATURATION_BOTTOM            (configFile.getInt("camera/bottom/saturation", SATURATION_TOP)),
    HUE_BOTTOM                   (configFile.getInt("camera/bottom/hue", HUE_TOP)),
    AUTO_WHITE_BALANCE_BOTTOM    (configFile.getInt("camera/bottom/autoWhiteBalance", AUTO_WHITE_BALANCE_TOP)),
    WHITE_BALANCE_BOTTOM         (configFile.getInt("camera/bottom/whiteBalance", WHITE_BALANCE_TOP)),
    AUTO_EXPOSURE_BOTTOM         (configFile.getInt("camera/bottom/autoExposure", AUTO_EXPOSURE_TOP)),
    EXPOSURE_BOTTOM              (configFile.getInt("camera/bottom/exposure", EXPOSURE_TOP)),
    GAIN_BOTTOM                  (configFile.getInt("camera/bottom/gain", GAIN_TOP)),
    HORIZONTAL_FLIP_BOTTOM       (configFile.getInt("camera/bottom/horizontalFlip", HORIZONTAL_FLIP_TOP)),
    VERTICAL_FLIP_BOTTOM         (configFile.getInt("camera/bottom/verticalFlip", VERTICAL_FLIP_TOP)),
    SHARPNESS_BOTTOM             (configFile.getInt("camera/bottom/sharpness", SHARPNESS_TOP)),
    BACKLIGHT_COMPENSATION_BOTTOM(configFile.getInt("camera/bottom/backlightCompensation", BACKLIGHT_COMPENSATION_TOP)),
    log(_log),
    topCameraFd(-1),
    bottomCameraFd(-1),
    buffersTop(NULL),
    buffersBottom(NULL),
    numBuffersTop(0),
    numBuffersBottom(0),
    currentBufferTop(0),
    currentBufferBottom(0),
    v4l2BuffersTop(),
    v4l2BuffersBottom(),
    currentV4l2BufferTop(&v4l2BuffersTop[0]),
    currentV4l2BufferBottom(&v4l2BuffersBottom[0]),
    nextV4l2BufferTop(&v4l2BuffersTop[1]),
    nextV4l2BufferBottom(&v4l2BuffersBottom[1]),
    topCameraThread(),
    bottomCameraThread(),
    topThreadRunning(false),
    bottomThreadRunning(false),
    freshImage(),
    freshImageMutex(),
    freshImageTop(false),
    freshImageBottom(false),
    usingBottomCamera(true),
    enqueuedTop(false),
    enqueuedBottom(false) {
  // Create the condition variable and its mutex
  if (pthread_cond_init(&freshImage, NULL) < 0) {
    return;
  }
  if (pthread_mutex_init(&freshImageMutex, NULL) < 0) {
    return;
  }

}
void OBSBasic::on_actionRemoveProfile_triggered()
{
	std::string newName;
	std::string newPath;
	ConfigFile config;

	std::string oldDir = config_get_string(App()->GlobalConfig(),
			"Basic", "ProfileDir");
	std::string oldName = config_get_string(App()->GlobalConfig(),
			"Basic", "Profile");

	auto cb = [&](const char *name, const char *filePath)
	{
		if (strcmp(oldName.c_str(), name) != 0) {
			newName = name;
			newPath = filePath;
			return false;
		}

		return true;
	};

	EnumProfiles(cb);

	/* this should never be true due to menu item being grayed out */
	if (newPath.empty())
		return;

	QString text = QTStr("ConfirmRemove.Text");
	text.replace("$1", QT_UTF8(oldName.c_str()));

	QMessageBox::StandardButton button = QMessageBox::question(this,
			QTStr("ConfirmRemove.Title"), text);
	if (button == QMessageBox::No)
		return;

	size_t newPath_len = newPath.size();
	newPath += "/basic.ini";

	if (config.Open(newPath.c_str(), CONFIG_OPEN_ALWAYS) != 0) {
		blog(LOG_ERROR, "ChangeProfile: Failed to load file '%s'",
				newPath.c_str());
		return;
	}

	newPath.resize(newPath_len);

	const char *newDir = strrchr(newPath.c_str(), '/') + 1;

	config_set_string(App()->GlobalConfig(), "Basic", "Profile",
			newName.c_str());
	config_set_string(App()->GlobalConfig(), "Basic", "ProfileDir",
			newDir);

	config.Swap(basicConfig);
	InitBasicConfigDefaults();
	ResetProfileData();
	DeleteProfile(oldName.c_str(), oldDir.c_str());
	RefreshProfiles();
	config_save_safe(App()->GlobalConfig(), "tmp", nullptr);

	blog(LOG_INFO, "Switched to profile '%s' (%s)",
			newName.c_str(), newDir);
	blog(LOG_INFO, "------------------------------------------------");

	UpdateTitleBar();
}
Exemplo n.º 28
0
void NSISUpdater::slotSetSeenVersion()
{
    ConfigFile cfg;
    QSettings settings(cfg.configFile(), QSettings::IniFormat);
    settings.setValue(seenVersionC, updateInfo().version());
}
Exemplo n.º 29
0
void cfgSetVirtual(const wchar * Section, const wchar * Key, const wchar * String)
{
	cfgdb.set(string(Section), string(Key), string(String), true);
}
Exemplo n.º 30
0
static void upgrade_settings(void)
{
	char path[512];
	int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");

	if (pathlen <= 0)
		return;
	if (!os_file_exists(path))
		return;

	os_dir_t *dir = os_opendir(path);
	if (!dir)
		return;

	struct os_dirent *ent = os_readdir(dir);

	while (ent) {
		if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
				strcmp(ent->d_name, "..") != 0) {
			strcat(path, "/");
			strcat(path, ent->d_name);
			strcat(path, "/basic.ini");

			ConfigFile config;
			int ret;

			ret = config.Open(path, CONFIG_OPEN_EXISTING);
			if (ret == CONFIG_SUCCESS) {
				if (update_ffmpeg_output(config) ||
				    update_reconnect(config)) {
					config_save_safe(config, "tmp",
							nullptr);
				}
			}


			if (config) {
				const char *sEnc = config_get_string(config,
						"AdvOut", "Encoder");
				const char *rEnc = config_get_string(config,
						"AdvOut", "RecEncoder");

				/* replace "cbr" option with "rate_control" for
				 * each profile's encoder data */
				path[pathlen] = 0;
				strcat(path, "/");
				strcat(path, ent->d_name);
				strcat(path, "/recordEncoder.json");
				convert_14_2_encoder_setting(rEnc, path);

				path[pathlen] = 0;
				strcat(path, "/");
				strcat(path, ent->d_name);
				strcat(path, "/streamEncoder.json");
				convert_14_2_encoder_setting(sEnc, path);
			}

			path[pathlen] = 0;
		}

		ent = os_readdir(dir);
	}

	os_closedir(dir);
}