예제 #1
0
bool augeas_init()  {
    fs::path incl_path = getConfigPath(fs::path(MODULE_CONFDIR));

    if(!fs::exists(incl_path)) {
        // Complain hard; even if we can create it, any files won't be picked up
        // after we've done aug_load. And user probably wont have any use of an empty
        // dir anyway, so tell him to fix it instead.
        AGO_ERROR() << "Cannot use " << incl_path << " as confdir, does not exist";
        return false;
    } else if (!fs::is_directory(incl_path)) {
        AGO_ERROR() << "Cannot use " << incl_path << " as confdir, not a directory";
        return false;
    }

    incl_path /= "*.conf";

    // Look for augeas lens files in conf path too, in case
    // we have not installed globally
    fs::path extra_loadpath = getConfigPath();

    if(augeas) {
        // Re-init
        aug_close(augeas);
    }

    AGO_TRACE() << "Loading Augeas with extra_loadpath="
        << extra_loadpath.string()
        << " and include path="
        << incl_path.string();

    augeas = aug_init(NULL, extra_loadpath.c_str(), AUG_SAVE_BACKUP | AUG_NO_MODL_AUTOLOAD);
    if (augeas == NULL) {
        AGO_ERROR() << "Can't initalize augeas";
        return false;
    }

    aug_set(augeas, "/augeas/load/Agocontrol/lens", "agocontrol.lns");
    aug_set(augeas, "/augeas/load/Agocontrol/incl", incl_path.c_str());
    if (aug_load(augeas) != 0) {
        // We can get errors below, even if we have 0
        AGO_ERROR() << "Augeas load ret -1";
    }

    if(aug_error(augeas)) {
        std::string err = augeasGetError();
        AGO_ERROR() << "Augeas error: " << err;

        aug_close(augeas);
        augeas = NULL;
        return false;
    }else
        AGO_TRACE() << "Augeas inited without errors";

    return true;
}
예제 #2
0
int get_config_dir_name( char *buff, int len )
{
#if defined( WIN32 ) 
    if ( strlen( CONFIG_DIR ) +1 > len ) {
	return 1;
    }
    strcpy( buff, CONFIG_DIR );
    return 0;
#elif defined(__APPLE__)
    const char * configDir = getConfigPath();
    assert(configDir);

    if ( strlen( configDir ) + 1 > len ) {
    assert(0);
	return 1;
    }
    strcpy( buff, configDir );
    return 0;
#else
    struct passwd *pwent;

    pwent = getpwuid( getuid() );
    if ( pwent == NULL ) {
	perror( "getpwuid" );
	return 1;
    }

    if ( strlen( pwent->pw_dir ) + strlen( CONFIG_DIR) + 2 > len ) {
	return 1;
    }

    sprintf( buff, "%s/%s", pwent->pw_dir, CONFIG_DIR );
    return 0;
#endif /* defined( WIN32 ) */
}
예제 #3
0
bool InputManager::loadInputConfig(InputConfig* config)
{
	std::string path = getConfigPath();
	if(!fs::exists(path))
		return false;
	
	pugi::xml_document doc;
	pugi::xml_parse_result res = doc.load_file(path.c_str());

	if(!res)
	{
		LOG(LogError) << "Error parsing input config: " << res.description();
		return false;
	}

	pugi::xml_node root = doc.child("inputList");
	if(!root)
		return false;

	pugi::xml_node configNode = root.find_child_by_attribute("inputConfig", "deviceGUID", config->getDeviceGUIDString().c_str());
	if(!configNode)
		configNode = root.find_child_by_attribute("inputConfig", "deviceName", config->getDeviceName().c_str());
	if(!configNode)
		return false;

	config->loadFromXML(configNode);
	return true;
}
예제 #4
0
파일: MainFrm.cpp 프로젝트: cw2018/xtpui
BOOL CMainFrame::CreateRibbonBar()
{
    std::wstring xcbfile(getConfigPath() + g_factoryRoot->GetString(L"xcbfile"));
    CFile file(xcbfile.c_str(), CFile::modeRead);
    CArchive ar(&file, CArchive::load);
    
    m_cmdbars->LoadDesignerBars(ar);

    CXTPRibbonBar* pRibbonBar = DYNAMIC_DOWNCAST(
        CXTPRibbonBar, m_cmdbars->GetMenuBar());
    if (NULL == pRibbonBar)
        return FALSE;

    SetRibbonFont();

    std::wstring themeName(getUIOptions()->GetString(L"themeName"));
    if (themeName.find(L"WINDOWS7") != std::wstring::npos
        || themeName.find(L"OFFICE201") != std::wstring::npos)
    {
        pRibbonBar->GetSystemButton()->SetStyle(xtpButtonCaption);
    }
    pRibbonBar->EnableFrameTheme();

    return TRUE;
}
예제 #5
0
void SystemData::writeExampleConfig()
{
	std::string path = getConfigPath();

	std::ofstream file(path.c_str());

	file << "# This is the EmulationStation Systems configuration file." << std::endl;
	file << "# Lines that begin with a hash (#) are ignored, as are empty lines." << std::endl;
	file << "# A sample system might look like this:" << std::endl;
	file << "#NAME=nes" << std::endl;
	file << "#DESCNAME=Nintendo Entertainment System" << std::endl;
	file << "#PATH=~/ROMs/nes/" << std::endl;
	file << "#EXTENSION=.nes .NES" << std::endl;
	file << "#COMMAND=retroarch -L ~/cores/libretro-fceumm.so %ROM%" << std::endl << std::endl;

	file << "#NAME is a short name used internally (and in alternative paths)." << std::endl;
	file << "#DESCNAME is a descriptive name to identify the system. It may be displayed in a header." << std::endl;
	file << "#PATH is the path to start the recursive search for ROMs in. ~ will be expanded into the $HOME variable." << std::endl;
	file << "#EXTENSION is a list of extensions to search for, separated by spaces. You MUST include the period, and it must be exact - it's case sensitive, and no wildcards." << std::endl;
	file << "#COMMAND is the shell command to execute when a game is selected. %ROM% will be replaced with the (bash special-character escaped) path to the ROM." << std::endl << std::endl;

	file << "#Now try your own!" << std::endl;
	file << "NAME=" << std::endl;
	file << "DESCNAME=" << std::endl;
	file << "PATH=" << std::endl;
	file << "EXTENSION=" << std::endl;
	file << "COMMAND=" << std::endl;

	file.close();
}
예제 #6
0
void SystemData::writeExampleConfig()
{
	std::string path = getConfigPath();

	std::ofstream file(path.c_str());

	file << "# This is the EmulationStation Systems configuration file." << std::endl;
	file << "# Lines that begin with a hash (#) are ignored, as are empty lines." << std::endl;
	file << "# A sample system might look like this:" << std::endl;
	file << "#NAME=Nintendo Entertainment System" << std::endl;
	file << "#PATH=~/ROMs/nes/" << std::endl;
	file << "#EXTENSION=.nes" << std::endl;
	file << "#COMMAND=retroarch -L ~/cores/libretro-fceumm.so %ROM%" << std::endl << std::endl;

	file << "#NAME is just a name to identify the system." << std::endl;
	file << "#PATH is the path to start the recursive search for ROMs in. ~ will be expanded into the $HOME variable." << std::endl;
	file << "#EXTENSION is the exact extension to search for. You MUST include the period, and it must be exact - no regex or wildcard support (sorry!)." << std::endl;
	file << "#COMMAND is the shell command to execute when a game is selected. %ROM% will be replaced with the path to the ROM." << std::endl << std::endl;

	file << "#Now try your own!" << std::endl;
	file << "NAME=" << std::endl;
	file << "PATH=" << std::endl;
	file << "EXTENSION=" << std::endl;
	file << "COMMAND=" << std::endl;

	file.close();
}
예제 #7
0
void InputManager::loadConfig()
{
	//clear any old config
	joystickButtonMap.clear();
	joystickAxisPosMap.clear();
	joystickAxisNegMap.clear();

	std::string path = getConfigPath();

	std::ifstream file(path.c_str());

	while(file.good())
	{
		std::string line;
		std::getline(file, line);

		//skip blank lines and comments
		if(line.empty() || line[0] == *"#")
			continue;


		//I know I could probably just read from the file stream directly, but I feel it would be harder to catch errors in a readable way
		std::istringstream stream(line);

		std::string token[3];
		int tokNum = 0;

		while(std::getline(stream, token[tokNum], ' '))
		{
			if(tokNum >= 3)
			{
				std::cerr << "Error - input config line \"" << line << "\" has more than three tokens!\n";
				return;
			}
			tokNum++;
		}


		if(token[0] == "BUTTON")
		{
			joystickButtonMap[atoi(token[1].c_str())] = (InputButton)atoi(token[2].c_str());
		}else if(token[0] == "AXISPOS")
		{
			joystickAxisPosMap[atoi(token[1].c_str())] = (InputButton)atoi(token[2].c_str());
		}else if(token[0] == "AXISNEG")
		{
			joystickAxisNegMap[atoi(token[1].c_str())] = (InputButton)atoi(token[2].c_str());
		}else{
			std::cerr << "Invalid input type - " << token[0] << "\n";
			return;
		}

	}

	if(SDL_NumJoysticks() > 0)
	{
		SDL_JoystickOpen(0);
	}
}
예제 #8
0
bool CFrameWndFactory::CreateFrameWnd(LPCWSTR factoryFile)
{
    CXTPWinDwmWrapper().SetProcessDPIAware();   // Support high DPI on Vista or above.

    std::wstring xtpfile(getTranslationsPath(L"ToolkitPro.Resource.xml"));
    if (PathFileExistsW(xtpfile.c_str()))
        XTPResourceManager()->SetResourceFile(xtpfile.c_str());
    else
        TRACE1("Warning: no translation file '%s'\n", xtpfile.c_str());

    Object<IConfigXml> xmlfile(x3::clsidXmlFile);
    ASSERT_MESSAGE(xmlfile, "Need the configxml plugin.");
    xmlfile->SetFileName((getConfigPath() + factoryFile).c_str());
    ASSERT_MESSAGE(xmlfile->Reload(), "No xml file or need to setup MSXML4.");

    ConfigSection root(xmlfile->GetData()->GetSection(L""));
    ConfigSection mainframe(root.GetSection(L"mainframe"));
    bool mdi = root->GetBool(L"mdi", false);

    g_factoryRoot = root;
    g_factoryRoot->SetString(L"_appid", m_appid.c_str());

    Object<IUIOptionsInit> initOptions(clsidUIOptions);
    initOptions->setFileName((getConfigPath() + 
        root->GetString(L"optionsFile", L"uioptions.xml")).c_str());

    RegisterDocTemplate(mdi, mainframe, root.GetSection(L"views"));
    if (mdi)
    {
        CMainMDIFrame* pFrame = new CMainMDIFrame;
        if (!pFrame->LoadFrame(0))
            return FALSE;

        std::vector<ViewItem>::const_iterator it = s_views.begin();
        for (; it != s_views.end(); ++it)
        {
            if (!it->caption.empty())
            {
                CDocument* pDoc = it->pTemplate->OpenDocumentFile(NULL);
                pDoc->SetTitle(it->caption.c_str());
            }
        }
    }

    return ProcessShellCommand();
}
예제 #9
0
void InputManager::writeDeviceConfig(InputConfig* config)
{
    assert(initialized());

    std::string path = getConfigPath();

    pugi::xml_document doc;

    if(fs::exists(path))
    {
        // merge files
        pugi::xml_parse_result result = doc.load_file(path.c_str());
        if(!result)
        {
            LOG(LogError) << "Error parsing input config: " << result.description();
        }
        else
        {
            // successfully loaded, delete the old entry if it exists
            pugi::xml_node root = doc.child("inputList");
            if(root)
            {
                // if inputAction @type=onfinish is set, let onfinish command take care for creating input configuration.
                // we just put the input configuration into a temporary input config file.
                pugi::xml_node actionnode = root.find_child_by_attribute("inputAction", "type", "onfinish");
                if(actionnode)
                {
                    path = getTemporaryConfigPath();
                    doc.reset();
                    root = doc.append_child("inputList");
                    root.append_copy(actionnode);
                }
                else
                {
                    pugi::xml_node oldEntry = root.find_child_by_attribute("inputConfig", "deviceGUID",
                                              config->getDeviceGUIDString().c_str());
                    if(oldEntry)
                    {
                        root.remove_child(oldEntry);
                    }
                    oldEntry = root.find_child_by_attribute("inputConfig", "deviceName",
                                                            config->getDeviceName().c_str());
                    if(oldEntry)
                    {
                        root.remove_child(oldEntry);
                    }
                }
            }
        }
    }

	pugi::xml_node root = doc.child("inputList");
	if(!root)
		root = doc.append_child("inputList");

	config->writeToXML(root);
	doc.save_file(path.c_str());
}
bool InputManager::loadInputConfig(InputConfig* config)
{
	std::string path = getConfigPath();
	if(!fs::exists(path))
		return false;
	
	pugi::xml_document doc;
	pugi::xml_parse_result res = doc.load_file(path.c_str());

	if(!res)
	{
		LOG(LogError) << "Error parsing input config: " << res.description();
		return false;
	}

	pugi::xml_node root = doc.child("inputList");
	if(!root)
		return false;

	// looking for a device having the same guid and name, or if not, one with the same guid or in last chance, one with the same name
	pugi::xml_node configNode(NULL);

	bool found_guid = false;
	bool found_exact = false;
	for (pugi::xml_node item = root.child("inputConfig"); item; item = item.next_sibling("inputConfig")) {
	  // check the guid
	  if(strcmp(config->getDeviceGUIDString().c_str(), item.attribute("deviceGUID").value()) == 0) {
	    // found a correct guid
	    found_guid = true; // no more need to check the name only
	    configNode = item;
	    
	    if(strcmp(config->getDeviceName().c_str(), item.attribute("deviceName").value()) == 0) {
	      // found the exact device
	      found_exact = true;
	      configNode = item;
	      break;
	    }
	  }

	  // check for a name if no guid is found
	  if(found_guid == false) {
	    if(strcmp(config->getDeviceName().c_str(), item.attribute("deviceName").value()) == 0) {
	      configNode = item;
	    }
	  }
	}
	    
	if(!configNode)
		return false;

	if(found_exact == false) {
	  LOG(LogInfo) << "Approximative device found using guid=" << configNode.attribute("deviceGUID").value() << " name=" << configNode.attribute("deviceName").value() << ")";
	}
	  
	config->loadFromXML(configNode);
	return true;
}
예제 #11
0
파일: cursynth.cpp 프로젝트: Lemm/cursynth
 void Cursynth::saveToFile(const std::string& file_name) {
   confirmPathExists(getConfigPath());
   confirmPathExists(getUserPatchesPath());
   std::ofstream save_file;
   std::string path = getUserPatchesPath();
   path = path + "/" + file_name;
   save_file.open(path.c_str());
   save_file << writeStateToString();
   save_file.close();
 }
