int loadLabels(const char* fn) { int res = 1; QString path(fn); QString line; QString name; QStringList arr; QFile file; xAdr xadr; if (path.isEmpty()) path = QFileDialog::getOpenFileName(NULL, "Load SJASM labels"); if (path.isEmpty()) { res = 0; // no file specified } else { conf.labels.clear(); file.setFileName(path); if (file.open(QFile::ReadOnly)) { while(!file.atEnd()) { line = file.readLine(); arr = line.split(QRegExp("[: \r\n]"),QString::SkipEmptyParts); if (arr.size() > 2) { xadr.type = MEM_RAM; xadr.bank = arr.at(0).toInt(NULL,16); xadr.adr = arr.at(1).toInt(NULL,16) & 0x3fff; xadr.abs = (xadr.bank << 14) | xadr.adr; name = arr.at(2); switch (xadr.bank) { case 0xff: xadr.type = MEM_ROM; xadr.bank = -1; break; case 0x05: xadr.adr |= 0x4000; break; case 0x02: xadr.adr |= 0x8000; break; default: xadr.adr |= 0xc000; break; } if (xadr.bank > 0) xadr.bank = xadr.abs >> 8; conf.labels[name] = xadr; } } } else {
vector<QStringList> MainWindow::getFromCsv(QString path){ vector<QStringList> fileDate; QFile file; file.setFileName(path); file.open(QIODevice::ReadOnly); cout<<"FilePath - "<<path.toUtf8().constData()<<endl; while(!file.atEnd()){ QString str= file.readLine(); str.replace(',','.'); QStringList oneString=str.split(';'); cout<<str.toUtf8().constData()<<endl; fileDate.push_back(oneString); } file.close(); return fileDate; }
bool WorldFile::read_line(QFile & file, double & value) { char buffer[256]; if (-1 == file.readLine(buffer, sizeof (buffer))) { qDebug() << SG_PREFIX_E << "Failed to read line from file" << file.errorString(); return false; } bool ok = false; value = QString(buffer).toDouble(&ok); if (!ok) { qDebug() << SG_PREFIX_E << "Failed to convert" << buffer << "to double"; return false; } qDebug() << SG_PREFIX_I << "Read value" << value; return true; }
void WordList::init(const QString locale) { //Create 'Binary Tree' //QFile in(":/words.dict");//Assumed to be in alphabetical order already QFile in; if (locale=="fr") { in.setFileName(":/liste_fr.txt"); } else { in.setFileName(":/wordlist2.txt"); } bool opened = in.open(QFile::Text | QFile::ReadOnly); Q_ASSERT(opened); int c=0; char cur[LEN_MAX]; char curIdx[2];//Assumed all words have at least 2 letters curIdx[0] = ' '; curIdx[1] = ' '; m_words.clear(); while(in.readLine(cur,LEN_MAX) > 0) { //qDebug() << QString(cur).toLower().trimmed(); if(cur[0]=='\n' || cur[0]=='\0') continue; m_words << QString(cur).toLower().trimmed(); sprintf(dict[c],"%s", cur); if(curIdx[0] < cur[0]) { //Assumed each of the 26 letters starts at least one word curIdx[0] = cur[0]; curIdx[1] = 'a'; idx[(curIdx[0]-'a') * 26] = c; } while(curIdx[1] < cur[1]) { curIdx[1]++; Q_ASSERT(curIdx[1] >= 'a' && curIdx[1] <= 'z'); idx[(curIdx[0]-'a') * 26 + (curIdx[1] - 'a')] = c; } c++; } numWords = c; Q_ASSERT(m_words.count() == c);//Assumed no duplicates in.close(); }
dlgAboutIqr::dlgAboutIqr(QWidget* parent) : QDialog(parent) { setupUi(this); #ifdef _WINDOWS char *cwd = getcwd (NULL, 0); string strAppDir = cwd; #else string strAppDir; char * pcIQR_HOME = NULL; pcIQR_HOME = getenv ("IQR_HOME"); if (pcIQR_HOME!=NULL){ strAppDir = pcIQR_HOME; } else { strAppDir = "/usr/lib/iqr/"; } #endif QString qstrVersion = ""; QString qstrFilename = string(strAppDir + "/iqr.version").c_str(); QFile qfile (qstrFilename); if(qfile.exists()){ qfile.open( QIODevice::ReadOnly); char buf[1024]; qfile.readLine(buf, sizeof(buf) ); qfile.close(); qtxteditVersion->setText(buf ); } else { cerr << "iqr.version not found" << endl; } QString qstrMovieFile = string(strAppDir + "/iqr-logo-lg.gif").c_str(); qlblMovie->setMovie(new QMovie (qstrMovieFile)); if(qlblMovie->movie()!=NULL){ qlblMovie->movie()->setPaused(false); } }
void Animxmlparser::searchForVersion () { QFile * f = new QFile (m_traceFileName); if (f->open (QIODevice::ReadOnly | QIODevice::Text)) { QString firstLine = QString (f->readLine ()); int startIndex = 0; int endIndex = 0; QString versionField = VERSION_FIELD_DEFAULT; startIndex = firstLine.indexOf (versionField); endIndex = firstLine.lastIndexOf ("\""); if ((startIndex != -1) && (endIndex > startIndex)) { int adjustedStartIndex = startIndex + versionField.length (); QString v = firstLine.mid (adjustedStartIndex, endIndex-adjustedStartIndex); m_version = v.toDouble (); } f->close (); delete f; } }
QStringList SQLTextEdit::loadKeywords(const QString &driver) { QFile listfile; if (driver == "QSQLITE") listfile.setFileName(":/txt/keywords/sqlite-keywords.txt"); else if (driver == "QMYSQL") listfile.setFileName(":/txt/keywords/mysql-keywords.txt"); else if (driver == "QPSQL") listfile.setFileName(":/txt/keywords/postgresql-keywords.txt"); else return QStringList(); listfile.open(QIODevice::ReadOnly); QStringList list; QString line; while (!(line = listfile.readLine()).isEmpty()) { list << line.trimmed(); } return list; }
int main(int argc, char **argv) { #if !defined(Q_OS_WIN) // QtService stores service settings in SystemScope, which normally require root privileges. // To allow testing this example as non-root, we change the directory of the SystemScope settings file. QSettings::setPath(QSettings::NativeFormat, QSettings::SystemScope, QDir::tempPath()); qWarning("(Example uses dummy settings file: %s/QtSoftware.conf)", QDir::tempPath().toLatin1().constData()); #endif int result = processArgs(argc, argv); if (QString::fromLocal8Bit(argv[argc - 1]) == QLatin1String("-w") || QString::fromLocal8Bit(argv[argc - 1]) == QLatin1String("-wait")) { printf("\nPress Enter to continue..."); QFile input; input.open(stdin, QIODevice::ReadOnly); input.readLine(); printf("\n"); } return result; }
void Dialog::getSourceCodeStringsNumber() { QString str; QFile srcFile; for (ptrdiff_t i=0; i<files->count(); i++) { srcFile.setFileName(files->at(i)); srcFile.open(QIODevice::ReadOnly); while (!srcFile.atEnd()) { str = srcFile.readLine().trimmed(); if ( (!str.isEmpty()) && (!str.isNull()) ) { lines++; } } srcFile.close(); } }
void BasicMixedProviderPrivate::update(const QString &path, QMap <QString, QString> *data) { data->clear(); QFile file (path); if (!file.open(QIODevice::ReadOnly)) { return; } while (!file.atEnd()) { QString line = file.readLine(); QStringList lineSplitted = line.split(";"); if (lineSplitted.count() == 1) { data->insert(lineSplitted.at(0).trimmed(), QString()); } if (lineSplitted.count() == 2) { data->insert(lineSplitted.at(0).trimmed(), lineSplitted.at(1).trimmed()); } } file.close(); }
void TsunamiEvacModel::on_actionLoad_cost_grid_triggered() { QString fileName; fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), QDir::homePath(), tr("Image Files (*.csv)")); QList<QStringList> myMat; QFile file; file.setFileName(fileName); if(file.open(QIODevice::ReadOnly)) setStatus("File opened"); else setStatus("Could not open file"); while (!file.atEnd()){ QByteArray line = file.readLine(); QStringList temp; for(int i = 0; i < line.split(',').size(); i++) temp.append(line.split(',').at(i)); myMat.append(temp); } QString temp; delete myGrid; myGrid = new Grid(myMat.size(),myMat.at(1).size(),this); for(int i = 0; i < myMat.size(); i++){ for(int j = 0; j < myMat.at(i).size(); j++){ myGrid->setValue(i,j,myMat.at(i).at(j).toInt()); temp.append(myMat.at(i).at(j)); temp.append(" "); } temp.append("\n"); } ui->textBrowser->append(temp); }
void DictModel::load(QFile& file) { beginResetModel(); m_dicts.clear(); QByteArray bytes; while (!(bytes = file.readLine()).isEmpty()) { QString line = QString::fromUtf8(bytes).trimmed(); QStringList items = line.split(","); if (items.size() < m_requiredKeys.size()) { continue; } bool failed = false; QMap<QString, QString> dict; Q_FOREACH(const QString& item, items) { if (!item.contains('=')) { failed = true; break; } QString key = item.section('=', 0, 0); QString value = item.section('=', 1, -1); if (!m_requiredKeys.contains(key)) { continue; } dict[key] = value; } if (!failed && m_requiredKeys.size() == dict.size()) { m_dicts << dict; } } endResetModel(); }
void CLoaderRecipe::getRecipe() { QFile *file; QDir dir("recipe"); if (!dir.exists()) qWarning("Cannot find the example directory"); dir.setFilter(QDir::Files); QFileInfoList list = dir.entryInfoList(); for (int loop = 0; loop < list.size(); ++loop) { QFileInfo fileInfo = list.at(loop); file = new QFile(fileInfo.filePath()); file->open(QIODevice::ReadOnly | QIODevice::Text); QString line; while (!file->atEnd()) { line = file->readLine(); QStringList lineList = line.split(";"); if (lineList.size() == 6) recipeList.append(new CRecipe(lineList[0], lineList[1], lineList[2], lineList[3], lineList[4], lineList[5].remove("\n"), fileInfo.filePath())); } delete file; } }
QByteArray FcitxQtConnectionPrivate::localMachineId() { #if QT_VERSION >= QT_VERSION_CHECK(4, 8, 0) return QDBusConnection::localMachineId(); #else QFile file1("/var/lib/dbus/machine-id"); QFile file2("/etc/machine-id"); QFile* fileToRead = NULL; if (file1.open(QIODevice::ReadOnly)) { fileToRead = &file1; } else if (file2.open(QIODevice::ReadOnly)) { fileToRead = &file2; } if (fileToRead) { QByteArray result = fileToRead->readLine(1024); fileToRead->close(); result = result.trimmed(); if (!result.isEmpty()) return result; } return "machine-id"; #endif }
void MainWindow::getcpu() { QString tempStr; //读取文件信息字符串 QFile tempFile; //用于打开系统文件 int pos; //读取文件的位置 tempFile.setFileName("/proc/cpuinfo"); //打开CPU信息文件 if ( !tempFile.open(QIODevice::ReadOnly) ) { QMessageBox::warning(this, tr("warning"), tr("The cpuinfo file can not open!"), QMessageBox::Yes); return; } for(int i=0;i<10;i++) { tempStr = tempFile.readLine(); pos = tempStr.indexOf("model name"); if (pos != -1) { pos += 13; //跳过前面的"model name:"所占用的字符 QString *cpu_name = new QString( tempStr.mid(pos, tempStr.length()-13) ); fg5=cpu_name->contains("i5"); fg7=cpu_name->contains("i7"); } } }
bool PlaylistImporter::parsePlaylist_m3u(QFile &data, QStringList &fileList, const QDir &baseDir, const QDir &rootDir) { const QTextCodec *codec = QTextCodec::codecForName("System"); const bool preferUTF8 = data.fileName().endsWith(".m3u8", Qt::CaseInsensitive); bool foundAtLeastOneFile = false; data.reset(); while(!data.atEnd()) { QString filePath[3]; QByteArray line = data.readLine(); if(preferUTF8) { filePath[0] = QString(QDir::fromNativeSeparators(QString::fromUtf8(line.constData(), line.size()).trimmed())); filePath[1] = QString(QDir::fromNativeSeparators(codec->toUnicode(line.constData(), line.size()).trimmed())); filePath[2] = QString(QDir::fromNativeSeparators(QString::fromLatin1(line.constData(), line.size()).trimmed())); } else { filePath[0] = QString(QDir::fromNativeSeparators(codec->toUnicode(line.constData(), line.size()).trimmed())); filePath[1] = QString(QDir::fromNativeSeparators(QString::fromLatin1(line.constData(), line.size()).trimmed())); filePath[2] = QString(QDir::fromNativeSeparators(QString::fromUtf8(line.constData(), line.size()).trimmed())); } for(size_t i = 0; i < 3; i++) { if(!(filePath[i].isEmpty() || filePath[i].startsWith("#") || filePath[i].contains(QChar(QChar::ReplacementCharacter)))) { QFileInfo filename(filePath[i]); filename.setCaching(false); fixFilePath(filename, baseDir, rootDir); if(filename.exists() && filename.isFile()) { qDebug("Found: \"%s\"", filePath[i].toUtf8().constData()); if(isPlaylist(filename.canonicalFilePath()) == notPlaylist) { fileList << filename.canonicalFilePath(); } foundAtLeastOneFile = true; break; } } } } //If we did not find any files yet, try UTF-16 now if(!foundAtLeastOneFile) { const char* codecs[2] = {"UTF-16LE", "UTF-16BE"}; for(size_t i = 0; i < 2; i++) { QTextStream stream(&data); stream.setAutoDetectUnicode(false); stream.setCodec(codecs[i]); stream.seek(0i64); while(!stream.atEnd()) { QString filePath = stream.readLine().trimmed(); if(!(filePath.isEmpty() || filePath.startsWith("#") || filePath.contains(QChar(QChar::ReplacementCharacter)))) { QFileInfo filename(filePath); filename.setCaching(false); fixFilePath(filename, baseDir, rootDir); if(filename.exists() && filename.isFile()) { if(isPlaylist(filename.canonicalFilePath()) == notPlaylist) { fileList << filename.canonicalFilePath(); } foundAtLeastOneFile = true; } } } if(foundAtLeastOneFile) break; } } return true; }
//------------------------------------------------------------------------------ MetaInfo BibleQuoteModule::readInfo(QFile &file) { bool useShortName = false; m_moduleName.clear(); m_moduleShortName.clear(); int countlines = 0; QString encoding = getEncodingFromFile(file.fileName()); m_codec = QTextCodec::codecForName(encoding.toStdString().c_str()); QTextDecoder *decoder = m_codec->makeDecoder(); while(!file.atEnd()) { /*if (countlines > 50) { //wenn eine ini datei ungueltig ist soll damit nicht zuviel zeit verguedet werden break; }*/ QByteArray byteline = file.readLine(); QString line = decoder->toUnicode(byteline); if(!line.startsWith("//")) { countlines++; } else { continue; } if(line.contains("BibleName", Qt::CaseInsensitive) and m_moduleName.isEmpty()) { m_moduleName = formatFromIni(line. remove(QRegExp("BibleName(\\s*)=(\\s*)", Qt::CaseInsensitive))); if(m_moduleName.isEmpty()) { useShortName = true; } if(useShortName && !m_moduleShortName.isEmpty()) { break; } /// what is ? // else if(!useShortName) // { // break; // } } if(line.contains("BibleShortName", Qt::CaseInsensitive) and m_moduleShortName.isEmpty()) { m_moduleShortName = formatFromIni(line. remove(QRegExp("BibleShortName(\\s*)=(\\s*)", Qt::CaseInsensitive))); if(useShortName) break; } } file.close(); if(useShortName) { m_moduleName = m_moduleShortName; } if(m_moduleName.isEmpty()) { myWarning() << "invalid ini File " << file.fileName(); } MetaInfo ret; ret.setName(m_moduleName); ret.setShortName(m_moduleShortName); if (m_typeModule == "Apocrypha") ret.type = OBVCore::Type_BibleQuoteApocrypha; if (m_typeModule == "Comments") ret.type = OBVCore::Type_BibleQuoteComments; if (m_typeModule == "Bible") ret.type = OBVCore::Type_BibleQuoteModule; if (m_typeModule == "Book") ret.type = OBVCore::Type_BibleQuoteBook; return ret; return MetaInfo(); }
bool MOomc::startServer() { try { // evalMutex.unlock(); QString msg; const char *omhome = getenv("OPENMODELICAHOME"); QString omcPath; #ifdef WIN32 if (!omhome) { InfoSender::instance()->send(Info("OPEN_MODELICA_HOME_NOT_FOUND")); return false; } omcPath = QString( omhome ) + "bin/omc.exe"; #else /* unix */ omcPath = (omhome ? QString(omhome)+"bin/omc" : QString(CONFIG_DEFAULT_OPENMODELICAHOME) + "/bin/omc"); #endif // Check the IOR file created by omc.exe QFile objectRefFile; QString fileIdentifier; fileIdentifier = qApp->sessionId().append(QTime::currentTime().toString(tr("hh:mm:ss:zzz")).remove(":")); #ifdef WIN32 // Win32 objectRefFile.setFileName(QString(QDir::tempPath()).append(QDir::separator()).append("openmodelica.objid.").append(this->mName).append(fileIdentifier)); #else // UNIX environment char *user = getenv("USER"); if (!user) { user = "******"; } objectRefFile.setFileName(QString(QDir::tempPath()).append(QDir::separator()).append("openmodelica.").append(QString(user)).append(".objid.").append(this->mName).append(fileIdentifier)); #endif if (objectRefFile.exists()) objectRefFile.remove(); mObjectRefFile = objectRefFile.fileName(); // Start the omc.exe QStringList parameters; parameters << QString("+c=").append(mName).append(fileIdentifier) << QString("+d=interactiveCorba") << QString("+corbaObjectReferenceFilePath=").append(QDir::tempPath()); QProcess *omcProcess = new QProcess(); QFile omcOutputFile; #ifdef WIN32 // Win32 omcOutputFile.setFileName(QString(QDir::tempPath()).append(QDir::separator()).append("openmodelica.omc.output.").append(mName)); #else // UNIX environment omcOutputFile.setFileName(QString(QDir::tempPath()).append(QDir::separator()).append("openmodelica.").append(( QString(user))).append(".omc.output.").append(mName)); #endif omcProcess->setProcessChannelMode(QProcess::MergedChannels); omcProcess->setStandardOutputFile(omcOutputFile.fileName()); omcProcess->start(omcPath, parameters); // wait for the server to start. int ticks = 0; while (!objectRefFile.exists()) { SleeperThread::msleep(1000); ticks++; if (ticks > 20) { msg = "Unable to find " + OMCHelper::applicationName + " server, Object reference file " + mObjectRefFile + " not created."; throw std::runtime_error(msg.toStdString()); } } // ORB initialization. int argc = 2; static const char *argv[] = { "-ORBgiopMaxMsgSize", "10485760" }; CORBA::ORB_var orb = CORBA::ORB_init(argc, (char **)argv); objectRefFile.open(QIODevice::ReadOnly); char buf[1024]; objectRefFile.readLine( buf, sizeof(buf) ); QString uri( (const char*)buf ); CORBA::Object_var obj = orb->string_to_object(uri.trimmed().toLatin1()); mOMC = OmcCommunication::_narrow(obj); mHasInitialized = true; } catch(std::exception &e) { QString msg = e.what(); InfoSender::instance()->send(Info(msg,ListInfo::ERROR2)); mHasInitialized = false; return false; } catch (CORBA::Exception&) { QString msg = "Unable to communicate with OMC"; InfoSender::instance()->send(Info(msg,ListInfo::ERROR2)); mHasInitialized = false; return false; } evalCommand("getInstallationDirectoryPath()"); OMCHelper::OpenModelicaHome = StringHandler::removeFirstLastQuotes(getResult()); initTempDirectory(); // set the OpenModelicaLibrary variable. evalCommand("getModelicaPath()"); OMCHelper::OpenModelicaLibrary = StringHandler::removeFirstLastQuotes(getResult()); return true; }
void ODBCDialog::updateStatistics() { // Variables... int pidTotal = 0; bool statsFail = FALSE; int handleNum = 0; QString tempString; QString processUser = ""; QString processName = ""; QFile processFile; uid_t userID; struct passwd* passwdItem; // Set file name... processFile.setName("status"); // Get statistics... if (!statsHandle) { if (uodbc_open_stats(&statsHandle, UODBC_STATS_READ) != 0) { statsFail = TRUE; statsHandle = 0; } } if (statsFail == FALSE) { // Get stats for summary tab... if (uodbc_get_stats(statsHandle, -1, statsResult, 4) == 4) { // Get progress bars max value... if (statsResult[0].value.l_value > progressMaxValue) progressMaxValue = statsResult[0].value.l_value; if (statsResult[1].value.l_value > progressMaxValue) progressMaxValue = statsResult[1].value.l_value; if (statsResult[2].value.l_value > progressMaxValue) progressMaxValue = statsResult[2].value.l_value; if (statsResult[3].value.l_value > progressMaxValue) progressMaxValue = statsResult[3].value.l_value; // Set progress bars and label values... envProgress->setProgress(statsResult[0].value.l_value, progressMaxValue); envLabel->setText(QString::number(statsResult[0].value.l_value)); conProgress->setProgress(statsResult[1].value.l_value, progressMaxValue); conLabel->setText(QString::number(statsResult[1].value.l_value)); staProgress->setProgress(statsResult[2].value.l_value, progressMaxValue); staLabel->setText(QString::number(statsResult[2].value.l_value)); desProgress->setProgress(statsResult[3].value.l_value, progressMaxValue); desLabel->setText(QString::number(statsResult[3].value.l_value)); // Get stats for details tab... pidTotal = uodbc_get_stats(statsHandle, 0, pidResults, MAXPROCESSES); detailsTable->setNumRows(pidTotal); // Update stat details table... for (int pidNumber = 0; pidNumber < pidTotal; pidNumber++) { // Reset variables... processUser = ""; processName = ""; handleNum = uodbc_get_stats(statsHandle, pidResults[pidNumber].value.l_value, handleResult, MAXHANDLES); if (handleNum > 0) { // Get Process information (program name, username)... tempString = "/proc/"; tempString.append(QString::number(pidResults[pidNumber].value.l_value)); QDir::setCurrent(tempString); if (processFile.open(IO_ReadOnly)) { while ((processFile.atEnd() == FALSE) && ((processName.isEmpty() == TRUE) || (processUser.isEmpty() == TRUE))) { processFile.readLine(tempString, 500); if (tempString.contains("Name:") > 0) { processName = tempString.right(tempString.length() - 6); } if (tempString.contains("Uid:") > 0) { processUser = tempString.mid(5, (tempString.find((char)9, 6) - 5)); userID = processUser.toInt(); passwdItem = getpwuid(userID); processUser = passwdItem->pw_name; } } processFile.close(); } // Update the table... detailsTable->setText(pidNumber, 0, processUser); detailsTable->setText(pidNumber, 1, processName); detailsTable->setText(pidNumber, 2, QString::number(pidResults[pidNumber].value.l_value)); for (int handle = 0; handle < MAXHANDLES; handle++) { detailsTable->setText(pidNumber, handle + 3, QString::number(handleResult[handle].value.l_value)); } } else { clearDetailRow(pidNumber); } } } else { statsFail = TRUE; } } }
//===================================== // main program... //------------------------------------- int main(int argc,char*argv[]) { //===================================== // init variables... //------------------------------------- bool uniFont = false; bool noBorder = false; bool fastSetup = false; bool withDialog = false; bool yastMode = false; bool useHwData = false; bool fullScreen = false; bool setInfo = false; bool set3D = false; bool setXIdle = false; bool checkPacs = false; for (int n=0;n<argc;n++) { if (strcmp(argv[n],"-style") == 0) { globalStyle = (char*) malloc (sizeof(char) * 128); sprintf(globalStyle,"%s",argv[n+1]); break; } } //===================================== // check for root priviliges... //------------------------------------- if (! accessAllowed()) { fprintf (stderr,"xapi: only root can do this\n"); usage(); } //===================================== // start logging... //------------------------------------- logInit(); //===================================== // allocate main qt object... //------------------------------------- for (int i=0;i<argc;i++) { QString item (argv[i]); if ((item == "-h") || (item == "--help")) { logExit(); usage(); exit(0); } } QApplication app(argc,argv); //===================================== // get additional options... //------------------------------------- QString* idlePID = NULL; QString* cardName3D = NULL; QString* popUpDialog = NULL; QString* cardDriver = NULL; while (1) { int option_index = 0; static struct option long_options[] = { {"usehwdata" , 0 , 0 , 'u'}, {"fullscreen" , 0 , 0 , 'l'}, {"info" , 0 , 0 , 'i'}, {"yast" , 0 , 0 , 'y'}, {"checkpacs" , 0 , 0 , 'c'}, {"noborder" , 0 , 0 , 'n'}, {"3d" , 1 , 0 , 'D'}, {"driver" , 1 , 0 , 'd'}, {"frameWidth" , 1 , 0 , 'w'}, {"dialog" , 1 , 0 , 'O'}, {"unifont" , 0 , 0 , 'U'}, {"xidle" , 0 , 0 , 'x'}, {"pid" , 1 , 0 , 'p'}, {"fast" , 0 , 0 , 'f'}, {"help" , 0 , 0 , 'h'}, {0 , 0 , 0 , 0 } }; int c = getopt_long ( argc, argv, "uicD:fhxlw:d:yp:nUO:",long_options, &option_index ); if (c == -1) break; switch (c) { case 0: fprintf (stderr,"xapi: option %s", long_options[option_index].name); if (optarg) fprintf (stderr," with arg %s", optarg); fprintf (stderr,"\n"); break; case 'f': fastSetup = true; break; case 'U': uniFont = true; break; case 'O': withDialog = true; popUpDialog = new QString (optarg); break; case 'n': noBorder = true; break; case 'y': yastMode = true; break; case 'w': globalFrameWidth = atoi (optarg); break; case 'u': useHwData = true; break; case 'l': fullScreen = true; break; case 'i': setInfo = true; break; case 'c': checkPacs = true; break; case 'D': set3D = true; cardName3D = new QString (optarg); break; case 'p': idlePID = new QString (optarg); break; case 'd': cardDriver = new QString (optarg); break; case 'x': setXIdle = true; break; case 'h': logExit(); usage(); break; default: logExit(); exit(1); } } //===================================== // check if xapi should act as xidle //------------------------------------- if (setXIdle) { XTimeElapsed* idleTimer = new XTimeElapsed ( idlePID ); app.setMainWidget (idleTimer); idleTimer->show(); return app.exec(); } //===================================== // check md5 sum of current config //------------------------------------- if ((! setInfo) && (! set3D) && (! checkPacs) && (! useHwData) && (! fastSetup) ) { bool createMD5sum = false; QFileInfo xc (MD5CONFIG); if (xc.exists()) { QString mD5Sum = qx(MD5,STDOUT,1,"%s",XCONFIG); QFile mHandle (MD5CONFIG); if (mHandle.open(IO_ReadOnly)) { QString compare; mHandle.readLine(compare,MAX_LINE_LENGTH); mHandle.close(); compare = compare.stripWhiteSpace(); if (compare == mD5Sum) { fastSetup = true; } else { fastSetup = false; } } } else { fastSetup = false; } if (createMD5sum) { QString mD5Sum = qx(MD5,STDOUT,1,"%s",XCONFIG); QFile mHandle (MD5CONFIG); if (mHandle.open(IO_WriteOnly)) { mHandle.writeBlock (mD5Sum.ascii(),mD5Sum.length()); mHandle.close(); } } } //===================================== // check option combinations... //------------------------------------- if (useHwData == true) { fastSetup = false; } //===================================== // set root window cursor to the watch //------------------------------------- setMouseCursor ("watch"); //===================================== // init program... //------------------------------------- QWidget::WFlags wflags = Qt::WType_TopLevel; if (noBorder) { wflags |= Qt::WStyle_Customize | Qt::WStyle_NoBorder; } if (uniFont) { QFont currentFont = QFont( "Helvetica", 12 ); currentFont.setStyleHint( QFont::SansSerif, QFont::PreferBitmap ); currentFont.setRawName (UNIFONT); qApp->setFont (currentFont); } xapi = new XFrame ( globalFrameWidth, wflags ); if (setInfo) { signal (SIGHUP ,gotKill); signal (SIGKILL,gotKill); signal (SIGABRT,gotKill); signal (SIGTERM,gotKill); XInfo infoBox (xapi); infoBox.showIntroBox(); logExit(); setMouseCursor (); exit ( infoBox.returnCode() ); } if (set3D) { XInfo infoBox (xapi); infoBox.show3DBox (*cardName3D,cardDriver); printf("%d\n",infoBox.returnCode()); logExit(); setMouseCursor (); exit ( infoBox.returnCode() ); } if (fastSetup) { xapi->fastSetup = true; } if (useHwData) { xapi->useHwData = true; } if (fullScreen) { xapi->fullScreen = true; } if (yastMode) { xapi->yastMode = true; } //===================================== // check 3D environment //------------------------------------- XStringList packageInfo ( qx (GET3D,STDOUT) ); packageInfo.setSeperator (":"); QString package = packageInfo.getList().at(0); QString real3d = packageInfo.getList().at(1); QString soft3d = packageInfo.getList().at(2); QString general = packageInfo.getList().at(3); QString active = packageInfo.getList().at(4); QString answer = packageInfo.getList().at(5); QString flag = packageInfo.getList().at(6); global3DActive = active.toInt(); QString status1 ("1"); if (checkPacs) { // ... // if the 3D Answer was no, there is no need // to check for any packages or scripts // --- if (answer == "no") { setMouseCursor (); exit (0); } // ... // install the missing packages using YaST2 // sw_single mode // --- if (package != "<none>") { if (setMessage("InstallPackage",xapi)) { status1 = qx ( GETINSTALLED,STDOUT,1,"%s",package.ascii() ); } } setMouseCursor (); exit (0); } //===================================== // remove lilo code file... //------------------------------------- unlink (LILOCODE); //===================================== // init main frame... //------------------------------------- if (! xapi->frameInitialized()) { xapi->setFrame (); } //===================================== // set signal handler... //------------------------------------- signal (SIGUSR2,SIG_IGN); signal (SIGINT ,gotInterrupted); //===================================== // init dialogs... //------------------------------------- XIntro* intro = new XIntro(); XAccessX* xaccess = new XAccessX(); XMouse* mouse = new XMouse(); XCard* card = new XCard(); XDesktop* desktop = new XDesktop(); XDisplayGeometry* geo = new XDisplayGeometry(); XKeyboard* keyboard = new XKeyboard(); XLayout* layout = new XLayout(); XMonitor* monitor = new XMonitor(); XMultihead* multi = new XMultihead(); XTablet* tablet = new XTablet(); XTouchScreen* toucher = new XTouchScreen(); XOpenGL* opengl = new XOpenGL(); XVirtual* virtuals = new XVirtual(); Xvnc* vnc = new Xvnc(); intro -> addTo (xapi); xaccess -> addTo (xapi,intro); mouse -> addTo (xapi,intro); card -> addTo (xapi,intro); desktop -> addTo (xapi,intro); geo -> addTo (xapi,intro); keyboard -> addTo (xapi,intro); layout -> addTo (xapi,intro); monitor -> addTo (xapi,intro); multi -> addTo (xapi,intro); tablet -> addTo (xapi,intro); toucher -> addTo (xapi,intro); opengl -> addTo (xapi,intro); virtuals -> addTo (xapi,intro); vnc -> addTo (xapi,intro); //===================================== // save intro pointer... //------------------------------------- introPointer = intro; //===================================== // make sure the serverlayout structure // is created at least one time //------------------------------------- XLayout* layoutDialog; layoutDialog = (XLayout*) intro -> retrieve (Layout); layoutDialog -> setupLayout(); //===================================== // make sure the card dialog was build // in init stage //------------------------------------- XCard* cardDialog; cardDialog = (XCard*) intro -> retrieve (Card); cardDialog -> showSetupWindow (false); cardDialog -> slotRun (Card); cardDialog -> showSetupWindow (true); //===================================== // call resetPage of the desktop dialog // to check for framebuffer usage //------------------------------------- XDesktop* desktopDialog; desktopDialog = (XDesktop*) intro -> retrieve (Colors); desktopDialog -> resetPage ( PAGE_RELOAD ); //===================================== // add margin around pushbutton texts // this is only needed for QT3 //------------------------------------- #if 1 QObject* obj; QObjectList* l = xapi->queryList( "QPushButton" ); QObjectListIt it( *l ); QDict<char>* mText = xapi->getTextPointer(); while ( (obj=it.current()) != 0 ) { ++it; QPushButton* btn = (QPushButton*) obj; QString text = btn->text(); if (! text.isNull()) { QDictIterator<char> n (*mText); for (; n.current(); ++n) { if (n.current() == text) { QString* newText = new QString(); QTextOStream (newText) << " " << text << " "; mText->replace (n.currentKey(),*newText); break; } } QString addText; QTextOStream (&addText) << " " << text << " "; btn->setText (addText); } } delete l; // ... // special keys which are used dynamically on widgets // with initially other texts // --- QList<char> keyList; keyList.append ( "finish" ); keyList.append ( "Next" ); QListIterator<char> io ( keyList ); for (; io.current(); ++io) { QString key ( io.current() ); QString curText (mText->operator[](key)); QString* newText = new QString(); QTextOStream (newText) << " " << curText << " "; mText->replace (key,*newText); } #endif //===================================== // remove xfine cache directory... //------------------------------------- removeXFineCache(); //===================================== // go to main event loop... //------------------------------------- app.setMainWidget(xapi); xapi -> show(); xapi -> enterEvent ( 0 ); xapi -> activateFirstItem(); setMouseCursor(); if (! withDialog) { intro -> checkDetected(); } else { if ( *popUpDialog == "Monitor" ) { xapi -> runDialog (Monitor); } else if ( *popUpDialog == "Card") { xapi -> runDialog (Card); } else { fprintf (stderr,"xapi: no such dialog: %s\n",popUpDialog->ascii()); exit (1); } } return app.exec(); }
void txCommonParameters::readConfigFile(const QString &cfgFileName) { createNeededFiles(); QFile cfgFile1(cfgFileName); QFile cfgFile2(QDir::homePath() + QDir::separator() + cfgFileName); QFile cfgFile; if ( cfgFile1.exists() ) { cfgFile.setFileName(cfgFile1.fileName()); } else if ( cfgFile2.exists() ) { cfgFile.setFileName(cfgFile2.fileName()); } else { const QString myPreferences = "//\n// This is r49 configuration file. " "Parameter-Value delimeter is \"=\" symbol.\n// " "Text after \"//\" is comment.\n//\n\n" "// Temporary rewrited source data files\nsrc_file_name_EU3=" + m_srcFileNameEU3 + "\n" "src_file_name_EU0=" + m_srcFileNameEU0 + "\n" "src_file_name_points=" + m_srcFileNamePoints + "\n" "src_file_name_redpwr=" + m_srcFileNameRedPwr + "\n\n" "// Directory for calculation results\nreports_dir_name=" + m_reportsDirName + "\n\n" "// Measuring nozzle diameter " "(engine inlet air mass flow calculation)\nDn=" + QString::number(m_Dn) + "\n\n" "// Air oxygen concentration\nconc_O2air=" + QString::number(m_concO2air) + "\n\n" "//\nRr=" + QString::number(m_Rr) + "\n\n" "// Stoichiometric air/fuel ratio\nL0=" + QString::number(m_L0) + "\n\n" "// Opacimeter effective base\nL=" + QString::number(m_L) + "\n\n" "// Air carbon dioxide concentration\nconc_CO2air=" + QString::number(m_concCO2air) + "\n\n" "// Fuel percentage\nWH=" + QString::number(m_WH) + "\n" "WO2=" + QString::number(m_WO2) + "\n" "WN=" + QString::number(m_WN) + "\n\n" "// Molecular weights\nmuNO2=" + QString::number(m_muNO2) + "\n" "muCO=" + QString::number(m_muCO) + "\n" "muCH=" + QString::number(m_muCH) + "\n"; if ( cfgFile1.open(QIODevice::WriteOnly | QIODevice::Text) ) { cfgFile1.write(myPreferences.toUtf8()); cfgFile1.close(); cfgFile.setFileName(cfgFile1.fileName()); } else if ( cfgFile2.open(QIODevice::WriteOnly | QIODevice::Text) ) { cfgFile2.write(myPreferences.toUtf8()); cfgFile2.close(); cfgFile.setFileName(cfgFile2.fileName()); } else { throw txError("Can not create config file!"); } return; } if ( !cfgFile.open(QIODevice::ReadOnly | QIODevice::Text) ) { throw txError("Can not open config file " + cfgFileName + "!"); } QString s; QStringList elements; QRegExp rx("^//"); while ( !cfgFile.atEnd() ) { s = cfgFile.readLine().trimmed(); if ( s.isEmpty() || s.contains(rx) ) { continue; } elements = s.split("="); if ( elements[0] == "src_file_name_EU3" ) { m_srcFileNameEU3 = elements[1]; } else if ( elements[0] == "src_file_name_EU0" ) { m_srcFileNameEU0 = elements[1]; } else if ( elements[0] == "src_file_name_points" ) { m_srcFileNamePoints = elements[1]; } else if ( elements[0] == "src_file_name_redpwr" ) { m_srcFileNameRedPwr = elements[1]; } else if ( elements[0] == "reports_dir_name" ) { m_reportsDirName = elements[1]; } else if ( elements[0] == "Dn" ) { m_Dn = (elements[1]).toDouble(); } else if ( elements[0] == "conc_O2air" ) { m_concO2air = (elements[1]).toDouble(); } else if ( elements[0] == "Rr" ) { m_Rr = (elements[1]).toDouble(); } else if ( elements[0] == "L0" ) { m_L0 = (elements[1]).toDouble(); } else if ( elements[0] == "L" ) { m_L = (elements[1]).toDouble(); } else if ( elements[0] == "conc_CO2air" ) { m_concCO2air = (elements[1]).toDouble(); } else if ( elements[0] == "WH" ) { m_WH = (elements[1]).toDouble(); } else if ( elements[0] == "WO2" ) { m_WO2 = (elements[1]).toDouble(); } else if ( elements[0] == "WN" ) { m_WN = (elements[1]).toDouble(); } else if ( elements[0] == "muNO2" ) { m_muNO2 = (elements[1]).toDouble(); } else if ( elements[0] == "muCO" ) { m_muCO = (elements[1]).toDouble(); } else if ( elements[0] == "muCH" ) { m_muCH = (elements[1]).toDouble(); } elements.clear(); } elements.clear(); cfgFile.close(); }
vector<Triangle*> PlyFileParser::ParseFile(string fileName, double scale, Vector3D translation) { VertexCache.clear(); ModelCache.clear(); QString qfileName = QString::fromStdString(fileName); QFile qFile (qfileName); qFile.open(QIODevice::ReadOnly); QRegularExpression elementTag = QRegularExpression("(element)\\s(.*?)\\s([0-9]*)"); QRegularExpression propertyTag = QRegularExpression("(property)\\s(.*?)\\s(.*)"); QRegularExpression dataLine = QRegularExpression("[0-9\\.\\-]*[\\s\\n]"); QRegularExpression endHeader = QRegularExpression("end.*"); queue<ElementInfo> elementTypes; bool finishedParsingHeader = false; //QTextStream qCout (stdout); while (!qFile.atEnd()) { QString line = qFile.readLine(); QRegularExpressionMatch elementMatches = elementTag.match(line); if(!finishedParsingHeader) { if (elementMatches.hasMatch()) { ElementInfo elementInfo; elementInfo.elementName = elementMatches.captured(2).toStdString(); elementInfo.elementCount = elementMatches.captured(3).toInt(); elementTypes.push(elementInfo); } QRegularExpressionMatch propertyMatch = propertyTag.match(line); if (propertyMatch.hasMatch()) { PropertyInfo propertyInfo; propertyInfo.type = propertyMatch.captured(2).toStdString(); propertyInfo.name = propertyMatch.captured(3).toStdString(); elementTypes.front().properties.push(propertyInfo); } } else { ParseDataLine(line, elementTypes.front(), scale, translation); elementTypes.front().elementCount--; if (elementTypes.front().elementCount == 0) { elementTypes.pop(); } } if(line.contains(QRegularExpression("end.*"))) { finishedParsingHeader = true; } //qCout << line; //qCout.flush(); } qFile.close(); return ConvertToVector(ModelCache); }
void QgsApplication::init( QString customConfigPath ) { if ( customConfigPath.isEmpty() ) { if ( getenv( "QGIS_CUSTOM_CONFIG_PATH" ) ) { customConfigPath = getenv( "QGIS_CUSTOM_CONFIG_PATH" ); } else { customConfigPath = QStringLiteral( "%1/.qgis3/" ).arg( QDir::homePath() ); } } qRegisterMetaType<QgsGeometry::Error>( "QgsGeometry::Error" ); qRegisterMetaType<QgsProcessingFeatureSourceDefinition>( "QgsProcessingFeatureSourceDefinition" ); qRegisterMetaType<QgsProcessingOutputLayerDefinition>( "QgsProcessingOutputLayerDefinition" ); QString prefixPath( getenv( "QGIS_PREFIX_PATH" ) ? getenv( "QGIS_PREFIX_PATH" ) : applicationDirPath() ); // QgsDebugMsg( QString( "prefixPath(): %1" ).arg( prefixPath ) ); // check if QGIS is run from build directory (not the install directory) QFile f; // "/../../.." is for Mac bundled app in build directory Q_FOREACH ( const QString &path, QStringList() << "" << "/.." << "/bin" << "/../../.." ) { f.setFileName( prefixPath + path + "/qgisbuildpath.txt" ); if ( f.exists() ) break; } if ( f.exists() && f.open( QIODevice::ReadOnly ) ) { ABISYM( mRunningFromBuildDir ) = true; ABISYM( mBuildSourcePath ) = f.readLine().trimmed(); ABISYM( mBuildOutputPath ) = f.readLine().trimmed(); qDebug( "Running from build directory!" ); qDebug( "- source directory: %s", ABISYM( mBuildSourcePath ).toUtf8().data() ); qDebug( "- output directory of the build: %s", ABISYM( mBuildOutputPath ).toUtf8().data() ); #ifdef _MSC_VER ABISYM( mCfgIntDir ) = prefixPath.split( '/', QString::SkipEmptyParts ).last(); qDebug( "- cfg: %s", ABISYM( mCfgIntDir ).toUtf8().data() ); #endif } if ( ABISYM( mRunningFromBuildDir ) ) { // we run from source directory - not installed to destination (specified prefix) ABISYM( mPrefixPath ) = QString(); // set invalid path #if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA) setPluginPath( ABISYM( mBuildOutputPath ) + '/' + QString( QGIS_PLUGIN_SUBDIR ) + '/' + ABISYM( mCfgIntDir ) ); #else setPluginPath( ABISYM( mBuildOutputPath ) + '/' + QStringLiteral( QGIS_PLUGIN_SUBDIR ) ); #endif setPkgDataPath( ABISYM( mBuildSourcePath ) ); // directly source path - used for: doc, resources, svg ABISYM( mLibraryPath ) = ABISYM( mBuildOutputPath ) + '/' + QGIS_LIB_SUBDIR + '/'; #if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA) ABISYM( mLibexecPath ) = ABISYM( mBuildOutputPath ) + '/' + QGIS_LIBEXEC_SUBDIR + '/' + ABISYM( mCfgIntDir ) + '/'; #else ABISYM( mLibexecPath ) = ABISYM( mBuildOutputPath ) + '/' + QGIS_LIBEXEC_SUBDIR + '/'; #endif } else { char *prefixPath = getenv( "QGIS_PREFIX_PATH" ); if ( !prefixPath ) { #if defined(Q_OS_MACX) || defined(Q_OS_WIN) setPrefixPath( applicationDirPath(), true ); #elif defined(ANDROID) // this is "/data/data/org.qgis.qgis" in android QDir myDir( QDir::homePath() ); myDir.cdUp(); QString myPrefix = myDir.absolutePath(); setPrefixPath( myPrefix, true ); #else QDir myDir( applicationDirPath() ); myDir.cdUp(); QString myPrefix = myDir.absolutePath(); setPrefixPath( myPrefix, true ); #endif } else { setPrefixPath( prefixPath, true ); } } if ( !customConfigPath.isEmpty() ) { ABISYM( mConfigPath ) = customConfigPath + '/'; // make sure trailing slash is included } ABISYM( mDefaultSvgPaths ) << qgisSettingsDirPath() + QStringLiteral( "svg/" ); ABISYM( mAuthDbDirPath ) = qgisSettingsDirPath(); if ( getenv( "QGIS_AUTH_DB_DIR_PATH" ) ) { setAuthDatabaseDirPath( getenv( "QGIS_AUTH_DB_DIR_PATH" ) ); } // store system environment variables passed to application, before they are adjusted QMap<QString, QString> systemEnvVarMap; QString passfile( QStringLiteral( "QGIS_AUTH_PASSWORD_FILE" ) ); // QString, for comparison Q_FOREACH ( const QString &varStr, QProcess::systemEnvironment() ) { int pos = varStr.indexOf( QLatin1Char( '=' ) ); if ( pos == -1 ) continue; QString varStrName = varStr.left( pos ); QString varStrValue = varStr.mid( pos + 1 ); if ( varStrName != passfile ) { systemEnvVarMap.insert( varStrName, varStrValue ); } }
void Dialog::openWithFile(QString sFileName) { const bool debug = true; LOG_FUNC(Dialog::openWithFile); //当传入的文件名不为空的时候调用下面的组件 if(!sFileName.isEmpty()) { QFile qFile; qFile.setFileName(sFileName); if(!qFile.open(QIODevice::ReadOnly)) { QMessageBox qMsgBox; qMsgBox.setText("Cannot find this unl file!!"); qMsgBox.exec(); qDebug()<<"Open file failed:"<<sFileName; return; } if(debug)qDebug()<<"set window title."; //设置窗口标题 this->setWindowTitle(sFileName + " -- CDR Reader"); //设置FileName的Label QString sPrompt("FileName:"); qLabel->setText(sPrompt+sFileName); qLabel->setEnabled(true); qLabel->setWordWrap(true); qLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); if(debug)qDebug()<<"clear related tab info."; //清除已有的相关tab信息 this->qTab->clear(); if(debug)qDebug()<<"preparing for loop."; //相关信息梳理,为循环准备 QByteArray qByteArray; QString qStr; int iRecordNo = 0; //create MODEL QFileInfo qFileinfo(sFileName); CCdrDefine* pcCdrDefine = this->vcCdrDefines.findMatchedCDR(qFileinfo.baseName()); if(pcCdrDefine == 0) return; if(debug)qDebug()<<"interact with widget in top-right cornor."; //此时,还要与右上角的控件进行互动 //清空当前的textEdit控件的文本 qTextEdit->clear(); //设置当前的comboBox显示正确的选项. int iIndexOfComboBox = qComboBox_selectCDRType->findText(pcCdrDefine->vcCdrAttr.getValue("name")); if(iIndexOfComboBox == -1) iIndexOfComboBox = 0; qComboBox_selectCDRType->setCurrentIndex(iIndexOfComboBox); for(qByteArray = qFile.readLine();qByteArray.count()>1;qByteArray = qFile.readLine()) { qStr = qByteArray; //设置当前标签页的名字 QString sTabTitle = pcCdrDefine->vcCdrAttr.getValue("name"); if(sTabTitle.size() == 0) { sTabTitle = "Record"; } sTabTitle += " "; sTabTitle.append(iRecordNo + '1'); iRecordNo++; //设置该标签页 this->setTabWidget(qStr,pcCdrDefine,sTabTitle); } qFile.close(); } }
/*! Load a spkac FILE into this request structure. The file format follows the conventions understood by the 'openssl ca' command. (see: 'man ca') */ int pki_x509req::load_spkac(const QString filename) { QFile file; x509name subject; EVP_PKEY *pktmp = NULL; pki_ign_openssl_error(); file.setFileName(filename); if (!file.open(QIODevice::ReadOnly)) return 1; while (!file.atEnd()) { int idx, nid; QByteArray line = file.readLine(); if (line.size() == 0) continue; idx = line.indexOf('='); if (idx == -1) goto err; QString type = line.left(idx).trimmed(); line = line.mid(idx+1).trimmed(); idx = type.lastIndexOf(QRegExp("[:,\\.]")); if (idx != -1) type = type.mid(idx+1); if ((nid = OBJ_txt2nid(CCHAR(type))) == NID_undef) { if (type != "SPKAC") goto err; pki_ign_openssl_error(); spki = NETSCAPE_SPKI_b64_decode(line, line.size()); if (!spki) goto err; /* Now extract the key from the SPKI structure and check the signature. */ pktmp = NETSCAPE_SPKI_get_pubkey(spki); if (pktmp == NULL) goto err; if (NETSCAPE_SPKI_verify(spki, pktmp) != 1) goto err; } else { // gather all values in the x509name subject. subject.addEntryByNid(nid, filename2QString(line.constData())); } } if (!pktmp) goto err; setSubject(subject); X509_REQ_set_pubkey(request, pktmp); EVP_PKEY_free(pktmp); return 0; err: if (pktmp) EVP_PKEY_free(pktmp); if (spki) { NETSCAPE_SPKI_free(spki); spki = NULL; } return 1; }
int main(int argc, char *argv[]) { // Под Windows устанавливаем кодировку cp1251 #ifdef Q_WS_WIN QTextCodec *codec = QTextCodec::codecForName("Windows-1251"); // Под остальными ОС - utf8 #else QTextCodec *codec = QTextCodec::codecForName("UTF-8"); #endif QString param; QString org_file_name; org_file_name = "org_name.conf"; for (int i = 0; i<argc; i++) { param = codec->toUnicode(argv[i]); if (check_extention(param, ".conf")) { //ключ c - передается файл с названием организации org_file_name = param; } } bool get_name = false; QString org_name = "IP_Volkov"; QString app_name = "CenGen"; QFile *file = new QFile(org_file_name); if (!file->exists()) get_name = true; file->open(QFile::ReadOnly); if (!file->isOpen()) get_name = true; if (get_name) { //открываем диалоговое окно, вводим название организации //сохраняем полученный результат в файл file->open(QFile::WriteOnly); QTextStream out(file); out << "org_name = " + org_name + "\n"; out << "app_name = " + app_name + "\n"; } else { //читаем название организации из файла QString name; QByteArray line; while (!file->atEnd()) { line = file->readLine(); if (line.at(0) != '#') { if (line.contains("org_name")) { name = line; if (name.split("=").count()>1) { name = name.split("=").at(1).trimmed(); org_name = name; } } if (line.contains("app_name")) { name = line; if (name.split("=").count()>1) { name = name.split("=").at(1).trimmed(); app_name = name; } } } } } file->close(); //qDebug() << "Org name " << org_name; //устанавливаем название организации QCoreApplication::setOrganizationName(org_name); QCoreApplication::setApplicationName(app_name); QFileInfo *fi = new QFileInfo; fi->setFile(org_file_name); QString path = fi->absolutePath(); QApplication a(argc, argv); QTranslator myTranslator; myTranslator.load("cengen_ru.qm", path); a.installTranslator(&myTranslator); cengen w; w.set_org_name(org_name, app_name); for (int i = 0; i<argc; i++) { param = codec->toUnicode(argv[i]); if (check_extention(param, ".tov")) { w.open_tovar_list(param); } if (check_extention(param, ".fli")) { w.turn_filter_ON(); w.load_filter_settings_file(param); } if (check_extention(param, ".das")) { w.load_source_settings_file(param); } if (check_extention(param, ".dbf")) { qDebug() << "Trying to load dbf file"; w.save_source_settings_file("_$tmp.das"); bool good = w.set_source_from_dbf(param); if (good) w.load_all_records(); w.load_source_settings_file("_$tmp.das"); w.repaint(); } if (check_extention(param, "frf")) { w.set_ext_shablon_name(param); } if (check_extention(param, "csf")) { QLabel *lbl = new QLabel("Please wait! Executing scenarium file"); lbl->show(); lbl->repaint(); w.execute_macro_file(param); lbl->hide(); } } w.show(); return a.exec(); }
QString QHostInfo::localDomainName() { #if !defined(Q_OS_VXWORKS) resolveLibrary(); if (local_res_ninit) { // using thread-safe version res_state_ptr state = res_state_ptr(qMalloc(sizeof(*state))); Q_CHECK_PTR(state); memset(state, 0, sizeof(*state)); local_res_ninit(state); QString domainName = QUrl::fromAce(state->defdname); if (domainName.isEmpty()) domainName = QUrl::fromAce(state->dnsrch[0]); local_res_nclose(state); qFree(state); return domainName; } if (local_res_init && local_res) { // using thread-unsafe version #if defined(QT_NO_GETADDRINFO) // We have to call res_init to be sure that _res was initialized // So, for systems without getaddrinfo (which is thread-safe), we lock the mutex too QMutexLocker locker(::getHostByNameMutex()); #endif local_res_init(); QString domainName = QUrl::fromAce(local_res->defdname); if (domainName.isEmpty()) domainName = QUrl::fromAce(local_res->dnsrch[0]); return domainName; } #endif // nothing worked, try doing it by ourselves: QFile resolvconf; #if defined(_PATH_RESCONF) resolvconf.setFileName(QFile::decodeName(_PATH_RESCONF)); #else resolvconf.setFileName(QLatin1String("/etc/resolv.conf")); #endif if (!resolvconf.open(QIODevice::ReadOnly)) return QString(); // failure QString domainName; while (!resolvconf.atEnd()) { QByteArray line = resolvconf.readLine().trimmed(); if (line.startsWith("domain ")) return QUrl::fromAce(line.mid(sizeof "domain " - 1).trimmed()); // in case there's no "domain" line, fall back to the first "search" entry if (domainName.isEmpty() && line.startsWith("search ")) { QByteArray searchDomain = line.mid(sizeof "search " - 1).trimmed(); int pos = searchDomain.indexOf(' '); if (pos != -1) searchDomain.truncate(pos); domainName = QUrl::fromAce(searchDomain); } } // return the fallen-back-to searched domain return domainName; }
void menu::recurse(QMenu *cm, QFile &istr) { QString p1,p2,p3; while(! istr.atEnd()) { QTextStream til(istr.readLine(1024)); til >> p1; // command if(p1.isEmpty() || p1 == "#") continue; if(p1 == "End") return; if(p1 == "Separator") { cm->addSeparator(); continue; } til >> p2; // menu label if(p2.isEmpty()) continue; p3 = til.readLine(); // command line if(p2[0] == '"') { if(p2[p2.length()-1] != '"') { int i = p3.indexOf('"'); if(i == -1) continue; p2 += p3.left(i); p2 = p2.mid(1, p2.length()-1); p3 = p3.right(p3.length()-i-1); } else p2 = p2.mid(1, p2.length()-2); } if(p1 == "Menu") { QMenu *nm = new QMenu(p2); Q_CHECK_PTR(nm); cm->addMenu(nm); recurse(nm, istr); continue; } if(p1 == "Quit") { act_quit->setText(p2); cm->addAction(act_quit); continue; } if(p1 == "Kill") { act_kill->setText(p2); cm->addAction(act_kill); continue; } if(p1 == "Restart") { act_rest->setText(p2); cm->addAction(act_rest); continue; } if(p1 != "Entry") continue; p3 = p3.simplified(); if(p3.isEmpty()) continue; QAction *act_run = new QAction(p2, cm); act_run->setData(QVariant(p3)); cm->addAction(act_run); } }
bool PlaylistImporter::parsePlaylist_pls(QFile &data, QStringList &fileList, const QDir &baseDir, const QDir &rootDir) { QRegExp plsEntry("File(\\d+)=(.+)", Qt::CaseInsensitive); const QTextCodec *codec = QTextCodec::codecForName("System"); bool foundAtLeastOneFile = false; data.reset(); while(!data.atEnd()) { QString filePath[3]; QByteArray line = data.readLine(); filePath[0] = QString(QDir::fromNativeSeparators(codec->toUnicode(line.constData(), line.size()).trimmed())); filePath[1] = QString(QDir::fromNativeSeparators(QString::fromLatin1(line.constData(), line.size()).trimmed())); filePath[2] = QString(QDir::fromNativeSeparators(QString::fromUtf8(line.constData(), line.size()).trimmed())); for(size_t i = 0; i < 3; i++) { if(!filePath[i].contains(QChar(QChar::ReplacementCharacter))) { if(plsEntry.indexIn(filePath[i]) >= 0) { QFileInfo filename(QDir::fromNativeSeparators(plsEntry.cap(2)).trimmed()); filename.setCaching(false); fixFilePath(filename, baseDir, rootDir); if(filename.exists() && filename.isFile()) { if(isPlaylist(filename.canonicalFilePath()) == notPlaylist) { fileList << filename.canonicalFilePath(); } foundAtLeastOneFile = true; break; } } } } } //If we did not find any files yet, try UTF-16 now if(!foundAtLeastOneFile) { const char* codecs[2] = {"UTF-16LE", "UTF-16BE"}; for(size_t i = 0; i < 2; i++) { QTextStream stream(&data); stream.setAutoDetectUnicode(false); stream.setCodec(codecs[i]); stream.seek(0i64); while(!stream.atEnd()) { QString filePath = stream.readLine().trimmed(); if(!filePath.contains(QChar(QChar::ReplacementCharacter))) { if(plsEntry.indexIn(filePath) >= 0) { QFileInfo filename(QDir::fromNativeSeparators(plsEntry.cap(2)).trimmed()); filename.setCaching(false); fixFilePath(filename, baseDir, rootDir); if(filename.exists() && filename.isFile()) { if(isPlaylist(filename.canonicalFilePath()) == notPlaylist) { fileList << filename.canonicalFilePath(); } foundAtLeastOneFile = true; } } } } if(foundAtLeastOneFile) break; } } return foundAtLeastOneFile; }
void UpdateAlgePap::updatedata() { updatemessage[0] << "Update failed, verify your Internet connexion ..."; updatemessage[1] << QString::fromUtf8("فشل التحديث، تحقق من اتصال الانترنت ..."); updatemessage[0] << "Your databases are up to date ..."; updatemessage[1] << QString::fromUtf8("قاعدة البيانات حديثة ..."); updatemessage[0] << " : was updated with succeed.\n"; updatemessage[1] << QString::fromUtf8(" : تم تحديثها بنجاح.\n"); updatemessage[0] << " : not updated (shucksums failed).\n"; updatemessage[1] << QString::fromUtf8(" : لم يتم تحديثها (تشفير الملف خاطئ).\n"); updatemessage[0] << " : not updated (connexion failed).\n"; updatemessage[1] << QString::fromUtf8("لم يتم تحديثها (الاتصال فشل).\n"); if(!checkupdate()) { QMessageBox::information(this, updatealgepapwindowlabel[*languageindex], updatemessage[*languageindex].at(0)); return; } if(!linkdownload.open(QIODevice::ReadOnly | QIODevice::Text)) return; if(linkdownload.atEnd()) { QMessageBox::information(this, updatealgepapwindowlabel[*languageindex], updatemessage[*languageindex].at(1)); iniVisible(); return; } QString listresult(""); QString loc, scope[2], link, hash; bool update(true); while(!linkdownload.atEnd()) { loc = scope[0] = scope[1] = link = hash = ""; loc = QString::fromUtf8(linkdownload.readLine()); scope[0] = QString::fromUtf8(linkdownload.readLine()); link = QString::fromUtf8(linkdownload.readLine()); hash = QString::fromUtf8(linkdownload.readLine()); scope[1] = QString::fromUtf8(linkdownload.readLine()); loc.remove("\n"); scope[0].remove("\n"); scope[0].remove("downloadscript/Dnd"); scope[0].remove("information/Dni"); link.remove("\n"); hash.remove("\n"); scope[1].remove("\n"); QString linkupdate = "wget -t5 \""+link+"\" --output-document \""+DirPath+"/TMP/"+scope[0]+"\""; if(!system(linkupdate.toAscii().constData())) { QFile tmp(DirPath+"/TMP/"+scope[0]); if(!tmp.open(QIODevice::ReadOnly | QIODevice::Text)) return; QByteArray array = tmp.readAll(); tmp.close(); QString newhash(QCryptographicHash::hash(array,QCryptographicHash::Sha1).toHex()); if(newhash == hash) { QString commandmv = "mv -f \""+DirPath+"/TMP/"+scope[0]+"\" \""+DirPath+loc+"\""; system(commandmv.toAscii().constData()); listresult+=scope[*languageindex] + updatemessage[*languageindex][2]; } else { listresult+=scope[*languageindex] + updatemessage[*languageindex][3]; update = false; } } else { listresult+=scope[*languageindex] + updatemessage[*languageindex][4]; update = false; } } l->setText(listresult); if(update) { settings = new QSettings("AlgePap","UpdateAlgePap"); settings->setValue("Update/LastUpdate",QDate::currentDate().toString()); settings->setValue("Update/LastUpdatear",QDate::currentDate().toString()); delete(settings); } }