void MainWindow_M::extractEdgeImage() { QString path = QFileDialog::getExistingDirectory(this, tr("Open Directory"),".\\database", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if(path == "") return; QDir dir(path); if(!dir.exists()) return; QString eifilename = path.section('\\',-1); eifilename = path + "\\" + eifilename + ".xml"; // convert the fileName from QString to char* char file[256]; int len = 0; for(;len < eifilename.length(); len++) { file[len] = (eifilename.at(len)).toAscii(); } file[len] = '\0'; // store this edge image FileStorage fs(file,FileStorage::WRITE); if(!fs.isOpened()) { return; } CSAImageProcess imageProcess; QImage srcImage; QString fileName; dir.setFilter(QDir::Files | QDir::NoSymLinks); QFileInfoList list = dir.entryInfoList(); int i = 0; while(i < list.size()) { QFileInfo fileInfo = list.at(i++); fileName = fileInfo.fileName(); if(fileName.section('.',-1) != "png" && fileName.section('.',-1) != "PNG") continue; fileName = fileInfo.path() + "/"+fileName; // convert the fileName from QString to char* char file[256]; int len = 0; for(;len < fileName.length(); len++) { file[len] = (fileName.at(len)).toAscii(); } file[len] = '\0'; // read the image Mat mat = imread(file,CV_LOAD_IMAGE_COLOR); Mat edgelength,edgeorientation,m,m_n,edgeresponse; imageProcess.edgeextraction(mat,edgelength,edgeorientation,m,m_n,edgeresponse); // save this edge image char name[256]; sprintf(name,"edgeimage_%d",i); fs<<name<<edgelength; } fs.release(); }
void cLogAnalyser::storePattern( const unsigned int p_uiFileId, cActionDefList::tiPatternList p_itPattern, const QString &p_qsLogLine, tmFoundPatternList::iterator *p_poInsertPos ) throw( cSevException ) { cTracer obTracer( &g_obLogger, "cLogAnalyser::storePattern", p_itPattern->name().toStdString() ); QString qsLogLine = p_qsLogLine.section( ':', 1 ); // Remove line number from front qsLogLine.chop( 1 ); // and the new line character from end QRegExp obTimeStampRegExp = m_poActionDefList->timeStampRegExp(); if( obTimeStampRegExp.indexIn( qsLogLine ) == -1 ) throw cSevException( cSeverity::ERROR, QString( "TimeStamp Regular Expression does not match on Log Line \"%1\"" ).arg( qsLogLine ).toStdString() ); QStringList slTimeStampParts = obTimeStampRegExp.capturedTexts(); tsFoundPattern suFoundPattern; suFoundPattern.qsTimeStamp = slTimeStampParts.at( 0 ); for( int i = 1; i < slTimeStampParts.size(); i++ ) { switch( m_poActionDefList->timeStampPart( i - 1 ) ) { case cTimeStampPart::YEAR: suFoundPattern.suTimeStamp.uiYear = slTimeStampParts.at( i ).toUInt(); break; case cTimeStampPart::MONTH: suFoundPattern.suTimeStamp.uiMonth = slTimeStampParts.at( i ).toUInt(); break; case cTimeStampPart::DAY: suFoundPattern.suTimeStamp.uiDay = slTimeStampParts.at( i ).toUInt(); break; case cTimeStampPart::HOUR: suFoundPattern.suTimeStamp.uiHour = slTimeStampParts.at( i ).toUInt(); break; case cTimeStampPart::MINUTE: suFoundPattern.suTimeStamp.uiMinute = slTimeStampParts.at( i ).toUInt(); break; case cTimeStampPart::SECOND: suFoundPattern.suTimeStamp.uiSecond = slTimeStampParts.at( i ).toUInt(); break; case cTimeStampPart::MSECOND: suFoundPattern.suTimeStamp.uiMSecond = slTimeStampParts.at( i ).toUInt(); break; default: ; } } suFoundPattern.uiFileId = p_uiFileId; suFoundPattern.ulLineNum = p_qsLogLine.section( ':', 0, 0 ).toULong(); QStringList slCaptures = p_itPattern->captures(); if( slCaptures.size() ) { QStringList slCapturedTexts = p_itPattern->capturedTexts( qsLogLine ); for( int i = 0; i < slCaptures.size(); i++ ) { if( i < slCapturedTexts.size() - 1 ) { QString qsCapturedValue = slCapturedTexts.at( i + 1 ); qsCapturedValue.replace( "\"", "\\\"" ); qsCapturedValue.replace( "\'", "\\\'" ); suFoundPattern.maCapturedAttribs.insert( pair<QString,QString>( slCaptures.at( i ), qsCapturedValue ) ); } } } *p_poInsertPos = m_maFoundPatterns.insert( *p_poInsertPos, pair<QString, tsFoundPattern>( p_itPattern->name(), suFoundPattern ) ); if( m_poActionDefList->combilogColor() != "" ) { tm tmTime; tmTime.tm_wday = 0; tmTime.tm_yday = 0; tmTime.tm_isdst = 0; tmTime.tm_year = suFoundPattern.suTimeStamp.uiYear - 1900; tmTime.tm_mon = suFoundPattern.suTimeStamp.uiMonth - 1; tmTime.tm_mday = suFoundPattern.suTimeStamp.uiDay; tmTime.tm_hour = suFoundPattern.suTimeStamp.uiHour; tmTime.tm_min = suFoundPattern.suTimeStamp.uiMinute; tmTime.tm_sec = suFoundPattern.suTimeStamp.uiSecond; time_t uiTime = mktime( &tmTime ); unsigned long long ulTime = (unsigned long long)uiTime * 1000LL; ulTime += suFoundPattern.suTimeStamp.uiMSecond; if( m_poOC ) m_poOC->addCombilogEntry( ulTime, qsLogLine, m_poActionDefList->combilogColor() ); } }
void US_Win::terminated( int code, QProcess::ExitStatus status ) { qDebug() << "PROCESS terminated: code" << code << "status" << status; QList<procData*>::iterator pr; for ( pr = procs.begin(); pr != procs.end(); pr++ ) { procData* d = *pr; QProcess* process = d->proc; int index = d->index; if ( process->state() == QProcess::NotRunning ) { qDebug() << "PROCESS NotRunning index" << index << "Proc name" << d->name; if ( status == QProcess::CrashExit ) { // Process crashed: output a message and possibly do a pop-up QString msg_sb; QString msg_mb; QString msg_ru = p[ index ].runningMsg; QString estderr = QString( process->readAllStandardError() ) .right( 2000 ); // End lines of STDERR bool badallo = estderr.contains( "bad_alloc" ); qDebug() << "PROCESS status" << status << "e-stderr len" << estderr.length(); //qDebug() << "PROCESS bad_alloc? " << badallo; if ( badallo ) { // It was a "bad_alloc" crash msg_sb = tr( "MEMORY ALLOC crash: " ) + msg_ru; msg_mb = tr( "Process MEMORY ALLOCATION Crash:\n" ) + msg_ru; } else { // It was other than bad_alloc int kwhat = estderr.lastIndexOf( "what(): " ); if ( kwhat > 0 ) { // We have a "what():" hint in stderr QString msg_wh = estderr.mid( kwhat + 7, 20 ).simplified(); msg_sb = "[ " + msg_wh + " ] crash: " + msg_ru; msg_mb = tr( "Process Crash [ " ) + msg_wh + " ]\n" + msg_ru; } else { // Crash type is undetermined msg_sb = "[ unknown type ] crash: " + msg_ru; msg_mb = tr( "Process Crash [ unknown type ]\n" ) + msg_ru; } } // Report the crash in the status bar and in a message box pop-up statusBar()->showMessage( msg_sb ); QString selines = estderr.endsWith( "\n" ) ? estderr.section( "\n", -4, -2 ) : estderr.section( "\n", -3, -1 ); msg_mb += tr( "\n\nLast several stderr lines --\n\n" ) + selines; QMessageBox::warning( this, tr( "Process Crash" ), msg_mb ); } procs.removeOne( d ); p[ index ].currentRunCount--; delete process; // Deleting the process structure delete d; // Deleting the procData structure if ( index == 0 ) apply_prefs(); return; } } }
/*! * \brief Converts a spice netlist into Qucs format and outputs it. */ void SimMessage::nextSPICE() { QString Line; for(;;) { // search for next SPICE component Line = *(Collect.begin()); Collect.erase(Collect.begin()); if(Line == "*") { // worked on all components ? startSimulator(); // <<<<<================== go on === return; } // FIXME #warning SPICE section below not being covered? qDebug() << "goin thru SPICE branch on simmmessage.cpp"; if(Line.left(5) == "SPICE") { if(Line.at(5) != 'o') insertSim = true; else insertSim = false; break; } Collect.append(Line); } QString FileName = Line.section('"', 1,1); Line = Line.section('"', 2); // port nodes if(Line.isEmpty()) makeSubcircuit = false; else makeSubcircuit = true; QString prog; QStringList com; prog = QucsSettings.Qucsconv; if(makeSubcircuit) com << "-g" << "_ref"; com << "-if" << "spice" << "-of" << "qucs"; QFile SpiceFile; if(FileName.indexOf(QDir::separator()) < 0) // add path ? SpiceFile.setFileName(QucsSettings.QucsWorkDir.path() + QDir::separator() + FileName); else SpiceFile.setFileName(FileName); if(!SpiceFile.open(QIODevice::ReadOnly)) { ErrText->appendPlainText(tr("ERROR: Cannot open SPICE file \"%1\".").arg(FileName)); FinishSimulation(-1); return; } if(makeSubcircuit) { Stream << "\n.Def:" << misc::properName(FileName) << " "; Line.replace(',', ' '); Stream << Line; if(!Line.isEmpty()) Stream << " _ref"; } Stream << "\n"; ProgressText = ""; qDebug() << "start QucsConv" << prog << com.join(" "); SimProcess.start(prog, com); if(!SimProcess.Running) { ErrText->appendPlainText(tr("SIM ERROR: Cannot start QucsConv!")); FinishSimulation(-1); return; } QByteArray SpiceContent = SpiceFile.readAll(); SpiceFile.close(); QString command(SpiceContent); //to convert byte array to string SimProcess.setStandardInputFile(command); //? FIXME works? qDebug() << command; connect(&SimProcess, SIGNAL(wroteToStdin()), SLOT(slotCloseStdin())); }
QDomDocument createDescribeFeatureTypeDocument( QgsServerInterface *serverIface, const QgsProject *project, const QString &version, const QgsServerRequest &request ) { Q_UNUSED( version ); QDomDocument doc; QgsServerRequest::Parameters parameters = request.parameters(); QgsAccessControl *accessControl = serverIface->accessControls(); //xsd:schema QDomElement schemaElement = doc.createElement( QStringLiteral( "schema" )/*xsd:schema*/ ); schemaElement.setAttribute( QStringLiteral( "xmlns" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema" ) ); schemaElement.setAttribute( QStringLiteral( "xmlns:xsd" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema" ) ); schemaElement.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE ); schemaElement.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE ); schemaElement.setAttribute( QStringLiteral( "xmlns:qgs" ), QGS_NAMESPACE ); schemaElement.setAttribute( QStringLiteral( "targetNamespace" ), QGS_NAMESPACE ); schemaElement.setAttribute( QStringLiteral( "elementFormDefault" ), QStringLiteral( "qualified" ) ); schemaElement.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0" ) ); doc.appendChild( schemaElement ); //xsd:import QDomElement importElement = doc.createElement( QStringLiteral( "import" )/*xsd:import*/ ); importElement.setAttribute( QStringLiteral( "namespace" ), GML_NAMESPACE ); importElement.setAttribute( QStringLiteral( "schemaLocation" ), QStringLiteral( "http://schemas.opengis.net/gml/2.1.2/feature.xsd" ) ); schemaElement.appendChild( importElement ); QStringList typeNameList; QDomDocument queryDoc; QString errorMsg; if ( queryDoc.setContent( parameters.value( QStringLiteral( "REQUEST_BODY" ) ), true, &errorMsg ) ) { //read doc QDomElement queryDocElem = queryDoc.documentElement(); QDomNodeList docChildNodes = queryDocElem.childNodes(); if ( docChildNodes.size() ) { for ( int i = 0; i < docChildNodes.size(); i++ ) { QDomElement docChildElem = docChildNodes.at( i ).toElement(); if ( docChildElem.tagName() == QLatin1String( "TypeName" ) ) { QString typeName = docChildElem.text().trimmed(); if ( typeName.contains( ':' ) ) typeNameList << typeName.section( ':', 1, 1 ); else typeNameList << typeName; } } } } else { QString typeNames = request.parameter( QStringLiteral( "TYPENAME" ) ); if ( !typeNames.isEmpty() ) { QStringList typeNameSplit = typeNames.split( ',' ); for ( int i = 0; i < typeNameSplit.size(); ++i ) { QString typeName = typeNameSplit.at( i ).trimmed(); if ( typeName.contains( ':' ) ) typeNameList << typeName.section( ':', 1, 1 ); else typeNameList << typeName; } } } QStringList wfsLayerIds = QgsServerProjectUtils::wfsLayerIds( *project ); for ( int i = 0; i < wfsLayerIds.size(); ++i ) { QgsMapLayer *layer = project->mapLayer( wfsLayerIds.at( i ) ); if ( layer->type() != QgsMapLayer::LayerType::VectorLayer ) { continue; } QString name = layer->name(); if ( !layer->shortName().isEmpty() ) name = layer->shortName(); name = name.replace( ' ', '_' ); if ( !typeNameList.isEmpty() && !typeNameList.contains( name ) ) { continue; } if ( accessControl && !accessControl->layerReadPermission( layer ) ) { if ( !typeNameList.isEmpty() ) { throw QgsSecurityAccessException( QStringLiteral( "Feature access permission denied" ) ); } else { continue; } } QgsVectorLayer *vLayer = qobject_cast<QgsVectorLayer *>( layer ); QgsVectorDataProvider *provider = vLayer->dataProvider(); if ( !provider ) { continue; } setSchemaLayer( schemaElement, doc, const_cast<QgsVectorLayer *>( vLayer ) ); } return doc; }
/*! * \brief Insert file details into database. * If it is an audio file, read the metadata and insert * that information at the same time. * * If it is an image file, just insert the filename and * type. * * \param filename Full path to file. * * \returns Nothing. */ void FileScanner::AddFileToDB(const QString &filename) { QString extension = filename.section( '.', -1 ) ; QString directory = filename; directory.remove(0, m_startdir.length()); directory = directory.section( '/', 0, -2); QString nameFilter = gCoreContext->GetSetting("AlbumArtFilter", "*.png;*.jpg;*.jpeg;*.gif;*.bmp"); // If this file is an image, insert the details into the music_albumart table if (nameFilter.indexOf(extension.toLower()) > -1) { QString name = filename.section( '/', -1); MSqlQuery query(MSqlQuery::InitCon()); query.prepare("INSERT INTO music_albumart SET filename = :FILE, " "directory_id = :DIRID, imagetype = :TYPE;"); query.bindValue(":FILE", name); query.bindValue(":DIRID", m_directoryid[directory]); query.bindValue(":TYPE", AlbumArtImages::guessImageType(name)); if (!query.exec() || query.numRowsAffected() <= 0) { MythDB::DBError("music insert artwork", query); } return; } Decoder *decoder = Decoder::create(filename, NULL, NULL, true); if (decoder) { VERBOSE(VB_FILE, QString("Reading metadata from %1").arg(filename)); Metadata *data = decoder->readMetadata(); if (data) { QString album_cache_string; // Set values from cache int did = m_directoryid[directory]; if (did > 0) data->setDirectoryId(did); int aid = m_artistid[data->Artist().toLower()]; if (aid > 0) { data->setArtistId(aid); // The album cache depends on the artist id album_cache_string = data->getArtistId() + "#" + data->Album().toLower(); if (m_albumid[album_cache_string] > 0) data->setAlbumId(m_albumid[album_cache_string]); } int gid = m_genreid[data->Genre().toLower()]; if (gid > 0) data->setGenreId(gid); // Commit track info to database data->dumpToDatabase(); // Update the cache m_artistid[data->Artist().toLower()] = data->getArtistId(); m_genreid[data->Genre().toLower()] = data->getGenreId(); album_cache_string = data->getArtistId() + "#" + data->Album().toLower(); m_albumid[album_cache_string] = data->getAlbumId(); delete data; } delete decoder; } }
/** * Parse CDDB text */ Cddb::Album& Cddb::Album::operator =(const QString& rhs) { discGenre.clear(); discID = 0; artist.clear(); title.clear(); genre.clear(); year = 0; submitter = "MythTV " MYTH_BINARY_VERSION; rev = 1; isCompilation = false; tracks.clear(); toc.clear(); extd.clear(); ext.clear(); enum { kNorm, kToc } eState = kNorm; QString cddb = QString::fromUtf8(rhs.toLatin1().constData()); while (!cddb.isEmpty()) { // Lines should be of the form "FIELD=value\r\n" QString line = cddb.section(QRegExp("[\r\n]"), 0, 0); if (line.startsWith("# Track frame offsets:")) { eState = kToc; } else if (line.startsWith("# Disc length:")) { QString s = line.section(QRegExp("[ \t]"), 3, 3); unsigned secs = s.toULong(); if (toc.size()) secs -= msf2sec(toc[0]); toc.push_back(sec2msf(secs)); eState = kNorm; } else if (line.startsWith("# Revision:")) { QString s = line.section(QRegExp("[ \t]"), 2, 2); bool bValid = false; int v = s.toInt(&bValid); if (bValid) rev = v; } else if (line.startsWith("# Submitted via:")) { submitter = line.section(QRegExp("[ \t]"), 3, 3); } else if (line.startsWith("#")) { if (kToc == eState) { bool bValid = false; QString s = line.section(QRegExp("[ \t]"), 1).trimmed(); unsigned long lsn = s.toUInt(&bValid); if (bValid) toc.push_back(lsn2msf(lsn)); else eState = kNorm; } } else { QString value = line.section('=', 1, 1); QString art; if (value.contains(" / ")) { art = value.section(" / ", 0, 0); // Artist in *TITLE value = value.section(" / ", 1, 1); } if (line.startsWith("DISCID=")) { bool isValid = false; ulong discID2 = value.toULong(&isValid,16); if (isValid) discID = discID2; } else if (line.startsWith("DTITLE=")) { // Albums (and maybe artists?) can wrap over multiple lines: artist += art; title += value; } else if (line.startsWith("DYEAR=")) { bool isValid = false; int val = value.toInt(&isValid); if (isValid) year = val; } else if (line.startsWith("DGENRE=")) { if (!value.isEmpty()) genre = value; } else if (line.startsWith("TTITLE")) { int trk = line.remove("TTITLE").section('=', 0, 0).toInt(); if (trk >= 0 && trk < CDROM_LEADOUT_TRACK) { if (trk >= tracks.size()) tracks.resize(trk + 1); Cddb::Track& track = tracks[trk]; // Titles can wrap over multiple lines, so we load+store: track.title += value; track.artist += art; if (art.length()) isCompilation = true; } } else if (line.startsWith("EXTD=")) { if (!value.isEmpty()) extd = value; } else if (line.startsWith("EXTT")) { int trk = line.remove("EXTT").section('=', 0, 0).toInt(); if (trk >= 0 && trk < CDROM_LEADOUT_TRACK) { if (trk >= ext.size()) ext.resize(trk + 1); ext[trk] = value; } } } // Next response line: cddb = cddb.section('\n', 1); } return *this; }
// ************************************************************ void QucsFilter::slotTakeEr(const QString& Text) { // If the ComboBox text was a material property, the material name // is separated by two spaces. So, cut off the name. ComboEr->lineEdit()->setText(Text.section(" ", 0, 0)); }
void middle6::show_tabWidgetInfo(int index) { if(index == 0) { connect(pushButton_processkill2, SIGNAL(clicked()), this, SLOT(on_pushButton_pkill_clicked2())); thread1->start("bash ps-amaz.sh"); thread2->start("bash ps-firfo.sh"); thread3->start("bash ps-gogl.sh"); thread4->start("bash ps-qc.sh"); thread5->start("bash ps-ql.sh"); thread6->start("bash ps-soft-cent.sh"); thread7->start("bash ps-term.sh"); thread8->start("bash ps-wp.sh"); thread9->start("bash ps-evi.sh"); if(!thread1->waitForStarted()) { qDebug()<<"failed start!"; } if(!thread2->waitForStarted()) { qDebug()<<"failed start!"; } if(!thread3->waitForStarted()) { qDebug()<<"failed start!"; } if(!thread4->waitForStarted()) { qDebug()<<"failed start!"; } if(!thread5->waitForStarted()) { qDebug()<<"failed start!"; } if(!thread6->waitForStarted()) { qDebug()<<"failed start!"; } if(!thread7->waitForStarted()) { qDebug()<<"failed start!"; } if(!thread8->waitForStarted()) { qDebug()<<"failed start!"; } if(!thread9->waitForStarted()) { qDebug()<<"failed start!"; } while(true == thread1->waitForFinished()); { bool ok1; QString ver1 = thread1->readAllStandardOutput(); int dec1 = ver1.toInt(&ok1,10); if(dec1 > 1 && flag1 == 0) { item1 = new QListWidgetItem(listWidget2); flag1 = 1; item1->setIcon(QIcon(":images/amazon.png")); item1->setText("亚马逊 正在运行中..."); listWidget2->addItem(item1); } if(dec1 < 2 && flag1 == 1) { listWidget2->removeItemWidget(item1); delete item1; flag1 = 0; dec1 = 0; } } while(true == thread2->waitForFinished()); { bool ok2; QString ver2 = thread2->readAllStandardOutput(); int dec2 = ver2.toInt(&ok2,10); if(dec2 >1 && flag2 == 0) { item2 = new QListWidgetItem; flag2 = 1; item2->setIcon(QIcon(":images/firefox.png")); item2->setText("火狐浏览器 正在运行中..."); listWidget2->addItem(item2); } if(dec2 < 2 && flag2 == 1) { listWidget2->removeItemWidget(item2); delete item2; flag2 = 0; } } while(true == thread3->waitForFinished()); { bool ok3; QString ver3= thread3->readAllStandardOutput(); int dec3 = ver3.toInt(&ok3,10); if(dec3 > 2 && flag3 == 0) { item3 = new QListWidgetItem; flag3 = 1; item3->setIcon(QIcon(":images/google.png")); item3->setText("谷歌浏览器 正在运行中..."); listWidget2->addItem(item3); } if(dec3 < 3 && flag3 == 1) { listWidget2->removeItemWidget(item3); delete item3; dec3 = 0; flag3 = 0; } } while(true == thread4->waitForFinished()); { bool ok4; QString ver4 = thread4->readAllStandardOutput(); int dec4 = ver4.toInt(&ok4,10); if(dec4 > 2 && flag4 == 0) { item4 = new QListWidgetItem; flag4 = 1; item4->setIcon(QIcon(":/images/qt.png")); item4->setText("Qt Creater 正在运行中..."); listWidget2->addItem(item4); } if(dec4 < 2 && flag4 == 1) { listWidget2->removeItemWidget(item4); delete item4; dec4 = 0; flag4 = 0; } } while(true == thread5->waitForFinished()); { bool ok5; QString ver5 = thread5->readAllStandardOutput(); int dec5 = ver5.toInt(&ok5,10); // qDebug()<< dec5; if(dec5> 2 && flag5 == 0) { item5 = new QListWidgetItem; flag5 = 1; item5->setIcon(QIcon(":/images/qq.png")); item5->setText("qq 正在运行中..."); listWidget2->addItem(item5); } if(dec5 < 3 && flag5 == 1) { listWidget2->removeItemWidget(item5); delete item5; flag5 = 0; } } while(true == thread6->waitForFinished()); { bool ok6; QString ver6 = thread6->readAllStandardOutput(); int dec6 = ver6.toInt(&ok6,10); if(dec6> 1 && flag6 == 0) { item6 = new QListWidgetItem; flag6 = 1; item6->setIcon(QIcon(":/images/software-center.png")); item6->setText("ubuntu软件中心 正在运行中..."); listWidget2->addItem(item6); } if(dec6 < 2 && flag6 == 1) { listWidget2->removeItemWidget(item6); delete item6; flag6 = 0; } } while(true == thread7->waitForFinished()); { bool ok7; QString ver7 = thread7->readAllStandardOutput(); int dec7 = ver7.toInt(&ok7,10); if(dec7> 1 && flag7 == 0) { item7 = new QListWidgetItem; flag7 = 1; item7->setIcon(QIcon(":/images/terminal.png")); item7->setText("终端 正在运行中..."); listWidget2->addItem(item7); } if(dec7 < 2 && flag7 == 1) { listWidget2->removeItemWidget(item7); delete item7; flag7 = 0; } } while(true == thread8->waitForFinished()); { bool ok8; QString ver8 = thread8->readAllStandardOutput(); int dec8 = ver8.toInt(&ok8,10); if(dec8> 1 && flag8 == 0) { item8 = new QListWidgetItem; flag8 = 1; item8->setIcon(QIcon(":/images/wps.png")); item8->setText("wps文本编辑器 正在运行中..."); listWidget2->addItem(item8); } if(dec8 < 2 && flag8 == 1) { listWidget2->removeItemWidget(item8); delete item8; flag8 = 0; } } while(true == thread9->waitForFinished()); { bool ok9; QString ver9 = thread9->readAllStandardOutput(); int dec9 = ver9.toInt(&ok9,10); if(dec9> 1 && flag9 == 0) { item9 = new QListWidgetItem; flag9 = 1; item9->setIcon(QIcon(":/images/evnice.png")); item9->setText("pdf文本编辑器 正在运行中..."); listWidget2->addItem(item9); } if(dec9 < 2 && flag9 == 1) { listWidget2->removeItemWidget(item9); delete item9; flag9 = 0; } } } if(index == 1) { QString tempStr; //读取文件信息字符串 QFile tempFile; //用于打开系统文件 // int pos; //读取文件的位置 this->listWidget->clear(); connect(this->pushButton_processfresh, SIGNAL(clicked()), this, SLOT(on_pushButton_prefresh_clicked())); connect(this->pushButton_processkill, SIGNAL(clicked()), this, SLOT(on_pushButton_pkill_clicked())); QDir qd("/proc"); QStringList qsList = qd.entryList(); QString qs = qsList.join("\n"); QString id_of_pro; bool ok; int find_start = 3; int a, b; int nProPid; //进程PID int totalProNum = 0; //进程总数 QString proName; //进程名 QString proState; //进程状态 QString proPri; //进程优先级 QString proMem; //进程占用内存 QListWidgetItem *title = new QListWidgetItem("PID\t" + QString::fromUtf8("名称") + "\t\t" + QString::fromUtf8("状态") + "\t" + QString::fromUtf8("优先级") + "\t" + QString::fromUtf8("占用内存"), this->listWidget); //循环读取进程 while (1) { //获取进程PID a = qs.indexOf("\n", find_start); b = qs.indexOf("\n", a+1); find_start = b; id_of_pro = qs.mid(a+1, b-a-1); totalProNum++; nProPid = id_of_pro.toInt(&ok, 10); if(!ok) { break; } //打开PID所对应的进程状态文件 tempFile.setFileName("/proc/" + id_of_pro + "/stat"); if ( !tempFile.open(QIODevice::ReadOnly) ) { // QMessageBox::warning(this, tr("warning"), tr("The pid stat file can not open!"), QMessageBox::Yes); return; } tempStr = tempFile.readLine(); if (tempStr.length() == 0) { break; } a = tempStr.indexOf("("); b = tempStr.indexOf(")"); proName = tempStr.mid(a+1, b-a-1); proName.trimmed(); //删除两端的空格 proState = tempStr.section(" ", 2, 2); proPri = tempStr.section(" ", 17, 17); proMem = tempStr.section(" ", 22, 22); if (proName.length() >= 12) { QListWidgetItem *item = new QListWidgetItem(id_of_pro + "\t" + proName + "\t" + proState + "\t" + proPri + "\t" + proMem, this->listWidget); } else { QListWidgetItem *item = new QListWidgetItem(id_of_pro + "\t" + proName + "\t\t" + proState + "\t" + proPri + "\t" + proMem, this->listWidget); } } tempFile.close(); //关闭该PID进程的状态文件 } }
QString Editor::suffixe ( QString filename ) { return filename.section ( ".", -1, -1 ); }
/** * \brief Creates MythMedia instances for sysfs removable media devices. * * Block devices are represented as directories in sysfs with directories * for each partition underneath the parent device directory. * * This function recursively calls itself to find all partitions on a block * device and creates a MythHDD instance for each partition found. If no * partitions are found and the device is a CD or DVD device a MythCDROM * instance is created. Otherwise a MythHDD instance is created for the * entire block device. * * \param dev path to sysfs block device. * \param checkPartitions check for partitions on block device. * \return true if MythMedia instances are created. */ bool MediaMonitorUnix::FindPartitions(const QString &dev, bool checkPartitions) { LOG(VB_MEDIA, LOG_DEBUG, LOC + ":FindPartitions(" + dev + QString(",%1").arg(checkPartitions ? " true" : " false" ) + ")"); MythMediaDevice* pDevice = NULL; if (checkPartitions) { // check for partitions QDir sysfs(dev); sysfs.setFilter(QDir::Dirs | QDir::NoDotAndDotDot); bool found_partitions = false; QStringList parts = sysfs.entryList(); for (QStringList::iterator pit = parts.begin(); pit != parts.end(); ++pit) { // skip some sysfs dirs that are _not_ sub-partitions if (*pit == "device" || *pit == "holders" || *pit == "queue" || *pit == "slaves" || *pit == "subsystem" || *pit == "bdi" || *pit == "power") continue; found_partitions |= FindPartitions( sysfs.absoluteFilePath(*pit), false); } // no partitions on block device, use main device if (!found_partitions) found_partitions |= FindPartitions(sysfs.absolutePath(), false); return found_partitions; } QString device_file = GetDeviceFile(dev); if (device_file.isEmpty()) return false; QStringList cdroms = GetCDROMBlockDevices(); if (cdroms.contains(dev.section('/', -1))) { // found cdrom device pDevice = MythCDROM::get( this, device_file.toLatin1().constData(), false, m_AllowEject); } else { // found block or partition device pDevice = MythHDD::Get( this, device_file.toLatin1().constData(), false, false); } if (AddDevice(pDevice)) return true; if (pDevice) pDevice->deleteLater(); return false; }
void AppLauncherPlugin::loadButton(){ QString def = this->ID().section("::",1,50).section("---",0,0).simplified(); QString path = this->readSetting("applicationpath",def).toString(); //use the default if necessary //qDebug() << "Default Application Launcher:" << def << path; bool ok = QFile::exists(path); if(!ok){ emit RemovePlugin(this->ID()); return;} int icosize = this->height()-4 - 2.2*button->fontMetrics().height(); button->setFixedSize( this->width()-4, this->height()-4); button->setIconSize( QSize(icosize,icosize) ); QString txt; if(path.endsWith(".desktop") && ok){ XDGDesktop file = LXDG::loadDesktopFile(path, ok); if(path.isEmpty() || !QFile::exists(path) || !ok){ button->setWhatsThis(""); button->setIcon( QIcon(LXDG::findIcon("quickopen-file","").pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) ); txt = tr("Click to Set"); if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); } }else{ button->setWhatsThis(file.filePath); button->setIcon( QIcon(LXDG::findIcon(file.icon,"quickopen").pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) ); txt = file.name; if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); } watcher->addPath(file.filePath); //make sure to update this shortcut if the file changes } }else if(ok){ QFileInfo info(path); button->setWhatsThis(info.absoluteFilePath()); if(info.isDir()){ button->setIcon( LXDG::findIcon("folder","") ); }else if(LUtils::imageExtensions().contains(info.suffix().toLower()) ){ button->setIcon( QIcon(QPixmap(path).scaled(256,256)) ); //max size for thumbnails in memory }else{ button->setIcon( QIcon(LXDG::findMimeIcon(path).pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) ); } txt = info.fileName(); if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); } watcher->addPath(path); //make sure to update this shortcut if the file changes }else{ //InValid File button->setWhatsThis(""); button->setIcon( QIcon(LXDG::findIcon("quickopen","").pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) ); button->setText( tr("Click to Set") ); if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); } } //If the file is a symlink, put the overlay on the icon if(QFileInfo(path).isSymLink()){ QImage img = button->icon().pixmap(QSize(icosize,icosize)).toImage(); int oSize = icosize/3; //overlay size QPixmap overlay = LXDG::findIcon("emblem-symbolic-link").pixmap(oSize,oSize).scaled(oSize,oSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); QPainter painter(&img); painter.drawPixmap(icosize-oSize,icosize-oSize,overlay); //put it in the bottom-right corner button->setIcon( QIcon(QPixmap::fromImage(img)) ); } //Now adjust the visible text as necessary based on font/grid sizing button->setToolTip(txt); //Double check that the visual icon size matches the requested size - otherwise upscale the icon if(button->fontMetrics().width(txt) > (button->width()-OUTMARGIN) ){ //Text too long, try to show it on two lines //txt = button->fontMetrics().elidedText(txt, Qt::ElideRight, 2*(button->width()-OUTMARGIN), Qt::TextWordWrap); txt =txt.section(" ",0,2).replace(" ","\n"); //First take care of any natural breaks //Go through and combine any lines if(txt.contains("\n")){ //need to check each line QStringList txtL = txt.split("\n"); for(int i=0; i<txtL.length(); i++){ if(( i+1<txtL.length()) && (button->fontMetrics().width(txtL[i]) < button->width()/2) ){ txtL[i] = txtL[i]+" "+txtL[i+1]; txtL.removeAt(i+1); } } txt = txtL.join("\n").section("\n",0,2); } if(txt.contains("\n")){ //need to check each line QStringList txtL = txt.split("\n"); for(int i=0; i<txtL.length(); i++){ if(i>1){ txtL.removeAt(i); i--; } //Only take the first two lines else{ txtL[i] = button->fontMetrics().elidedText(txtL[i], Qt::ElideRight, (button->width()-OUTMARGIN) ); } } txt = txtL.join("\n"); }else{ txt = this->fontMetrics().elidedText(txt,Qt::ElideRight, 2*(button->width()-OUTMARGIN)); //Now split the line in half for the two lines txt.insert( ((txt.count())/2), "\n"); } } if(!txt.contains("\n")){ txt.append("\n "); } //always use two lines //qDebug() << " - Setting Button Text:" << txt; button->setText(txt); QTimer::singleShot(100, this, SLOT(update()) ); //Make sure to re-draw the image in a moment }
void SynthSettings::commitSettings() { if (m_fluidSettings) ::delete_fluid_settings(m_fluidSettings); m_fluidSettings = ::new_fluid_settings(); if ((m_audioGroups == 0) && m_audioChannels != 0) { m_audioGroups = m_audioChannels; } // We'll need these to avoid pedandic compiler warnings... char *pszKey; char *pszVal; // First we'll force all other conmmand line options... if (!m_midiDriver.isEmpty()) { pszKey = (char *) "midi.driver"; ::fluid_settings_setstr(m_fluidSettings, pszKey,m_midiDriver.toLocal8Bit().data()); } if (m_midiDriver == "alsa_seq" || m_midiDriver == "coremidi") { QString sKey = "midi." + m_midiDriver + ".id"; if (!m_midiName.isEmpty()) { ::fluid_settings_setstr(m_fluidSettings, sKey.toLocal8Bit().data(), m_midiName.toLocal8Bit().data()); } } else if (!m_midiDevice.isEmpty()) { QString sMidiKey = "midi."; if (m_midiDriver == "alsa_raw") sMidiKey += "alsa"; else sMidiKey += m_midiDriver; sMidiKey += ".device"; ::fluid_settings_setstr(m_fluidSettings, sMidiKey.toLocal8Bit().data(), m_midiDevice.toLocal8Bit().data()); } if (!m_audioDriver.isEmpty()) { pszKey = (char *) "audio.driver"; ::fluid_settings_setstr(m_fluidSettings, pszKey, m_audioDriver.toLocal8Bit().data()); } if (!m_audioDevice.isEmpty()) { QString sAudioKey = "audio." + m_audioDriver + '.'; if (m_audioDriver == "file") sAudioKey += "name"; else sAudioKey += "device"; ::fluid_settings_setstr(m_fluidSettings, sAudioKey.toLocal8Bit().data(), m_audioDevice.toLocal8Bit().data()); } if (!m_jackName.isEmpty()) { pszKey = (char *) "audio.jack.id"; ::fluid_settings_setstr(m_fluidSettings, pszKey, m_jackName.toLocal8Bit().data()); } pszKey = (char *) "audio.jack.autoconnect"; ::fluid_settings_setint(m_fluidSettings, pszKey, int(m_jackAutoConnect)); pszKey = (char *) "audio.jack.multi"; pszVal = (char *) (m_jackMulti ? "yes" : "no"); ::fluid_settings_setstr(m_fluidSettings, pszKey, pszVal); if (!m_sampleFormat.isEmpty()) { pszKey = (char *) "audio.sample-format"; ::fluid_settings_setstr(m_fluidSettings, pszKey, m_sampleFormat.toLocal8Bit().data()); } if (m_audioBufferSize > 0) { pszKey = (char *) "audio.period-size"; ::fluid_settings_setint(m_fluidSettings, pszKey, m_audioBufferSize); } if (m_audioBufferCount > 0) { pszKey = (char *) "audio.periods"; ::fluid_settings_setint(m_fluidSettings, pszKey, m_audioBufferCount); } if (m_midiChannels > 0) { pszKey = (char *) "synth.midi-channels"; ::fluid_settings_setint(m_fluidSettings, pszKey, m_midiChannels); } pszKey = (char *) "synth.midi-bank-select"; ::fluid_settings_setstr(m_fluidSettings, pszKey, m_midiBankSelect.toLocal8Bit().data()); if (m_audioChannels > 0) { pszKey = (char *) "synth.audio-channels"; ::fluid_settings_setint(m_fluidSettings, pszKey, m_audioChannels); } if (m_audioGroups > 0) { pszKey = (char *) "synth.audio-groups"; ::fluid_settings_setint(m_fluidSettings, pszKey, m_audioGroups); } if (m_sampleRate > 0.0) { pszKey = (char *) "synth.sample-rate"; ::fluid_settings_setnum(m_fluidSettings, pszKey, m_sampleRate); } if (m_polyphony > 0) { pszKey = (char *) "synth.polyphony"; ::fluid_settings_setint(m_fluidSettings, pszKey, m_polyphony); } pszKey = (char *) "synth.reverb.active"; pszVal = (char *) (m_reverbActive ? "yes" : "no"); ::fluid_settings_setstr(m_fluidSettings, pszKey, pszVal); pszKey = (char *) "synth.chorus.active"; pszVal = (char *) (m_chorusActive ? "yes" : "no"); ::fluid_settings_setstr(m_fluidSettings, pszKey, pszVal); pszKey = (char *) "synth.ladspa.active"; pszVal = (char *) (m_ladspaActive ? "yes" : "no"); ::fluid_settings_setstr(m_fluidSettings, pszKey, pszVal); // Last we set user supplied options... QStringListIterator iter(m_options); while (iter.hasNext()) { const QString sOpt = iter.next(); const QString sKey = sOpt.section('=', 0, 0); const QString sVal = sOpt.section('=', 1, 1); QByteArray tmp = sKey.toLocal8Bit(); pszKey = tmp.data(); switch (::fluid_settings_get_type(m_fluidSettings, pszKey)) { case FLUID_NUM_TYPE: ::fluid_settings_setnum(m_fluidSettings, pszKey, sVal.toFloat()); break; case FLUID_INT_TYPE: ::fluid_settings_setint(m_fluidSettings, pszKey, sVal.toInt()); break; case FLUID_STR_TYPE: default: ::fluid_settings_setstr(m_fluidSettings, pszKey, sVal.toLocal8Bit().data()); break; } } }
int NetworkKernerl_Linux::httpConnection(QString hostName) { struct sockaddr_in servaddr; char buf[4096]; fd_set t_set1; fd_set mask; struct timeval tv; int ret; this->result.clear(); if(this->setupSockfd() <0) return -1; QString hosts = hostName.section('/',0,0); QString hostPath = hostName.section('/',1); ret = this->setupServerAddr(servaddr,hosts.toLatin1().data()); if(ret<0) return ret; int flags=fcntl(sockfd,F_GETFL,0); fcntl(sockfd,F_SETFL,flags|O_NONBLOCK); ret = connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); if (-1 == ret) { if(errno != EINPROGRESS) { qDebug()<<"[E] connect failed,errno is EINPROGRESS "<<endl; close(sockfd); return NONETWORKCONNNECT; } FD_ZERO(&mask); FD_SET(sockfd,&mask); tv.tv_sec = 5; tv.tv_usec = 0; switch(select(sockfd+1,NULL,&mask,NULL,&tv)) { case -1: qDebug()<<"[E] select read failed,errno is -1 "<<endl; close(sockfd); return NONETWORKCONNNECT; case 0: qDebug()<<"[E] select read failed, TIMEOUT "<<endl; close(sockfd); return NONETWORKCONNNECT; // default: // int error=0; // socklen_t len = sizeof(int); // if(getsockopt(sockfd,SOL_SOCKET,SO_ERROR,&error,&len)) // { // if(0 == error) // { // printf("has connect"); // } // } } } char *s = this->generateHttpRequest(hosts,hostPath); ret = write(sockfd,s,strlen(s)); if (ret < 0){ qDebug()<<"[E] socket write failed"<<endl; close(sockfd); return NONETWORKCONNNECT; } FD_ZERO(&t_set1); FD_SET(sockfd, &t_set1); ret =0; while(1){ //设置超时为1秒,如果1秒还没有反应直接返回 tv.tv_sec= 5; tv.tv_usec= 0; memset(buf, 0, sizeof(buf)); int h= select(sockfd +1, &t_set1, NULL, NULL, &tv); if (h == 0){ qDebug()<<"[W] select2 write failed,timeout "<<endl; break; } else if (h < 0) { qDebug()<<"[E] select2 read failed,errno is -1 "<<endl; ret = NONETWORKCONNNECT; } else { int i= read(sockfd, buf, sizeof(buf)); if(i>0) { // result = result + buf; QTextCodec *gbk = QTextCodec::codecForName("GBK"); result = result + gbk->toUnicode(buf);// gbk convert utf8 } else break; } } close(sockfd); return ret; }
static inline QString embracedString( const QString & s ) { return s.section( '(', 1 ).section( ')', 0, 0 ); }
QVariant DatabaseModel::getDataByType(QByteArray *data, QString varType) { if (varType.contains(QRegExp("^Vector<")) || varType.contains(QRegExp("^SortedVector<"))) { QString subVarType = varType.section('<', 1, -1, QString::SectionSkipEmpty).simplified(); subVarType.chop(1); int size = DatabaseModel::instance()->getInt(data); QString retVal("<"); int i = 0; for (; i < size; i++) { retVal += instance()->getDataByType(data, subVarType).toString() + QString(":"); } if (i > 0) retVal.chop(1); retVal += ">"; return retVal; } if (varType.contains(QRegExp("^DeltaVector<"))) { QString subVarType = varType.section('<', 1, -1, QString::SectionSkipEmpty).simplified(); subVarType.chop(1); short size = DatabaseModel::instance()->getShort(data); QString retVal; for (int i = 0; i < size; i++) { QString varName = instance()->getString(data); retVal += varName + " ("; /*unsigned int serializedSize = */instance()->getInt(data); if (varName == "vector") retVal += instance()->getDataByType(data, "Vector<" + subVarType + ">").toString() + "); "; else if (varName == "updateCounter") retVal += QString::number(instance()->getInt(data)) + "); "; else if (varName == "_className") retVal += ");"; } return retVal; } if (varType.contains(QRegExp("^VectorMapEntry<"))) { QString subVarType = varType.section('<', 1, -1, QString::SectionSkipEmpty).simplified(); subVarType.chop(1); QString key = subVarType.section(',', 0, 0, QString::SectionSkipEmpty).simplified(); QString value = subVarType.section(',', 1, -1, QString::SectionSkipEmpty).simplified(); QString retVal = instance()->getDataByType(data, key).toString(); retVal += "," + instance()->getDataByType(data, value).toString(); return retVal; } if (varType.contains(QRegExp("^VectorMap<"))) { QString subVarType = varType.section('<', 1, -1, QString::SectionSkipEmpty).simplified(); subVarType.chop(1); return instance()->getDataByType(data, "Vector<VectorMapEntry<" + subVarType + "> >"); } if (varType.contains(QRegExp("^DeltaVectorMap<"))) { QString subVarType = varType.section('<', 1, -1, QString::SectionSkipEmpty).simplified(); subVarType.chop(1); short size = DatabaseModel::instance()->getShort(data); QString retVal; for (int i = 0; i < size; i++) { QString varName = instance()->getString(data); retVal += varName + " ("; /*unsigned int serializedSize = */instance()->getInt(data); if (varName == "vectorMap") retVal += instance()->getDataByType(data, "VectorMap<" + subVarType + ">").toString() + "); "; else if (varName == "updateCounter") retVal += QString::number(instance()->getInt(data)) + "); "; else if (varName == "_className") retVal += ");"; } return retVal; } QVariant val; if (varType == "string") val = DatabaseModel::instance()->getString(data); else if (varType == "unicode") val = DatabaseModel::instance()->getUnicode(data); else if (varType == "unsigned int") val = DatabaseModel::instance()->getUnsignedInt(data); else if (varType == "unsigned short") val = DatabaseModel::instance()->getUnsignedShort(data); else if (varType == "boolean") val = DatabaseModel::instance()->getBoolean(data); else if (varType == "byte") val = DatabaseModel::instance()->getByte(data); else if (varType == "short") val = DatabaseModel::instance()->getShort(data); else if (varType == "int") val = DatabaseModel::instance()->getInt(data); else if (varType == "float") val = DatabaseModel::instance()->getFloat(data); else if (varType == "double") val = DatabaseModel::instance()->getDouble(data); else if (varType == "unsigned long") val = DatabaseModel::instance()->getUnsignedLong(data); else if (varType == "long") val = DatabaseModel::instance()->getLong(data); else val = "0x" + QString::number(DatabaseModel::instance()->getUnsignedLong(data), 16).toUpper(); return val; }
void ProjectGenerator::init() { int file_count = 0; verifyCompilers(); project->loadSpec(); project->evaluateFeatureFile("default_pre.prf"); project->evaluateFeatureFile("default_post.prf"); project->evaluateConfigFeatures(); project->values("CONFIG").clear(); Option::postProcessProject(project); ProValueMap &v = project->variables(); QString templ = Option::globals->user_template.isEmpty() ? QString("app") : Option::globals->user_template; if (!Option::globals->user_template_prefix.isEmpty()) templ.prepend(Option::globals->user_template_prefix); v["TEMPLATE_ASSIGN"] += templ; //the scary stuff if(project->first("TEMPLATE_ASSIGN") != "subdirs") { QString builtin_regex = project_builtin_regx(); QStringList dirs = Option::projfile::project_dirs; if(Option::projfile::do_pwd) { if(!v["INCLUDEPATH"].contains(".")) v["INCLUDEPATH"] += "."; dirs.prepend(qmake_getpwd()); } for(int i = 0; i < dirs.count(); ++i) { QString dir, regex, pd = dirs.at(i); bool add_depend = false; if(exists(pd)) { QFileInfo fi(fileInfo(pd)); if(fi.isDir()) { dir = pd; add_depend = true; if(dir.right(1) != Option::dir_sep) dir += Option::dir_sep; if (Option::recursive) { QStringList files = QDir(dir).entryList(QDir::Files); for (int i = 0; i < files.count(); i++) dirs.append(dir + files[i] + QDir::separator() + builtin_regex); } regex = builtin_regex; } else { QString file = pd; int s = file.lastIndexOf(Option::dir_sep); if(s != -1) dir = file.left(s+1); if(addFile(file)) { add_depend = true; file_count++; } } } else { //regexp regex = pd; } if(!regex.isEmpty()) { int s = regex.lastIndexOf(Option::dir_sep); if(s != -1) { dir = regex.left(s+1); regex = regex.right(regex.length() - (s+1)); } if (Option::recursive) { QStringList entries = QDir(dir).entryList(QDir::Dirs | QDir::NoDotAndDotDot); for (int i = 0; i < entries.count(); i++) dirs.append(dir + entries[i] + QDir::separator() + regex); } QStringList files = QDir(dir).entryList(QDir::nameFiltersFromString(regex)); for(int i = 0; i < (int)files.count(); i++) { QString file = dir + files[i]; if (addFile(file)) { add_depend = true; file_count++; } } } if(add_depend && !dir.isEmpty() && !v["DEPENDPATH"].contains(dir, Qt::CaseInsensitive)) { QFileInfo fi(fileInfo(dir)); if(fi.absoluteFilePath() != qmake_getpwd()) v["DEPENDPATH"] += fileFixify(dir); } } } if(!file_count) { //shall we try a subdir? QStringList knownDirs = Option::projfile::project_dirs; if(Option::projfile::do_pwd) knownDirs.prepend("."); const QString out_file = fileFixify(Option::output.fileName()); for(int i = 0; i < knownDirs.count(); ++i) { QString pd = knownDirs.at(i); if(exists(pd)) { QString newdir = pd; QFileInfo fi(fileInfo(newdir)); if(fi.isDir()) { newdir = fileFixify(newdir); ProStringList &subdirs = v["SUBDIRS"]; if(exists(fi.filePath() + QDir::separator() + fi.fileName() + Option::pro_ext) && !subdirs.contains(newdir, Qt::CaseInsensitive)) { subdirs.append(newdir); } else { QStringList profiles = QDir(newdir).entryList(QStringList("*" + Option::pro_ext), QDir::Files); for(int i = 0; i < (int)profiles.count(); i++) { QString nd = newdir; if(nd == ".") nd = ""; else if(!nd.isEmpty() && !nd.endsWith(QString(QChar(QDir::separator())))) nd += QDir::separator(); nd += profiles[i]; fileFixify(nd); if (!subdirs.contains(nd, Qt::CaseInsensitive) && !out_file.endsWith(nd)) subdirs.append(nd); } } if (Option::recursive) { QStringList dirs = QDir(newdir).entryList(QDir::Dirs | QDir::NoDotAndDotDot); for(int i = 0; i < (int)dirs.count(); i++) { QString nd = fileFixify(newdir + QDir::separator() + dirs[i]); if (!knownDirs.contains(nd, Qt::CaseInsensitive)) knownDirs.append(nd); } } } } else { //regexp QString regx = pd, dir; int s = regx.lastIndexOf(Option::dir_sep); if(s != -1) { dir = regx.left(s+1); regx = regx.right(regx.length() - (s+1)); } QStringList files = QDir(dir).entryList(QDir::nameFiltersFromString(regx), QDir::Dirs | QDir::NoDotAndDotDot); ProStringList &subdirs = v["SUBDIRS"]; for(int i = 0; i < (int)files.count(); i++) { QString newdir(dir + files[i]); QFileInfo fi(fileInfo(newdir)); { newdir = fileFixify(newdir); if(exists(fi.filePath() + QDir::separator() + fi.fileName() + Option::pro_ext) && !subdirs.contains(newdir)) { subdirs.append(newdir); } else { QStringList profiles = QDir(newdir).entryList(QStringList("*" + Option::pro_ext), QDir::Files); for(int i = 0; i < (int)profiles.count(); i++) { QString nd = newdir + QDir::separator() + files[i]; fileFixify(nd); if(files[i] != "." && files[i] != ".." && !subdirs.contains(nd, Qt::CaseInsensitive)) { if(newdir + files[i] != Option::output_dir + Option::output.fileName()) subdirs.append(nd); } } } if (Option::recursive && !knownDirs.contains(newdir, Qt::CaseInsensitive)) knownDirs.append(newdir); } } } } v["TEMPLATE_ASSIGN"] = ProStringList("subdirs"); return; } //setup deplist QList<QMakeLocalFileName> deplist; { const ProStringList &d = v["DEPENDPATH"]; for(int i = 0; i < d.size(); ++i) deplist.append(QMakeLocalFileName(d[i].toQString())); } setDependencyPaths(deplist); ProStringList &h = v["HEADERS"]; bool no_qt_files = true; static const char *srcs[] = { "SOURCES", "YACCSOURCES", "LEXSOURCES", "FORMS", 0 }; for (int i = 0; srcs[i]; i++) { const ProStringList &l = v[srcs[i]]; QMakeSourceFileInfo::SourceFileType type = QMakeSourceFileInfo::TYPE_C; QMakeSourceFileInfo::addSourceFiles(l, QMakeSourceFileInfo::SEEK_DEPS, type); for(int i = 0; i < l.size(); ++i) { QStringList tmp = QMakeSourceFileInfo::dependencies(l.at(i).toQString()); if(!tmp.isEmpty()) { for(int dep_it = 0; dep_it < tmp.size(); ++dep_it) { QString dep = tmp[dep_it]; dep = fixPathToQmake(dep); QString file_dir = dep.section(Option::dir_sep, 0, -2), file_no_path = dep.section(Option::dir_sep, -1); if(!file_dir.isEmpty()) { for(int inc_it = 0; inc_it < deplist.size(); ++inc_it) { QMakeLocalFileName inc = deplist[inc_it]; if(inc.local() == file_dir && !v["INCLUDEPATH"].contains(inc.real(), Qt::CaseInsensitive)) v["INCLUDEPATH"] += inc.real(); } } if(no_qt_files && file_no_path.indexOf(QRegExp("^q[a-z_0-9].h$")) != -1) no_qt_files = false; QString h_ext; for(int hit = 0; hit < Option::h_ext.size(); ++hit) { if(dep.endsWith(Option::h_ext.at(hit))) { h_ext = Option::h_ext.at(hit); break; } } if(!h_ext.isEmpty()) { for(int cppit = 0; cppit < Option::cpp_ext.size(); ++cppit) { QString src(dep.left(dep.length() - h_ext.length()) + Option::cpp_ext.at(cppit)); if(exists(src)) { ProStringList &srcl = v["SOURCES"]; if(!srcl.contains(src, Qt::CaseInsensitive)) srcl.append(src); } } } else if(dep.endsWith(Option::lex_ext) && file_no_path.startsWith(Option::lex_mod)) { addConfig("lex_included"); } if(!h.contains(dep, Qt::CaseInsensitive)) h += dep; } } } } //strip out files that are actually output from internal compilers (ie temporary files) const ProStringList &quc = project->values("QMAKE_EXTRA_COMPILERS"); for (ProStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it) { QString tmp_out = project->first(ProKey(*it + ".output")).toQString(); if(tmp_out.isEmpty()) continue; ProStringList var_out = project->values(ProKey(*it + ".variable_out")); bool defaults = var_out.isEmpty(); for(int i = 0; i < var_out.size(); ++i) { ProString v = var_out.at(i); if(v.startsWith("GENERATED_")) { defaults = true; break; } } if(defaults) { var_out << "SOURCES"; var_out << "HEADERS"; var_out << "FORMS"; } const ProStringList &tmp = project->values(ProKey(*it + ".input")); for (ProStringList::ConstIterator it2 = tmp.begin(); it2 != tmp.end(); ++it2) { ProStringList &inputs = project->values((*it2).toKey()); for (ProStringList::Iterator input = inputs.begin(); input != inputs.end(); ++input) { QString path = replaceExtraCompilerVariables(tmp_out, (*input).toQString(), QString(), NoShell); path = fixPathToQmake(path).section('/', -1); for(int i = 0; i < var_out.size(); ++i) { ProString v = var_out.at(i); ProStringList &list = project->values(v.toKey()); for(int src = 0; src < list.size(); ) { if(list[src] == path || list[src].endsWith("/" + path)) list.removeAt(src); else ++src; } } } } } }
void LuaEngine::loadMultiRet(QFile *file) { //Now read our code. QString luaCode = QTextStream(file).readAll(); //Now load our code by lua and check for common compile errors int errorCode = luautil_loadlua(L, luaCode.toLocal8Bit().data(), luaCode.length(), luaCode.section('/', -1).section('\\', -1).toLocal8Bit().data()); //If we get an error, then handle it if(errorCode){ qWarning() << "Got lua error, reporting... [loadMultiRet] " << file->fileName(); m_errorReporterFunc(QString(lua_tostring(L, -1)), QString("")); m_lateShutdown = true; shutdown(); return; } }
/*! * \brief Updates a file in the database. * * \param filename Full path to file. * * \returns Nothing. */ void FileScanner::UpdateFileInDB(const QString &filename) { QString directory = filename; directory.remove(0, m_startdir.length()); directory = directory.section( '/', 0, -2); Decoder *decoder = Decoder::create(filename, NULL, NULL, true); if (decoder) { Metadata *db_meta = decoder->getMetadata(); Metadata *disk_meta = decoder->readMetadata(); if (db_meta && disk_meta) { disk_meta->setID(db_meta->ID()); disk_meta->setRating(db_meta->Rating()); QString album_cache_string; // Set values from cache int did = m_directoryid[directory]; if (did > 0) disk_meta->setDirectoryId(did); int aid = m_artistid[disk_meta->Artist().toLower()]; if (aid > 0) { disk_meta->setArtistId(aid); // The album cache depends on the artist id album_cache_string = disk_meta->getArtistId() + "#" + disk_meta->Album().toLower(); if (m_albumid[album_cache_string] > 0) disk_meta->setAlbumId(m_albumid[album_cache_string]); } int gid = m_genreid[disk_meta->Genre().toLower()]; if (gid > 0) disk_meta->setGenreId(gid); // Commit track info to database disk_meta->dumpToDatabase(); // Update the cache m_artistid[disk_meta->Artist().toLower()] = disk_meta->getArtistId(); m_genreid[disk_meta->Genre().toLower()] = disk_meta->getGenreId(); album_cache_string = disk_meta->getArtistId() + "#" + disk_meta->Album().toLower(); m_albumid[album_cache_string] = disk_meta->getAlbumId(); } if (disk_meta) delete disk_meta; if (db_meta) delete db_meta; delete decoder; } }
void LuaEngine::postLateShutdownError(luabind::error &error) { QString runtimeErrorMsg = error.what(); m_errorReporterFunc(runtimeErrorMsg.section('\n', 0, 0), runtimeErrorMsg.section('\n', 1)); m_lateShutdown = true; }
// static bool Cddb::Query(Matches& res, const Toc& toc) { if (toc.size() < 2) return false; const unsigned totalTracks = toc.size() - 1; unsigned secs = 0; const discid_t discID = Discid(secs, toc.data(), totalTracks); // Is it cached? if (Dbase::Search(res, discID)) return res.matches.size() > 0; // Construct query // cddb query discid ntrks off1 off2 ... nsecs QString URL2 = URL + QString("cddb+query+%1+%2+").arg(discID,0,16).arg(totalTracks); for (unsigned t = 0; t < totalTracks; ++t) URL2 += QString("%1+").arg(msf2lsn(toc[t])); URL2 += QString::number(secs); // Send the request URL2 += "&hello=" + helloID() + "&proto=5"; LOG(VB_MEDIA, LOG_INFO, "CDDB lookup: " + URL2); QString cddb; QByteArray data; if (!GetMythDownloadManager()->download(URL2, &data)) return false; cddb = data; // Check returned status const uint stat = cddb.left(3).toUInt(); // Extract 3 digit status: cddb = cddb.mid(4); switch (stat) { case 200: // Unique match LOG(VB_MEDIA, LOG_INFO, "CDDB match: " + cddb.trimmed()); // e.g. "200 rock 960b5e0c Nichole Nordeman / Woven & Spun" res.discID = discID; res.isExact = true; res.matches.push_back(Match( cddb.section(' ', 0, 0), // genre cddb.section(' ', 1, 1).toUInt(0,16), // discID cddb.section(' ', 2).section(" / ", 0, 0), // artist cddb.section(' ', 2).section(" / ", 1) // title )); break; case 202: // No match for disc ID... LOG(VB_MEDIA, LOG_INFO, "CDDB no match"); Dbase::New(discID, toc); // Stop future lookups return false; case 210: // Multiple exact matches case 211: // Multiple inexact matches // 210 Found exact matches, list follows (until terminating `.') // 211 Found inexact matches, list follows (until terminating `.') res.discID = discID; res.isExact = 210 == stat; // Remove status line cddb = cddb.section('\n', 1); // Append all matches while (!cddb.isEmpty() && !cddb.startsWith(".")) { LOG(VB_MEDIA, LOG_INFO, QString("CDDB %1 match: %2"). arg(210 == stat ? "exact" : "inexact"). arg(cddb.section('\n',0,0))); res.matches.push_back(Match( cddb.section(' ', 0, 0), // genre cddb.section(' ', 1, 1).toUInt(0,16), // discID cddb.section(' ', 2).section(" / ", 0, 0), // artist cddb.section(' ', 2).section(" / ", 1) // title )); cddb = cddb.section('\n', 1); } if (res.matches.size() <= 0) Dbase::New(discID, toc); // Stop future lookups break; default: // TODO try a (telnet 8880) CDDB lookup LOG(VB_GENERAL, LOG_INFO, QString("CDDB query error: %1").arg(stat) + cddb.trimmed()); return false; } return true; }
int main(int argc, char **argv) { QApplication app(argc, argv, true); QTranslator custranldr; QTranslator translator; QString tnapplang; QString tnappcoun; QString clangcode = ""; QStringList allappargs = app.arguments(); QList<QPair<QString, QString> > oppairs; for (QList<QString>::const_iterator i = allappargs.constBegin(); i < allappargs.constEnd(); ++i) { if (i->count('=') == 1) oppairs.append(QPair<QString, QString>(i->section('=', 0, 0).simplified(), i->section('=',1, 1).simplified())); } for (QList<QPair<QString, QString> >::const_iterator i = oppairs.constBegin(); i < oppairs.constEnd(); ++i) { if (i->first.contains("lang", Qt::CaseInsensitive)) { clangcode = i->second; tnapplang = clangcode.left(2); if (clangcode.contains('_') && clangcode.size() == 5) { tnappcoun = clangcode.section('_', -1, -1); } break; } } if (clangcode.isEmpty()) { clangcode = QLocale::system().name(); tnapplang = clangcode.left(2); if (clangcode.contains('_') && clangcode.size() == 5) { tnappcoun = clangcode.section('_', -1, -1); } } QDir applocdir(app.applicationDirPath()); QStringList applocfiles = applocdir.entryList(QStringList() << "*.qm", QDir::Files); if (!applocfiles.isEmpty()) { QString custqmfilepath = applocfiles.at(0); if (!applocfiles.filter("unetbootin").isEmpty()) { custqmfilepath = applocfiles.filter("unetbootin").at(0); if (!applocfiles.filter("unetbootin").filter(tnapplang).isEmpty()) { custqmfilepath = applocfiles.filter("unetbootin").filter(tnapplang).at(0); if (!tnappcoun.isEmpty() && !applocfiles.filter("unetbootin").filter(tnapplang).filter(tnappcoun).isEmpty()) custqmfilepath = applocfiles.filter("unetbootin").filter(tnapplang).filter(tnappcoun).at(0); } } if (custranldr.load(custqmfilepath, app.applicationDirPath())) app.installTranslator(&custranldr); } if (!tnappcoun.isEmpty() && QFile::exists(QString("%1/unetbootin_%2_%3.qm").arg(app.applicationDirPath()).arg(tnapplang).arg(tnappcoun)) && translator.load(QString("%1/unetbootin_%2_%3.qm").arg(app.applicationDirPath()).arg(tnapplang).arg(tnappcoun))) { app.installTranslator(&translator); } else if (!tnappcoun.isEmpty() && QFile::exists(QString(":/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)) && translator.load(QString(":/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun))) { app.installTranslator(&translator); } else if (!tnappcoun.isEmpty() && QFile::exists(QString("/usr/share/unetbootin/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)) && translator.load(QString("/usr/share/unetbootin/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun))) { app.installTranslator(&translator); } else if (QFile::exists(QString("%1/unetbootin_%2.qm").arg(app.applicationDirPath(), tnapplang)) && translator.load(QString("%1/unetbootin_%2.qm").arg(app.applicationDirPath(), tnapplang))) { app.installTranslator(&translator); } else if (QFile::exists(QString(":/unetbootin_%1.qm").arg(tnapplang)) && translator.load(QString(":/unetbootin_%1.qm").arg(tnapplang))) { app.installTranslator(&translator); } else if (QFile::exists(QString("/usr/share/unetbootin/unetbootin_%1.qm").arg(tnapplang)) && translator.load(QString("/usr/share/unetbootin/unetbootin_%1.qm").arg(tnapplang))) { app.installTranslator(&translator); } else { tnapplang = "en"; tnappcoun = "US"; clangcode = "en_US"; } app.installTranslator(&translator); if (QObject::tr("LeftToRight") == "RightToLeft") app.setLayoutDirection(Qt::RightToLeft); #ifdef Q_OS_UNIX bool disabledrootcheck = false; for (QList<QPair<QString, QString> >::const_iterator i = oppairs.constBegin(); i < oppairs.constEnd(); ++i) { if (i->first.contains("rootcheck", Qt::CaseInsensitive)) { if (i->second.contains('n', Qt::CaseInsensitive)) disabledrootcheck = true; break; } } if (!disabledrootcheck) { QProcess whoamip; whoamip.start("whoami"); whoamip.waitForFinished(); if (QString(whoamip.readAll()).remove("\r").remove("\n") != "root") { QString argsconc = ""; for (int i = 1; i < allappargs.size(); ++i) { argsconc += QString("\"%1\" ").arg(allappargs.at(i)); } argsconc += "'rootcheck=no'"; QString gksulocation = checkforgraphicalsu("gksu"); if (gksulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(gksulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString kdesulocation = checkforgraphicalsu("kdesu"); if (kdesulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(kdesulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString gnomesulocation = checkforgraphicalsu("gnomesu"); if (gnomesulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(gnomesulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString kdesudolocation = checkforgraphicalsu("kdesudo"); if (kdesudolocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(kdesudolocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QMessageBox rootmsgb; rootmsgb.setIcon(QMessageBox::Warning); rootmsgb.setWindowTitle(uninstaller::tr("Must run as root")); rootmsgb.setTextFormat(Qt::RichText); rootmsgb.setText(uninstaller::tr("%2 must be run as root. Close it, and re-run using either:<br/><b>sudo %1</b><br/>or:<br/><b>su -c '%1'</b>").arg(app.applicationFilePath()).arg(UNETBOOTINB)); rootmsgb.setStandardButtons(QMessageBox::Ok); switch (rootmsgb.exec()) { case QMessageBox::Ok: break; default: break; } } } #endif #ifdef Q_OS_WIN32 QSettings chkinst("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\UNetbootin", QSettings::NativeFormat); #endif #ifdef Q_OS_UNIX QSettings chkinst(QSettings::SystemScope, "UNetbootin"); #endif if (chkinst.contains("Location")) { QMessageBox uninstmsgb; uninstmsgb.setIcon(QMessageBox::Information); uninstmsgb.setWindowTitle(uninstaller::tr("%1 Uninstaller").arg(UNETBOOTINB)); uninstmsgb.setText(uninstaller::tr("%1 is currently installed. Remove the existing version?").arg(UNETBOOTINB)); uninstmsgb.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); switch (uninstmsgb.exec()) { case QMessageBox::Ok: { ubnUninst(); } case QMessageBox::Cancel: break; default: break; } return 0; } unetbootin unetbootin; unetbootin.appNlang = tnapplang; unetbootin.appDir = QDir::toNativeSeparators(QString("%1/").arg(app.applicationDirPath())); unetbootin.appLoc = app.applicationFilePath(); bool automate = unetbootin.ubninitialize(oppairs); unetbootin.show(); if (automate) unetbootin.on_okbutton_clicked(); return app.exec(); }
bool DVDStream::OpenFile(const QString &filename, uint /*retry_ms*/) { rwlock.lockForWrite(); const QString root = filename.section("/VIDEO_TS/", 0, 0); const QString path = filename.section(root, 1); if (m_reader) DVDClose(m_reader); m_reader = DVDOpen(qPrintable(root)); if (!m_reader) { LOG(VB_GENERAL, LOG_ERR, QString("DVDStream DVDOpen(%1) failed").arg(filename)); rwlock.unlock(); return false; } if (!path.isEmpty()) { // Locate the start block of the requested title uint32_t len; m_start = UDFFindFile(m_reader, const_cast<char*>(qPrintable(path)), &len); if (m_start == 0) { LOG(VB_GENERAL, LOG_ERR, QString("DVDStream(%1) UDFFindFile(%2) failed"). arg(root).arg(path)); DVDClose(m_reader); m_reader = 0; rwlock.unlock(); return false; } else { m_list.append(BlockRange(0, Len2Blocks(len), 0)); } } else { // Create a list of the possibly encrypted files uint32_t len, start; // Root menu char name[64] = "VIDEO_TS/VIDEO_TS.VOB"; start = UDFFindFile(m_reader, name, &len); if( start != 0 && len != 0 ) m_list.append(BlockRange(start, Len2Blocks(len), 0)); const int kTitles = 100; for ( int title = 1; title < kTitles; ++title) { // Menu snprintf(name, sizeof name, "/VIDEO_TS/VTS_%02d_0.VOB", title); start = UDFFindFile(m_reader, name, &len); if( start != 0 && len != 0 ) m_list.append(BlockRange(start, Len2Blocks(len), title)); for ( int part = 1; part < 10; ++part) { // A/V track snprintf(name, sizeof name, "/VIDEO_TS/VTS_%02d_%d.VOB", title, part); start = UDFFindFile(m_reader, name, &len); if( start != 0 && len != 0 ) m_list.append(BlockRange(start, Len2Blocks(len), title + part * kTitles)); } } qSort( m_list); // Open the root menu so that CSS keys are generated now dvd_file_t *file = DVDOpenFile(m_reader, 0, DVD_READ_MENU_VOBS); if (file) DVDCloseFile(file); else LOG(VB_GENERAL, LOG_ERR, "DVDStream DVDOpenFile(VOBS_1) failed"); } rwlock.unlock(); return true; }
int main(int argc, char *argv[]) { QApplication a(argc, argv); // apply default settings QucsSettings.x = 60; QucsSettings.y = 30; QucsSettings.dx = 640; QucsSettings.dy = 400; QucsSettings.font = QFont("Helvetica", 12); // is application relocated? char * var = getenv ("QUCSDIR"); QDir QucsDir; if (var != NULL) { QucsDir = QDir (QString(var)); QString QucsDirStr = QucsDir.canonicalPath (); QucsSettings.DocDir = QDir::convertSeparators (QucsDirStr + "/share/qucs/docs/"); QucsSettings.LangDir = QDir::convertSeparators (QucsDirStr + "/share/qucs/lang/"); } else { QString QucsApplicationPath = QCoreApplication::applicationDirPath(); #ifdef __APPLE__ QucsDir = QDir(QucsApplicationPath.section("/bin",0,0)); #else QucsDir = QDir(QucsApplicationPath); QucsDir.cdUp(); #endif QucsSettings.DocDir = QucsDir.canonicalPath() + "/share/qucs/docs/"; QucsSettings.LangDir = QucsDir.canonicalPath() + "/share/qucs/lang/"; } loadSettings(); a.setFont(QucsSettings.font); QTranslator tor( 0 ); QString locale = QucsSettings.Language; if(locale.isEmpty()) locale = QString(QLocale::system().name()); tor.load( QString("qucs_") + locale, QucsSettings.LangDir); a.installTranslator( &tor ); QucsHelpDir = QucsSettings.DocDir + locale; if (!QucsHelpDir.exists () || !QucsHelpDir.isReadable ()) { int p = locale.indexOf ('_'); if (p != -1) { QucsHelpDir = QucsSettings.DocDir + locale.left (p); if (!QucsHelpDir.exists () || !QucsHelpDir.isReadable ()) { QucsHelpDir = QucsSettings.DocDir + "en"; } } else QucsHelpDir = QucsSettings.DocDir + "en"; } QString Page; if(argc > 1) Page = argv[1]; qInstallMsgHandler(qucsMessageOutput); QucsHelp *qucs = new QucsHelp(Page); //a.setMainWidget(qucs); qucs->resize(QucsSettings.dx, QucsSettings.dy); // size and position ... qucs->move(QucsSettings.x, QucsSettings.y); // ... before "show" !!! qucs->show(); int result = a.exec(); saveApplSettings(qucs); return result; }
QString QgsWcsCapabilities::stripNS( const QString & name ) { return name.contains( ":" ) ? name.section( ':', 1 ) : name; }
void MainUI::loadHomePage(){ //Load the settings for the webUI QStringList settings; QFile file("/usr/local/etc/appcafe.conf"); if(file.exists()){ if(file.open(QIODevice::ReadOnly | QIODevice::Text)){ QTextStream in(&file); while(!in.atEnd()){ settings << in.readLine(); } file.close(); } } QString port = "8885"; bool usessl = false; for(int i=0; i<settings.length(); i++){ if(settings[i].startsWith(";")){ continue; } if(settings[i].startsWith("port =")){ port = settings[i].section("=",1,1).simplified(); }else if(settings[i].startsWith("ssl =")){ usessl = settings[i].section("=",1,1).simplified()=="true"; } } if( QFile::exists("/tmp/.rebootRequired") ){ //System waiting to reboot - put up a notice and disable the web viewer webview->setHtml("<p><strong>"+tr("System needs to reboot to finish applying updates!")+"</strong></p>"); backA->setVisible(false); forA->setVisible(false); refA->setVisible(false); stopA->setVisible(false); progA->setVisible(false); return; } //Load the main page baseURL = BASEWEBURL; baseURL = baseURL.replace("<port>", port); if(usessl){ baseURL = baseURL.replace("http://","https://"); } if(DEBUG){ qDebug() << "Base URL:" << baseURL; } QString tmpURL = baseURL; if( !AUTHCOMPLETE ){ //Only perform the authorization if necessary QString authkey = pcbsd::Utils::getLineFromCommandOutput("/usr/local/bin/pc-su /usr/local/share/appcafe/dispatcher-localauth 2>/dev/null").simplified(); AUTHCOMPLETE = !authkey.isEmpty(); if(DEBUG){ qDebug() << "Got Auth Key:" << AUTHCOMPLETE << authkey; } if ( authkey.indexOf(":") != -1 ) authkey = authkey.section(":", 1, 1); if(AUTHCOMPLETE){ tmpURL.append("/?setDisId="+authkey); } } //Now clear the history (if any) //Now load the page if(AUTHCOMPLETE){ webview->load( QUrl(tmpURL) ); webview->show(); }else{ //System waiting to reboot - put up a notice and disable the web viewer webview->setHtml("<p><strong>"+tr("You are not authorized to view the AppCafe. Please contact a system administrator for assistance.")+"</strong></p>"); backA->setEnabled(false); forA->setEnabled(false); refA->setVisible(false); stopA->setVisible(false); progA->setVisible(false); } }
bool ParseOptions(__DIE_OPTIONS *pOptions,QStringList *pListArguments,QStringList *pListFiles) { QString sParam; QString sTemp; QStringList listTemp1; for(int i=1; i<pListArguments->count(); i++) { sParam=pListArguments->at(i); if(sParam.toLower().contains("-showerrors:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bShowErrors=true; } else if(sTemp=="no") { pOptions->bShowErrors=false; } else { printf("Invalid parameter: %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-showoptions:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bShowOptions=true; } else if(sTemp=="no") { pOptions->bShowOptions=false; } else { printf("Invalid parameter: %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-showversion:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bShowVersion=true; } else if(sTemp=="no") { pOptions->bShowVersion=false; } else { printf("Invalid parameter: %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-subfolders:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bScanSubfolders=true; } else if(sTemp=="no") { pOptions->bScanSubfolders=false; } else { printf("Invalid parameter: %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-showentropy:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bShowEntropy=true; } else if(sTemp=="no") { pOptions->bShowEntropy=false; } else { printf("Invalid parameter: %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-singlelineoutput:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bSingleLineOutput=true; } else if(sTemp=="no") { pOptions->bSingleLineOutput=false; } else { printf("Invalid parameter %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-showfileformatonce:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bShowFileFormatOnce=true; } else if(sTemp=="no") { pOptions->bShowFileFormatOnce=false; } else { printf("Invalid parameter: %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-fullscan:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bFullScan=true; } else if(sTemp=="no") { pOptions->bFullScan=false; } else { printf("Invalid parameter: %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-database:")) { sTemp=sParam.section(":",1,1).toLower(); QDir _dir; if(_dir.exists(Utils::convertPath(sTemp))) { pOptions->sDataBasePath=sTemp; } else { printf("Invalid database name: %s",sTemp.toAscii().data()); return false; } } else { listTemp1.append(sParam); } } if(listTemp1.count()==0) { printf("No file specified"); return false; } QFile file; QDir dir; // QDir dir2; // int nNumberOfSlash=0; // QStringList listTemp2; // QFileInfoList fil; // QString sBaseName; for(int i=0; i<listTemp1.count(); i++) { file.setFileName(listTemp1.at(i)); dir.setPath(listTemp1.at(i)); if(listTemp1.at(i)==".") { continue; } else if(listTemp1.at(i)=="..") { continue; } else if(dir.exists()) { FindFiles(listTemp1.at(i),pListFiles,pOptions->bScanSubfolders); } else if(file.exists()) { pListFiles->append(listTemp1.at(i)); } else if(listTemp1.at(i).contains("*")||listTemp1.at(i).contains("?")) { QStringList nameFilters; nameFilters.append(listTemp1.at(i)); QDir _dir; QFileInfoList listFI=_dir.entryInfoList(nameFilters); for(int j=0; j<listFI.count(); j++) { if(listFI.at(j).isDir()) { FindFiles(listFI.at(j).absoluteFilePath(),pListFiles,pOptions->bScanSubfolders); } else if(listFI.at(j).isFile()) { pListFiles->append(listFI.at(j).absoluteFilePath()); } } } else { printf("Invalid parameter or file name: %s",listTemp1.at(i).toAscii().data()); return false; } // if(listTemp1.at(i).contains("*")||listTemp1.at(i).contains("?")) // { // sTemp=listTemp1.at(i); // sTemp.replace("/",QDir::separator()); // sTemp.replace("\\",QDir::separator()); // nNumberOfSlash=sTemp.count(QDir::separator()); // if(nNumberOfSlash) // { // dir2.setPath(sTemp.section(QDir::separator(),0,nNumberOfSlash-1)+QDir::separator()); // sTemp=sTemp.section(QDir::separator(),nNumberOfSlash); // } // fil=dir2.entryInfoList(QStringList()<<sTemp); // for(int j=0;j<fil.count();j++) // { // sBaseName=fil.at(j).baseName(); // if((sBaseName!=".")&&(sBaseName!="..")&&(sBaseName!="")) // { // listTemp2.append(fil.at(j).absoluteFilePath()); // } // } // } // else // { // listTemp2.append(listTemp1.at(i)); // } } // QDir _dir; // QFileInfoList listFI=_dir.entryInfoList(nameFilters); //// listAnother2.append(dir2.entryList(listFilters)); // for(int i=0;i<listTemp2.count();i++) // { // file.setFileName(listTemp2.at(i)); // dir.setPath(listTemp2.at(i)); // if(listTemp2.at(i)==".") // { // continue; // } // else if(listTemp2.at(i)=="..") // { // continue; // } // else if(dir.exists()) // { // FindFiles(listTemp2.at(i),pListFiles,pOptions->bScanSubfolders); // } // else if(file.exists()) // { // pListFiles->append(listTemp2.at(i)); // } // else // { // printf("Invalid parameter or file name: %s",listTemp2.at(i).toAscii().data()); // return false; // } // } return true; }
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice, const QString &fname, QString currentPath, bool ignoreErrors) { Q_ASSERT(m_errorDevice); const QChar slash = QLatin1Char('/'); if (!currentPath.isEmpty() && !currentPath.endsWith(slash)) currentPath += slash; QXmlStreamReader reader(inputDevice); QStack<RCCXmlTag> tokens; QString prefix; QLocale::Language language = QLocale::c().language(); QLocale::Country country = QLocale::c().country(); QString alias; int compressLevel = m_compressLevel; int compressThreshold = m_compressThreshold; while (!reader.atEnd()) { QXmlStreamReader::TokenType t = reader.readNext(); switch (t) { case QXmlStreamReader::StartElement: if (reader.name() == m_strings.TAG_RCC) { if (!tokens.isEmpty()) reader.raiseError(QLatin1String("expected <RCC> tag")); else tokens.push(RccTag); } else if (reader.name() == m_strings.TAG_RESOURCE) { if (tokens.isEmpty() || tokens.top() != RccTag) { reader.raiseError(QLatin1String("unexpected <RESOURCE> tag")); } else { tokens.push(ResourceTag); QXmlStreamAttributes attributes = reader.attributes(); language = QLocale::c().language(); country = QLocale::c().country(); if (attributes.hasAttribute(m_strings.ATTRIBUTE_LANG)) { QString attribute = attributes.value(m_strings.ATTRIBUTE_LANG).toString(); QLocale lang = QLocale(attribute); language = lang.language(); if (2 == attribute.length()) { // Language only country = QLocale::AnyCountry; } else { country = lang.country(); } } prefix.clear(); if (attributes.hasAttribute(m_strings.ATTRIBUTE_PREFIX)) prefix = attributes.value(m_strings.ATTRIBUTE_PREFIX).toString(); if (!prefix.startsWith(slash)) prefix.prepend(slash); if (!prefix.endsWith(slash)) prefix += slash; } } else if (reader.name() == m_strings.TAG_FILE) { if (tokens.isEmpty() || tokens.top() != ResourceTag) { reader.raiseError(QLatin1String("unexpected <FILE> tag")); } else { tokens.push(FileTag); QXmlStreamAttributes attributes = reader.attributes(); alias.clear(); if (attributes.hasAttribute(m_strings.ATTRIBUTE_ALIAS)) alias = attributes.value(m_strings.ATTRIBUTE_ALIAS).toString(); compressLevel = m_compressLevel; if (attributes.hasAttribute(m_strings.ATTRIBUTE_COMPRESS)) compressLevel = attributes.value(m_strings.ATTRIBUTE_COMPRESS).toString().toInt(); compressThreshold = m_compressThreshold; if (attributes.hasAttribute(m_strings.ATTRIBUTE_THRESHOLD)) compressThreshold = attributes.value(m_strings.ATTRIBUTE_THRESHOLD).toString().toInt(); // Special case for -no-compress. Overrides all other settings. if (m_compressLevel == -2) compressLevel = 0; } } else { reader.raiseError(QString(QLatin1String("unexpected tag: %1")).arg(reader.name().toString())); } break; case QXmlStreamReader::EndElement: if (reader.name() == m_strings.TAG_RCC) { if (!tokens.isEmpty() && tokens.top() == RccTag) tokens.pop(); else reader.raiseError(QLatin1String("unexpected closing tag")); } else if (reader.name() == m_strings.TAG_RESOURCE) { if (!tokens.isEmpty() && tokens.top() == ResourceTag) tokens.pop(); else reader.raiseError(QLatin1String("unexpected closing tag")); } else if (reader.name() == m_strings.TAG_FILE) { if (!tokens.isEmpty() && tokens.top() == FileTag) tokens.pop(); else reader.raiseError(QLatin1String("unexpected closing tag")); } break; case QXmlStreamReader::Characters: if (reader.isWhitespace()) break; if (tokens.isEmpty() || tokens.top() != FileTag) { reader.raiseError(QLatin1String("unexpected text")); } else { QString fileName = reader.text().toString(); if (fileName.isEmpty()) { const QString msg = QString::fromLatin1("RCC: Warning: Null node in XML of '%1'\n").arg(fname); m_errorDevice->write(msg.toUtf8()); } if (alias.isNull()) alias = fileName; alias = QDir::cleanPath(alias); while (alias.startsWith(QLatin1String("../"))) alias.remove(0, 3); alias = QDir::cleanPath(m_resourceRoot) + prefix + alias; QString absFileName = fileName; if (QDir::isRelativePath(absFileName)) absFileName.prepend(currentPath); QFileInfo file(absFileName); if (!file.exists()) { m_failedResources.push_back(absFileName); const QString msg = QString::fromLatin1("RCC: Error in '%1': Cannot find file '%2'\n").arg(fname).arg(fileName); m_errorDevice->write(msg.toUtf8()); if (ignoreErrors) continue; else return false; } else if (file.isFile()) { const bool arc = addFile(alias, RCCFileInfo(alias.section(slash, -1), file, language, country, RCCFileInfo::NoFlags, compressLevel, compressThreshold) ); if (!arc) m_failedResources.push_back(absFileName); } else { QDir dir; if (file.isDir()) { dir.setPath(file.filePath()); } else { dir.setPath(file.path()); dir.setNameFilters(QStringList(file.fileName())); if (alias.endsWith(file.fileName())) alias = alias.left(alias.length()-file.fileName().length()); } if (!alias.endsWith(slash)) alias += slash; QDirIterator it(dir, QDirIterator::FollowSymlinks|QDirIterator::Subdirectories); while (it.hasNext()) { it.next(); QFileInfo child(it.fileInfo()); if (child.fileName() != QLatin1String(".") && child.fileName() != QLatin1String("..")) { const bool arc = addFile(alias + child.fileName(), RCCFileInfo(child.fileName(), child, language, country, child.isDir() ? RCCFileInfo::Directory : RCCFileInfo::NoFlags, compressLevel, compressThreshold) ); if (!arc) m_failedResources.push_back(child.fileName()); } } } } break; default: break; } } if (reader.hasError()) { if (ignoreErrors) return true; int errorLine = reader.lineNumber(); int errorColumn = reader.columnNumber(); QString errorMessage = reader.errorString(); QString msg = QString::fromLatin1("RCC Parse Error: '%1' Line: %2 Column: %3 [%4]\n").arg(fname).arg(errorLine).arg(errorColumn).arg(errorMessage); m_errorDevice->write(msg.toUtf8()); return false; } if (m_root == 0) { const QString msg = QString::fromUtf8("RCC: Warning: No resources in '%1'.\n").arg(fname); m_errorDevice->write(msg.toUtf8()); if (!ignoreErrors && m_format == Binary) { // create dummy entry, otherwise loading with QResource will crash m_root = new RCCFileInfo(QString(), QFileInfo(), QLocale::C, QLocale::AnyCountry, RCCFileInfo::Directory); } } return true; }
void getCMD(int argc, char ** argv, QString& binary, QString& args, QString& path){ //Get the input file QString inFile; bool showDLG = false; //flag to bypass any default application setting if(argc > 1){ for(int i=1; i<argc; i++){ if(QString(argv[i]).simplified() == "-select"){ showDLG = true; }else{ inFile = argv[i]; break; } } }else{ printUsageInfo(); } //Make sure that it is a valid file/URL bool isFile=false; bool isUrl=false; if(QFile::exists(inFile)){ isFile=true; } else if(QUrl(inFile).isValid()){ isUrl=true; } if( !isFile && !isUrl ){ qDebug() << "Error: Invalid file or URL"; return;} //Determing the type of file (extension) QString extension; if(isFile){ QFileInfo info(inFile); extension=info.completeSuffix(); if(info.isDir()){ extension="directory"; } else if(info.isExecutable() && extension!="desktop"){ extension="binary"; } }else if(isUrl){ extension = inFile.section(":",0,0); } //if not an application - find the right application to open the file QString cmd; bool useInputFile = false; if(extension=="desktop" && !showDLG){ bool ok = false; XDGDesktop DF = LXDG::loadDesktopFile(inFile, ok); if(!ok){ qDebug() << "[ERROR] Input *.desktop file could not be read:" << inFile; exit(1); } switch(DF.type){ case XDGDesktop::APP: if(!DF.exec.isEmpty()){ cmd = LXDG::getDesktopExec(DF); if(!DF.path.isEmpty()){ path = DF.path; } }else{ qDebug() << "[ERROR] Input *.desktop application file is missing the Exec line:" << inFile; exit(1); } break; case XDGDesktop::LINK: if(!DF.url.isEmpty()){ //This is a URL - so adjust the input variables appropriately inFile = DF.url; cmd.clear(); extension = inFile.section(":",0,0); }else{ qDebug() << "[ERROR] Input *.desktop link file is missing the URL line:" << inFile; exit(1); } break; case XDGDesktop::DIR: if(!DF.path.isEmpty()){ //This is a directory link - adjust inputs inFile = DF.path; cmd.clear(); extension = "directorypath"; }else{ qDebug() << "[ERROR] Input *.desktop directory file is missing the Path line:" << inFile; exit(1); } break; default: qDebug() << "[ERROR] Unknown *.desktop file type:" << inFile; exit(1); } } if(cmd.isEmpty()){ if(extension=="binary"){ cmd = inFile; } else{ //Find out the proper application to use this file/directory useInputFile=true; cmd = cmdFromUser(argc, argv, inFile, extension, path, showDLG); } } //qDebug() << "Found Command:" << cmd << "Extension:" << extension; //Clean up the command appropriately for output if(cmd.contains("%")){cmd = cmd.remove("%U").remove("%u").remove("%F").remove("%f").simplified(); } binary = cmd; if(useInputFile){ args = inFile; } }
void MainWindow_M::importFile(const char* folder,int* file,double* color,int size,bool bkg) { // if CSAEncodeImages object not exist, create it if(m_pSAEncodeImg == NULL) { qDebug()<<"loading the encoded file"; QString fileName = folder; //fileName += "\\"+fileName.section('\\',-1) + ".sa"; fileName += "\\"+fileName.section('\\',-1) + ".data"; m_pSAEncodeImg = new CSAEncodeVectorImages(); m_pSAEncodeImg->loadFromFile(fileName.toAscii()); qDebug()<<"encoded file loaded"; } // clear the graphics scene m_graphicsScene.clear(); // draw the shadow QImage resultImage,tmp; resultImage = QImage(480,480,QImage::Format_ARGB32); resultImage.fill(qRgba(255,255,255,0)); tmp = QImage(120,120,QImage::Format_ARGB32); int displaynum = min(m_iDisplayNearestNum,size); if(renderarea->m_pSkeleton) { Skeleton* pSkeleton = renderarea->m_pSkeleton; // Nearest neighbor in graphics view for(int i = 0; i < displaynum /*&& i < 20*/; i++) { tmp.fill(qRgba(255,255,255,0)); int ix = (displaynum - i) * (colormap.size() - 1) / displaynum; // use the colormap to describe the probability QColor color2(colormap[ix][0] * 255,colormap[ix][1] * 255,colormap[ix][2] * 255); //QColor color2(colormap[colormap.size()-1-i*3][0] * 255,colormap[colormap.size()-1-i*3][1] * 255,colormap[colormap.size()-1-i*3][2] * 255); QPainter painter(&tmp); painter.setPen(color2); for(int j = 1; j < m_pSAEncodeImg->m_sJointName.size(); j++) { string child_name = m_pSAEncodeImg->m_sJointName[j]; Bone* pBone = NULL; pBone = pSkeleton->findBoneByName(pSkeleton->getRoot(),child_name.c_str()); string parent_name = pBone->parent_name; int k = 0; for(; k < m_pSAEncodeImg->m_sJointName.size(); k++) { if(parent_name == m_pSAEncodeImg->m_sJointName[k]) break; } painter.drawLine(m_pSAEncodeImg->m_iJointPosition[file[i]][k*2]/4,m_pSAEncodeImg->m_iJointPosition[file[i]][k*2+1]/4,m_pSAEncodeImg->m_iJointPosition[file[i]][j*2]/4,m_pSAEncodeImg->m_iJointPosition[file[i]][j*2+1]/4); } painter.end(); QPixmap pixmap; pixmap.convertFromImage(tmp); CSACustomGraphicsPixmapItem* graphicspixmapitem = new CSACustomGraphicsPixmapItem(&m_graphicsScene); graphicspixmapitem->setPixmap(pixmap); graphicspixmapitem->setPos(4 + i%2*124,4 + i/2*124); graphicspixmapitem->setImageIndex(file[i]); } } // background images //for(int i = 0; i < displaynum; i++) //{ // QColor color(250-i*100.0/(displaynum-1),250-i*100.0/(displaynum-1),250-i*100.0/(displaynum-1)); // for(int j = 0; j < m_pSAEncodeImg->m_sJointName.size(); j += 2) // { // int m = m_pSAEncodeImg->m_iJointPosition[file[displaynum-1-i]][j]; // int n = m_pSAEncodeImg->m_iJointPosition[file[displaynum-1-i]][j+1]; // resultImage.setPixel(m,n,color.rgb()); // } //} //*/ if(bkg) renderarea->setCurrentCanvas(resultImage); }