예제 #12
0
std::string CrossPlatform::getDataPath()
{
#if defined(__unix__)
    char *maybeDataHome = getenv("XDG_DATA_HOME");
    if (maybeDataHome == nullptr || *maybeDataHome == '\0')
        return getHomeDirectory() + "/.local/share/falltergeist";
    return std::string(maybeDataHome) + "/falltergiest";
#else
    return getConfigPath();
#endif
}
예제 #13
0
qpid::types::Variant::Map getConfigTree() {
    qpid::types::Variant::Map tree;
    if (augeas==NULL) augeas_init();
    if (augeas == NULL) {
        AGO_ERROR() << "cannot initialize augeas";
        return tree;
    }
    char **matches;
    std::stringstream path;
    path << "/files";
    path << getConfigPath(MODULE_CONFDIR).string();
    path << "/";
    std::string prefix = path.str();
    path << "/*";
    int num = aug_match(augeas, path.str().c_str(), &matches);
    for (int i=0; i < num; i++) {
        const char *val;
        aug_get(augeas, matches[i], &val);
        if (val != NULL) {
            std::vector<std::string> elements;
            std::string match = matches[i];
            AGO_TRACE() << "getConfigTree:augeas match result[" << i << "]:" << match << ": " << val;
            replaceString(match, prefix, "");
            replaceString(match, ".conf", "");
            elements = split(match, '/');
            if (elements.size() != 3) {
                AGO_ERROR() << "augeas match ignored: does not split by / in three parts: " << match;
                continue;
            }
            std::string file = elements[0];
            std::string section = elements[1];
            std::string option = elements[2];
            AGO_TRACE() << "File: " << file << " Section: " << section << " Option: " << option;

            qpid::types::Variant::Map fileMap;
            qpid::types::Variant::Map sectionMap;
            if (!(tree[file].isVoid())) {
                fileMap = tree[file].asMap();
            }
            if (!(fileMap[section].isVoid())) {
                sectionMap = fileMap[section].asMap();
            }
            sectionMap[option] = val;
            fileMap[section] = sectionMap;
            tree[file] = fileMap;
        }
        free((void *) matches[i]);
    }
    free(matches);
    return tree;

}
예제 #14
0
파일: MainFrm.cpp 프로젝트: cw2018/xtpui
BOOL CMainFrame::BeforeLoadFrame(CFrameWnd* pMainWnd)
{
    m_mainwnd = pMainWnd;
    m_frameNode = g_factoryRoot.GetSection(L"mainframe");
    m_appid = g_factoryRoot->GetString(L"_appid");
    m_appname = g_factoryRoot->GetString(L"appname");
    m_id = GetNodeID(m_frameNode, L"id");
    ASSERT(!m_appname.empty());

    m_barsfile = getConfigPath() + g_factoryRoot->GetString(L"cmdbarsFile", L"cmdbars.xml");

    return TRUE;
}
예제 #15
0
WeatherGlobal::WeatherGlobal()
{
	QStringList serverList = QStringList::split(";", config_file.readEntry("Weather", "Servers"));
	QStringList serversUsing = QStringList::split(";", config_file.readEntry("Weather", "ServersUsing"));

	QDir dir(dataPath(WeatherConfigPath), "*.ini");
	dir.setFilter(QDir::Files);

	QStringList iniFiles;
	for (unsigned int i = 0; i < dir.count(); ++i)
		iniFiles.append(dir[i]);

	// Remove non-existent files from the server list
	//
	for (unsigned int i = 0; i < serverList.count(); ++i)
	{
		QStringList::iterator file = iniFiles.find(serverList[i]);
		if (file == iniFiles.end())
		{
			serverList.removeAt(i);
			serversUsing.removeAt(i);
		}
		else
			iniFiles.erase(file);
	}

	// Add new files to the server list
	//
	serverList += iniFiles;
	for (unsigned int i = 0; i < iniFiles.count(); ++i)
		serversUsing.append("1");

	// Load server configs and initialize server list
	//
	for (unsigned int i = 0; i < serverList.count(); ++i)
	{
		PlainConfigFile wConfig(getConfigPath(serverList[i]));
		servers_.append(Server(wConfig.readEntry("Header","Name"), serverList[i], serversUsing[i] == "1"));
	}

	// Load recent locations search list
	//
	for (unsigned int i = 0; i < RECENT_LOCATIONS_COUNT; i++)
	{
		QString city = config_file.readEntry("Weather", QString("Location%1").arg(i + 1));
		if (!city.isEmpty() && !recentLocations_.contains(city))
			recentLocations_.push_back(city);
	}

}
예제 #16
0
void InputManager::writeDeviceConfig(InputConfig* config)
{
    assert(initialized());

    std::string path = getConfigPath();

    pugi::xml_document doc;

    if(fs::exists(path))
    {
        // merge files
        pugi::xml_parse_result result = doc.load_file(path.c_str());
        if(!result)
        {
            LOG(LogError) << "Error parsing input config: " << result.description();
        }
        else
        {
            // successfully loaded, delete the old entry if it exists
            pugi::xml_node root = doc.child("inputList");
            if(root)
            {
                pugi::xml_node oldEntry = root.find_child_by_attribute("inputConfig", "deviceGUID",
                                          config->getDeviceGUIDString().c_str());
                if(oldEntry)
                {
                    root.remove_child(oldEntry);
                }
                oldEntry = root.find_child_by_attribute(
                               "inputConfig", "deviceName", config->getDeviceName().c_str());
                if(oldEntry)
                {
                    root.remove_child(oldEntry);
                }
            }
        }
    }

    pugi::xml_node root = doc.child("inputList");
    if(!root)
    {
        root = doc.append_child("inputList");
    }

    config->writeToXML(root);
    doc.save_file(path.c_str());
}
void InputManager::writeDeviceConfig(InputConfig* config)
{
	assert(initialized());

	std::string path = getConfigPath();

	pugi::xml_document doc;

	if(fs::exists(path))
	{
		// merge files
		pugi::xml_parse_result result = doc.load_file(path.c_str());
		if(!result)
		{
			LOG(LogError) << "Error parsing input config: " << result.description();
		}else{
			// successfully loaded, delete the old entry if it exists
			pugi::xml_node root = doc.child("inputList");
			if(root)
			{
				pugi::xml_node oldEntry(NULL);
				for (pugi::xml_node item = root.child("inputConfig"); item; item = item.next_sibling("inputConfig")) {
				  if(strcmp(config->getDeviceGUIDString().c_str(), item.attribute("deviceGUID").value()) == 0 &&
				     strcmp(config->getDeviceName().c_str(),       item.attribute("deviceName").value()) == 0) {
				    oldEntry = item;
				    break;
				  }
				}

				if(oldEntry)
					root.remove_child(oldEntry);
				//oldEntry = root.find_child_by_attribute("inputConfig", "deviceName", config->getDeviceName().c_str());
				//if(oldEntry)
				//	root.remove_child(oldEntry);
			}
		}
	}

	pugi::xml_node root = doc.child("inputList");
	if(!root)
		root = doc.append_child("inputList");

	config->writeToXML(root);
	doc.save_file(path.c_str());
}
예제 #18
0
void InputManager::doOnFinish()
{
    assert(initialized());
    std::string path = getConfigPath();
    pugi::xml_document doc;

    if(fs::exists(path))
    {
        pugi::xml_parse_result result = doc.load_file(path.c_str());
        if(!result)
        {
            LOG(LogError) << "Error parsing input config: " << result.description();
        }
        else
        {
            pugi::xml_node root = doc.child("inputList");
            if(root)
            {
                root = root.find_child_by_attribute("inputAction", "type", "onfinish");
                if(root)
                {
                    for(pugi::xml_node command = root.child("command"); command;
                            command = command.next_sibling("command"))
                    {
                        std::string tocall = command.text().get();

                        LOG(LogInfo) << "	" << tocall;
                        std::cout << "==============================================\ninput config finish command:\n";
                        int exitCode = runSystemCommand(tocall);
                        std::cout << "==============================================\n";

                        if(exitCode != 0)
                        {
                            LOG(LogWarning) << "...launch terminated with nonzero exit code " << exitCode << "!";
                        }
                    }
                }
            }
        }
    }
}
예제 #19
0
파일: cursynth.cpp 프로젝트: Lemm/cursynth
  void Cursynth::saveConfiguration() {
    confirmPathExists(getConfigPath());

    // Store all the MIDI learn data into JSON.
    cJSON* root = cJSON_CreateObject();
    std::map<int, std::string>::iterator iter = midi_learn_.begin();
    for (; iter != midi_learn_.end(); ++iter) {
      cJSON* midi = cJSON_CreateNumber(iter->first);
      cJSON_AddItemToObject(root, iter->second.c_str(), midi);
    }

    // Write the configuration JSON to the configuration file.
    char* json = cJSON_Print(root);
    std::ofstream save_file;
    save_file.open(getConfigFile().c_str());
    MOPO_ASSERT(save_file.is_open());
    save_file << json;
    save_file.close();

    free(json);
    cJSON_Delete(root);
  }
