Example #1
0
int globalInit(void) {
	if (estgbconf.useFileConfig) {
		if (readFileConfig() != 0) {
			printf(
					"Warning! Failed to read config files. Checking for command line config...\n");
		}
	}
	 
	if (!checkConfig()) {
		printHelp();
		printConfig();
		printf("Configuration error. Nothing to do.\n\n");
		return 0;
	}

	if (telebot_create(&estgbconf.handle, estgbconf.token)
			!= TELEBOT_ERROR_NONE) {
		printf("Error. Telebot create failed (bad token?)\n\n");
		return 0;
	}

	if (estgbconf.proxy_addr != NULL) {
		estgbconf.ret = telebot_set_proxy(estgbconf.handle,
				estgbconf.proxy_addr, estgbconf.proxy_auth);
		if (estgbconf.ret != TELEBOT_ERROR_NONE) {
			printf("Warning! Failed to init proxy: %d \n", estgbconf.ret);
		}
	}

	return 1;
}
Example #2
0
int main(int argc, char* argv[])
{
    /* create VirtualMachine */
    VM SVM;
    SVM.errorCode = 0;
    SVM.mode = 0;

    /* check arguments */
    if (checkArgs(argc, argv, &SVM.mode)) return 1;

    /* check configuration file */
    checkConfig(&SVM.config, &SVM.errorCode);
    if (SVM.errorCode != 0) return 1;

    /* initialization memory */
    SVM.memory.space = createMemory(SVM.config.memorySize);
    if(SVM.memory.space == NULL) return 1;
    SVM.memory.currentAddress = SVM.config.memorySize - 1;

    /* initialization stack */
    SVM.stack = initStack();

    /* start */
    if (!runVM(&SVM, argv[1])) return 1;
    return 0;
}
Example #3
0
void NWNEngine::init() {
	LoadProgress progress(21);

	progress.step("Detecting game version");
	detectVersion();

	progress.step("Loading user game config");
	initConfig();
	checkConfig();

	if (EventMan.quitRequested())
		return;

	progress.step("Declare string encodings");
	declareEncodings();

	initResources(progress);

	if (EventMan.quitRequested())
		return;

	progress.step("Loading game cursors");
	initCursors();

	if (EventMan.quitRequested())
		return;

	progress.step("Initializing internal game config");
	initGameConfig();

	progress.step("Starting script system");
	_scriptFuncs = new ScriptFunctions();

	progress.step("Successfully initialized the engine");
}
void ProjectConfigDialog::onOK(void)
{
    if (checkConfig())
    {
        m_dialogResult = true;
    }
}
Example #5
0
QStringList KStandardDirs::findDirs( const char *type,
                                     const QString& reldir ) const
{
    QDir testdir;
    QStringList list;
    if (!QDir::isRelativePath(reldir))
    {
        testdir.setPath(reldir);
        if (testdir.exists())
        {
            if (reldir.endsWith("/"))
               list.append(reldir);
            else
               list.append(reldir+'/');
        }
        return list;
    }

    checkConfig();

    if (d && d->restrictionsActive && (strcmp(type, "data")==0))
       applyDataRestrictions(reldir);
    QStringList candidates = resourceDirs(type);

    for (QStringList::ConstIterator it = candidates.begin();
         it != candidates.end(); ++it) {
        testdir.setPath(*it + reldir);
        if (testdir.exists())
            list.append(testdir.absPath() + '/');
    }

    return list;
}
Example #6
0
QString KStandardDirs::saveLocation(const char *type,
				    const QString& suffix,
				    bool create) const
{
    checkConfig();

    QString *pPath = savelocations.find(type);
    if (!pPath)
    {
       QStringList *dirs = relatives.find(type);
       if (!dirs && (
                     (strcmp(type, "socket") == 0) ||
                     (strcmp(type, "tmp") == 0) ||
                     (strcmp(type, "cache") == 0) ))
       {
          (void) resourceDirs(type); // Generate socket|tmp|cache resource.
          dirs = relatives.find(type); // Search again.
       }
       if (dirs)
       {
          // Check for existence of typed directory + suffix
          if (strncmp(type, "xdgdata-", 8) == 0)
             pPath = new QString(realPath(localxdgdatadir() + dirs->last()));
          else if (strncmp(type, "xdgconf-", 8) == 0)
             pPath = new QString(realPath(localxdgconfdir() + dirs->last()));
          else
             pPath = new QString(realPath(localkdedir() + dirs->last()));
       }
       else {
          dirs = absolutes.find(type);
          if (!dirs)
             qFatal("KStandardDirs: The resource type %s is not registered", type);
          pPath = new QString(realPath(dirs->last()));
       }

       savelocations.insert(type, pPath);
    }
    QString fullPath = *pPath + (pPath->endsWith("/") ? "" : "/") + suffix;

    KDE_struct_stat st;
    if (KDE_stat(QFile::encodeName(fullPath), &st) != 0 || !(S_ISDIR(st.st_mode))) {
	if(!create) {
#ifndef NDEBUG
	    kdDebug() << QString("save location %1 doesn't exist").arg(fullPath) << endl;
#endif
	    return fullPath;
	}
	if(!makeDir(fullPath, 0700)) {
	    return fullPath;
	}
        dircache.remove(type);
    }
    if (!fullPath.endsWith("/"))
	    fullPath += "/";
    return fullPath;
}
Example #7
0
QStringList
KStandardDirs::findAllResources( const char *type,
			         const QString& filter,
				 bool recursive,
			         bool unique,
                                 QStringList &relList) const
{
    QStringList list;
    QString filterPath;
    QString filterFile;

    if (filter.length())
    {
       int slash = filter.findRev('/');
       if (slash < 0)
	   filterFile = filter;
       else {
	   filterPath = filter.left(slash + 1);
	   filterFile = filter.mid(slash + 1);
       }
    }

    checkConfig();

    QStringList candidates;
	if (!QDir::isRelativePath(filter)) // absolute path
    {
#ifdef Q_OS_WIN
        candidates << filterPath.left(3); //e.g. "C:\"
        filterPath = filterPath.mid(3);
#else
        candidates << "/";
        filterPath = filterPath.mid(1);
#endif
    }
    else
    {
        if (d && d->restrictionsActive && (strcmp(type, "data")==0))
            applyDataRestrictions(filter);
        candidates = resourceDirs(type);
    }
    if (filterFile.isEmpty())
	filterFile = "*";

    QRegExp regExp(filterFile, true, true);

    for (QStringList::ConstIterator it = candidates.begin();
         it != candidates.end(); ++it)
    {
        lookupPrefix(*it, filterPath, "", regExp, list,
                     relList, recursive, unique);
    }

    return list;
}
Example #8
0
int main(int argc, char *argv[]) {
    bool ret = true;

    s3ext_loglevel = EXT_ERROR;
    s3ext_logtype = STDERR_LOG;

    if (argc == 1) {
        printUsage(stderr);
        exit(EXIT_FAILURE);
    }

    /* Prepare to receive interrupts */
    registerSignalHandler();

    map<char, string> optionPairs = parseCommandLineArgs(argc, argv);

    validateCommandLineArgs(optionPairs);

    if (!optionPairs.empty()) {
        const char *arg = optionPairs.begin()->second.c_str();

        switch (optionPairs.begin()->first) {
            case 'c':
                ret = checkConfig(arg);
                break;
            case 'd':
                ret = downloadS3(arg);
                break;
            case 'u':
            case 'f':
                ret = uploadS3(optionPairs['u'].c_str(), optionPairs['f'].c_str());
                break;
            case 'h':
                printUsage(stdout);
                break;
            case 't':
                printTemplate();
                break;
            default:
                printUsage(stderr);
                exit(EXIT_FAILURE);
        }
    }

    // Abort should not print the failed info
    if (ret || S3QueryIsAbortInProgress()) {
        exit(EXIT_SUCCESS);
    } else {
        fprintf(stderr, "Failed. Please check the arguments and configuration file.\n\n");
        printUsage(stderr);
        exit(EXIT_FAILURE);
    }
}
void MLX90621::measure() {
	if (checkConfig()) {
		readEEPROM();
		writeTrimmingValue();
		setConfiguration();
	}
	readPTAT();
	readIR();
	calculateTA();
	readCPIX();
	calculateTO();
}
Example #10
0
//	actual processing of a SDC block. 
bool	sdcProcessor::processSDC (theSignal *v) {
int32_t	i;

	checkConfig ();
	if (qammode == mscConfig::QAM4) {
	   metrics	rawBits [2 * nrCells];
	   uint8_t	reconstructed [2 * nrCells];
	   my_qam4_metrics -> computemetrics (v, nrCells, rawBits);
	   stream_0	   -> handle_stream (rawBits, reconstructed,
	                                          &sdcBits [4], false);
	}
	else {
           metrics Y0_stream	[2 * nrCells];
	   metrics Y1_stream	[2 * nrCells];
	   uint8_t level_0	[2 * nrCells];
	   uint8_t level_1	[2 * nrCells];

	   for (i = 0; i < 5; i ++) {
	      my_qam16_metrics -> computemetrics (v, nrCells, 0, 
	                                          Y0_stream, 
	                                          i != 0,
	                                          level_0, level_1);

	      stream_0	-> handle_stream (Y0_stream,
	                                  level_0,
	                                  &sdcBits [4],
	                                  true);
	      my_qam16_metrics -> computemetrics (v, nrCells, 1, 
	                                          Y1_stream,
	                                          true,
	                                          level_0, level_1);
	      stream_1	-> handle_stream (Y1_stream,
	                                  level_1,
	                                &sdcBits [4 + stream_0 -> lengthOut ()],
	                                  true);
	   }
	}
//
//	apply PRBS
	thePRBS -> doPRBS (&sdcBits [4]);

	sdcBits [0] = sdcBits [1] = sdcBits [2] = sdcBits [3] = 0;
	if (!theCRC. doCRC (sdcBits, 4 + lengthofSDC)) {
	   my_facDB	-> set_SDC_crc (false);
	   return false;
	}

	my_facDB	-> interpretSDC (sdcBits, lengthofSDC);
	my_facDB	-> set_SDC_crc (true);
	return true;
}
int 
ConfigurationParserTest::parseFileTest(){
  int retval = 0;

  const string testFileName = "configurationParserTest.cfg";
  const ConfigurationScope *outerScope = ConfigurationParserHandle::parseFile( testFileName );
  
  if( outerScope == 0 ){
    retval = -1;
  }
  else{
    retval = checkConfig( *outerScope );
  }

  return retval;
}
Example #12
0
void setDefaultConfig() {
	config.stepMode = StepHalf;
	config.brakeMode = BrakeSmart;
	
	config.tickTime = 3500;
	config.homeTime = 3500;
	config.fixTime = 3500;
	
	config.maxSteps = 8000;
	config.homeSteps = 8000;
	config.fixSteps = 8000;
	
	config.brakeTicks = 10000;

	config.minStepDelta = 10;

	if (!checkConfig(&config))
		internalError(ERROR_INTERNAL_DEFAULT_CONFIG_FAULT);
}
Example #13
0
void KotOREngine::init() {
	initConfig();
	checkConfig();

	if (EventMan.quitRequested())
		return;

	initResources();

	if (EventMan.quitRequested())
		return;

	initCursors();

	if (EventMan.quitRequested())
		return;

	initGameConfig();
}
Example #14
0
void NWNEngine::init() {
	initConfig();
	checkConfig();

	if (EventMan.quitRequested())
		return;

	initResources();

	if (EventMan.quitRequested())
		return;

	initCursors();

	if (EventMan.quitRequested())
		return;

	initGameConfig();

	_scriptFuncs = new ScriptFunctions();
}
Example #15
0
/**
 * @brief MainWindow::MainWindow
 * @param parent
 */
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    process(new QProcess(this)),
    fusedav(this),
    keygen(NULL),
    tray(NULL)
{
//    connect(process.data(), SIGNAL(readyReadStandardOutput()), this, SLOT(readyRead()));
    connect(process.data(), SIGNAL(error(QProcess::ProcessError)), this, SLOT(processError(QProcess::ProcessError)));
    connect(process.data(), SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(processFinished(int, QProcess::ExitStatus)));
    ui->setupUi(this);
    enableUiElements(true);
    wrapperRunning = false;
    execQueue = new QQueue<execQueueItem>;
    ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
    firstRun = true;
    startupPhase = true;
    if (!checkConfig()) {
        // no working config
        QApplication::quit();
    }
    QtPass = NULL;
}
Example #16
0
void KotOR2Engine::init() {
	LoadProgress progress(17);

	progress.step("Declare languages");
	declareLanguages();

	if (evaluateLanguage(true, _language))
		status("Setting the language to %s", LangMan.getLanguageName(_language).c_str());
	else
		warning("Failed to detect this game's language");

	LangMan.setCurrentLanguage(_language);

	progress.step("Loading user game config");
	initConfig();
	checkConfig();

	if (EventMan.quitRequested())
		return;

	initResources(progress);

	if (EventMan.quitRequested())
		return;

	progress.step("Loading game cursors");
	initCursors();

	if (EventMan.quitRequested())
		return;

	progress.step("Initializing internal game config");
	initGameConfig();

	progress.step("Successfully initialized the engine");
}
Example #17
0
void EasySFML::install(){

    if (checkConfig()){

        SetColor(DARKGREEN);

        string version;
        bool ok=true;
        string finalpath;
        string command = "";

        // Final Path
        if(ok){

            SetColor(DARKGREEN);
            cout << "# Enter where you want to install sfml:" << endl;
            cout << "# ex: C:/" << endl;
            SetColor(WHITE);
            cout << "SFML path >> " ;
            getline(cin, finalpath);
            cout << endl;

            if (finalpath != ""){
                finalpath = clean_path(finalpath);
                if (!dirExist(finalpath)){
                    SetColor(RED);
                    cout << "ERROR: Impossible to find folder '" << finalpath << "' ."<< endl << endl;
                    SetColor(WHITE);
                    ok = false;
                }
            }
            else{
                SetColor(RED);
                cout << "ERROR: Impossible to find folder '" << finalpath << "' ."<< endl << endl;
                SetColor(WHITE);
                ok = false;
            }
        }

        if (ok){
            SetColor(DARKGREEN);
            cout << "# Enter the sfml version to install." << endl;
            cout << "# ex: 1" << endl;

            XMLNode xMainNode=XMLNode::openFileHelper("conf/version.xml","PMML");
            XMLNode xversions=xMainNode.getChildNode("versions");
            int n=xversions.nChildNode("version");
            for (int i = 0; i < n;i++ ){
                XMLNode xversion =xversions.getChildNode("version",i);
                cout << i << " : " << xversion.getChildNode("name").getText() << endl;
            }

            SetColor(WHITE);
            cout << "Version >> " ;
            getline(cin, version);
            cout << endl;

            int i = atoi(version.c_str());
            if (!(i >= 0 && i < n) || version == ""){
                ok = false;
                SetColor(RED);
                cout << "ERROR: Impossible to choose version '" << version << "' ."<< endl << endl;
                SetColor(WHITE);
            }
            else{
               // _compilertype = version;
               int i = atoi(version.c_str());
                XMLNode xversion =xversions.getChildNode("version",i);
                string sfmlPath = xversion.getChildNode("path").getText();
                if (!dirExist(sfmlPath)){
                    cout << "Create new dir: '"<< sfmlPath <<"'" << endl;
                    if (!dirExist("download/versions/")) mkdir("download/versions/");
                    mkdir(sfmlPath.c_str());

                }

                if (!fileExist(xversion.getChildNode("zip").getText())){
                    cout << "Download: "<< xversion.getChildNode("url").getText() << "..." << endl;
                    get_http_data(xversion.getChildNode("url").getText(),xversion.getChildNode("zip").getText());
                }



                cout << "Delete: "<< xversion.getChildNode("src").getText() << "..." << endl;
                command = xversion.getChildNode("src").getText();
                command = "rd /s /q \""+command+"\"";
                system( command.c_str() );
                cout << "Unzip: "<< xversion.getChildNode("zip").getText() << "..." << endl;
                extract_zip(xversion.getChildNode("path").getText(),xversion.getChildNode("zip").getText());

                // Compilation
                string mainpath = GetPath();
                string compiler = getCompiler();
                string src_sfml = xversion.getChildNode("src").getText();

                command = "";
                command += "cd " + src_sfml + " && ";
                command += "set PATH=\""+_compilerpath +"bin/\";%PATH%" + " && ";
                command += "set PATH=\""+_cmakepath +"bin/\";%PATH%" + " && ";
                command += "cmake -G \""+compiler+"\" -D CMAKE_BUILD_TYPE=Release -D BUILD_SHARED_LIBS=TRUE \"" + mainpath+"/"+src_sfml + "\" && ";
                command += "mingw32-make &&";
                command += "cmake -G \""+compiler+"\" -D CMAKE_BUILD_TYPE=Debug -D BUILD_SHARED_LIBS=TRUE \"" + mainpath+"/"+src_sfml + "\" && ";
                command += "mingw32-make && ";
                command += "cmake -G \""+compiler+"\" -D CMAKE_BUILD_TYPE=Release -D BUILD_SHARED_LIBS=FALSE \"" + mainpath+"/"+src_sfml + "\" && ";
                command += "mingw32-make && ";
                command += "cmake -G \""+compiler+"\" -D CMAKE_BUILD_TYPE=Debug -D BUILD_SHARED_LIBS=FALSE \"" + mainpath+"/"+src_sfml + "\" && ";
                command += "mingw32-make";
                //cout << command << endl;
                int resCMD = system(command.c_str());

                if (resCMD == 0 && errno == 0)
                {
                    cout << "Finalize installation..." << endl;
                    command = xversion.getChildNode("name").getText();
                    command = "xcopy  \""+ mainpath+"/"+src_sfml +"\" \""+finalpath+"/"+command+"\" /s /e /y /i";
                    cout << command << endl;
                    system(command.c_str());

                    cout << endl << "Installation complete." << endl;
                }
                else{
                    SetColor(RED);
                    cout << "ERROR: Impossible to cmake or compile." << endl;
                    SetColor(WHITE);
                }



            }
        }

    }



}
Example #18
0
int main(int argc, char *argv[]){

	configuration_t *conf = clparser(argc, argv);
	wav_t newCarrier;


	wav_t carrierFile;
	dataHolder_t carrierData;

	if(conf != NULL)
		showConfig(conf);
	checkConfig(&conf);
	if(conf != NULL) {
		LOG("opening carrier file: %s\n", conf->carrierFile);
		carrierFile = newWavFromFile(conf->carrierFile);
		carrierData = wavGetData(carrierFile);

		if(conf->embed == steg_embed){
			fileContainer_t payload;
			char *ext = NULL;
			dataHolder_t payloadRawHolder, resultPayload;
			FCRead(conf->sourceFile, &payload);

			//Embeding
			if(conf->encriptation == NULL){
				//Embeding without encryptation.
				resultPayload.data = payload.rawData;
				resultPayload.size = payload.size;
				ext = payload.extension;
			} else {
				//Embeding with encryptation.
				typeConvertFCtoDH(&payload, &payloadRawHolder);
				crypto_Execute(*conf->encriptation, payloadRawHolder, &resultPayload);
				ext = NULL;
			}

			stegEmbed(&carrierData, &resultPayload, conf->stegMode, ext);
			newCarrier = newWavFromData(wavGetFMT(carrierFile), carrierData);
			wavWriteToFile(newCarrier, conf->targetFile);

		} else {
			fileContainer_t resultPayloadFile;
			dataHolder_t payloadData;
			if(conf->encriptation == NULL){
				LOG("extracting without decryption\n");
				//Extracting without decription
				stegExtract(&carrierData, &payloadData, conf->stegMode, resultPayloadFile.extension);

				resultPayloadFile.rawData = payloadData.data;
				resultPayloadFile.size = payloadData.size;
				LOG("got payload file size: %d, and extention %s\n", resultPayloadFile.size, resultPayloadFile.extension);
			} else {
				//Extracting with decription
				LOG("extrating with encryption\n");
				dataHolder_t cipherPayload;
				stegExtract(&carrierData, &cipherPayload, conf->stegMode, NULL);
				LOG("extracted cipherPayload({%d,%p})\n",cipherPayload.size, cipherPayload.data);
				crypto_Execute(*conf->encriptation, cipherPayload, &payloadData);
				typeConvertDHtoFC(&resultPayloadFile, &payloadData);
			}

			FCWrite(conf->targetFile, &resultPayloadFile);
		}

	} else {
		printf("user -h for help\n");
	}

	return 0;
}
Example #19
0
EtaKeyboard::EtaKeyboard(QWidget *parent)
    : QMainWindow(parent)
{
    setWindowFlags(Qt::WindowStaysOnTopHint |
                   Qt::FramelessWindowHint |
                   Qt::WindowSystemMenuHint |
                   Qt::WindowDoesNotAcceptFocus |
                   Qt::X11BypassWindowManagerHint);

    QDesktopWidget dw;
    screenWidth = dw.screenGeometry(dw.primaryScreen()).width();
    screenHeight = dw.screenGeometry(dw.primaryScreen()).height();

    key_height = screenHeight / 16;
    key_width = screenWidth / 26;
    dock_height = screenHeight / 30;
    m_width = 13*key_width;
    m_height = key_height*4+dock_height;

    configpath = QDir::homePath() + "/.config/etak/config.ini";
    color = "gray";
    Settings::setLanguage("trq");
    Settings::setAutoShowBool(true);

    QFileInfo checkConfig(configpath);

    if (checkConfig.exists() && checkConfig.isFile()) {
        preferences = new QSettings(configpath,QSettings::IniFormat);
        preferences->beginGroup("etak");
        Settings::setLanguage(preferences->value("Language").toString());
        color= preferences->value("Color").toString();
        Settings::setAutoShowBool(preferences->value("AutoShow").toBool());
        preferences->endGroup();
    }

    Settings::setColors(color); // 'blue' or 'gray'
    Helpers::langChange(Settings::getLanguage()); // intialization of X keyboard layout as trq



    setStyleSheet("background-color: "+Settings::getBackgroundColor()+";");

    setGeometry(screenWidth/2+m_width,0,m_width,0);



    out = LabelInstance::Instance();  // Output text right up to keyboard
    out->setParent(this);
    out->setGeometry(0,0,m_width,dock_height);
    out->setStyleSheet("QLabel{color: white; qproperty-alignment: AlignCenter;}");
    QFont f;
    f.setPointSize(key_height / 5);
    out->setFont(f);


    settingsRectangle = new QDialog(this,Qt::X11BypassWindowManagerHint);
    settingsRectangle->setStyleSheet("background-color: "+Settings::getBackgroundColor()+";");
    settingsRectangle->hide();

    toggleAuto = new QPushButton(settingsRectangle);
    toggleAuto->setGeometry(0,0,key_width*2,dock_height);
    toggleAuto->setCheckable(true);
    toggleAuto->setChecked(Settings::getAutoShowBool());
    if(Settings::getAutoShowBool()) {
        toggleAuto->setText(QString::fromUtf8("Otomatik çıkma : Kapat"));
    } else {
        toggleAuto->setText(QString::fromUtf8("Otomatik çıkma : Aç"));
    }
    toggleAuto->setStyleSheet(Settings::getStyleSheet()+Settings::getStyleSheetExtra());
    QFont g;
    g.setPointSize(key_height / 9);
    toggleAuto->setFont(g);

    connect(toggleAuto,SIGNAL(clicked()),this,SLOT(toggleAutoShow()));

    passwordButton = new QPushButton(this);
    passwordButton->setGeometry(1,1,dock_height,dock_height);
    passwordButton->setStyleSheet(Settings::getStyleSheet()+Settings::getStyleSheetExtra());
    passwordButton->setCheckable(true);
    passwordButton->setChecked(false);
    passwordButton->setText("P");
    g.setBold(true);
    g.setPointSize(key_height/4);
    passwordButton->setFont(g);
    QRegion *region = new QRegion(*(new QRect(passwordButton->x()+2,passwordButton->y()+2,dock_height-6,dock_height-6)),QRegion::Ellipse);
    passwordButton->setMask(*region);
    connect(passwordButton,SIGNAL(clicked()),this,SLOT(togglePassword()));


    QHash<int, QList<unsigned int> > hash;
    QList<unsigned int> listtmp;
    for ( int i = 24 ; i < 36 ; ++i) {
        listtmp.append(i);
    }
    hash.insert(1,listtmp);
    listtmp.clear();
    for ( int j = 38 ; j < 49 ; ++j) {
        listtmp.append(j);
    }
    hash.insert(2,listtmp);
    listtmp.clear();
    for ( int k = 52 ; k < 61 ; ++k) {
        listtmp.append(k);
    }
    hash.insert(3,listtmp);
    listtmp.clear();
    Key *tmp;
    int posrow = key_width;
    int posy = dock_height;
    int posx;

    AlphaKey *tmp2;

    QString tmpLanguageLayout ="";
    if (Settings::getLanguage() == "trq") {
        tmpLanguageLayout = "TRQ";
    } else if (Settings::getLanguage() == "trf") {
        tmpLanguageLayout = "TRF";
    } else if (Settings::getLanguage() == "arabic") {
        tmpLanguageLayout = QString::fromUtf8("العربئة");
    }

    lang = new SpecialKey(settingsRectangle,0,dock_height,key_width,key_height,tmpLanguageLayout);
    connect(lang,SIGNAL(clicked()),this,SLOT(changeLanguage()));

    tmp2 = new AlphaKey(this,0,dock_height,key_width,key_height,9,"Esc"); //Escape
    alpha_keys.append(tmp2);

    change = new SpecialKey(this,0,key_height+dock_height,key_width*3/2,key_height,"?123+");
    connect(change,SIGNAL(clicked()),this,SLOT(toggleAlterns()));
    leftshift = new AlphaKey(this,0,key_height*2+dock_height,key_width*2,key_height,50,QString::fromUtf8("↑")); //caps
    alpha_keys.append(leftshift);
    connect(leftshift,SIGNAL(clicked()),this,SLOT(toggleCaps()));
    for (int y = 1 ; y<=3 ; ++y) {
        posx=posrow;
        for (int x =0; x < hash[y].length(); ++x) {
            if (y==2 && x==10) {
                tmp = new Key(this,posx,posy,key_width*3/2,key_height,hash[y].at(x));
            } else {
                tmp = new Key(this,posx,posy,key_width,key_height,hash[y].at(x));
            }
            keys.append(tmp);
            posx += key_width;
        }
        posy += key_height;
        posrow += key_width / 2;
    }
    tmp2 = new AlphaKey(this, posx, posy - key_height, key_width * 2, key_height, 22, QString::fromUtf8("⌫")); //backspace
    alpha_keys.append(tmp2);

    settingsButton = new QPushButton(this);
    settingsButton->setGeometry(0,posy,key_width,key_height);
    settingsButton->setStyleSheet(Settings::getStyleSheet());

    QPixmap pm(":/icons/gear.png");
    settingsButton->setIcon(QIcon(pm));
    settingsButton->setIconSize(QSize(settingsButton->width()*2/3,settingsButton->height()*2/3));

    connect(settingsButton,SIGNAL(clicked()),this,SLOT(toggleSettings()));

    hideButton = new QPushButton(this);
    hideButton->setGeometry(m_width-dock_height-1,1,dock_height,dock_height);
    QPixmap pm2(":/icons/window-close.png");
    hideButton->setIcon(QIcon(pm2));
    hideButton->setIconSize(QSize(hideButton->width(),hideButton->height()));

    connect(hideButton,SIGNAL(clicked()),this,SLOT(animationToggle()));

    colorButton = new QPushButton(settingsRectangle);
    colorButton->setGeometry(key_width,dock_height,key_width,key_height);
    colorButton->setStyleSheet(Settings::getStyleSheet());

    connect(colorButton,SIGNAL(clicked()),this,SLOT(toggleColor()));

    tmp = new Key(this,key_width,posy,key_width,key_height,20); //asterix
    bottom_keys.append(tmp);
    tmp = new Key(this,key_width*2,posy,key_width*13/2,key_height,65); // space
    bottom_keys.append(tmp);
    tmp = new Key(this,key_width*17/2,posy,key_width,key_height,51); // comma
    bottom_keys.append(tmp);
    tmp = new Key(this,key_width*19/2,posy,key_width,key_height,61); // dot
    bottom_keys.append(tmp);

    tmp2 = new AlphaKey(this,key_width*21/2,posy,key_width*5/2,key_height,36,QString::fromUtf8("↵")); // enter
    alpha_keys.append(tmp2);

    server = new EtaLocalServer(this);
    Q_CHECK_PTR(server);
    const QString fullServerName =  QString(QDir::homePath()+"/"+SERVER_NAME);

    QFile file(fullServerName);
    if (file.exists()) {
         file.remove();
    }
    if (server->listen(QDir::homePath()+"/"+SERVER_NAME)) {
        //qDebug() << "Listenning";
    } else {
        //qDebug() << "Failed to listen";
    }
    connect(server, SIGNAL(newCommand(char*)), this, SLOT(onNewCommand(char*)));
    anime = new QPropertyAnimation(this, "geometry");
    tog =  false;
    QList<QString> alternatives;

    alternatives.append("1");
    alternatives.append("2");
    alternatives.append("3");
    alternatives.append("4");
    alternatives.append("5");
    alternatives.append("6");
    alternatives.append("7");
    alternatives.append("8");
    alternatives.append("9");
    alternatives.append("0");
    alternatives.append("braceleft");
    alternatives.append("braceright");

    alternatives.append("at");
    alternatives.append("numbersign");
    alternatives.append("dollar");
    alternatives.append("percent");
    alternatives.append("ampersand");
    alternatives.append("parenleft");
    alternatives.append("parenright");
    alternatives.append("minus");
    alternatives.append("less");
    alternatives.append("greater");
    alternatives.append("exclam");

    alternatives.append("semicolon");
    alternatives.append("colon");
    alternatives.append("apostrophe");
    alternatives.append("quotedbl");
    alternatives.append("question");
    alternatives.append("slash");
    alternatives.append("plus");
    alternatives.append("equal");
    alternatives.append("underscore");

     for (int cnt = 0; cnt < keys.size(); ++cnt) {
         keys.at(cnt)->setAlternString(alternatives.at(cnt));
     }
}
Example #20
0
int main(int argc, char* argv[]) {
	string config_path, house_path, algo_path, score_path;
	map<string, string> houses_mapName, algo_mapName, config_mapName, score_mapName;
	vector <fs::path> fileName_currDir;
	vector <House*> houses;
	vector <AbstractAlgorithm*> algos;
	map<string, string> configBeforeValid;
	map<string, int> config;
	map<string, string> ErrorMSGHouse;
	vector<unique_ptr<AbstractAlgorithm>> Algos;
	map<string, string> ErrorMSGAlgo;
	string ErrorMSGScore = "";
	bool makeVideo = false;
	int number_threads;
	vector<void*> handlersVector;
	void* scoreHandler;
	scoreFunc scorefunction = nullptr;
	bool house_exist, config_exist, algo_exist, score_exist;
	checkArguments(argc, argv, config_path, algo_path, house_path, score_path, number_threads, makeVideo);
	if (makeVideo && (number_threads > 1)) {
		cout << "Cannot create video with more than one thread" << endl;
		return 1;
	}
	house_exist = updateFilesFromDirectory(houses_mapName, ".house", house_path);
	config_exist = updateFilesFromDirectory(config_mapName, ".ini", config_path);
	algo_exist = updateFilesFromDirectory(algo_mapName, "_.so", algo_path);
	if (score_path != "") {
		score_exist = updateFilesFromDirectory(score_mapName, "score_formula.so", score_path);
		if (score_exist) {
			for (auto scoreFilesNames : score_mapName) {
				const char* tmpname = scoreFilesNames.first.c_str();
				scoreHandler = dlopen(tmpname, RTLD_NOW);
				if (scoreHandler == nullptr) {
					ErrorMSGScore = "score_formula.so exists in '" + score_path + "' but cannot be opened or is not a valid .so";
					break;
				}
				*(void **)(&scorefunction) = dlsym(scoreHandler, "calc_score");
				if (scorefunction == nullptr) {
					ErrorMSGScore = "score_formula.so is a valid.so but it does not have a valid score formula";
					break;
				}
			}
		}
	}
	else {
		scorefunction = nullptr;
		score_exist = true;
	}

	if (!house_exist || !algo_exist || !config_exist || !score_exist) {
		Usage(house_path, config_path, algo_path, score_path, house_exist, config_exist, algo_exist, score_exist);
		return 1;

	}
	if (ErrorMSGScore != "") {
		cout << ErrorMSGScore << endl;
		return 1;
	}

	int numberOfValidHouses = checkHouses(houses_mapName, &houses, &ErrorMSGHouse);
	if (!checkConfig(config_mapName.begin()->first, &configBeforeValid, config_path)) {
		return 1;
	}
	convertToMapInt(configBeforeValid, &config);
	for (auto algoSoFilesNames : algo_mapName) {
		int resNum = AlgorithmRegistrar::getInstance().loadAlgorithm(algoSoFilesNames.first, algoSoFilesNames.first);
		if (resNum == -1) {
			ErrorMSGAlgo[algoSoFilesNames.first] = "file cannot be loaded or is not a valid .so";
			continue;
		}
		else if (resNum == -2) {
			ErrorMSGAlgo[algoSoFilesNames.first] = "valid .so but no algorithm was registered after loading it";
			continue;
		}
	}

	Algos = AlgorithmRegistrar::getInstance().getAlgorithms();
	list<string> algorithmNames = AlgorithmRegistrar::getInstance().getAlgorithmNames();
	for (vector<unique_ptr<AbstractAlgorithm>>::size_type k = 0; k != Algos.size(); k++) {
		auto l_front = algorithmNames.begin();
		std::advance(l_front, k);
		string algoName = *l_front;
		if (ErrorMSGAlgo.find(algoName) == ErrorMSGAlgo.end())
			algos.push_back(Algos[k].release());
	}
	bool scoreError = true;
	int numberOfValidAlgo = algos.size();
	if (numberOfValidAlgo && numberOfValidHouses) {
		vector<string> algoOnlyNames, houseonlyNames;
		createVcetorFromMapValues(algoOnlyNames, algo_mapName, ErrorMSGAlgo);
		createVcetorFromMapValues(houseonlyNames, houses_mapName, ErrorMSGHouse);
		Simulator sim(houses, algos, config, algoOnlyNames, houseonlyNames, makeVideo);
		scoreError = sim.runSimulator(algoOnlyNames, houseonlyNames, number_threads, scorefunction);
	}
	if (ErrorMSGHouse.size() > 0 || ErrorMSGAlgo.size() > 0) {
		cout << "\n" << "Errors:" << endl;
		if (houses.size() == 0)
			cout << "All house files in target folder " << "'" << house_path << "'" << " cannot be opened or are invalid:" << endl;
		PrintErrors(ErrorMSGHouse, houses_mapName, "house");
		if (algos.size() == 0)
			cout << "All algorithm files in target folder " << "'" << algo_path << "'" << " cannot be opened or are invalid:" << endl;
		PrintErrors(ErrorMSGAlgo, algo_mapName, "so");
	}
	if (!scoreError)
		cout << "Score formula could not calculate some scores, see -1 in the results table" << endl;
	for (auto it = houses.begin(); it != houses.end(); it++)
		delete *it;


	AlgorithmRegistrar::getInstance().closeAlgorithms();

	houses.clear();
	Algos.clear();

	return 0;
}
Example #21
0
int DOTCONFDocument::setContent(const char * _fileName)
{
    int ret = 0;
    char realpathBuf[PATH_MAX];

    if(realpath(_fileName, realpathBuf) == NULL){
        error(0, NULL, "realpath(%s) failed: %s", _fileName, strerror(errno));
        return -1;
    }

    fileName = strdup(realpathBuf);

    processedFiles.push_back(strdup(realpathBuf));

    if(( file = fopen(fileName, "r")) == NULL){
        error(0, NULL, "failed to open file '%s': %s", fileName, strerror(errno));
        return -1;
    }
    // Try read utf8 header and skip it if exist
    uint32 utf8header = 0;
    fgets((char*)&utf8header, 4, file); // Try read header
    if (utf8header!=0x00BFBBEF)         // If not exist
        fseek(file, 0, SEEK_SET);       // Reset read position

    ret = parseFile();

    (void) fclose(file);

    if(!ret){

        if( (ret = checkConfig(nodeTree.begin())) == -1){
            return -1;
        }

        std::list<DOTCONFDocumentNode*>::iterator from;
        DOTCONFDocumentNode * tagNode = NULL;
        int vi = 0;
        for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i!=nodeTree.end(); ++i){
            tagNode = *i;
            if(!cmp_func("DOTCONFPPIncludeFile", tagNode->name)){
                vi = 0;
                while( vi < tagNode->valuesCount ){
                    if(access(tagNode->values[vi], R_OK) == -1){
                        error(tagNode->lineNum, tagNode->fileName, "%s: %s", tagNode->values[vi], strerror(errno));
                        return -1;
                    }
                    if(realpath(tagNode->values[vi], realpathBuf) == NULL){
                        error(tagNode->lineNum, tagNode->fileName, "realpath(%s) failed: %s", tagNode->values[vi], strerror(errno));
                        return -1;
                    }

                    bool processed = false;
                    for(std::list<char*>::const_iterator itInode = processedFiles.begin(); itInode != processedFiles.end(); ++itInode){
                        if(!strcmp(*itInode, realpathBuf)){
                            processed = true;
                            break;
                        }
                    }
                    if(processed){
                        break;
                    }

                    processedFiles.push_back(strdup(realpathBuf));

                    file = fopen(tagNode->values[vi], "r");
                    if(file == NULL){
                        error(tagNode->lineNum, fileName, "failed to open file '%s': %s", tagNode->values[vi], strerror(errno));
                        return -1;
                    }

                    fileName = strdup(realpathBuf);
                    from = nodeTree.end(); --from;

                    ret = parseFile();
                    (void) fclose(file);
                    if(ret == -1)
                        return -1;
                    if(checkConfig(++from) == -1){
                        return -1;
                    }
                    ++vi;
                }
            }
        }


        if(!requiredOptions.empty())
            ret = checkRequiredOptions();
    }

    return ret;
}
Example #22
0
int main() {
    //Do forks and stuff to run as a service
    daemonize();
    syslog(LOG_INFO, "%s version %d started.", PROGRAM_NAME, PROGRAM_VERSION);
    
    //Reading the configuration
    setDefault(&config);
    if (parseConfigFile(&config) == 0) {
        if (checkConfig(&config) == 0) {
            /*
            syslog(LOG_INFO, "%s %s", VIDEO_SAVE_DIRECTORY, config.VideoSaveDirectory);
            syslog(LOG_INFO, "%s %s", THUMBNAIL_SAVE_DIRECTORY, config.ThumbnailSaveDirectory);
            syslog(LOG_INFO, "%s %s", FFMPEG_PATH, config.ffmpegPath);
            syslog(LOG_INFO, "%s %lu", MINIMUM_FREE_DISK_SPACE, config.MinimumFreeDiskSpace);
            syslog(LOG_INFO, "%s %s", RASPIVID_ROTATION, config.RaspividRotation);
            syslog(LOG_INFO, "%s %s", RASPIVID_WIDTH, config.RaspividWidth);
            syslog(LOG_INFO, "%s %s", RASPIVID_HEIGHT, config.RaspividHeight);
            syslog(LOG_INFO, "%s %s", RASPIVID_CRF, config.RaspividCRF);
            syslog(LOG_INFO, "%s %s", RASPIVID_PREVIEW, config.RaspividPreview);
            syslog(LOG_INFO, "%s %s", RASPIVID_FRAMERATE, config.RaspividFramerate);
            syslog(LOG_INFO, "%s %s", RASPIVID_SEGMENT_DURATION, config.RaspividSegmentDuration);
            syslog(LOG_INFO, "%s %s", RASPIVID_INTRAFRAME_INTERVAL, config.RaspividIntraframeInterval);
            syslog(LOG_INFO, "%s %s", RASPIVID_EXPOSURE, config.RaspividExposure);
            syslog(LOG_INFO, "%s %s", RASPIVID_WHITEBLANCE, config.RaspividAWB);
            syslog(LOG_INFO, "%s %s", RASPIVID_METERING, config.RaspividMetering);
            syslog(LOG_INFO, "%s %s", RASPIVID_PROFILE, config.RaspividProfile);
            syslog(LOG_INFO, "%s %s", THUMBNAIL_WIDTH, config.ThumbnailWidth);
            syslog(LOG_INFO, "%s %s", THUMBNAIL_FORMAT, config.ThumbnailFormat);
            syslog(LOG_INFO, "%s %s", THUMBNAIL_OPTIONS, config.ThumbnailOptions);
            syslog(LOG_INFO, "%s %s", TEMPORARY_DIRECTORY, config.TemporaryDirectory);
            syslog(LOG_INFO, "%s %hho", NUMBER_TEMPORARY_RAW_FILES, config.NumberTemporaryRawFiles);
            */
            
            //Creating directories
            mkdir(config.TemporaryDirectory, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
            mkdir(config.VideoSaveDirectory, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
            mkdir(config.ThumbnailSaveDirectory, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

            //Muxing and removing any h264 files in temp folder
            muxAll();
            
            //While there's not enough free space, delete old videos
            unsigned long long freeSpace = getFreeSpace(config.VideoSaveDirectory);
            while (freeSpace < config.MinimumFreeDiskSpace) {
                deleteOldestVideo();
                freeSpace = getFreeSpace(config.VideoSaveDirectory);
            }
            
            //Start the camera
            raspivid = startCamera(&config);
            if (raspivid > 0) {
                syslog(LOG_INFO, "Raspivid started with pid %d.", raspivid);

                //Waiting for a bit to get a little behind the camera
                sleep(1);

                //Main loop
                run = 1;
                while (run) {
                    //Wait some time before looking for raw files
                    sleep(20);

                    //While there's not enough free space, delete old videos
                    unsigned long long freeSpace = getFreeSpace(config.VideoSaveDirectory);
                    while (freeSpace < config.MinimumFreeDiskSpace) {
                        deleteOldestVideo();
                        freeSpace = getFreeSpace(config.VideoSaveDirectory);
                    }

                    //Mux and delete h264 files that aren't being recorded to
                    checkForReadyh264Files();
                }
            } else {
                syslog(LOG_ERR, "Error starting raspivid.", raspivid);
            }
        }
    }
    
    //Freeing up memory from config struct
    freeConfig(&config);
    
    syslog(LOG_NOTICE, "%s terminated.", PROGRAM_NAME);
    closelog();
    
    return (EXIT_SUCCESS);
}
Example #23
0
int DOTCONFDocument::setContent(const char * _fileName)
{
    int ret = 0;
    char realpathBuf[PATH_MAX];

    if(realpath(_fileName, realpathBuf) == NULL) {
        error(0, NULL, "realpath(%s) failed: %s", _fileName, strerror(errno));
        return -1;
    }

    fileName = strdup(realpathBuf);

    processedFiles.push_back(strdup(realpathBuf));

    if(( file = fopen(fileName, "r")) == NULL) {
        error(0, NULL, "failed to open file '%s': %s", fileName, strerror(errno));
        return -1;
    }

    ret = parseFile();

    (void) fclose(file);

    if(!ret) {

        if( (ret = checkConfig(nodeTree.begin())) == -1) {
            return -1;
        }

        std::list<DOTCONFDocumentNode*>::iterator from;
        DOTCONFDocumentNode * tagNode = NULL;
        int vi = 0;
        for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i!=nodeTree.end(); i++) {
            tagNode = *i;
            if(!cmp_func("DOTCONFPPIncludeFile", tagNode->name)) {
                vi = 0;
                while( vi < tagNode->valuesCount ) {
                    if(access(tagNode->values[vi], R_OK) == -1) {
                        error(tagNode->lineNum, tagNode->fileName, "%s: %s", tagNode->values[vi], strerror(errno));
                        return -1;
                    }
                    if(realpath(tagNode->values[vi], realpathBuf) == NULL) {
                        error(tagNode->lineNum, tagNode->fileName, "realpath(%s) failed: %s", tagNode->values[vi], strerror(errno));
                        return -1;
                    }

                    bool processed = false;
                    for(std::list<char*>::const_iterator itInode = processedFiles.begin(); itInode != processedFiles.end(); itInode++) {
                        if(!strcmp(*itInode, realpathBuf)) {
                            processed = true;
                            break;
                        }
                    }
                    if(processed) {
                        break;
                    }

                    processedFiles.push_back(strdup(realpathBuf));

                    file = fopen(tagNode->values[vi], "r");
                    if(file == NULL) {
                        error(tagNode->lineNum, fileName, "failed to open file '%s': %s", tagNode->values[vi], strerror(errno));
                        return -1;
                    }

                    fileName = strdup(realpathBuf);
                    from = nodeTree.end();
                    from--;

                    ret = parseFile();
                    (void) fclose(file);
                    if(ret == -1)
                        return -1;
                    if(checkConfig(++from) == -1) {
                        return -1;
                    }
                    vi++;
                }
            }
        }


        if(!requiredOptions.empty())
            ret = checkRequiredOptions();
    }

    return ret;
}
Example #24
0
int
main(int argc, char **argv)
{
	int get;
	int opt_index = 0;          /* for getopt */
	char *cc_string = NULL;
	char *bcc_string = NULL;
	const char *opts = "f:n:a:p:oVedvtb?c:s:r:u:i:g:m:H:x:";

	/* Set certian global options to NULL */
	conf_file = NULL;
	memset(&Mopts, 0, sizeof(struct mailer_options));
	Mopts.encoding = true;

	/* Check if they need help */
	if ((argc > 1) && (!strcmp(argv[1], "-h") ||
		!strcmp(argv[1], "-help") || !strcmp(argv[1], "--help"))) {
		if (argc == 3) {
			moduleUsage(argv[2]);
		} else if (argc == 2) {
			usage();
		} else {
			fprintf(stderr, "Only specify one option with %s: \n", argv[1]);
			usage();
		}
	}

	table = dhInit(28, defaultDestr);
	if (!table) {
		fprintf(stderr, "ERROR: Could not initialize Hash table.\n");
		exit(0);
	}

	while ((get = getopt_long_only(argc, argv, opts, Gopts, &opt_index)) > EOF) {
		switch (get) {
		case 'n':
			setConfValue("MY_NAME", xstrdup(optarg));
			break;
		case 'f':
			setConfValue("MY_EMAIL", xstrdup(optarg));
			break;
		case 'a':
			if (!Mopts.attach) {
				Mopts.attach = dlInit(defaultDestr);
			}
			dlInsertTop(Mopts.attach, xstrdup(optarg));
			break;
		case 'V':
			Mopts.verbose = true;
			break;
		case 'p':
			setConfValue("SMTP_PORT", xstrdup(optarg));
			break;
		case 'o':
			Mopts.priority = 1;
			break;
		case 'e':
			Mopts.gpg_opts |= GPG_ENC;
			break;
		case 's':
			Mopts.subject = optarg;
			break;
		case 'r':
			setConfValue("SMTP_SERVER", xstrdup(optarg));
			break;
		case 'c':
			conf_file = optarg;
			break;
		case 't':
			checkConfig();
			printf("Configuration file is proper.\n");
			dhDestroy(table);
			return (0);
			break;
		case 'v':
			printf("email - By Dean Jones; Version %s\n", EMAIL_VERSION);
			dhDestroy(table);
			exit(EXIT_SUCCESS);
			break;
		case 'b':
			Mopts.blank = 1;
			break;
		case 'u':
			setConfValue("SMTP_AUTH_USER", xstrdup(optarg));
			break;
		case 'i':
			setConfValue("SMTP_AUTH_PASS", xstrdup(optarg));
			break;
		case 'm':
			setConfValue("SMTP_AUTH", xstrdup(optarg));
			break;
		case 'g':
			setConfValue("GPG_PASS", xstrdup(optarg));
			break;
		case 'H':
			if (!Mopts.headers) {
				Mopts.headers = dlInit(defaultDestr);
			}
			dlInsertTop(Mopts.headers, xstrdup(optarg));
			break;
		case 'x':
			setConfValue("TIMEOUT", xstrdup(optarg));
			break;
		case '?':
			usage();
			break;
		case 1:
			Mopts.html = 1;
			break;
		case 2:
			Mopts.gpg_opts |= GPG_SIG;
			break;
		case 3:
			cc_string = optarg;
			break;
		case 4:
			bcc_string = optarg;
			break;
		case 5:
			/* To name? */
			break;
		case 6:
			setConfValue("USE_TLS", xstrdup("true"));
			break;
		case 7:
			Mopts.encoding = false;
			break;
		default:
			/* Print an error message here  */
			usage();
			break;
		}
	}

	/* first let's check to make sure they specified some recipients */
	if (optind == argc) {
		usage();
	}

	configure();

	/* Check to see if we need to attach a vcard. */
	if (getConfValue("VCARD")) {
		dstrbuf *vcard = expandPath(getConfValue("VCARD"));
		if (!Mopts.attach) {
			Mopts.attach = dlInit(defaultDestr);
		}
		dlInsertTop(Mopts.attach, xstrdup(vcard->str));
		dsbDestroy(vcard);
	}

	/* set to addresses if argc is > 1 */
	if (!(Mopts.to = getNames(argv[optind]))) {
		fatal("You must specify at least one recipient!\n");
		properExit(ERROR);
	}

	/* Set CC and BCC addresses */
	if (cc_string) {
		Mopts.cc = getNames(cc_string);
	}
	if (bcc_string) {
		Mopts.bcc = getNames(bcc_string);
	}

	signal(SIGTERM, properExit);
	signal(SIGINT, properExit);
	signal(SIGPIPE, properExit);
	signal(SIGHUP, properExit);
	signal(SIGQUIT, properExit);

	createMail();
	properExit(0);

	/* We never get here, but gcc will whine if i don't return something */
	return 0;
}
Example #25
0
/**
 * configuration parser
 *
 * @param pConf     ServerConfig structure
 * @param pszFilePath   file path of egis.conf
 * @return true if successful otherwise returns false
 */
bool loadConfig(struct ServerConfig *pConf, char *pszFilePath)
{
    if (pszFilePath == NULL || !strcmp(pszFilePath, "")) {
        return false;
    }

    // parse configuration file
    qlisttbl_t *conflist = qconfig_parse_file(NULL, pszFilePath, '=', true);
    if (conflist == NULL) {
        DEBUG("Can't open file %s", pszFilePath);
        return false;
    }

    // copy to structure
    qstrcpy(pConf->szConfigFile, sizeof(pConf->szConfigFile), pszFilePath);

    fetch2Str(conflist, pConf->szPidFile, "PidFile");
    fetch2Str(conflist, pConf->szMimeFile, "MimeFile");

    fetch2Int(conflist, pConf->nPort, "Port");

    fetch2Int(conflist, pConf->nStartServers, "StartServers");
    fetch2Int(conflist, pConf->nMinSpareServers, "MinSpareServers");
    fetch2Int(conflist, pConf->nMaxSpareServers, "MaxSpareServers");
    fetch2Int(conflist, pConf->nMaxIdleSeconds, "MaxIdleSeconds");
    fetch2Int(conflist, pConf->nMaxClients, "MaxClients");
    fetch2Int(conflist, pConf->nMaxRequestsPerChild, "MaxRequestsPerChild");

    fetch2Bool(conflist, pConf->bEnableKeepAlive, "EnableKeepAlive");
    fetch2Int(conflist, pConf->nMaxKeepAliveRequests, "MaxKeepAliveRequests");

    fetch2Int(conflist, pConf->nConnectionTimeout, "ConnectionTimeout");
    fetch2Bool(conflist, pConf->bIgnoreOverConnection, "IgnoreOverConnection");
    fetch2Int(conflist, pConf->nResponseExpires, "ResponseExpires");

    fetch2Str(conflist, pConf->szDocumentRoot, "DocumentRoot");

    fetch2Str(conflist, pConf->szAllowedMethods, "AllowedMethods");

    fetch2Str(conflist, pConf->szDirectoryIndex, "DirectoryIndex");

    fetch2Bool(conflist, pConf->bEnableLua, "EnableLua");
    fetch2Str(conflist, pConf->szLuaScript, "LuaScript");

    fetch2Bool(conflist, pConf->bEnableStatus, "EnableStatus");
    fetch2Str(conflist, pConf->szStatusUrl, "StatusUrl");

    fetch2Str(conflist, pConf->szErrorLog, "ErrorLog");
    fetch2Str(conflist, pConf->szAccessLog, "AccessLog");
    fetch2Int(conflist, pConf->nLogRotate, "LogRotate");
    fetch2Int(conflist, pConf->nLogLevel, "LogLevel");

    // check config
    checkConfig(pConf);

    //
    // free resources
    //
    conflist->free(conflist);

    return true;
}
Example #26
0
void
loop ()
{
  // event interface
  int fd = -1;			/* the file descriptor for the device */
  int i;			/* loop counter */
  size_t read_bytes;		/* how many bytes were read */
  struct input_event ev[64];	/* the events (up to 64 at once) */
  int key;			/*key code */
  /* used if event hit fn */
  int hasSomething;

#ifdef HAVE_LIBXOSD
  // prepare queue handling
  int flag = 0, brightness = 0, sound = 0;
  createqueue ();
#endif
  
  if (strcasecmp(devinput,"AUTO")==0) { // try to figure out rigth event value for keyboard
	  snprintf(devinput,MAX_DEVINPUT_SIZE,"/dev/input/event%d",getItemEvent(DEFAULT_KEYBOARD_NAME));
	  syslog(LOG_INFO,"autodevice determines %s as keyboard event",devinput);
  }
  
  if ((fd = open (devinput, O_RDONLY)) < 0)
    {
      syslog (LOG_CRIT,"event interface (%s) open failed: %m",devinput);
      // shoot auto as LAST chance
      snprintf(devinput,MAX_DEVINPUT_SIZE,"/dev/input/event%d",getItemEvent(DEFAULT_KEYBOARD_NAME));
      syslog(LOG_CRIT,"autodevice determines %s as a last chance keyboard event",devinput);
      if ((fd = open (devinput, O_RDONLY)) < 0)
        {
	      syslog(LOG_CRIT,"Event interface (%s) open failed: %m",devinput);
              cleanExit(EXIT_FAILURE);
	}
    }

  /* handle important signal */
  if (signal(SIGTERM,signal_handler) < 0)
    {
      perror("signal");
      exit(EXIT_FAILURE);
    }
  if (signal(SIGHUP,signal_handler) < 0)
    {
      perror("signal");
      exit(EXIT_FAILURE);
    }

  syslog(LOG_INFO,"fsfn loaded");


  while (1)
    {				/* loop */
      hasSomething = 0;		/* nothing yet */

      /*
       * read the event interface 
       */
      if ( (read_bytes = read (fd, ev, sizeof (struct input_event) * 64))==-1) {
	      //fprintf(stderr,"Error: %d\n",errno);
	      if (errno==ENODEV) { // event is now invalid ? must be back from sleep...
		      syslog(LOG_NOTICE,"Start sleeping...");
		      sleep(10);		      
		      syslog(LOG_NOTICE,"End sleeping...");

		      close(fd); // is this needed ??
		      
		      syslog(LOG_NOTICE,"Input device changed, back from suspend ?: %m");
		      
		      // get new event
		      snprintf(devinput,MAX_DEVINPUT_SIZE,"/dev/input/event%d",getItemEvent(DEFAULT_KEYBOARD_NAME));
      		      syslog(LOG_NOTICE,"autodevice determines %s as new event",devinput);
		      
		      // reopen - seems to be problems after a hibernate :(
      		      if ((fd = open (devinput, O_RDONLY)) < 0)
        	        {
				syslog(LOG_CRIT,"New event interface (%s) open failed: %m",devinput); 
				cleanExit(EXIT_FAILURE);
			}
		      // read it
		      if ((read_bytes = read (fd, ev, sizeof (struct input_event) * 64))==-1) 
		        {
				syslog(LOG_CRIT,"Reading new device (%s) failed: %m",devinput);
				cleanExit(EXIT_FAILURE);
		        }
	      }
	      else {
		      syslog(LOG_CRIT,"Input device reading failed: %m");
		      cleanExit(EXIT_FAILURE);
	      }
	}
      	
      if (read_bytes < (int) sizeof (struct input_event))
	{
	  syslog (LOG_CRIT,"short read: %m");
	  cleanExit(EXIT_FAILURE);
	}
      
      /*
       * Loop for all readed events until we have something
       * interesting.. 
       */
      for (i = 0;
	   !hasSomething
	   && (i < (int) (read_bytes / sizeof (struct input_event))); i++)
	{
	  hasSomething = (ev[i].type == FN_INPUT_TYPE)
	    && (ev[i].code == FN_INPUT_CODE)
	    && (ev[i].value == FN_INPUT_VALUE);
	}
      
      /*
       * If we got a FN event, plz do something... 
       */
      if (hasSomething && (key = getCodes ()))
	{
	  if ((key & FN_F5) == FN_F5)
	    { 
	      	// check config
	      	if (!checkConfig("F5_CMD"))
		  {
	      		// lower brightness
#ifdef HAVE_LIBXOSD
	      		flag = MOD_BRIGHTNESS;
	      		brightness = setBrightness (getBrightness () - 1);
	      		sendmsg (flag, brightness, sound);
			sendcmd (FN_F5);
#else
	      		setBrightness (getBrightness () - 1);
#endif
		  }
	    }
	  if ((key & FN_F6) == FN_F6)
	    {
	    	// check config
		if (!checkConfig("F6_CMD")) 
		  {
		  	
	    		// higher brightness
#ifdef HAVE_LIBXOSD
	      		flag = MOD_BRIGHTNESS;
	      		brightness = setBrightness (getBrightness () + 1);
	      		sendmsg (flag, brightness, sound);
			sendcmd (FN_F6);
#else
	      		setBrightness (getBrightness () + 1);
#endif
		  }
	    }

	  if ((key & FN_F2) == FN_F2)
	    {
		// check config
		if (!checkConfig("F2_CMD"))
		  {
#ifdef HAVE_LIBXOSD
	      		flag = MOD_SOUND;
	      		sound = mute (SOUND_STEP);
	      		sendmsg (flag, brightness, sound);
			sendcmd(FN_F2);
#else
	      		mute (SOUND_STEP);			
#endif
		  }
	    }
	  if ((key & FN_F3) == FN_F3)
	    {
		if (!checkConfig("F3_CMD"))
	          {
#ifdef HAVE_LIBXOSD
	      		flag = MOD_SOUND;
	      		sound = volume_down (SOUND_STEP);	//mod by SilSha
	      		sendmsg (flag, brightness, sound);
			sendcmd(FN_F3);
#else
	      		volume_down (SOUND_STEP);
#endif
		  }
	    }
	  if ((key & FN_F4) == FN_F4)
	    {
	       if (!checkConfig("F4_CMD"))
	         {
#ifdef HAVE_LIBXOSD
	      		flag = MOD_SOUND;
	      		sound = volume_up (SOUND_STEP);		//mod by SilSha
	      		sendmsg (flag, brightness, sound);
			sendcmd(FN_F4);
#else
	      		volume_up (SOUND_STEP);
#endif
		 }	
	    }
	 /* NO built in commands */
	  if ((key & FN_F7) == FN_F7)
	    {
#ifdef HAVE_LIBXOSD
	      if (!checkConfig("F7_CMD"))
		sendcmd(FN_F7);
#else
	      sendcmd(FN_F7);
#endif
	    }
	  if ((key & FN_F10) == FN_F10)
	    {
#ifdef HAVE_LIBXOSD
	      if(!checkConfig("F10_CMD"))
		sendcmd(FN_F10);
#else
	      sendcmd(FN_F10);
#endif
	    }
	  if ((key & FN_F12) == FN_F12)
	    {
#ifdef HAVE_LIBXOSD
	      if (!checkConfig("F12_CMD"))
		sendcmd(FN_F12);
#else
	      checkConfig("F12_CMD");
#endif
	    }
	  if (( key & S1_BTN) == S1_BTN) 
	    {
#ifdef HAVE_LIBXOSD
	      if (!checkConfig("S1_CMD"))
		sendcmd(S1_BTN);
#else
	      checkConfig("S1_CMD");
#endif
	    }
	  if (( key & S2_BTN) == S2_BTN)
	    {
#ifdef HAVE_LIBXOSD
	      if (!checkConfig("S2_CMD"))
		sendcmd(S2_BTN);
#else
	      checkConfig("S2_CMD");
#endif
	    }		  
	}
    }// while
}
Example #27
0
void
loopcmd()
{
  int cmd;
  if (loadqueue ()!=-1) {
    while (1 == 1) {
      if (getcmd(&cmd)==-1) {
	break;
      }
#ifdef USE_MORECONF      
      if (cmd==FN_F5)	    checkConfig("F5_CMD");
      else if (cmd==FN_F6) checkConfig("F6_CMD");
      else if (cmd==FN_F2)  checkConfig("F2_CMD");
      else if (cmd==FN_F3)  checkConfig("F3_CMD");
      else if (cmd==FN_F4)  checkConfig("F4_CMD"); 
      else if (cmd==FN_F7)  checkConfig("F7_CMD");
      else if (cmd==FN_F10) checkConfig("F10_CMD");
      else if (cmd==FN_F12) checkConfig("F12_CMD");
      else if (cmd==S1_BTN) checkConfig("S1_CMD");
      else if (cmd==S2_BTN) checkConfig("S2_CMD");
      else syslog(LOG_INFO,"Unknow cmd send: %d\n",cmd); 
#else
      switch(cmd) {
      case FN_F5: checkConfig("F5_CMD"); break;
      case FN_F6: checkConfig("F6_CMD"); break;
      case FN_F2: checkConfig("F2_CMD"); break;
      case FN_F3: checkConfig("F3_CMD"); break;
      case FN_F4: checkConfig("F4_CMD"); break;
      case FN_F7: checkConfig("F7_CMD"); break;
      case FN_F10:checkConfig("F10_CMD"); break;
      case FN_F12:checkConfig("F12_CMD"); break;
      case S1_BTN:checkConfig("S1_CMD"); break;
      case S2_BTN:checkConfig("S2_CMD"); break;
      default:
	syslog(LOG_INFO,"Unknow cmd send: %d\n",cmd);
	break;
      }
#endif
    }
  }
}
Example #28
0
int main(int argc, char* argv[])
{
	srand((unsigned int)time(0));

	int xres = 1024;
	int yres = 768;

	bool usePatch = true;

	for(int i = 1; i < argc; ++i)
	{
		if(!strcmp(argv[i], "-f")) 
			fullscreen = 1;
		else if(!strcmp(argv[i], "-w")) 
			fullscreen = 0;
		else if(!strcmp(argv[i], "-1024") || !strcmp(argv[i], "-1024x768"))
		{
			xres = 1024;
			yres = 768;
		}
		else if(!strcmp(argv[i], "-1280") || !strcmp(argv[i], "-1280x1024"))
		{
			xres = 1280;
			yres = 1024;
		}
		else if(!strcmp(argv[i], "-1280x960"))
		{
			xres = 1280;
			yres = 960;
		}
		else if(!strcmp(argv[i], "-1400") || !strcmp(argv[i], "-1400x1050"))
		{
			xres = 1400;
			yres = 1050;
		}
		else if(!strcmp(argv[i], "-1280x800"))
		{
			xres = 1280;
			yres = 800;
		}
		else if(!strcmp(argv[i], "-1600") || !strcmp(argv[i], "-1600x1200"))
		{
			xres = 1600;
			yres = 1200;
		}
		else if(!strcmp(argv[i], "-1920") || !strcmp(argv[i], "-1920x1200"))
		{
			xres = 1920;
			yres = 1200;
		}
		else if(!strcmp(argv[i], "-2048") || !strcmp(argv[i], "-2048x1536"))
		{
			xres = 2048;
			yres = 1536;
		}
		
		else if(!strcmp(argv[i], "-p"))
			usePatch = true;
		else if(!strcmp(argv[i], "-np"))
			usePatch = false;
	}

	checkConfig();

	/*if(!loadPath())
	{
		getGamePath();
	}
	else
	{
		getGamePath() = loadPath();
	}*/

	getGamePath();
	CreateStrips();

	gLog("[World of Warcraft Studio - Editor] - " APP_TITLE " : " APP_VERSION "\n[World of Warcraft Studio - Editor] - Game path: %s\n[World of Warcraft Studio - Editor] - Game Version: %d\n", gamepath, loadGameVersion());
	GraphicCard(); // Send to Log info about Graphic Card

	checkConfig2();

	vector<string> archiveNames;
	fillArchiveNameVector(archiveNames);
	for(size_t i = 0; i < archiveNames.size(); ++i)
		MPQArchive *archive = new MPQArchive(archiveNames[i].c_str());

	if(gOpenArchives.empty())
	{
		gLog("[World of Warcraft Studio - Editor] - ERROR: No one archive found");
		return 1;
	}

	gAreaDB.open();

	video.init(xres, yres, fullscreen != 0);

	gLog("[World of Warcraft Studio - Editor] - Initializing Ground Effects\n");
	InitGroundEffects();
	gLog("[World of Warcraft Studio - Editor] - Initializing Fonts\n");
	InitFonts();
	gLog("[World of Warcraft Studio - Editor] - Main Initializing complete\n");

	float ftime;
	uint32 t, last_t, frames = 0, time = 0, fcount = 0, ft = 0;
	AppState* as;
	gFPS = 0;

	gLog("[World of Warcraft Studio - Editor] - Creating Menu\n");
	Menu* m = new Menu();
	as = m;

	gStates.push_back(as);

	if(glExtGetGLProcs_VertexProgram_1_0_ARB() == 0)
	{
		gLog("[World of Warcraft Studio - Editor] - Unable to load ARB Vertex Program Code\n");
		return 0;
	}
	loadWaterShader();

	bool done = false;
	t = SDL_GetTicks();
	gLog("[World of Warcraft Studio - Editor] - Entering Main Loop\n");
	while(gStates.size() > 0 && !done)
	{
		last_t = t;
		t = SDL_GetTicks();
		Uint32 dt = t - last_t;
		time += dt;
		ftime = time / 1000.0f;

		as = gStates[gStates.size()-1];

		SDL_Event event;
		while(SDL_PollEvent(&event))
		{
			if(event.type == SDL_QUIT)
				done = true;
			else if(event.type == SDL_MOUSEMOTION)
			{
				if(SDL_GetAppState()&SDL_APPMOUSEFOCUS)
					as->mousemove(&event.motion);
			}
			else if((event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP) && (SDL_GetAppState()&SDL_APPINPUTFOCUS))
			{	
				if(event.button.type == SDL_MOUSEBUTTONUP)
					as->mouseclick(&event.button);
				else if(SDL_GetAppState()&SDL_APPMOUSEFOCUS)
					as->mouseclick(&event.button);
			}
			else if(event.type == SDL_KEYDOWN || event.type == SDL_KEYUP)
			{
				if(SDL_GetAppState()&SDL_APPINPUTFOCUS)
					as->keypressed(&event.key);
			}
			else if(event.type == SDL_VIDEORESIZE)
				video.resize(event.resize.w, event.resize.h);
		}

		if(SDL_GetAppState()&SDL_APPACTIVE)
		{
			as->tick(ftime, dt / 1000.0f);
			as->display(ftime, dt / 1000.0f);
		}

		if(gPop) 
		{
			gPop = false;
			gStates.pop_back();
			delete as;
		}

		frames++;
		fcount++;
		ft += dt;
		
		if(ft >= 1000)
		{
            float fps = (float)fcount / (float)ft * 1000.0f;
			gFPS = fps;
			char buf[32];
			sprintf_s(buf, APP_TITLE " - %.2f fps", fps);
			SDL_WM_SetCaption(buf, NULL);
            ft = 0;
			fcount = 0;
		}

		video.flip();
	}
	gLog("[World of Warcraft Studio - Editor] - Exited Main Loop\n");

	deleteFonts();
	
	video.close();

	for(deque<MPQArchive*>::iterator it = archives.begin(); it != archives.end(); ++it)
        (*it)->close();
		
	archives.clear();

	gLog("\n[World of Warcraft Studio - Editor] - Exiting.\n");

	return 0;
}
Example #29
0
int sc_main(int argc, char ** argv){
	sc_report_handler::set_actions("/IEEE_Std_1666/deprecated", SC_DO_NOTHING);
	system("set SC_SIGNAL_WRITE_CHECK=\"DISABLE\"");

	printHeader();

	for (int i = 1; i< argc; i++)
	{
		string args = string(argv[i]);
		if (args == "-f")
		{
			i++;
			if (i<argc && argv[i][0] !='-')
				ga_configPath = string(argv[i]);
			else {
				cout << "Argument to '-f' is missing" << endl; 
				return 0;
			}
		}
		else if (args == "-e")
		{
			i++;
			if (i<argc && argv[i][0] !='-')
				ga_elfPath = string(argv[i]);
			else {
				cout << "Argument to '-e' is missing" << endl; 
				return 0;
			}
		}
		else{
			cout << args <<" Recognized option" << endl;
			return 0;
		}
	}
	
	char nirgamHomeTempStr[100];
	g_nirgamHome = rwDirInLinuxStyl(string(getcwd(nirgamHomeTempStr, 100)));
	g_configHome = getDirOfFile(ga_configPath);
	if(loadConfig(ga_configPath) == false)
		return 1;
	if(checkConfig() ==  false)
		return 1;
	printConfig(cout);

	tryDir(gc_resultHome);

	g_clkPeriod = 1/gc_simFreq;
	g_simPeriod = g_clkPeriod * gc_simNum;
	g_clock = new sc_clock("NW_CLOCK",g_clkPeriod, SC_NS);
	g_a = analyze(gc_topoFile, cout);	
	if(g_a == NULL){
		cout << "Error occurred. Exit Simulation" << endl; return 1;
	}
	g_tileNum = g_a->nodeNum;


	if (gc_simMode == 1)
		initStandardMode();
	else if (gc_simMode == 2)
		initDebugMode();
	else if (gc_simMode == 3)
		initSelfcheckMode();

	NoC noc("noc", g_a);
	noc.switch_cntrl(*g_clock);

	g_tracker = new Tracker();
	g_tracker->addProbes(noc);
	g_tracker->printRouteTables();
//////////////////////////////////////////////////////////////////////////
// soclib tile
#ifdef SL_TILE
	if (gc_tileType == 1){
		cerr << "SLNIRGAM is used for soclib IP" << endl;
		return 1;
	}
	sc_start(sc_time(0, SC_NS));
	g_resetN = false;
	sc_start(sc_time(1, SC_NS));
	g_resetN = true;
#else
	if (gc_tileType == 2){
		cerr << "NIRGAM is used for generic IP" << endl;
		return 1;
	}
#endif
//////////////////////////////////////////////////////////////////////////

	if (gc_simMode == 1)
		doStandardMode();
	else if (gc_simMode == 2)
		doDebugMode();
	else if (gc_simMode == 3)
		doSelfcheckMode();

	if (gc_simMode == 1)
		finaStandardMode();
	else if (gc_simMode == 2)
		finaDebugMode();
	else if (gc_simMode == 3)
		finaSelfcheckMode();
}
bool mdtSerialPortPosix::open(mdtSerialPortConfig &cfg)
{
  QString strNum;

  // Close previous opened device
  this->close();
  // Try to open port
  //  O_RDWR : Read/write access
  //  O_NOCTTY: not a terminal
  //  O_NDELAY: ignore DCD signal
  lockMutex();
  // In read only mode, we handle no lock
  if(cfg.readOnly()){
    pvFd = ::open(pvName.toStdString().c_str(), O_RDONLY | O_NOCTTY | O_NONBLOCK);
  }else{
    pvFd = pvPortLock->openLocked(pvName, O_RDWR | O_NOCTTY | O_NONBLOCK);
  }
  if(pvFd < 0){
    pvPortLock->unlock();
    mdtError e(MDT_UNDEFINED_ERROR, "Unable to open port: " + pvName, mdtError::Error);
    e.setSystemError(errno, strerror(errno));
    MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix");
    e.commit();
    unlockMutex();
    return false;
  }
  // Get current config and save it to pvOriginalTermios
  if(tcgetattr(pvFd, &pvOriginalTermios) < 0){
    ::close(pvFd);
    pvFd = -1;
    pvPortLock->unlock();
    mdtError e(MDT_UNDEFINED_ERROR, "tcgetattr() failed, " + pvName + " is not a serial port, or is not available", mdtError::Error);
    e.setSystemError(errno, strerror(errno));
    MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix");
    e.commit();
    unlockMutex();
    return false;
  }
  // Get current system config on "work copy"
  if(tcgetattr(pvFd, &pvTermios) < 0){
    ::close(pvFd);
    pvFd = -1;
    pvPortLock->unlock();
    mdtError e(MDT_UNDEFINED_ERROR, "tcgetattr() failed, " + pvName + " is not a serial port, or is not available", mdtError::Error);
    e.setSystemError(errno, strerror(errno));
    MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix");
    e.commit();
    unlockMutex();
    return false;
  }
  // Set baud rate
  if(!setBaudRate(cfg.baudRate())){
    ::close(pvFd);
    pvFd = -1;
    pvPortLock->unlock();
    strNum.setNum(cfg.baudRate());
    mdtError e(MDT_UNDEFINED_ERROR, "unsupported baud rate '" + strNum + "' for port " + pvName, mdtError::Error);
    e.setSystemError(errno, strerror(errno));
    MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix");
    e.commit();
    unlockMutex();
    return false;
  }
  // Set local mode and enable the receiver
  pvTermios.c_cflag |= (CLOCAL | CREAD);
  // Set data bits
  if(!setDataBits(cfg.dataBitsCount())){
    ::close(pvFd);
    pvFd = -1;
    pvPortLock->unlock();
    strNum.setNum(cfg.dataBitsCount());
    mdtError e(MDT_UNDEFINED_ERROR, "unsupported data bits count '" + strNum + "' for port " + pvName, mdtError::Error);
    MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix");
    e.commit();
    unlockMutex();
    return false;
  }
  // Set stop bits
  if(!setStopBits(cfg.stopBitsCount())){
    ::close(pvFd);
    pvFd = -1;
    pvPortLock->unlock();
    strNum.setNum(cfg.stopBitsCount());
    mdtError e(MDT_UNDEFINED_ERROR, "unsupported stop bits count '" + strNum + "' for port " + pvName, mdtError::Error);
    MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix");
    e.commit();
    unlockMutex();
    return false;
  }
  // Set parity
  setParity(cfg.parity());
  // Set flow control
  setFlowCtlRtsCts(cfg.flowCtlRtsCtsEnabled());
  setFlowCtlXonXoff(cfg.flowCtlXonXoffEnabled(), cfg.xonChar(), cfg.xoffChar());
  // Set raw data mode
  pvTermios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
  pvTermios.c_oflag &= ~OPOST;
  // Apply the setup
  if(tcsetattr(pvFd, TCSANOW, &pvTermios) < 0){
    ::close(pvFd);
    pvFd = -1;
    pvPortLock->unlock();
    mdtError e(MDT_UNDEFINED_ERROR, "unable to apply configuration for port " + pvName, mdtError::Error);
    e.setSystemError(errno, strerror(errno));
    MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix");
    e.commit();
    unlockMutex();
    return false;
  }
  // Check if configuration could really be set
  if(!checkConfig(cfg)){
    ::close(pvFd);
    pvFd = -1;
    pvPortLock->unlock();
    unlockMutex();
    return false;
  }

  // Set the read/write timeouts
  setReadTimeout(cfg.readTimeout());
  setWriteTimeout(cfg.writeTimeout());

  return mdtAbstractPort::open(cfg);
}