예제 #20
0
// --------------------------------------------------------------------------
//
// Function
//      Name:    BBInstance ProcessControl::generateBBInstanceFromPID(int)
//      Purpose: Obtiene todos los parametros y genera una instancia a partir de un PID
//      Created: 25/6/08
//
// ------------------
BBInstance ProcessControl::generateBBInstanceFromPID(int pid)
{
	QString configpath = getConfigPath(pid);
	unsigned int uid = getUID(pid);
	return BBInstance(configpath, userNamefromUID(uid),getBinaryPath(pid));
}
예제 #21
0
//creates systems from information located in a config file
bool SystemData::loadConfig()
{
	deleteSystems();

	std::string path = getConfigPath(false);

	LOG(LogInfo) << "Loading system config file " << path << "...";

	if(!fs::exists(path))
	{
		LOG(LogError) << "es_systems.cfg file does not exist!";
		writeExampleConfig(getConfigPath(true));
		return false;
	}

	pugi::xml_document doc;
	pugi::xml_parse_result res = doc.load_file(path.c_str());

	if(!res)
	{
		LOG(LogError) << "Could not parse es_systems.cfg file!";
		LOG(LogError) << res.description();
		return false;
	}

	//actually read the file
	pugi::xml_node systemList = doc.child("systemList");

	if(!systemList)
	{
		LOG(LogError) << "es_systems.cfg is missing the <systemList> tag!";
		return false;
	}

	for(pugi::xml_node system = systemList.child("system"); system; system = system.next_sibling("system"))
	{
		std::string name, fullname, path, cmd, themeFolder;
		PlatformIds::PlatformId platformId = PlatformIds::PLATFORM_UNKNOWN;

		name = system.child("name").text().get();
		fullname = system.child("fullname").text().get();
		path = system.child("path").text().get();

		// convert extensions list from a string into a vector of strings
		std::vector<std::string> extensions = readList(system.child("extension").text().get());

		cmd = system.child("command").text().get();

		// platform id list
		const char* platformList = system.child("platform").text().get();
		std::vector<std::string> platformStrs = readList(platformList);
		std::vector<PlatformIds::PlatformId> platformIds;
		for(auto it = platformStrs.begin(); it != platformStrs.end(); it++)
		{
			const char* str = it->c_str();
			PlatformIds::PlatformId platformId = PlatformIds::getPlatformId(str);
			
			if(platformId == PlatformIds::PLATFORM_IGNORE)
			{
				// when platform is ignore, do not allow other platforms
				platformIds.clear();
				platformIds.push_back(platformId);
				break;
			}

			// if there appears to be an actual platform ID supplied but it didn't match the list, warn
			if(str != NULL && str[0] != '\0' && platformId == PlatformIds::PLATFORM_UNKNOWN)
				LOG(LogWarning) << "  Unknown platform for system \"" << name << "\" (platform \"" << str << "\" from list \"" << platformList << "\")";
			else if(platformId != PlatformIds::PLATFORM_UNKNOWN)
				platformIds.push_back(platformId);
		}

		// theme folder
		themeFolder = system.child("theme").text().as_string(name.c_str());

		//validate
		if(name.empty() || path.empty() || extensions.empty() || cmd.empty())
		{
			LOG(LogError) << "System \"" << name << "\" is missing name, path, extension, or command!";
			continue;
		}

		//convert path to generic directory seperators
		boost::filesystem::path genericPath(path);
		path = genericPath.generic_string();

		SystemData* newSys = new SystemData(name, fullname, path, extensions, cmd, platformIds, themeFolder);
		if(newSys->getRootFolder()->getChildren().size() == 0)
		{
			LOG(LogWarning) << "System \"" << name << "\" has no games! Ignoring it.";
			delete newSys;
		}else{
			sSystemVector.push_back(newSys);
		}
	}

	return true;
}
예제 #22
0
//creates systems from information located in a config file
void SystemData::loadConfig()
{
	deleteSystems();

	std::string path = getConfigPath();

	std::cout << "Loading system config file \"" << path << "\"...\n";

	std::ifstream file(path.c_str());
	if(file.is_open())
	{
		std::string line;
		std::string sysName, sysPath, sysExtension, sysCommand;
		while(file.good())
		{
			std::getline(file, line);

			//skip blank lines and comments
			if(line.empty() || line[0] == *"#")
				continue;

			//find the name (left of the equals sign) and the value (right of the equals sign)
			bool lineValid = false;
			std::string varName, varValue;
			for(unsigned int i = 0; i < line.length(); i++)
			{
				if(line[i] == *"=")
				{
					lineValid = true;
					varName = line.substr(0, i);
					varValue = line.substr(i + 1, line.length() - 1);
					std::cout << "	" << varName << " = " << varValue << "\n";
					break;
				}
			}

			if(lineValid)
			{
				//map the value to the appropriate variable
				if(varName == "NAME")
					sysName = varValue;
				else if(varName == "PATH")
					sysPath = varValue;
				else if(varName == "EXTENSION")
					sysExtension = varValue;
				else if(varName == "COMMAND")
					sysCommand = varValue;
				else
					std::cerr << "Error reading config file - unknown variable name \"" << varName << "\"!\n";

				//we have all our variables - create the system object
				if(!sysName.empty() && !sysPath.empty() &&!sysExtension.empty() && !sysCommand.empty())
				{
					SystemData* newSystem = new SystemData(sysName, sysPath, sysExtension, sysCommand);
					if(newSystem->getRootFolder()->getFileCount() == 0)
					{
						std::cerr << "Error - system \"" << sysName << "\" has no games! Deleting.\n";
						delete newSystem;
					}else{
						sSystemVector.push_back(newSystem);
					}

					//reset the variables for the next block (should there be one)
					sysName = ""; sysPath = ""; sysExtension = ""; sysCommand = "";
				}
			}else{
				std::cerr << "Error reading config file \"" << path << "\" - no equals sign found on line \"" << line << "\"!\n";
				return;
			}
		}
	}else{
		std::cerr << "Error - could not load config file \"" << path << "\"!\n";
		return;
	}

	std::cout << "Finished loading config file - created " << sSystemVector.size() << " systems.\n";
	return;
}
예제 #23
0
	/** private **/
	const char* ApplicationBase::_config_path(const char* sub_path){
		return getConfigPath(sub_path)->c_str();
	}
예제 #24
0
void InputManager::loadConfig()
{
	LOG(LogDebug) << "Loading input config...";

	//clear any old config
	joystickButtonMap.clear();
	joystickAxisPosMap.clear();
	joystickAxisNegMap.clear();

	std::string path = getConfigPath();

	std::ifstream file(path.c_str());

	joystickName = "";

	while(file.good())
	{
		std::string line;
		std::getline(file, line);

		//skip blank lines and comments
		if(line.empty() || line[0] == *"#")
			continue;


		//I know I could probably just read from the file stream directly, but I feel it would be harder to catch errors in a readable way
		std::istringstream stream(line);

		std::string token[3];
		int tokNum = 0;

		while(std::getline(stream, token[tokNum], ' '))
		{
			tokNum++;

			//JOYNAME can have spaces
			if(tokNum == 1 && token[0] == "JOYNAME")
			{
				std::getline(stream, token[1]);
				break;
			}

			if(tokNum >= 3)
				break;
		}


		if(token[0] == "BUTTON")
		{
			joystickButtonMap[atoi(token[1].c_str())] = (InputButton)atoi(token[2].c_str());
		}else if(token[0] == "AXISPOS")
		{
			joystickAxisPosMap[atoi(token[1].c_str())] = (InputButton)atoi(token[2].c_str());
		}else if(token[0] == "AXISNEG")
		{
			joystickAxisNegMap[atoi(token[1].c_str())] = (InputButton)atoi(token[2].c_str());
		}else if(token[0] == "JOYNAME")
		{
			joystickName = token[1];
		}else{
			LOG(LogWarning) << "Invalid input type - " << token[0];
			return;
		}

	}

	LOG(LogDebug) << "Finished loading input config";

	openJoystick();
}
예제 #25
0
#include "ui_radeon_profile.h"
#include <QSettings>
#include <QMenu>
#include <QDir>
#include <QTreeWidgetItem>
#include <QDesktopWidget>
#include <QRect>

QString getConfigPath() {
    return QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + "/radeon-profile";
}

static const QString legacySettingsPath = QDir::homePath() + "/.radeon-profile-settings";
static const QString legacyAuxStuffPath = QDir::homePath() + "/.radeon-profile-auxstuff";

static const QString settingsPath = getConfigPath() + "/radeon-profile-settings";
static const QString auxStuffPath = getConfigPath() + "/radeon-profile-auxstuff";

static bool loadedFromLegacy = false;

// init of static struct with setting exposed to global scope
globalStuff::globalCfgStruct globalStuff::globalConfig;

void radeon_profile::saveConfig() {
    {
        // If settingsPath doesn't exist yet, running QSetting's destructor will create it.
        // It's important that happens before saving auxstuff later-on.
        QSettings settings(settingsPath,QSettings::IniFormat);

        settings.setValue("startMinimized",ui->cb_startMinimized->isChecked());
        settings.setValue("minimizeToTray",ui->cb_minimizeTray->isChecked());
예제 #26
0
파일: agoapp.cpp 프로젝트: mce35/agocontrol
int AgoApp::parseCommandLine(int argc, const char **argv) {
    po::options_description options;
    options.add_options()
        ("help,h", "produce this help message")
        ("log-level", po::value<std::string>(),
         (std::string("Log level. Valid values are one of\n ") +
          boost::algorithm::join(log_container::getLevels(), ", ")).c_str())
        ("log-method", po::value<std::string>(),
         "Where to log. Valid values are one of\n console, syslog")
        ("log-syslog-facility", po::value<std::string>(),
         (std::string("Which syslog facility to log to. Valid values are on of\n ") +
          boost::algorithm::join(log_container::getSyslogFacilities(), ", ")).c_str())
        ("debug,d", po::bool_switch(),
         "Shortcut to set console logging with level DEBUG")
        ("trace,t", po::bool_switch(),
         "Shortcut to set console logging with level TRACE")
        ("config-dir", po::value<std::string>(),
         "Directory with configuration files")
        ("state-dir", po::value<std::string>(),
         "Directory with local state files")
        ;

    appCmdLineOptions(options);
    try {
        po::variables_map &vm (cli_vars);
        po::store(po::parse_command_line(argc, argv, options), vm);
        po::notify(vm);

        if(vm.count("config-dir")) {
            std::string dir = vm["config-dir"].as<std::string>();
            try {
                AgoClientInternal::setConfigDir(dir);
            } catch(const fs::filesystem_error& error) {
                std::cout << "Could not use " << dir << " as config-dir: "
                    << error.code().message()
                    << std::endl;
                return 1;
            }
        }

        if(vm.count("state-dir")) {
            std::string dir = vm["state-dir"].as<std::string>();
            try {
                AgoClientInternal::setLocalStateDir(dir);
            } catch(const fs::filesystem_error& error) {
                std::cout << "Could not use " << dir << " as state-dir: "
                    << error.code().message()
                    << std::endl;
                return 1;
            }
        }

        // Init dirs before anything else, so we at least show correct in help output
        if (vm.count("help")) {
            initDirectorys();
            std::cout << "usage: " << argv[0] << std::endl
                << options << std::endl
                << std::endl
                << "Paths:" << std::endl
                << "  Default config dir: "
                <<  BOOST_PP_STRINGIZE(DEFAULT_CONFDIR) << std::endl
                << "  Default state dir : "
                <<  BOOST_PP_STRINGIZE(DEFAULT_LOCALSTATEDIR) << std::endl
                << "  Active config dir : "
                << getConfigPath().string() << std::endl
                << "  Active state dir  : "
                << getLocalStatePath().string() << std::endl
                << std::endl
                << "System configuration file      : "
                << getConfigPath("conf.d/system.conf").string() << std::endl
                << "App-specific configuration file: "
                << getConfigPath("conf.d/" + appShortName + ".conf").string() << std::endl
                ;
            return 1;
        }

        options_validator<std::string>(vm, "log-method")
            ("console")("syslog")
            .validate();

        options_validator<std::string>(vm, "log-syslog-facility")
            (log_container::getSyslogFacilities())
            .validate();

        options_validator<std::string>(vm, "log-level")
            (log_container::getLevels())
            .validate();
    }
    catch(std::exception& e)
    {
        std::cout << "Failed to parse command line: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}
예제 #27
0
static fs::path confPathFromApp(const std::string &app) {
    assert(!app.empty());
    return getConfigPath(MODULE_CONFDIR)
        / (app + ".conf");
}
예제 #28
0
void MainWin::initConnectionsTreeView()
{
    //connection manager
    connections = QSharedPointer<RedisConnectionsManager>(new RedisConnectionsManager(getConfigPath("connections.xml"), this));

    ui.serversTreeView->setModel(connections.data());

    connect(ui.serversTreeView, SIGNAL(clicked(const QModelIndex&)), 
            this, SLOT(OnConnectionTreeClick(const QModelIndex&)));
    connect(ui.serversTreeView, SIGNAL(wheelClicked(const QModelIndex&)), 
        this, SLOT(OnConnectionTreeWheelClick(const QModelIndex&)));

    //setup context menu    
    connect(ui.serversTreeView, SIGNAL(customContextMenuRequested(const QPoint &)),
            this, SLOT(OnTreeViewContextMenu(const QPoint &)));
}
예제 #29
0
#include "overlay_texture.h"
#include <Windows.h>
#include "filesystem.h"
#include "common.h"
#include "util.h"
#include "jvm_connection.hpp"
#include "logging.h"

static const char* RFACTOR_PATH = getRFactorPath();
static const char* PLUGIN_PATH = getPluginPath();
static const char* CONFIG_PATH = getConfigPath();

static char* fileBuffer = (char*)malloc( MAX_PATH );

OverlayTextureManager* textureManager = NULL;

unsigned short resX, resY;

static PixelBufferCallback* pixBuffCallback = new PixelBufferCallback();

unsigned char* PixelBufferCallback::getPixelBuffer( const unsigned char textureIndex, void** userObject )
{
    return ( getGlobal()->jvmConn.d3dFuncs.getPixelData( textureIndex ) );
}

void PixelBufferCallback::releasePixelBuffer( const unsigned char textureIndex, unsigned char* buffer, void* userObject )
{
    getGlobal()->jvmConn.d3dFuncs.releasePixelData( textureIndex, buffer );
}

void D3DManager::renderOverlay( void* d3dDev, const float postScaleX, const float postScaleY, JVMD3DUpdateFunctions* d3dFuncs )
QString DFMStandardPaths::location(DFMStandardPaths::StandardLocation type)
{
    switch (type) {
    case TrashPath:
        return QDir::homePath() + "/.local/share/Trash";
    case TrashFilesPath:
        return QDir::homePath() + "/.local/share/Trash/files";
    case TrashInfosPath:
        return QDir::homePath() + "/.local/share/Trash/info";
#ifdef APPSHAREDIR
    case TranslationPath: {
        QString path = APPSHAREDIR"/translations";
        if (!QDir(path).exists()) {
            path = qApp->applicationDirPath() + "/translations";
        }
        return path;
    }
    case TemplatesPath: {
        QString path = APPSHAREDIR"/templates";
        if (!QDir(path).exists()) {
            path = qApp->applicationDirPath() + "/templates";
        }
        return path;
    }
    case MimeTypePath: {
        QString path = APPSHAREDIR"/mimetypes";
        if (!QDir(path).exists()) {
            path = qApp->applicationDirPath() + "/mimetypes";
        }
        return path;
    }
#endif
#ifdef PLUGINDIR
    case PluginsPath: {
        QString path = PLUGINDIR;
        if (!QDir(path).exists()) {
            path = QString::fromLocal8Bit(PLUGINDIR).split(':').last();
        }
        return path;
    }
#endif
#ifdef QMAKE_TARGET
    case ApplicationConfigPath:
        return getConfigPath();
#endif
    case ThumbnailPath:
        return QDir::homePath() + "/.cache/thumbnails";
    case ThumbnailFailPath:
        return location(ThumbnailPath) + "/fail";
    case ThumbnailLargePath:
        return location(ThumbnailPath) + "/large";
    case ThumbnailNormalPath:
        return location(ThumbnailPath) + "/normal";
    case ThumbnailSmallPath:
        return location(ThumbnailPath) + "/small";
#ifdef APPSHAREDIR
    case ApplicationSharePath:
        return APPSHAREDIR;
#endif
    case RecentPath:
        return "recent:///";
    case HomePath:
        return QStandardPaths::standardLocations(QStandardPaths::HomeLocation).first();
    case DesktopPath:
        return QStandardPaths::standardLocations(QStandardPaths::DesktopLocation).first();
    case VideosPath:
        return QStandardPaths::standardLocations(QStandardPaths::MoviesLocation).first();
    case MusicPath:
        return QStandardPaths::standardLocations(QStandardPaths::MusicLocation).first();
    case PicturesPath:
        return QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).first();
    case DocumentsPath:
        return QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation).first();
    case DownloadsPath:
        return QStandardPaths::standardLocations(QStandardPaths::DownloadLocation).first();
    case CachePath:
        return getCachePath();
    case DiskPath:
        return QDir::rootPath();
#ifdef NETWORK_ROOT
    case NetworkRootPath:
        return NETWORK_ROOT;
#endif
#ifdef USERSHARE_ROOT
    case UserShareRootPath:
        return USERSHARE_ROOT;
#endif
#ifdef COMPUTER_ROOT
    case ComputerRootPath:
        return COMPUTER_ROOT;
#endif
    case Root:
        return "/";
    default:
        return QStringLiteral("bug://dde-file-manager-lib/interface/dfmstandardpaths.cpp#") + QT_STRINGIFY(type);
    }

    return QString();
}