コード例 #1
0
ファイル: wmhelper.cpp プロジェクト: claudiutraistaru/octopi
/*
 * Opens a terminal based on your DE.
 */
void WMHelper::openTerminal(const QString& dirName){
  QProcess *p = new QProcess(qApp->activeWindow());
  QStringList s;
  QFileInfo f(dirName);

  if (f.exists()){
    if(isXFCERunning() && UnixCommand::hasTheExecutable(ctn_XFCE_TERMINAL)){
      s << "--working-directory=" + dirName;
      p->startDetached( ctn_XFCE_TERMINAL, s );
    }
    else if (isKDERunning() && UnixCommand::hasTheExecutable(ctn_KDE_TERMINAL)){
      s << "--workdir";            
      s << dirName;

      if (UnixCommand::isRootRunning())
      {
        p->startDetached( "dbus-launch " + ctn_KDE_TERMINAL + " --workdir " + dirName);
      }
      else
      {
        p->startDetached( ctn_KDE_TERMINAL, s );
      }
    }
    else if (isTDERunning() && UnixCommand::hasTheExecutable(ctn_TDE_TERMINAL)){
      s << "--workdir";
      s << dirName;
      p->startDetached( ctn_TDE_TERMINAL, s );
    }
    else if (isLXDERunning() && UnixCommand::hasTheExecutable(ctn_LXDE_TERMINAL)){
      s << "--working-directory=" + dirName;
      p->startDetached( ctn_LXDE_TERMINAL, s );
    }
    else if (isMATERunning() && UnixCommand::hasTheExecutable(ctn_MATE_TERMINAL)){
      s << "--working-directory=" + dirName;
      p->startDetached( ctn_MATE_TERMINAL, s );
    }
    else if (isCinnamonRunning() && UnixCommand::hasTheExecutable(ctn_CINNAMON_TERMINAL)){
      s << "--working-directory=" + dirName;
      p->startDetached( ctn_CINNAMON_TERMINAL, s );
    }
    else if (UnixCommand::hasTheExecutable(ctn_XFCE_TERMINAL)){
      s << "--working-directory=" + dirName;
      p->startDetached( ctn_XFCE_TERMINAL, s );
    }
    else if (UnixCommand::hasTheExecutable(ctn_LXDE_TERMINAL)){
      s << "--working-directory=" + dirName;
      p->startDetached( ctn_LXDE_TERMINAL, s );
    }
    else if (UnixCommand::hasTheExecutable(ctn_XTERM)){
      QString cmd = ctn_XTERM +
          " -fn \"*-fixed-*-*-*-18-*\" -fg White -bg Black -title xterm -e \"" +
          "cd " + dirName + " && /bin/bash\"";
      p->startDetached( cmd );
    }
  }
}
コード例 #2
0
ファイル: indexrunner.cpp プロジェクト: BigOz/Nixnote2
// Index any files that are attached.
void IndexRunner::indexAttachment(qint32 lid, Resource &r) {
    if (!officeFound)
        return;
    QLOG_DEBUG() << "indexing attachment to note " << lid;
    if (!keepRunning || pauseIndexing) {
        indexTimer->start();
        return;
    }
    ResourceTable rtable(db);
    qint32 reslid = rtable.getLid(r.guid);
    if (lid <= 0) {
        indexTimer->start();
        return;
    }
    QLOG_DEBUG() << "Resource " << reslid;
    QString extension = "";
    ResourceAttributes attributes;
    if (r.attributes.isSet())
        attributes = r.attributes;
    if (attributes.fileName.isSet()) {
        extension = attributes.fileName;
        int i = extension.indexOf(".");
	if (i != -1)
	  extension = extension.mid(i);
    }
    if (extension != ".doc"  && extension != ".xls"  && extension != ".ppt" &&
        extension != ".docx" && extension != ".xlsx" && extension != ".pptx" &&
        extension != ".pps"  && extension != ".pdf"  && extension != ".odt"  &&
        extension != ".odf"  && extension != ".ott"  && extension != ".odm"  &&
        extension != ".html" && extension != ".txt"  && extension != ".oth"  &&
        extension != ".ods"  && extension != ".ots"  && extension != ".odg"  &&
        extension != ".otg"  && extension != ".odp"  && extension != ".otp"  &&
        extension != ".odb"  && extension != ".oxt"  && extension != ".htm"  &&
        extension != ".docm")
                return;

    QString file = global.fileManager.getDbaDirPath() + QString::number(reslid) +extension;
    QFile dataFile(file);
    if (!dataFile.exists()) {
        QDir dir(global.fileManager.getDbaDirPath());
        QStringList filterList;
        filterList.append(QString::number(lid)+".*");
        QStringList list= dir.entryList(filterList, QDir::Files);
        if (list.size() > 0) {
            file = global.fileManager.getDbaDirPath()+list[0];
        }
    }

    QString outDir = global.fileManager.getTmpDirPath();

    QProcess sofficeProcess;
    QString cmd = "soffice --headless --convert-to txt:\"Text\" --outdir "
                    +outDir + " "
                    +file;

    sofficeProcess.start(cmd,
                         QIODevice::ReadWrite|QIODevice::Unbuffered);

    QLOG_DEBUG() << "Starting soffice ";
    sofficeProcess.waitForStarted();
    QLOG_DEBUG() << "Waiting for completion";
    sofficeProcess.waitForFinished();
    int rc = sofficeProcess.exitCode();
    QLOG_DEBUG() << "soffice Errors:" << sofficeProcess.readAllStandardError();
    QLOG_DEBUG() << "soffice Output:" << sofficeProcess.readAllStandardOutput();
    QLOG_DEBUG() << "return code:" << rc;
    if (rc == 255) {
        QLOG_ERROR() << "soffice not found.  Disabling attachment indexing.";
        this->officeFound = false;
        return;
    }
    QFile txtFile(outDir+QString::number(reslid) +".txt");
    if (txtFile.open(QIODevice::ReadOnly)) {
        QString text;
        text = txtFile.readAll();
        NSqlQuery sql(db);
        db->lockForWrite();
        sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, 'recognition', :content)");
        sql.bindValue(":lid", lid);
        sql.bindValue(":weight", 100);
        sql.bindValue(":content", text);
        QLOG_DEBUG() << "Adding note resource to index DB";
        sql.exec();
        db->unlock();
        txtFile.close();
    }
    QDir dir;
    dir.remove(outDir+QString::number(reslid) +".txt");
}
コード例 #3
0
ファイル: utils.cpp プロジェクト: heliocentric/pcbsd
// Function which displays a info box and restarts networking
void Utils::restartNetworking()
{
    
   QMessageBox infoBox;
   infoBox.setWindowModality(Qt::ApplicationModal);
   infoBox.setWindowTitle(QObject::tr("Restarting network..."));
   infoBox.setInformativeText(QObject::tr("Network is restarting, please wait..."));
   infoBox.setStandardButtons(QMessageBox::NoButton);
   infoBox.show();

   QProcess cmd;
   cmd.start(QString("/etc/rc.d/netif"), QStringList() << "restart" );
   while ( cmd.state() != QProcess::NotRunning ) {
       cmd.waitForFinished(100);
       QCoreApplication::processEvents();
   }

   // Set the gateway device name
   QString route = getConfFileValue("/etc/rc.conf", "defaultrouter=", 1);
   if ( ! route.isEmpty() ) {
     infoBox.setInformativeText(QObject::tr("Setting default route..."));
     cmd.start(QString("route"), QStringList() << "delete" << "default" );
     while ( cmd.state() != QProcess::NotRunning ) {
         cmd.waitForFinished(100);
         QCoreApplication::processEvents();
     }

     cmd.start(QString("route"), QStringList() << "add" << "default" << route );
     while ( cmd.state() != QProcess::NotRunning ) {
         cmd.waitForFinished(100);
         QCoreApplication::processEvents();
     }
   }

   // Check for any devices to run DHCP on
   QStringList ifs = NetworkInterface::getInterfaces();
   for ( QStringList::Iterator it = ifs.begin(); it != ifs.end(); ++it )
   {
       QString dev = *it;

       // Devices we can safely skip
       if (dev.indexOf("lo") == 0 
           || dev.indexOf("fwe") == 0 
           || dev.indexOf("ipfw") == 0
           || dev.indexOf("plip") == 0
           || dev.indexOf("pfsync") == 0
           || dev.indexOf("pflog") == 0
           || dev.indexOf("usbus") == 0
           || dev.indexOf("vboxnet") == 0
           || dev.indexOf("tun") == 0)
	  continue;

	// Check if this device has DHCP enabled
	if ( Utils::getConfFileValue( "/etc/rc.conf", "ifconfig_" + dev + "=", 1 ).indexOf("DHCP") != -1 )
	{
	   qDebug() << "Running DHCP on " << dev;
           infoBox.setInformativeText(QObject::tr("Running DHCP..."));
     	   cmd.start(QString("/etc/rc.d/dhclient"), QStringList() << "start" << dev );
           while ( cmd.state() != QProcess::NotRunning ) {
             cmd.waitForFinished(100);
             QCoreApplication::processEvents();
           }
	}
   }

   infoBox.close();
}
コード例 #4
0
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::echoTest_performance()
{
    QProcess process;
    process.start("testProcessLoopback/testProcessLoopback");

    QByteArray array;
    array.resize(1024 * 1024);
    for (int j = 0; j < array.size(); ++j)
        array[j] = 'a' + (j % 20);

    QVERIFY(process.waitForStarted());

    QTime stopWatch;
    stopWatch.start();

    qint64 totalBytes = 0;
    QByteArray dump;
    QSignalSpy readyReadSpy(&process, SIGNAL(readyRead()));
    QVERIFY(readyReadSpy.isValid());
    while (stopWatch.elapsed() < 2000) {
        process.write(array);
        while (process.bytesToWrite() > 0) {
            int readCount = readyReadSpy.count();
            QVERIFY(process.waitForBytesWritten(5000));
            if (readyReadSpy.count() == readCount)
                QVERIFY(process.waitForReadyRead(5000));
        }

        while (process.bytesAvailable() < array.size())
            QVERIFY2(process.waitForReadyRead(5000), qPrintable(process.errorString()));
        dump = process.readAll();
        totalBytes += dump.size();
    }

    qDebug() << "Elapsed time:" << stopWatch.elapsed() << "ms;"
             << "transfer rate:" << totalBytes / (1048.576) / stopWatch.elapsed()
             << "MB/s";

    for (int j = 0; j < array.size(); ++j)
        QCOMPARE(char(dump.at(j)), char('a' + (j % 20)));

    process.closeWriteChannel();
    QVERIFY(process.waitForFinished());
}
コード例 #5
0
bool AnalyzeTask::analyzeAvisynthFile(const QString &filePath, AudioFileModel &info)
{
	QProcess process;
	lamexp_init_process(process, QFileInfo(m_avs2wavBin).absolutePath());

	process.start(m_avs2wavBin, QStringList() << QDir::toNativeSeparators(filePath) << "?");

	if(!process.waitForStarted())
	{
		qWarning("AVS2WAV process failed to create!");
		qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
		process.kill();
		process.waitForFinished(-1);
		return false;
	}

	bool bInfoHeaderFound = false;

	while(process.state() != QProcess::NotRunning)
	{
		if(*m_abortFlag)
		{
			process.kill();
			qWarning("Process was aborted on user request!");
			break;
		}
		
		if(!process.waitForReadyRead())
		{
			if(process.state() == QProcess::Running)
			{
				qWarning("AVS2WAV time out. Killing process and skipping file!");
				process.kill();
				process.waitForFinished(-1);
				return false;
			}
		}

		QByteArray data;

		while(process.canReadLine())
		{
			QString line = QString::fromUtf8(process.readLine().constData()).simplified();
			if(!line.isEmpty())
			{
				int index = line.indexOf(':');
				if(index > 0)
				{
					QString key = line.left(index).trimmed();
					QString val = line.mid(index+1).trimmed();

					if(bInfoHeaderFound && !key.isEmpty() && !val.isEmpty())
					{
						if(key.compare("TotalSeconds", Qt::CaseInsensitive) == 0)
						{
							bool ok = false;
							unsigned int duration = val.toUInt(&ok);
							if(ok) info.techInfo().setDuration(duration);
						}
						if(key.compare("SamplesPerSec", Qt::CaseInsensitive) == 0)
						{
							bool ok = false;
							unsigned int samplerate = val.toUInt(&ok);
							if(ok) info.techInfo().setAudioSamplerate (samplerate);
						}
						if(key.compare("Channels", Qt::CaseInsensitive) == 0)
						{
							bool ok = false;
							unsigned int channels = val.toUInt(&ok);
							if(ok) info.techInfo().setAudioChannels(channels);
						}
						if(key.compare("BitsPerSample", Qt::CaseInsensitive) == 0)
						{
							bool ok = false;
							unsigned int bitdepth = val.toUInt(&ok);
							if(ok) info.techInfo().setAudioBitdepth(bitdepth);
						}
					}
				}
				else
				{
					if(line.contains("[Audio Info]", Qt::CaseInsensitive))
					{
						info.techInfo().setAudioType("Avisynth");
						info.techInfo().setContainerType("Avisynth");
						bInfoHeaderFound = true;
					}
				}
			}
		}
	}
	
	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}

	//Check exit code
	switch(process.exitCode())
	{
	case 0:
		qDebug("Avisynth script was analyzed successfully.");
		return true;
		break;
	case -5:
		qWarning("It appears that Avisynth is not installed on the system!");
		return false;
		break;
	default:
		qWarning("Failed to open the Avisynth script, bad AVS file?");
		return false;
		break;
	}
}
コード例 #6
0
ファイル: main.cpp プロジェクト: sebastiendu/laguntzaile
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Un message de courriel est arrivé à l'adresse prefixe+id_lot_et_cle_du_lot_destinataire@domaine.
    // exemple : [email protected]

    // sur le serveur MX du domaine, dans /etc/alias, l'administrateur aura placé cette ligne :
    // prefixe: |/usr/bin/relai_de_courriel

    // Les rêglages sont à faire dans un fichier de configuration sous /etc ou ~/.config

    QSettings settings("Les Développements Durables", "Laguntzaile");

    // Vérifications préalables

    QString programme = settings.value("sendmail", "/usr/sbin/sendmail").toString();

    if (!QFile::exists(programme)) {
        qCritical()
                << "Introuvable programme d'envoi du courrier " << programme;
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }

    vector<const char*> env_requis;
    env_requis.push_back("EXTENSION");
    env_requis.push_back("SENDER");
    env_requis.push_back("USER");
    env_requis.push_back("DOMAIN");

    for (vector<const char*>::const_iterator i = env_requis.begin(); i != env_requis.end(); i++) {
        if (getenv(*i) == NULL) {
            qCritical()
                << "Erreur de lecture de la variable d'environnement" << *i
                << "- normalement le MTA renseigne cette variable.";
            cout << "4.3.5 System incorrectly configured" << endl;
            return EX_USAGE;
        }
    }

    // De EXTENSION, tirer l'id du lot de sa clé
    QString extension(getenv("EXTENSION"));

    bool aller = extension.contains(QRegExp("^\\d+_\\d+$"));
    bool retour = extension.contains(QRegExp("^\\d+_\\d+_\\d+$"));
    if (!aller && !retour) {
        qCritical()
                << "Cette adresse est invalide.";
        cout << "5.1.3 Bad destination mailbox address syntax" << endl;
        return EX_NOUSER;
    }

    // Le lot des destinataires est défini dans la base de données
    QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");

    // Connexion à la base de données
    // FIXME : permettre un accès sans mot de passe
    db.setHostName      (settings.value("database/hostName",        "localhost"     ).toString());
    db.setPort          (settings.value("database/port",            5432            ).toInt()   );
    db.setDatabaseName  (settings.value("database/databaseName",    "laguntzaile"   ).toString());
    db.setUserName      (settings.value("database/userName",        qgetenv("USER") ).toString());
    db.setPassword      (settings.value("database/password",        qgetenv("USER") ).toString());

    if(!db.open()) {
        qCritical()
                << "Erreur d'ouverture de la connexion à la base de données :"
                << db.lastError()
                << "Veuillez vérifier le fichier de configuration"
                << settings.fileName();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }

    // Un retour en erreur ; débarrassons nous de ce cas spécial en premier
    if (retour) {
        // lire id_lot, id_personne et cle
        QStringList identifiant = extension.split('_');
        int id_lot = identifiant.at(0).toInt();
        int id_personne = identifiant.at(1).toInt();
        int cle = identifiant.at(2).toInt();
        // vérification standard : lot_personne avec la bonne cle, traité et reussi et sans erreur
        QSqlQuery query_lot_personne;
        if(!query_lot_personne.prepare(
                    "select *"
                    " from lot_personne"
                    " where"
                    "  id_lot = :id_lot"
                    "  and id_personne = :id_personne"
                    "  and cle = :cle"
                    "  and traite"
                    "  and reussi"
                    "  and erreur is null")) {
            qCritical()
                    << "Erreur de préparation de la requête d'identification de l'envoi :"
                    << query_lot_personne.lastError();
            cout << "4.3.5 System incorrectly configured" << endl;
            return EX_CONFIG;
        }
        query_lot_personne.bindValue(":id_lot", id_lot);
        query_lot_personne.bindValue(":id_personne", id_personne);
        query_lot_personne.bindValue(":cle", cle);
        if(!query_lot_personne.exec()) {
            qCritical()
                    << "Erreur d'execution de la requête d'identification de l'envoi :"
                    << query_lot_personne.lastError();
            cout << "4.3.5 System incorrectly configured" << endl;
            return EX_CONFIG;
        }
        if (query_lot_personne.size() != 1) {
            qCritical()
                    << "Cette adresse retour est invalide."
                    << "query_lot_personne.size() = " << query_lot_personne.size()
                    << "id_lot" << id_lot
                    << "id_personne" << id_personne
                    << "cle" << cle
                    << query_lot_personne.executedQuery()
                    << query_lot_personne.boundValues()
                    << ".first()" << query_lot_personne.first();
            cout << "5.1.1 Bad destination mailbox address" << endl;
            return EX_NOUSER;
        }
        // marquer cet envoi comme pas réussi et renseigner l'erreur
        QSqlQuery setLotPersonneEnErreur;
        if (!setLotPersonneEnErreur.prepare(
                    "update lot_personne"
                    " set reussi = false,"
                    " erreur = :erreur"
                    " where id_lot = :id_lot"
                    " and id_personne = :id_personne")) {
            qCritical()
                    << "Erreur de préparation de la requête d'enregistrement de l'erreur d'envoi :"
                    << setLotPersonneEnErreur.lastError();
            cout << "4.3.5 System incorrectly configured" << endl;
            return EX_CONFIG;
        }
        QFile in;
        in.open(stdin, QIODevice::ReadOnly);
        setLotPersonneEnErreur.bindValue(":id_lot", id_lot);
        setLotPersonneEnErreur.bindValue(":id_personne", id_personne);
        setLotPersonneEnErreur.bindValue(":erreur", QString(in.readAll()));
        if(!setLotPersonneEnErreur.exec()) {
            qCritical()
                    << "Erreur d'execution de la requête d''identification de l'enregistrement de l'erreur d'envoi :"
                    << setLotPersonneEnErreur.lastError();
            cout << "4.3.5 System incorrectly configured" << endl;
            return EX_CONFIG;
        }

        cout << "2.1.5 Destination address valid" << endl;
        return EX_OK;
    }

    // Pas un retour mais un envoi vers un lot de destinataires

    QStringList identifiant = extension.split('_');
    int id_lot = identifiant.at(0).toInt();
    int cle = identifiant.at(1).toInt();

    // Lecture du lot
    QSqlQuery query_lot;
    if (!query_lot.prepare("select * from lot where id=? and cle=?")) {
        qCritical()
                << "Erreur de préparation de la requête de lecture du lot de destinataires :"
                << query_lot.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }
    query_lot.addBindValue(id_lot);
    query_lot.addBindValue(cle);
    if (!query_lot.exec()) {
        qCritical()
                << "Erreur d'execution de la requête de lecture du lot de destinataires :"
                << query_lot.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }
    if (!query_lot.first()) {
        qCritical()
                << "Cette adresse ne correspond pas à un lot de destinataires";
        cout << "5.1.1 Bad destination mailbox address" << endl;
        return EX_NOUSER;
    }
    if (query_lot.value("traite").toBool()) {
       qCritical()
               << "Ce lot a déjà été traité une fois. Il n'est pas possible de réutiliser un même lot.";
       cout << "4.2.1 Mailbox disabled, not accepting messages" << endl;
       return EX_UNAVAILABLE;
    }
#ifndef SKIP_DATE_TESTS
    if (query_lot.value("date_de_creation").toDateTime().secsTo(QDateTime::currentDateTime()) > 24*60*60) {
        qCritical()
                << "Ce lot est périmé. Un lot ne reste valide que pendant 24 heures."
                << "Date de création de ce lot : " << query_lot.value("date_de_creation");
        cout << "4.2.1 Mailbox disabled, not accepting messages" << endl;
        return EX_UNAVAILABLE;
    }
#endif

    // Lecture de l'évènement
    int id_evenement = query_lot.value("id_evenement").toInt();
    QSqlQuery query_evenement;
    if (!query_evenement.prepare("select fin from evenement where id=?")) {
        qCritical()
                << "Erreur de préparation de la requête de lecture de l'évenement :"
                << query_evenement.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }
    query_evenement.addBindValue(id_evenement);
    if (!query_evenement.exec()) {
        qCritical()
                << "Erreur d'execution de la requête de lecture de l'évènement :"
                << query_evenement.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }
    if (!query_evenement.first()) {
        qCritical()
                << "Ce lot ne correspond à aucun évènement (base de donnée incohérente)";
        cout << "5.1.1 Bad destination mailbox address" << endl;
        return EX_NOUSER;
    }
#ifndef SKIP_DATE_TESTS
    if (query_evenement.value("fin").toDateTime() < QDateTime::currentDateTime()) {
       qCritical()
               << "Cet évènement est déjà terminé.";
       cout << "4.2.1 Mailbox disabled, not accepting messages" << endl;
       return EX_UNAVAILABLE;
    }
#endif

    // Le message lui-même est à lire sur l'entrée standard

    istreambuf_iterator<char> bit(cin), eit;
    MimeEntity modele(bit, eit);

    // Adaptons le format du message et vérifions si on y trouve bien _URL_

    bool marqueurTrouve = preparer(&modele);

    if (!marqueurTrouve) {
        qCritical()
                << "Marqueur _URL_ introuvable dans le corps du message.";
        cout << "4.2.4 Mailing list expansion problem" << endl;
        return EX_DATAERR;
    }

    // Virer les headers Return-Path, X-Original-To, Delivered-To, X-*, Received ...
    for (Header::iterator i = modele.header().begin(); i != modele.header().end(); i++) {
        if (i->name() == "Received" ||
                i->name().substr(0,2) == "X-" ||
                i->name() == "Return-Path" ||
                i->name() == "Delivered-To" ||
                i->name() == "Message-Id"
                ) {
            modele.header().erase(i);
        }
    }

    // Récupération de la liste des destinataires
    QSqlQuery query_destinataires;
    if (!query_destinataires.prepare(
                "select distinct concat_ws(' ', prenom, nom) as libelle, email, id_personne, disponibilite.id as id_disponibilite, lot_personne.cle"
                " from lot_personne join personne on id_personne = personne.id"
                " join lot on id_lot = lot.id"
                " left join disponibilite using(id_personne, id_evenement)"
                " where id_lot=?"
                " and email like '%@%'"
                )) {
        qCritical()
                << "Erreur de préparation de la requête de lecture des destinataires du lot :"
                << query_destinataires.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }
    query_destinataires.addBindValue(id_lot);
    if (!query_destinataires.exec()) {
        qCritical()
                << "Erreur d'execution de la requête de lecture des destinataires du lot :"
                << query_destinataires.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }

    // Préparation des autres requètes dont on va avoir besoin
    QSqlQuery query_affectations;
    if (!query_affectations.prepare(
                "select affectation.id, affectation.statut, affectation.commentaire, tour.debut, tour.fin, poste.nom, poste.description"
                " from affectation"
                " join tour on id_tour = tour.id"
                " join poste on id_poste = poste.id"
                " where id_disponibilite = ?"
                )) {
        qCritical()
                << "Erreur de préparation de la requête de lecture des affectations du destinataire :"
                << query_affectations.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }

    QSqlQuery setLotPersonneTraite;
    if (!setLotPersonneTraite.prepare(
                "update lot_personne"
                " set"
                " traite = true,"
                " reussi = :reussi,"
                " erreur = :erreur"
                " where id_lot=:id_lot and id_personne=:id_personne"
                )) {
        qCritical()
                << "Erreur de préparation de la requête de marquage des envois traités :"
                << setLotPersonneTraite.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }

    QSqlQuery setLotTraite;
    if (!setLotTraite.prepare(
                "update lot"
                " set"
                " traite = true,"
                " modele = :modele,"
                " expediteur = :expediteur"
                " where id=:id_lot"
                )) {
        qCritical()
                << "Erreur de préparation de la requête de marquage du lot traité :"
                << setLotTraite.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }

    // Génération et envoi des messages personnalisés
    while (query_destinataires.next()) {
        QString libelle = query_destinataires.value("libelle").toString().trimmed();
        QString email = query_destinataires.value("email").toString().trimmed();
        int id_personne = query_destinataires.value("id_personne").toInt();
        int cle = query_destinataires.value("cle").toInt();

        stringstream b;
        b << modele;
        string s = b.str();
        MimeEntity instance(s.begin(), s.end());

        // Personnalisation du from, pour pouvoir identifier les personnes injoignables
        QString fromMailbox = QString("%1+%2_%3_%4").arg(getenv("USER")).arg(id_lot).arg(id_personne).arg(cle);
        QString fromDomaine = getenv("DOMAIN");

        MailboxList& from = instance.header().from();
        for (MailboxList::iterator i = from.begin(); i != from.end(); i++) {
            i->mailbox(fromMailbox.toStdString());
            i->domain(fromDomaine.toStdString());
        }

        // Génération du to
        Mailbox mailbox;
        mailbox.label(libelle.toStdString());
        mailbox.mailbox(email.split('@').at(0).toStdString());
        mailbox.domain(email.split('@').at(1).toStdString());
        MailboxList to;
        to.push_back(mailbox);
        instance.header().to(to.str());

        // substitution des marqueurs
        string url = settings.value("modele_url", "http://localhost/%1/%2").toString().arg(id_evenement).arg(id_personne).toStdString();
        string affectations = "";
        string affectations_html = "";
        if (!query_destinataires.value("id_disponibilite").isNull()) { // le destinataire est inscrit à l'évènement et a peut-être des affectations
            int id_disponibilite = query_destinataires.value("id_disponibilite").toInt();
            query_affectations.addBindValue(id_disponibilite);
            if (!query_affectations.exec()) {
                qCritical()
                        << "Erreur d'execution de la requête de lecture des affectations du destinataire :"
                        << query_affectations.lastError();
                cout << "4.3.5 System incorrectly configured" << endl;
                return EX_CONFIG;
            }
            if (query_affectations.size() > 0) { // il a des affectations
                affectations_html = settings.value("modele_affectations_html_prefixe", "<table><tr><th>De</th><th>à</th><th>Poste</th></tr>").toString().toStdString();
                while (query_affectations.next()) {
                    QString debut = query_affectations.value("debut").toDateTime().toString(); // TODO : formater les dates et les heures
                    QString fin = query_affectations.value("fin").toDateTime().toString();
                    QString nom = query_affectations.value("nom").toString();
                    affectations += settings.value("modele_affectations_texte", "%1 → %2 : %3\n").toString().arg(debut, fin, nom).toStdString();
                    affectations_html += settings.value("modele_affectations_html", "<tr><td>%1</td><td>%2</td><td>%3</td></tr>").toString().arg(debut, fin, nom).toStdString(); // TODO : htmlentities()
                }
                affectations_html += settings.value("modele_affectations_html_suffixe", "</table>").toString().toStdString();
            }
        }
        substituer(&instance, url, affectations, affectations_html);

        // envoi du message et marquage des destinataires traités
        QProcess sendmail;
        QStringList arguments;
        arguments << "-f" << QString("%1@%2").arg(fromMailbox).arg(fromDomaine);
        arguments << email;
        stringstream ss; ss << instance;
        QString entree = QString::fromStdString(ss.str());
        entree.replace(QString("\n.\n"), QString("\n..\n"));
        sendmail.start(programme, arguments);
        if (sendmail.waitForStarted()) {
            sendmail.write(entree.toUtf8());
            sendmail.closeWriteChannel();
            if (sendmail.waitForFinished() && sendmail.exitStatus() == QProcess::NormalExit && sendmail.exitCode() == EX_OK) {
                setLotPersonneTraite.bindValue(":reussi", true);
                setLotPersonneTraite.bindValue("erreur", QVariant());
            } else {
                setLotPersonneTraite.bindValue(":reussi", false);
                setLotPersonneTraite.bindValue("erreur", strerror(sendmail.exitCode()));
            }
        } else {
            setLotPersonneTraite.bindValue(":reussi", false);
            setLotPersonneTraite.bindValue(":erreur", sendmail.readAllStandardError());
        }
        setLotPersonneTraite.bindValue(":id_lot", id_lot);
        setLotPersonneTraite.bindValue(":id_personne", id_personne);
        if(!setLotPersonneTraite.exec()) {
            qCritical()
                << "Erreur d'execution de la requête de marquage des envois traités :"
                << setLotPersonneTraite.lastError();
            cout << "4.3.5 System incorrectly configured" << endl;
            return EX_CONFIG;
        }
    }
    // Marquage du lot traité
    QString sender(getenv("SENDER"));
    setLotTraite.bindValue(":id_lot", id_lot);

    stringstream b;
    b << modele;
    string modele_lot = b.str();
    setLotTraite.bindValue(":modele", modele_lot.c_str());
    setLotTraite.bindValue(":expediteur", sender);
    if(!setLotTraite.exec()) {
        qCritical()
            << "Erreur d'execution de la requête de marquage des envois traités :"
            << setLotTraite.lastError();
        cout << "2.1.5 Destination address valid mais le lot n'a pas été marqué 'traité'" << endl;
        return EX_OK;
    }

    // TODO : poster à SENDER la liste des adresses, nom, prenom, ville et identifiant des destinataires en erreur, le nombre d'envois faits (réussis et ratés), un rappel des sujet et date du message original

    cout << "2.1.5 Destination address valid" << endl;
    return EX_OK;
}
コード例 #7
0
ファイル: OSInfo.cpp プロジェクト: Githlar/mumble
QString OSInfo::getOSVersion() {
	static QString qsCached;

	if (! qsCached.isNull())
		return qsCached.isEmpty() ? QString() : qsCached;

	QString os;

#if defined(Q_OS_WIN)
	OSVERSIONINFOEXW ovi;
	memset(&ovi, 0, sizeof(ovi));

	ovi.dwOSVersionInfoSize=sizeof(ovi);
	if (!GetVersionEx(reinterpret_cast<OSVERSIONINFOW *>(&ovi))) {
		return QString();
	}

	os.sprintf("%d.%d.%d.%d", ovi.dwMajorVersion, ovi.dwMinorVersion, ovi.dwBuildNumber, (ovi.wProductType == VER_NT_WORKSTATION) ? 1 : 0);
#elif defined(Q_OS_MAC)
	SInt32 major, minor, bugfix;
	OSErr err = Gestalt(gestaltSystemVersionMajor, &major);
	if (err == noErr)
		err = Gestalt(gestaltSystemVersionMinor, &minor);
	if (err == noErr)
		err = Gestalt(gestaltSystemVersionBugFix, &bugfix);
	if (err != noErr)
		return QString::number(QSysInfo::MacintoshVersion, 16);

	const NXArchInfo *local = NXGetLocalArchInfo();
	const NXArchInfo *ai = local ? NXGetArchInfoFromCpuType(local->cputype, CPU_SUBTYPE_MULTIPLE) : NULL;
	const char *arch = ai ? ai->name : "unknown";

	os.sprintf("%i.%i.%i (%s)", major, minor, bugfix, arch);
#else
#ifdef Q_OS_LINUX
	QProcess qp;
	QStringList args;
	args << QLatin1String("-s");
	args << QLatin1String("-d");
	qp.start(QLatin1String("lsb_release"), args);
	if (qp.waitForFinished(5000)) {
		os = QString::fromUtf8(qp.readAll()).simplified();
		if (os.startsWith(QLatin1Char('"')) && os.endsWith(QLatin1Char('"')))
			os = os.mid(1, os.length() - 2).trimmed();
	}
	if (os.isEmpty())
		qWarning("OSInfo: Failed to execute lsb_release");

	qp.terminate();
	if (! qp.waitForFinished(1000))
		qp.kill();
#endif
	if (os.isEmpty()) {
		struct utsname un;
		if (uname(&un) == 0) {
			os.sprintf("%s %s", un.sysname, un.release);
		}
	}
#endif

	if (! os.isNull())
		qsCached = os;
	else
		qsCached = QLatin1String("");

	return qsCached;
}
コード例 #8
0
void ProcessLauncher::launchProcess()
{
    QString commandLine;
    if (m_launchOptions.processType == WebProcess) {
        commandLine = QLatin1String("%1 \"%2\" %3");
        QByteArray webProcessPrefix = qgetenv("QT_WEBKIT2_WP_CMD_PREFIX");
        commandLine = commandLine.arg(QLatin1String(webProcessPrefix.constData())).arg(QString(executablePathOfWebProcess()));
#if ENABLE(PLUGIN_PROCESS)
    } else if (m_launchOptions.processType == PluginProcess) {
        commandLine = QLatin1String("%1 \"%2\" %3 %4");
        QByteArray pluginProcessPrefix = qgetenv("QT_WEBKIT2_PP_CMD_PREFIX");
        commandLine = commandLine.arg(QLatin1String(pluginProcessPrefix.constData())).arg(QString(executablePathOfPluginProcess()));
#endif
    } else
        ASSERT_NOT_REACHED();

#if OS(DARWIN)
    // Create the listening port.
    mach_port_t connector;
    mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &connector);

    // Insert a send right so we can send to it.
    mach_port_insert_right(mach_task_self(), connector, connector, MACH_MSG_TYPE_MAKE_SEND);

    // Register port with a service name to the system.
    QString serviceName = QStringLiteral("com.nokia.Qt.WebKit.QtWebProcess-%1-%2");
    serviceName = serviceName.arg(QString().setNum(getpid()), QString().setNum((size_t)this));
    kern_return_t kr = bootstrap_register2(bootstrap_port, const_cast<char*>(serviceName.toUtf8().data()), connector, 0);
    ASSERT_UNUSED(kr, kr == KERN_SUCCESS);

    commandLine = commandLine.arg(serviceName);
#elif OS(WINDOWS)
    CoreIPC::Connection::Identifier connector, clientIdentifier;
    if (!CoreIPC::Connection::createServerAndClientIdentifiers(connector, clientIdentifier)) {
        // FIXME: What should we do here?
        ASSERT_NOT_REACHED();
    }
    commandLine = commandLine.arg(qulonglong(clientIdentifier));
    // Ensure that the child process inherits the client identifier.
    ::SetHandleInformation(clientIdentifier, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
#else
    int sockets[2];
    if (socketpair(AF_UNIX, SOCKET_TYPE, 0, sockets) == -1) {
        qDebug() << "Creation of socket failed with errno:" << errno;
        ASSERT_NOT_REACHED();
        return;
    }

    // Don't expose the ui socket to the web process
    while (fcntl(sockets[1], F_SETFD, FD_CLOEXEC)  == -1) {
        if (errno != EINTR) {
            ASSERT_NOT_REACHED();
            while (close(sockets[0]) == -1 && errno == EINTR) { }
            while (close(sockets[1]) == -1 && errno == EINTR) { }
            return;
        }
    }

    int connector = sockets[1];
    commandLine = commandLine.arg(sockets[0]);
#endif

#if ENABLE(PLUGIN_PROCESS)
    if (m_launchOptions.processType == PluginProcess)
        commandLine = commandLine.arg(QString(m_launchOptions.extraInitializationData.get("plugin-path")));
#endif

    QProcess* webProcessOrSUIDHelper = new QtWebProcess();
    webProcessOrSUIDHelper->setProcessChannelMode(QProcess::ForwardedChannels);

#if ENABLE(SUID_SANDBOX_LINUX)
    if (m_launchOptions.processType == WebProcess) {
        QString sandboxCommandLine = QLatin1String("\"%1\" \"%2\" %3");
        sandboxCommandLine = sandboxCommandLine.arg(QCoreApplication::applicationDirPath() + QLatin1String("/SUIDSandboxHelper"));
        sandboxCommandLine = sandboxCommandLine.arg(executablePathOfWebProcess());
        sandboxCommandLine = sandboxCommandLine.arg(sockets[0]);

        webProcessOrSUIDHelper->start(sandboxCommandLine);
    } else
        webProcessOrSUIDHelper->start(commandLine);
#else
    webProcessOrSUIDHelper->start(commandLine);
#endif

#if OS(UNIX) && !OS(DARWIN)
    // Don't expose the web socket to possible future web processes
    while (fcntl(sockets[0], F_SETFD, FD_CLOEXEC) == -1) {
        if (errno != EINTR) {
            ASSERT_NOT_REACHED();
            delete webProcessOrSUIDHelper;
            return;
        }
    }
#endif

    if (!webProcessOrSUIDHelper->waitForStarted()) {
        qDebug() << "Failed to start" << commandLine;
        ASSERT_NOT_REACHED();
#if OS(DARWIN)
        mach_port_deallocate(mach_task_self(), connector);
        mach_port_mod_refs(mach_task_self(), connector, MACH_PORT_RIGHT_RECEIVE, -1);
#endif
        delete webProcessOrSUIDHelper;
        return;
    }
#if OS(UNIX)
    setpriority(PRIO_PROCESS, webProcessOrSUIDHelper->pid(), 10);
#endif
    RunLoop::main()->dispatch(bind(&WebKit::ProcessLauncher::didFinishLaunchingProcess, this, webProcessOrSUIDHelper, connector));
}
コード例 #9
0
bool AC3Encoder::encode(const QString &sourceFile, const AudioFileModel_MetaInfo &metaInfo, const unsigned int duration, const QString &outputFile, volatile bool *abortFlag)
{
    QProcess process;
    QStringList args;

    switch(m_configRCMode)
    {
    case SettingsModel::VBRMode:
        args << "-q" << QString::number(qBound(0, m_configBitrate * 16, 1023));
        break;
    case SettingsModel::CBRMode:
        args << "-b" << QString::number(g_ac3BitratesLUT[qBound(0, m_configBitrate, 18)]);
        break;
    default:
        THROW("Bad rate-control mode!");
        break;
    }

    if(m_configAudioCodingMode >= 1)
    {
        args << "-acmod" << QString::number(m_configAudioCodingMode - 1);
    }
    if(m_configDynamicRangeCompression != 5)
    {
        args << "-dynrng" << QString::number(m_configDynamicRangeCompression);
    }
    if(m_configExponentSearchSize != 8)
    {
        args << "-exps" << QString::number(m_configExponentSearchSize);
    }
    if(m_configFastBitAllocation)
    {
        args << "-fba" << QString::number(1);
    }

    if(!m_configCustomParams.isEmpty()) args << m_configCustomParams.split(" ", QString::SkipEmptyParts);

    args << QDir::toNativeSeparators(sourceFile);
    args << QDir::toNativeSeparators(outputFile);

    if(!startProcess(process, m_binary, args))
    {
        return false;
    }

    bool bTimeout = false;
    bool bAborted = false;
    int prevProgress = -1;

    QRegExp regExp("progress:(\\s+)(\\d+)%(\\s+)\\|");

    while(process.state() != QProcess::NotRunning)
    {
        if(*abortFlag)
        {
            process.kill();
            bAborted = true;
            emit messageLogged("\nABORTED BY USER !!!");
            break;
        }
        process.waitForReadyRead(m_processTimeoutInterval);
        if(!process.bytesAvailable() && process.state() == QProcess::Running)
        {
            process.kill();
            qWarning("Aften process timed out <-- killing!");
            emit messageLogged("\nPROCESS TIMEOUT !!!");
            bTimeout = true;
            break;
        }
        while(process.bytesAvailable() > 0)
        {
            QByteArray line = process.readLine();
            QString text = QString::fromUtf8(line.constData()).simplified();
            if(regExp.lastIndexIn(text) >= 0)
            {
                bool ok = false;
                int progress = regExp.cap(2).toInt(&ok);
                if(ok && (progress > prevProgress))
                {
                    emit statusUpdated(progress);
                    prevProgress = qMin(progress + 2, 99);
                }
            }
            else if(!text.isEmpty())
            {
                emit messageLogged(text);
            }
        }
    }

    process.waitForFinished();
    if(process.state() != QProcess::NotRunning)
    {
        process.kill();
        process.waitForFinished(-1);
    }

    emit statusUpdated(100);
    emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

    if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
    {
        return false;
    }

    return true;
}
コード例 #10
0
ファイル: process.cpp プロジェクト: RSATom/Qt
bool zip()
{
//! [0]
    QProcess gzip;
    gzip.start("gzip", QStringList() << "-c");
    if (!gzip.waitForStarted())
        return false;

    gzip.write("Qt rocks!");
    gzip.closeWriteChannel();

    if (!gzip.waitForFinished())
        return false;

    QByteArray result = gzip.readAll();
//! [0]

    gzip.start("gzip", QStringList() << "-d" << "-c");
    gzip.write(result);
    gzip.closeWriteChannel();

    if (!gzip.waitForFinished())
        return false;

    qDebug("Result: %s", gzip.readAll().data());
    return true;
}
コード例 #11
0
ファイル: feedbackdialog.cpp プロジェクト: rubenmit/hw
void FeedbackDialog::GenerateSpecs()
{
    // Gather some information about the system and embed it into the report
    QDesktopWidget* screen = QApplication::desktop();
    QString os_version = "Operating system: ";
    QString qt_version = QString("Qt version: ") + QT_VERSION_STR + QString("\n");
    QString total_ram = "Total RAM: ";
    QString number_of_cores = "Number of cores: ";
    QString compiler_bits = "Compiler architecture: ";
    QString compiler_version = "Compiler version: ";
    QString kernel_line = "Kernel: ";
    QString screen_size = "Size of the screen(s): " +
        QString::number(screen->width()) + "x" + QString::number(screen->height()) + "\n";
    QString number_of_screens = "Number of screens: " + QString::number(screen->screenCount()) + "\n";
    QString processor_name = "Processor: ";

    // platform specific code
#ifdef Q_OS_MACX
    number_of_cores += QString::number(sysconf(_SC_NPROCESSORS_ONLN)) + "\n";

    uint64_t memsize;
    size_t len = sizeof(memsize);
    static int mib_s[2] = { CTL_HW, HW_MEMSIZE };
    if (sysctl (mib_s, 2, &memsize, &len, NULL, 0) == 0)
        total_ram += QString::number(memsize/1024/1024) + " MB\n";
    else
        total_ram += "Error getting total RAM information\n";

    int mib[] = {CTL_KERN, KERN_OSRELEASE};
    sysctl(mib, sizeof mib / sizeof(int), NULL, &len, NULL, 0);

    char *kernelVersion = (char *)malloc(sizeof(char)*len);
    sysctl(mib, sizeof mib / sizeof(int), kernelVersion, &len, NULL, 0);

    QString kernelVersionStr = QString(kernelVersion);
    free(kernelVersion);
    int major_version = kernelVersionStr.split(".").first().toUInt() - 4;
    int minor_version = kernelVersionStr.split(".").at(1).toUInt();
    os_version += QString("Mac OS X 10.%1.%2").arg(major_version).arg(minor_version) + " ";

    switch(major_version)
    {
        case 4:  os_version += "\"Tiger\"\n"; break;
        case 5:  os_version += "\"Leopard\"\n"; break;
        case 6:  os_version += "\"Snow Leopard\"\n"; break;
        case 7:  os_version += "\"Lion\"\n"; break;
        case 8:  os_version += "\"Mountain Lion\"\n"; break;
        default: os_version += "\"Unknown version\"\n"; break;
    }
#endif
#ifdef Q_OS_WIN
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    number_of_cores += QString::number(sysinfo.dwNumberOfProcessors) + "\n";
    MEMORYSTATUSEX status;
    status.dwLength = sizeof(status);
    GlobalMemoryStatusEx(&status);
    total_ram += QString::number(status.ullTotalPhys/1024/1024) + " MB\n";

    switch(QSysInfo::windowsVersion())
    {
        case QSysInfo::WV_NT: os_version += "Windows NT\n"; break;
        case QSysInfo::WV_2000: os_version += "Windows 2000\n"; break;
        case QSysInfo::WV_XP: os_version += "Windows XP\n"; break;
        case QSysInfo::WV_2003: os_version += "Windows Server 2003\n"; break;
        case QSysInfo::WV_VISTA: os_version += "Windows Vista\n"; break;
        case QSysInfo::WV_WINDOWS7: os_version += "Windows 7\n"; break;
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
        case QSysInfo::WV_WINDOWS8: os_version += "Windows 8\n"; break;
#endif
        default: os_version += "Windows (Unknown version)\n"; break;
    }
    kernel_line += "Windows kernel\n";
#endif
#ifdef Q_OS_LINUX
    number_of_cores += QString::number(sysconf(_SC_NPROCESSORS_ONLN)) + "\n";
    quint32 pages = sysconf(_SC_PHYS_PAGES);
    quint32 page_size = sysconf(_SC_PAGE_SIZE);
    quint32 total = pages * page_size / 1024 / 1024;
    total_ram += QString::number(total) + " MB\n";
    os_version += "GNU/Linux or BSD\n";
#endif

    // uname -a
#if defined(Q_OS_LINUX) || defined(Q_OS_MAC)
    QProcess *process = new QProcess();
    QStringList arguments = QStringList("-a");
    process->start("uname", arguments);
    if (process->waitForFinished())
        kernel_line += QString(process->readAll());
    delete process;
#endif

#if (!defined(Q_OS_MAC) && defined(__i386__)) || defined(__x86_64__)
    // cpu info
    quint32 registers[4];
    quint32 i;

    i = 0x80000002;
    asm volatile
      ("cpuid" : "=a" (registers[0]), "=b" (registers[1]), "=c" (registers[2]), "=d" (registers[3])
       : "a" (i), "c" (0));
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[0]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[1]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[2]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[3]), 4);
    i = 0x80000003;
    asm volatile
      ("cpuid" : "=a" (registers[0]), "=b" (registers[1]), "=c" (registers[2]), "=d" (registers[3])
       : "a" (i), "c" (0));
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[0]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[1]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[2]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[3]), 4);
    i = 0x80000004;
    asm volatile
      ("cpuid" : "=a" (registers[0]), "=b" (registers[1]), "=c" (registers[2]), "=d" (registers[3])
       : "a" (i), "c" (0));
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[0]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[1]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[2]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[3]), 4);
    processor_name += "\n";
#else
    processor_name += "Unknown";
#endif

    // compiler
#ifdef __GNUC__
    compiler_version += "GCC " + QString(__VERSION__) + "\n";
#else
    compiler_version += "Unknown\n";
#endif

    if(sizeof(void*) == 4)
        compiler_bits += "i386\n";
    else if(sizeof(void*) == 8)
        compiler_bits += "x86_64\n";

    // concat system info
    specs = qt_version
        + os_version
        + total_ram
        + screen_size
        + number_of_screens
        + processor_name
        + number_of_cores
        + compiler_version
        + compiler_bits
        + kernel_line;
}
コード例 #12
0
ファイル: movieexporter.cpp プロジェクト: chchwy/pencil2d
/** Runs the specified command (should be ffmpeg), and lets
 *  writeFrame pipe data into it 1 frame at a time.
 *
 *  @param[in]  strCmd A string containing the command to execute and
 *              all of its arguments
 *  @param[out] progress A function that takes one float argument
 *              (the percentage of the ffmpeg operation complete) and
 *              may display the output to the user in any way it
 *              sees fit.
 *  @param[in]  writeFrame A function that takes two arguments, a
 *              process (the ffmpeg process) and an integer
 *              (frames processed or -1, see full description).
 *              This function should write a single frame to the
 *              process. The function returns true value if it
 *              actually wrote a frame.
 *
 *  This function operates generally as follows:
 *  1. Spawn process with the command from strCmd
 *  2. Check ffmpeg's output for a progress update.
 *  3. Add frames with writeFrame until it returns false.
 *  4. Repeat from step 2 until all frames have been written.
 *
 *  The idea is that there are two forms of processing occuring
 *  simultaneously, generating frames to send to ffmpeg, and ffmpeg
 *  encoding those frames. Whether these this actually occur
 *  concurrently or one after another appears to depend on the environment.
 *
 *  The writeFrame function deserves a bit of extra details. It does
 *  not only return false when there is an error in generating or
 *  writing a frame, it also does it when it wants to "return control"
 *  to the rest of the executeFFMpegPipe function for the purposes of
 *  reading updates from ffmpeg's output. This should be done every
 *  once in a while if possible, but with some formats (specifically gif),
 *  all frames must be loaded before any processing can continue, so
 *  there is no point returning false for it until all frames have
 *  been written. writeFrame is also responsible for closing the writeChannel
 *  of the process when it has finished writing all frames. This indicates
 *  to executeFFMpegPipe that it no longer needs to call writeFrame.
 *
 *  @return Returns Status::OK if everything went well, and Status::FAIL
 *  and error is detected (usually a non-zero exit code for ffmpeg).
 */
Status MovieExporter::executeFFMpegPipe(QString strCmd, std::function<void(float)> progress, std::function<bool(QProcess&, int)> writeFrame)
{
    qDebug() << strCmd;

    QProcess ffmpeg;
    ffmpeg.setReadChannel(QProcess::StandardOutput);
    // FFmpeg writes to stderr only for some reason, so we just read both channels together
    ffmpeg.setProcessChannelMode(QProcess::MergedChannels);
    ffmpeg.start(strCmd);
    if (ffmpeg.waitForStarted())
    {
        int framesGenerated = 0;
        int lastFrameProcessed = 0;
        const int frameStart = mDesc.startFrame;
        const int frameEnd = mDesc.endFrame;
        while(ffmpeg.state() == QProcess::Running)
        {
            if (mCanceled)
            {
                ffmpeg.terminate();
                return Status::CANCELED;
            }

            // Check FFmpeg progress

            int framesProcessed = -1;
            if(ffmpeg.waitForReadyRead(10))
            {
                QString output(ffmpeg.readAll());
                QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
                for (const QString& s : sList)
                {
                    qDebug() << "[ffmpeg]" << s;
                }
                if(output.startsWith("frame="))
                {
                    lastFrameProcessed = framesProcessed = output.mid(6, output.indexOf(' ')).toInt();
                }
            }

            if(!ffmpeg.isWritable())
            {
                continue;
            }

            while(writeFrame(ffmpeg, framesProcessed))
            {
                framesGenerated++;

                const float percentGenerated = framesGenerated / static_cast<float>(frameEnd - frameStart);
                const float percentConverted = lastFrameProcessed / static_cast<float>(frameEnd - frameStart);
                progress((percentGenerated + percentConverted) / 2);
            }
            const float percentGenerated = framesGenerated / static_cast<float>(frameEnd - frameStart);
            const float percentConverted = lastFrameProcessed / static_cast<float>(frameEnd - frameStart);
            progress((percentGenerated + percentConverted) / 2);
        }

        QString output(ffmpeg.readAll());
        QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
        for (const QString& s : sList)
        {
            qDebug() << "[ffmpeg]" << s;
        }

        if(ffmpeg.exitStatus() != QProcess::NormalExit)
        {
            qDebug() << "ERROR: FFmpeg crashed";
            return Status::FAIL;
        }
    }
    else
    {
        qDebug() << "ERROR: Could not start FFmpeg.";
        return Status::FAIL;
    }

    return Status::OK;
}
コード例 #13
0
ファイル: mainwindow.cpp プロジェクト: chester890222/Bonds_Qt
void MainWindow::slot_pushButton_tb_info_clicked() {
//    ui->pushButton_tb_info->setEnabled(false);
    QProcess* process = new QProcess();
    process->startDetached("./app/BondInfo", QStringList()<<"000");
}
コード例 #14
0
Device::Device()
{
#ifdef i386
    m_model = EMULATOR;
    return;
#endif
    QStringList list;
    QProcess *myProcess = new QProcess();

    list << "-c" << "grep erial /proc/cpuinfo|cut -c12-15";
    myProcess->start("/bin/sh", list);
    if (myProcess->waitForReadyRead(10000)) {
        QByteArray array = myProcess->readAll();
        array.truncate(array.indexOf("\n"));

        bool ok;
        int sn = QString(array).toInt(&ok, 16);

        if (ok) {
            qDebug("serial: %X", sn);
        } else {
            qDebug("unexpected output");
            return;
        }

        switch(sn) {
        case 0xB002:
        case 0xB003:
            m_model = K2; // may not work as K2 doesn't print SN in cpuinfo
            break;
        case 0xB004:
        case 0xB005:
        case 0xB009:
            m_model = KDX;
            break;
        case 0xB006:
        case 0xB008:
        case 0xB00A:
            m_model = K3;
            break;
        case 0xB00E:
            m_model = K4NT;
            break;
        case 0xB00F:
        case 0xB010:
        case 0xB011:
        case 0xB012: // ???
            m_model = KT;
            break;
        case 0x9023:
        case 0xB023:
            m_model = K4NTB;
            break;
        case 0xB01B:
        case 0xB01C:
        case 0xB01D:
        case 0xB01F:
        case 0xB024:
            m_model = KPW;
            break;
        default:
            qDebug("Unknown model: %X", sn);
        }
    }
    myProcess->close();
}
コード例 #15
0
bool InitDriveThread::method_resizePartitions()
{
    int newStartOfRescuePartition = getFileContents(sysclassblock(_drive, 1)+"/start").trimmed().toInt();
    int newSizeOfRescuePartition  = sizeofBootFilesInKB()*1.024/1000 + 100;

    if (!umountSystemPartition())
    {
        emit error(tr("Error unmounting system partition."));
        return false;
    }

    if (!QFile::exists(partdev(_drive, 1)))
    {
        // SD card does not have a MBR.

        // Warn user that their SD card does not have an MBR and ask
        // if they would like us to create one for them
        QMessageBox::StandardButton answer;
        emit query(tr("Would you like NOOBS to create one for you?\nWARNING: This will erase all data on your SD card"),
                   tr("Error: No MBR present on SD Card"),
                   &answer);

        if(answer == QMessageBox::Yes)
        {
            emit statusUpdate(tr("Zeroing partition table"));
            if (!zeroMbr())
            {
                emit error(tr("Error zero'ing MBR/GPT. SD card may be broken or advertising wrong capacity."));
                return false;
            }

            // Create MBR containing single FAT partition
            emit statusUpdate(tr("Writing new MBR"));
            QProcess proc;
            proc.setProcessChannelMode(proc.MergedChannels);
            proc.start("/usr/sbin/parted "+_drive+" --script -- mktable msdos mkpartfs primary fat32 8192s -1");
            proc.waitForFinished(-1);
            if (proc.exitCode() != 0)
            {
                // Warn user if we failed to create an MBR on their card
                emit error(tr("Error creating MBR")+"\n"+proc.readAll());
                return false;
            }
            qDebug() << "Created missing MBR on SD card. parted output:" << proc.readAll();

            // Advise user that their SD card has now been formatted
            // suitably for installing NOOBS and that they will have to
            // re-copy the files before rebooting
            emit error(tr("SD card has now been formatted ready for NOOBS installation. Please re-copy the NOOBS files onto the card and reboot"));
            return false;
        }
        else
        {
            emit error(tr("SD card has not been formatted correctly. Please reformat using the SD Association Formatting Tool and try again."));
            return false;
        }

    }

    emit statusUpdate(tr("Removing partitions 2,3,4"));

    QFile f(_drive);
    f.open(f.ReadWrite);
    // Seek to partition entry 2
    f.seek(462);
    // Zero out partition 2,3,4 to prevent parted complaining about invalid constraints
    f.write(QByteArray(16*3, '\0'));
    f.flush();
    // Tell Linux to re-read the partition table
    ioctl(f.handle(), BLKRRPART);
    f.close();
    QThread::msleep(500);

    emit statusUpdate(tr("Resizing FAT partition"));

    /* Relocating the start of the FAT partition is a write intensive operation
     * only move it when it is not aligned on a MiB boundary already */
    if (newStartOfRescuePartition < 2048 || newStartOfRescuePartition % 2048 != 0)
    {
        newStartOfRescuePartition = PARTITION_ALIGNMENT; /* 4 MiB */
    }

    QString cmd = "/usr/sbin/parted --script "+_drive+" resize 1 "+QString::number(newStartOfRescuePartition)+"s "+QString::number(newSizeOfRescuePartition)+"M";
    qDebug() << "Executing" << cmd;
    QProcess p;
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    /* Suppress parted's big fat warning about its file system manipulation code not being robust.
       It distracts from any real error messages that may follow it. */
    env.insert("PARTED_SUPPRESS_FILE_SYSTEM_MANIPULATION_WARNING", "1");
    p.setProcessEnvironment(env);
    p.setProcessChannelMode(p.MergedChannels);
    p.start(cmd);
    p.closeWriteChannel();
    p.waitForFinished(-1);

    if (p.exitCode() != 0)
    {
        emit error(tr("Error resizing existing FAT partition")+"\n"+p.readAll());
        return false;
    }
    qDebug() << "parted done, output:" << p.readAll();
    QThread::msleep(500);

    emit statusUpdate(tr("Creating extended partition"));

    QByteArray partitionTable;
    int startOfOurPartition = getFileContents(sysclassblock(_drive, 1)+"/start").trimmed().toInt();
    int sizeOfOurPartition  = getFileContents(sysclassblock(_drive, 1)+"/size").trimmed().toInt();
    int startOfExtended = startOfOurPartition+sizeOfOurPartition;

    // Align start of settings partition on 4 MiB boundary
    int startOfSettings = startOfExtended + PARTITION_GAP;
    if (startOfSettings % PARTITION_ALIGNMENT != 0)
         startOfSettings += PARTITION_ALIGNMENT-(startOfSettings % PARTITION_ALIGNMENT);

    // Primary partitions
    partitionTable  = QByteArray::number(startOfOurPartition)+","+QByteArray::number(sizeOfOurPartition)+",0E\n"; /* FAT partition */
    partitionTable += QByteArray::number(startOfExtended)+",,E\n"; /* Extended partition with all remaining space */
    partitionTable += "0,0\n";
    partitionTable += "0,0\n";
    // Logical partitions
    partitionTable += QByteArray::number(startOfSettings)+","+QByteArray::number(SETTINGS_PARTITION_SIZE)+",L\n"; /* Settings partition */
    qDebug() << "Writing partition table" << partitionTable;

    /* Let sfdisk write a proper partition table */
    cmd = QString("/sbin/sfdisk -uS --force "+_drive);
    QProcess proc;
    proc.setProcessChannelMode(proc.MergedChannels);
    proc.start(cmd);
    proc.write(partitionTable);
    proc.closeWriteChannel();
    proc.waitForFinished(-1);
    if (proc.exitCode() != 0)
    {
        emit error(tr("Error creating extended partition")+"\n"+proc.readAll());
        return false;
    }
    qDebug() << "sfdisk done, output:" << proc.readAll();
    QThread::msleep(500);

    QProcess::execute("/sbin/mlabel -i "+partdev(_drive, 1)+" ::RECOVERY");

    return true;
}
コード例 #16
0
void PkgConfigTool::packages_helper() const
{
    QStringList args;
    args.append(QLatin1String("--list-all"));

    QProcess pkgconfig;
    pkgconfig.start(QLatin1String("pkg-config"), args);
    while (! pkgconfig.waitForFinished()) {
    }

    QTextStream in(&pkgconfig);
    forever {
        const QString line = in.readLine();

        if (line.isNull())
            break;

        else if (line.isEmpty())
            continue;

        int i = 0;
        for (; i != line.length(); ++i) {
            if (line.at(i).isSpace())
                break;
        }

        Package package;
        package.name = line.left(i).trimmed();
        package.description = line.mid(i).trimmed();

        QStringList args;
        args << package.name << QLatin1String("--cflags");
        pkgconfig.start(QLatin1String("pkg-config"), args);

        while (! pkgconfig.waitForFinished()) {
        }

        const QString cflags = QString::fromUtf8(pkgconfig.readAll());

        int index = 0;
        while (index != cflags.size()) {
            const QChar ch = cflags.at(index);

            if (ch.isSpace()) {
                do { ++index; }
                while (index < cflags.size() && cflags.at(index).isSpace());
            }

            else if (ch == QLatin1Char('-') && index + 1 < cflags.size()) {
                ++index;

                const QChar opt = cflags.at(index);

                if (opt == QLatin1Char('I')) {
                    // include paths.

                    int start = ++index;
                    for (; index < cflags.size(); ++index) {
                        if (cflags.at(index).isSpace())
                            break;
                    }

                    qDebug() << "*** add include path:" << cflags.mid(start, index - start);
                    package.includePaths.append(cflags.mid(start, index - start));
                }
            }

            else {
                for (; index < cflags.size(); ++index) {
                    if (cflags.at(index).isSpace())
                        break;
                }
            }
        }

        m_packages.append(package);
    }
}
コード例 #17
0
ファイル: logsdialog.cpp プロジェクト: kamnxt/opentx
void LogsDialog::exportToGoogleEarth()
{
  // filter data points
  QList<QStringList> dataPoints = filterGePoints(csvlog);
  int n = dataPoints.count(); // number of points to export
  if (n==0) return;

  int latcol=0, longcol=0, altcol=0, speedcol=0;
  QSet<int> nondataCols;
  for (int i=1; i<dataPoints.at(0).count(); i++) {
    // Long,Lat,Course,GPS Speed,GPS Alt
    if (dataPoints.at(0).at(i).contains("Long")) {
      longcol = i;
      nondataCols << i;
    }
    if (dataPoints.at(0).at(i).contains("Lat")) {
      latcol = i;
      nondataCols << i;
    }
    if (dataPoints.at(0).at(i).contains("GPS Alt") || dataPoints.at(0).at(i).contains("GAlt")) {
      altcol = i;
      nondataCols << i;
    }
    if (dataPoints.at(0).at(i).contains("GPS Speed")) {
      speedcol = i;
      nondataCols << i;
    }
  }

  if (longcol==0 || latcol==0) {
    return;
  }

  QString geIconFilename = generateProcessUniqueTempFileName("track0.png");
  if (QFile::exists(geIconFilename)) {
    QFile::remove(geIconFilename);
  }
  QFile::copy(":/images/track0.png", geIconFilename);

  QString geFilename = generateProcessUniqueTempFileName("flight.kml");
  if (QFile::exists(geFilename)) {
    QFile::remove(geFilename);
  }
  QFile geFile(geFilename);
  if (!geFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
    QMessageBox::warning(this, tr("Error"),
        tr("Cannot write file %1:\n%2.")
        .arg(geFilename)
        .arg(geFile.errorString()));
    return;
  }

  QTextStream outputStream(&geFile);

  // file header
  outputStream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\">\n";
  outputStream << "\t<Document>\n\t\t<name>" << logFilename << "</name>\n";
  outputStream << "\t\t<Style id=\"multiTrack_n\">\n\t\t\t<IconStyle>\n\t\t\t\t<Icon>\n\t\t\t\t\t<href>file://" << geIconFilename << "</href>\n\t\t\t\t</Icon>\n\t\t\t</IconStyle>\n\t\t\t<LineStyle>\n\t\t\t\t<color>991081f4</color>\n\t\t\t\t<width>6</width>\n\t\t\t</LineStyle>\n\t\t</Style>\n";
  outputStream << "\t\t<Style id=\"multiTrack_h\">\n\t\t\t<IconStyle>\n\t\t\t\t<scale>0</scale>\n\t\t\t\t<Icon>\n\t\t\t\t\t<href>file://" << geIconFilename << "</href>\n\t\t\t\t</Icon>\n\t\t\t</IconStyle>\n\t\t\t<LineStyle>\n\t\t\t\t<color>991081f4</color>\n\t\t\t\t<width>8</width>\n\t\t\t</LineStyle>\n\t\t</Style>\n";
  outputStream << "\t\t<StyleMap id=\"multiTrack\">\n\t\t\t<Pair>\n\t\t\t\t<key>normal</key>\n\t\t\t\t<styleUrl>#multiTrack_n</styleUrl>\n\t\t\t</Pair>\n\t\t\t<Pair>\n\t\t\t\t<key>highlight</key>\n\t\t\t\t<styleUrl>#multiTrack_h</styleUrl>\n\t\t\t</Pair>\n\t\t</StyleMap>\n";
  outputStream << "\t\t<Style id=\"lineStyle\">\n\t\t\t<LineStyle>\n\t\t\t\t<color>991081f4</color>\n\t\t\t\t<width>6</width>\n\t\t\t</LineStyle>\n\t\t</Style>\n";
  outputStream << "\t\t<Schema id=\"schema\">\n";
  outputStream << "\t\t\t<gx:SimpleArrayField name=\"GPSSpeed\" type=\"float\">\n\t\t\t\t<displayName>GPS Speed</displayName>\n\t\t\t</gx:SimpleArrayField>\n";
  
  // declare additional fields
  for (int i=0; i<dataPoints.at(0).count()-2; i++) {
    if (ui->FieldsTW->item(0,i)->isSelected() && !nondataCols.contains(i+2)) {
      QString origName = dataPoints.at(0).at(i+2);
      QString safeName = origName;
      safeName.replace(" ","_");
      outputStream << "\t\t\t<gx:SimpleArrayField name=\""<< safeName <<"\" ";
      outputStream << "type=\"string\"";   // additional fields have fixed type: string
      outputStream << ">\n\t\t\t\t<displayName>" << origName << "</displayName>\n\t\t\t</gx:SimpleArrayField>\n";
    }
  }

  QString planeName;
  if (logFilename.indexOf("-")>0) {
    planeName=logFilename.left(logFilename.indexOf("-"));
  } else {
    planeName=logFilename;
  }

  outputStream << "\t\t</Schema>\n";
  outputStream << "\t\t<Folder>\n\t\t\t<name>Log Data</name>\n\t\t\t<Placemark>\n\t\t\t\t<name>" << planeName << "</name>";
  outputStream << "\n\t\t\t\t<styleUrl>#multiTrack</styleUrl>";
  outputStream << "\n\t\t\t\t<gx:Track>\n";
  outputStream << "\n\t\t\t\t\t<altitudeMode>absolute</altitudeMode>\n";

  // time data points
  for (int i=1; i<n; i++) {
    QString tstamp=dataPoints.at(i).at(0)+QString("T")+dataPoints.at(i).at(1)+QString("Z");
    outputStream << "\t\t\t\t\t<when>"<< tstamp <<"</when>\n";
  }

  // coordinate data points
  for (int i=1; i<n; i++) {
    QString latitude = dataPoints.at(i).at(latcol).trimmed();
    QString longitude = dataPoints.at(i).at(longcol).trimmed();
    int altitude = altcol ? dataPoints.at(i).at(altcol).toFloat() : 0;
    latitude.sprintf("%3.8f", toDecimalCoordinate(latitude));
    longitude.sprintf("%3.8f", toDecimalCoordinate(longitude));
    outputStream << "\t\t\t\t\t<gx:coord>" << longitude << " " << latitude << " " <<  altitude << " </gx:coord>\n" ;
  }

  // additional data for data points
  outputStream << "\t\t\t\t\t<ExtendedData>\n\t\t\t\t\t\t<SchemaData schemaUrl=\"#schema\">\n";

  if (speedcol) {
    // gps speed data points
    outputStream << "\t\t\t\t\t\t\t<gx:SimpleArrayData name=\"GPSSpeed\">\n";
    for (int i=1; i<n; i++) {
      outputStream << "\t\t\t\t\t\t\t\t<gx:value>"<< dataPoints.at(i).at(speedcol) <<"</gx:value>\n";
    }
    outputStream << "\t\t\t\t\t\t\t</gx:SimpleArrayData>\n";
  }

  // add values for additional fields
  for (int i=0; i<dataPoints.at(0).count()-2; i++) {
    if (ui->FieldsTW->item(0,i)->isSelected() && !nondataCols.contains(i+2)) {
      QString safeName = dataPoints.at(0).at(i+2);;
      safeName.replace(" ","_");
      outputStream << "\t\t\t\t\t\t\t<gx:SimpleArrayData name=\""<< safeName <<"\">\n";
      for (int j=1; j<n; j++) {
        outputStream << "\t\t\t\t\t\t\t\t<gx:value>"<< dataPoints.at(j).at(i+2) <<"</gx:value>\n";
      }
      outputStream << "\t\t\t\t\t\t\t</gx:SimpleArrayData>\n";
    }
  }

  outputStream << "\t\t\t\t\t\t</SchemaData>\n\t\t\t\t\t</ExtendedData>\n\t\t\t\t</gx:Track>\n\t\t\t</Placemark>\n\t\t</Folder>\n\t</Document>\n</kml>";
  geFile.close();

  QString gePath = g.gePath();
  QStringList parameters;
#ifdef __APPLE__
  parameters << "-a";
  parameters << gePath;
  gePath = "/usr/bin/open";
#endif
  parameters << geFilename;
  QProcess *process = new QProcess(this);
  process->start(gePath, parameters);
}
コード例 #18
0
ファイル: Common.cpp プロジェクト: Krabi/idkaart_public
QString Common::applicationOs()
{
#if defined(Q_OS_LINUX)
	QProcess p;
	p.start( "lsb_release", QStringList() << "-s" << "-d" );
	p.waitForFinished();
	return QString::fromLocal8Bit( p.readAll().trimmed() );
#elif defined(Q_OS_MAC)
	SInt32 major, minor, bugfix;
	if( Gestalt(gestaltSystemVersionMajor, &major) == noErr &&
			Gestalt(gestaltSystemVersionMinor, &minor) == noErr &&
			Gestalt(gestaltSystemVersionBugFix, &bugfix) == noErr )
		return QString( "Mac OS %1.%2.%3 (%4)" ).arg( major ).arg( minor ).arg( bugfix ).arg( QSysInfo::WordSize );
	else
		return QString( "Mac OS 10.3 (%1)" ).arg( QSysInfo::WordSize );
#elif defined(Q_OS_WIN)
	QString os;
	OSVERSIONINFOEX osvi = { sizeof( OSVERSIONINFOEX ) };
	bool is64bit = false;
	if( GetVersionEx( (OSVERSIONINFO *)&osvi ) )
	{
		SYSTEM_INFO si;
		typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
		if( PGNSI pGNSI = PGNSI( QLibrary( "kernel32" ).resolve( "GetNativeSystemInfo" ) ) )
			pGNSI( &si );
		else
			GetSystemInfo( &si );
		switch( osvi.dwMajorVersion )
		{
		case 5:
			switch( osvi.dwMinorVersion )
			{
			case 0:
				os = QString( "Windows 2000 %1" ).arg( osvi.wProductType == VER_NT_WORKSTATION ? "Professional" : "Server" );
				break;
			case 1:
				os = QString( "Windows XP %1" ).arg( osvi.wSuiteMask & VER_SUITE_PERSONAL ? "Home" : "Professional" );
				break;
			case 2:
				if( GetSystemMetrics( SM_SERVERR2 ) )
					os = "Windows Server 2003 R2";
				else if( osvi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 )
				{
					is64bit = true;
					os = "Windows XP Professional";
				} else {
					os = "Windows Server 2003";
					if ( osvi.wProductType != VER_NT_WORKSTATION && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 )
						is64bit = true;
				}
				break;
			default: break;
			}
			break;
		case 6:
			switch( osvi.dwMinorVersion )
			{
			case 0:
				os = osvi.wProductType == VER_NT_WORKSTATION ? "Windows Vista" : "Windows Server 2008";
				break;
			case 1:
				os = osvi.wProductType == VER_NT_WORKSTATION ? "Windows 7" : "Windows Server 2008 R2";
				break;
			}
			if ( si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 )
				is64bit = true;
			break;
		default: break;
		}
	}
コード例 #19
0
static int getWordSizeOfOS()
{
#if defined(Q_OS_WIN64)
    return 64; // 64-bit process running on 64-bit windows
#elif defined(Q_OS_WIN32)

    // determine if 32-bit process running on 64-bit windows in WOW64 emulation
    // or 32-bit process running on 32-bit windows
    // default bIsWow64 to FALSE for 32-bit process on 32-bit windows

    BOOL bIsWow64 = FALSE; // must default to FALSE

    LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(
        GetModuleHandle("kernel32"), "IsWow64Process");

    if (NULL != fnIsWow64Process) {
        if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) {
            assert(false); // something went majorly wrong
        }
    }
    return bIsWow64 ? 64 : 32;

#elif defined (Q_OS_LINUX)
    // http://stackoverflow.com/questions/246007/how-to-determine-whether-a-given-linux-is-32-bit-or-64-bit
    QString exe(QLatin1String("getconf"));
    QStringList args;
    args << QLatin1String("LONG_BIT");
    QProcess proc;
    proc.setEnvironment(QProcess::systemEnvironment());
    proc.start(exe, args);
    if (proc.waitForStarted() && proc.waitForFinished()) {
        QByteArray info = proc.readAll();
        info.replace('\n',"");
        return info.toInt();
    }

    return 0; // failed

#elif defined (Q_OS_UNIX) || defined (Q_OS_MAC)
    QString exe(QLatin1String("uname"));
    QStringList args;
    args << QLatin1String("-m");
    QProcess proc;
    proc.setEnvironment(QProcess::systemEnvironment());
    proc.start(exe, args);
    if (proc.waitForStarted() && proc.waitForFinished()) {
        QByteArray info = proc.readAll();
        info.replace('\n',"");
        if (info.indexOf("x86_64") >= 0)
            return 64;
        else if (info.indexOf("amd64") >= 0)
            return 64;
        else if (info.indexOf("ia64") >= 0)
            return 64;
        else if (info.indexOf("ppc64") >= 0)
            return 64;
        else if (info.indexOf("i386") >= 0)
            return 32;
        else if (info.indexOf("i686") >= 0)
            return 32;
        else if (info.indexOf("x86") >= 0)
            return 32;
    }

    return 0; // failed
#else
    return 0; // unknown
#endif
}
コード例 #20
0
bool CameraOutV4L2::sudo(const QString &command,
                         const QStringList &argumments,
                         const QString &password) const
{
    if (password.isEmpty())
        return false;

    QProcess echo;
    QProcess su;

    echo.setStandardOutputProcess(&su);

    switch (this->m_rootMethod) {
        case RootMethodSu: {
            QStringList args;

            for (QString arg: argumments)
                args << arg.replace(" ", "\\ ");

            echo.start("echo", {password});
            su.start("su", {"-c", command + " " + args.join(" ")});

            break;
        }
        case RootMethodSudo: {
            echo.start("echo", {password});
            su.start("sudo", QStringList{"-S", command} << argumments);

            break;
        }
    }

    su.setProcessChannelMode(QProcess::ForwardedChannels);
    echo.waitForStarted();

    if (!su.waitForFinished(this->m_passwordTimeout)) {
        su.kill();
        echo.waitForFinished();

        return false;
    }

    echo.waitForFinished();

    if (su.exitCode()) {
        QByteArray outMsg = su.readAllStandardOutput();

        if (!outMsg.isEmpty())
            qDebug() << outMsg.toStdString().c_str();

        QByteArray errorMsg = su.readAllStandardError();

        if (!errorMsg.isEmpty())
            qDebug() << errorMsg.toStdString().c_str();

        return false;
    }

    return true;
}
コード例 #21
0
ファイル: ttsfestival.cpp プロジェクト: Brandon7357/rockbox
TTSStatus TTSFestival::voice(QString text, QString wavfile, QString* errStr)
{
    LOG_INFO() << "Voicing" << text << "->" << wavfile;

    QString path = RbSettings::subValue("festival-client",
            RbSettings::TtsPath).toString();
    QString cmd = QString("%1 --server localhost --otype riff --ttw --withlisp"
            " --output \"%2\" --prolog \"%3\" - ").arg(path).arg(wavfile).arg(prologPath);
    LOG_INFO() << "Client cmd:" << cmd;

    QProcess clientProcess;
    clientProcess.start(cmd);
    clientProcess.write(QString("%1.\n").arg(text).toLatin1());
    clientProcess.waitForBytesWritten();
    clientProcess.closeWriteChannel();
    clientProcess.waitForReadyRead();
    QString response = clientProcess.readAll();
    response = response.trimmed();
    if(!response.contains("Utterance"))
    {
        LOG_WARNING() << "Could not voice string: " << response;
        *errStr = tr("engine could not voice string");
        return Warning;
        /* do not stop the voicing process because of a single string
        TODO: needs proper settings */
    }
    clientProcess.closeReadChannel(QProcess::StandardError);
    clientProcess.closeReadChannel(QProcess::StandardOutput);
    clientProcess.terminate();
    clientProcess.kill();

    return NoError;
}
コード例 #22
0
void MetaEditorSupportPlugin::generateEditorWithQrmc()
{
	qrmc::MetaCompiler metaCompiler(qApp->applicationDirPath() + "/../qrmc", mLogicalRepoApi);

	IdList const metamodels = mLogicalRepoApi->children(Id::rootId());

	QProgressBar *progress = new QProgressBar(mMainWindowInterface->windowWidget());
	progress->show();
	int const progressBarWidth = 240;
	int const progressBarHeight = 20;

	QApplication::processEvents();
	QRect const screenRect = qApp->desktop()->availableGeometry();
	progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
	progress->setFixedWidth(progressBarWidth);
	progress->setFixedHeight(progressBarHeight);
	progress->setRange(0, 100);

	int forEditor = 60 / metamodels.size();

	foreach (Id const &key, metamodels) {
		QString const objectType = key.element();
		if (objectType == "MetamodelDiagram" && mLogicalRepoApi->isLogicalElement(key)) {
			QString nameOfTheDirectory = mLogicalRepoApi->stringProperty(key, "name of the directory");
			QString nameOfMetamodel = mLogicalRepoApi->stringProperty(key, "name");
			QString nameOfPlugin = nameOfTheDirectory.split("/").last();

			if (QMessageBox::question(mMainWindowInterface->windowWidget()
					, tr("loading..")
					, QString(tr("Do you want to compile and load editor %1?")).arg(nameOfPlugin)
					, QMessageBox::Yes, QMessageBox::No)
					== QMessageBox::No)
			{
				continue;
			}

			progress->setValue(5);

			if (!metaCompiler.compile(nameOfMetamodel)) { // generating source code for all metamodels
				QMessageBox::warning(mMainWindowInterface->windowWidget()
						, tr("error")
						, tr("Cannot generate source code for editor ") + nameOfPlugin);
				continue;
			}
			progress->setValue(20);

			QProcess builder;
			builder.setWorkingDirectory("../qrmc/plugins");
			builder.start(SettingsManager::value("pathToQmake").toString());
			qDebug()  << "qmake";
			if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
				progress->setValue(40);

				builder.start(SettingsManager::value("pathToMake").toString());

				bool finished = builder.waitForFinished(100000);
				qDebug()  << "make";
				if (finished && (builder.exitCode() == 0)) {
					qDebug()  << "make ok";

					progress->setValue(progress->value() + forEditor / 2);

					QString normalizedName = nameOfPlugin.at(0).toUpper() + nameOfPlugin.mid(1);
					if (!nameOfPlugin.isEmpty()) {
						if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
							QMessageBox::warning(mMainWindowInterface->windowWidget()
									, tr("error")
									, tr("cannot unload plugin ") + normalizedName);
							progress->close();
							delete progress;
							continue;
						}
					}

					QString const generatedPluginFileName = SettingsManager::value("prefix").toString()
							+ nameOfPlugin
							+ "."
							+ SettingsManager::value("pluginExtension").toString()
							;

					if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) {
						progress->setValue(progress->value() + forEditor / 2);
					}
				}
				progress->setValue(100);
			}
		}
	}
コード例 #23
0
const AudioFileModel AnalyzeTask::analyzeFile(const QString &filePath, int *type)
{
	*type = fileTypeNormal;
	AudioFileModel audioFile(filePath);

	QFile readTest(filePath);
	if(!readTest.open(QIODevice::ReadOnly))
	{
		*type = fileTypeDenied;
		return audioFile;
	}
	if(checkFile_CDDA(readTest))
	{
		*type = fileTypeCDDA;
		return audioFile;
	}
	readTest.close();

	bool skipNext = false;
	unsigned int id_val[2] = {UINT_MAX, UINT_MAX};
	cover_t coverType = coverNone;
	QByteArray coverData;

	QStringList params;
	params << QString("--Inform=file://%1").arg(QDir::toNativeSeparators(m_templateFile));
	params << QDir::toNativeSeparators(filePath);
	
	QProcess process;
	lamexp_init_process(process, QFileInfo(m_mediaInfoBin).absolutePath());

	process.start(m_mediaInfoBin, params);
		
	if(!process.waitForStarted())
	{
		qWarning("MediaInfo process failed to create!");
		qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
		process.kill();
		process.waitForFinished(-1);
		return audioFile;
	}

	while(process.state() != QProcess::NotRunning)
	{
		if(*m_abortFlag)
		{
			process.kill();
			qWarning("Process was aborted on user request!");
			break;
		}
		
		if(!process.waitForReadyRead())
		{
			if(process.state() == QProcess::Running)
			{
				qWarning("MediaInfo time out. Killing process and skipping file!");
				process.kill();
				process.waitForFinished(-1);
				return audioFile;
			}
		}

		QByteArray data;

		while(process.canReadLine())
		{
			QString line = QString::fromUtf8(process.readLine().constData()).simplified();
			if(!line.isEmpty())
			{
				//qDebug("Line:%s", QUTF8(line));
				
				int index = line.indexOf('=');
				if(index > 0)
				{
					QString key = line.left(index).trimmed();
					QString val = line.mid(index+1).trimmed();
					if(!key.isEmpty())
					{
						updateInfo(audioFile, &skipNext, id_val, &coverType, &coverData, key, val);
					}
				}
			}
		}
	}

	if(audioFile.metaInfo().title().isEmpty())
	{
		QString baseName = QFileInfo(filePath).fileName();
		int index = baseName.lastIndexOf(".");

		if(index >= 0)
		{
			baseName = baseName.left(index);
		}

		baseName = baseName.replace("_", " ").simplified();
		index = baseName.lastIndexOf(" - ");

		if(index >= 0)
		{
			baseName = baseName.mid(index + 3).trimmed();
		}

		audioFile.metaInfo().setTitle(baseName);
	}
	
	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}

	if((coverType != coverNone) && (!coverData.isEmpty()))
	{
		retrieveCover(audioFile, coverType, coverData);
	}

	if((audioFile.techInfo().audioType().compare("PCM", Qt::CaseInsensitive) == 0) && (audioFile.techInfo().audioProfile().compare("Float", Qt::CaseInsensitive) == 0))
	{
		if(audioFile.techInfo().audioBitdepth() == 32) audioFile.techInfo().setAudioBitdepth(AudioFileModel::BITDEPTH_IEEE_FLOAT32);
	}

	return audioFile;
}
コード例 #24
0
ファイル: mapview.cpp プロジェクト: minsoub/MapView
/**
 * Execute Symbol Editor Program
 */
void MapView::setSymbolEditor()
{
	QString program = "/root/workspace/Trunk/Trunk";
	QProcess *process = new QProcess(this);
	process->start(program);
}
コード例 #25
0
ファイル: createtorrent.cpp プロジェクト: VrajPandya/storm
void createTorrent::on_makeTorrent_Button_clicked()
{
    QString program = "/home/oyashi/Downloads/libtorrent-rasterbar-1.1.0/examples/make_torrent";
    QString outputFile = uiCreateTor->outputFileLineEdit->text();


    QMessageBox msgBox;

    if(!filePath.isEmpty()){
        if(!outputFile.isEmpty()){
            QString outputFileName = outputFile + ".torrent";
            QStringList arguments;
            arguments << filePath << "-o" << outputFileName ;

            if(!uiCreateTor->trackerLineEdit->text().isEmpty()){
                arguments.append("-t");
                arguments.append(uiCreateTor->trackerLineEdit->text());

            }

            if(!uiCreateTor->trackerLineEdit_2->text().isEmpty()){
                arguments.append("-t");
                arguments.append(uiCreateTor->trackerLineEdit_2->text());

            }

            if(!uiCreateTor->commentLineEdit->text().isEmpty()){
                arguments.append("-c");
                arguments.append(uiCreateTor->commentLineEdit->text());

            }

            if(!uiCreateTor->webSeedLineEdit->text().isEmpty()){
                arguments.append("-w");
                arguments.append(uiCreateTor->webSeedLineEdit->text());

            }

            if(!uiCreateTor->createdByLineEdit->text().isEmpty()){
                arguments.append("-C");
                arguments.append(uiCreateTor->createdByLineEdit->text());

            }

            QProcess *myProcess = new QProcess(this);
            myProcess->start(program,arguments);

            if(myProcess->waitForFinished(1000)){
                msgBox.setText("Torrent created successfully");
                msgBox.exec();
            }
        }
        else{
            msgBox.setText("Please provide the output file name");
            msgBox.exec();
        }
    }
    else{
        msgBox.setText("Please select the input file");
        msgBox.exec();
    }




}
コード例 #26
0
ファイル: LUtils.cpp プロジェクト: Nanolx/lumina
inline QStringList ProcessRun(QString cmd, QStringList args){
  //Assemble outputs
  QStringList out; out << "1" << ""; //error code, string output
  QProcess proc;
  QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
  env.insert("LANG", "C");
  env.insert("LC_MESSAGES", "C");
  proc.setProcessEnvironment(env);
  proc.setProcessChannelMode(QProcess::MergedChannels);
  if(args.isEmpty()){
    proc.start(cmd, QIODevice::ReadOnly);
  }else{
    proc.start(cmd,args ,QIODevice::ReadOnly);	  
  }
  QString info;
  while(!proc.waitForFinished(1000)){
    if(proc.state() == QProcess::NotRunning){ break; } //somehow missed the finished signal
    QString tmp = proc.readAllStandardOutput();
    if(tmp.isEmpty()){ proc.terminate(); }
    else{ info.append(tmp); }
  }
  out[0] = QString::number(proc.exitCode());
  out[1] = info+QString(proc.readAllStandardOutput());
  return out;	
}
コード例 #27
0
void StelLogger::init(const QString& logFilePath)
{
	logFile.setFileName(logFilePath);

	if (logFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text | QIODevice::Unbuffered))
		qInstallMessageHandler(StelLogger::debugLogHandler);

	// write timestamp
	writeLog(QString("%1").arg(QDateTime::currentDateTime().toString(Qt::ISODate)));
	// write info about operating system
	writeLog(StelUtils::getOperatingSystemInfo());

	// write compiler version
#if defined __GNUC__ && !defined __clang__
	#ifdef __MINGW32__
		#define COMPILER "MinGW GCC"
	#else
		#define COMPILER "GCC"
	#endif
	writeLog(QString("Compiled using %1 %2.%3.%4").arg(COMPILER).arg(__GNUC__).arg(__GNUC_MINOR__).arg(__GNUC_PATCHLEVEL__));
#elif defined __clang__
	writeLog(QString("Compiled using %1 %2.%3.%4").arg("Clang").arg(__clang_major__).arg(__clang_minor__).arg(__clang_patchlevel__));
#elif defined _MSC_VER
	writeLog(QString("Compiled using %1").arg(getMsvcVersionString(_MSC_VER)));
#else
	writeLog("Unknown compiler");
#endif

	// write Qt version
	writeLog(QString("Qt runtime version: %1").arg(qVersion()));
	writeLog(QString("Qt compilation version: %1").arg(QT_VERSION_STR));

	// write addressing mode
#if defined(__LP64__) || defined(_WIN64)
	writeLog("Addressing mode: 64-bit");
#else
	writeLog("Addressing mode: 32-bit");
#endif

	// write memory and CPU info
#ifdef Q_OS_LINUX

#ifndef BUILD_FOR_MAEMO
	QFile infoFile("/proc/meminfo");
	if(!infoFile.open(QIODevice::ReadOnly | QIODevice::Text))
		writeLog("Could not get memory info.");
	else
	{
		while(!infoFile.peek(1).isEmpty())
		{
			QString line = infoFile.readLine();
			line.chop(1);
			if (line.startsWith("Mem") || line.startsWith("SwapTotal"))
				writeLog(line);
		}
		infoFile.close();
	}

	infoFile.setFileName("/proc/cpuinfo");
	if (!infoFile.open(QIODevice::ReadOnly | QIODevice::Text))
		writeLog("Could not get CPU info.");
	else
	{
		while(!infoFile.peek(1).isEmpty())
		{
			QString line = infoFile.readLine();
			line.chop(1);
			if(line.startsWith("model name") || line.startsWith("cpu MHz"))
				writeLog(line);
		}
		infoFile.close();
	}

	QProcess lspci;
	lspci.start("lspci -v", QIODevice::ReadOnly);
	lspci.waitForFinished(300);
	const QString pciData(lspci.readAll());
	QStringList pciLines = pciData.split('\n', QString::SkipEmptyParts);
	for (int i = 0; i<pciLines.size(); i++)
	{
		if(pciLines.at(i).contains("VGA compatible controller"))
		{
			writeLog(pciLines.at(i));
			i++;
			while(i < pciLines.size() && pciLines.at(i).startsWith('\t'))
			{
				if(pciLines.at(i).contains("Kernel driver in use"))
					writeLog(pciLines.at(i).trimmed());
				else if(pciLines.at(i).contains("Kernel modules"))
					writeLog(pciLines.at(i).trimmed());
				i++;
			}
		}
	}
#endif

// Aargh Windows API
#elif defined Q_OS_WIN
	// Hopefully doesn't throw a linker error on earlier systems. Not like
	// I'm gonna test it or anything.
	if (QSysInfo::WindowsVersion >= QSysInfo::WV_2000)
	{
#ifdef __LP64__
		MEMORYSTATUSEX statex;
		GlobalMemoryStatusEx(&statex);
		writeLog(QString("Total physical memory: %1 MB (unreliable)").arg(statex.ullTotalPhys/(1024<<10)));
		writeLog(QString("Total virtual memory: %1 MB (unreliable)").arg(statex.ullTotalVirtual/(1024<<10)));
		writeLog(QString("Physical memory in use: %1%").arg(statex.dwMemoryLoad));
#else
		MEMORYSTATUS statex;
		GlobalMemoryStatus(&statex);
		writeLog(QString("Total memory: %1 MB (unreliable)").arg(statex.dwTotalPhys/(1024<<10)));
		writeLog(QString("Total virtual memory: %1 MB (unreliable)").arg(statex.dwTotalVirtual/(1024<<10)));
		writeLog(QString("Physical memory in use: %1%").arg(statex.dwMemoryLoad));
#endif
	}
	else
		writeLog("Windows version too old to get memory info.");

	HKEY hKey = NULL;
	DWORD dwType = REG_DWORD;
	DWORD numVal = 0;
	DWORD dwSize = sizeof(numVal);

	// iterate over the processors listed in the registry
	QString procKey = "Hardware\\Description\\System\\CentralProcessor";
	LONG lRet = ERROR_SUCCESS;
	int i;
	for(i = 0; lRet == ERROR_SUCCESS; i++)
	{
		lRet = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
					qPrintable(QString("%1\\%2").arg(procKey).arg(i)),
					0, KEY_QUERY_VALUE, &hKey);

		if(lRet == ERROR_SUCCESS)
		{
			if(RegQueryValueExA(hKey, "~MHz", NULL, &dwType, (LPBYTE)&numVal, &dwSize) == ERROR_SUCCESS)
				writeLog(QString("Processor speed: %1 MHz").arg(numVal));
			else
				writeLog("Could not get processor speed.");
		}

		// can you believe this trash?
		dwType = REG_SZ;
		char nameStr[512];
		DWORD nameSize = sizeof(nameStr);

		if (lRet == ERROR_SUCCESS)
		{
			if (RegQueryValueExA(hKey, "ProcessorNameString", NULL, &dwType, (LPBYTE)&nameStr, &nameSize) == ERROR_SUCCESS)
				writeLog(QString("Processor name: %1").arg(nameStr));
			else
				writeLog("Could not get processor name.");
		}

		RegCloseKey(hKey);
	}
	if(i == 0)
		writeLog("Could not get processor info.");

#elif defined Q_OS_MAC
	QProcess systemProfiler;
	systemProfiler.start("/usr/sbin/system_profiler -detailLevel mini SPHardwareDataType SPDisplaysDataType");
	systemProfiler.waitForStarted();
	systemProfiler.waitForFinished();
	const QString systemData(systemProfiler.readAllStandardOutput());
	QStringList systemLines = systemData.split('\n', QString::SkipEmptyParts);
	for (int i = 0; i<systemLines.size(); i++)
	{
		if(systemLines.at(i).contains("Model"))
		{
			writeLog(systemLines.at(i).trimmed());
		}

		if(systemLines.at(i).contains("Processor"))
		{
			writeLog(systemLines.at(i).trimmed());
		}

		if(systemLines.at(i).contains("Memory"))
		{
			writeLog(systemLines.at(i).trimmed());
		}

		if(systemLines.at(i).contains("VRAM"))
		{
			writeLog(systemLines.at(i).trimmed());
		}

	}

#elif defined Q_OS_BSD4
	QProcess dmesg;
	dmesg.start("/sbin/dmesg", QIODevice::ReadOnly);
	dmesg.waitForStarted();
	dmesg.waitForFinished();
	const QString dmesgData(dmesg.readAll());
	QStringList dmesgLines = dmesgData.split('\n', QString::SkipEmptyParts);
	for (int i = 0; i<dmesgLines.size(); i++)
	{
		if (dmesgLines.at(i).contains("memory"))
		{
			writeLog(dmesgLines.at(i).trimmed());
		}
		if (dmesgLines.at(i).contains("CPU"))
		{
			writeLog(dmesgLines.at(i).trimmed());
		}
		if (dmesgLines.at(i).contains("VGA"))
		{
			writeLog(dmesgLines.at(i).trimmed());
		}
	}

#endif
}
コード例 #28
0
bool InitDriveThread::method_resizePartitions()
{
    int newStartOfRescuePartition = getFileContents("/sys/class/block/mmcblk0p1/start").trimmed().toInt();
    int newSizeOfRescuePartition  = sizeofBootFilesInKB()/1000 + 100;

    if (!umountSystemPartition())
    {
        emit error(tr("Error unmounting system partition."));
        return false;
    }

    if (!QFile::exists("/dev/mmcblk0p1"))
    {
        // SD card does not have a MBR.

        // Warn user that their SD card does not have an MBR and ask
        // if they would like us to create one for them
        QMessageBox::StandardButton answer;
        emit query(tr("Would you like NOOBS to create one for you?\nWARNING: This will erase all data on your SD card"),
                   tr("Error: No MBR present on SD Card"),
                   &answer);

        if(answer == QMessageBox::Yes)
        {
            emit statusUpdate(tr("Zeroing partition table"));
            if (!zeroMbr())
            {
                emit error(tr("Error zero'ing MBR/GPT. SD card may be broken or advertising wrong capacity."));
                return false;
            }

            // Create MBR containing single FAT partition
            emit statusUpdate(tr("Writing new MBR"));
            QProcess proc;
            proc.setProcessChannelMode(proc.MergedChannels);
            proc.start("/usr/sbin/parted /dev/mmcblk0 --script -- mktable msdos mkpartfs primary fat32 8192s -1");
            proc.waitForFinished(-1);
            if (proc.exitCode() != 0)
            {
                // Warn user if we failed to create an MBR on their card
                emit error(tr("Error creating MBR")+"\n"+proc.readAll());
                return false;
            }
            qDebug() << "Created missing MBR on SD card. parted output:" << proc.readAll();

            // Advise user that their SD card has now been formatted
            // suitably for installing NOOBS and that they will have to
            // re-copy the files before rebooting
            emit error(tr("SD card has now been formatted ready for NOOBS installation. Please re-copy the NOOBS files onto the card and reboot"));
            return false;
        }
        else
        {
            emit error(tr("SD card has not been formatted correctly. Please reformat using the SD Association Formatting Tool and try again."));
            return false;
        }

    }

    emit statusUpdate(tr("Removing partitions 2,3,4"));

    QFile f("/dev/mmcblk0");
    f.open(f.ReadWrite);
    // Seek to partition entry 2
    f.seek(462);
    // Zero out partition 2,3,4 to prevent parted complaining about invalid constraints
    f.write(QByteArray(16*3, '\0'));
    f.flush();
    // Tell Linux to re-read the partition table
    ioctl(f.handle(), BLKRRPART);
    f.close();
    QThread::msleep(500);

    emit statusUpdate(tr("Resizing FAT partition"));

    /* Relocating the start of the FAT partition is a write intensive operation
     * only move it when it is not aligned on a MiB boundary already */
    if (newStartOfRescuePartition < 2048 || newStartOfRescuePartition % 2048 != 0)
    {
        newStartOfRescuePartition = 8192; /* 4 MiB */
    }

    QString cmd = "/usr/sbin/parted --script /dev/mmcblk0 resize 1 "+QString::number(newStartOfRescuePartition)+"s "+QString::number(newSizeOfRescuePartition)+"M";
    qDebug() << "Executing" << cmd;
    QProcess p;
    p.setProcessChannelMode(p.MergedChannels);
    p.start(cmd);
    p.closeWriteChannel();
    p.waitForFinished(-1);

    if (p.exitCode() != 0)
    {
        emit error(tr("Error resizing existing FAT partition")+"\n"+p.readAll());
        return false;
    }
    qDebug() << "parted done, output:" << p.readAll();
    QThread::msleep(500);

    emit statusUpdate(tr("Creating extended partition"));

    mbr_table extended_mbr;
    QByteArray partitionTable;
    int startOfOurPartition = getFileContents("/sys/class/block/mmcblk0p1/start").trimmed().toInt();
    int sizeOfOurPartition = getFileContents("/sys/class/block/mmcblk0p1/size").trimmed().toInt();
    int startOfExtended = startOfOurPartition + sizeOfOurPartition;
    // Align on 4 MiB boundary
    startOfExtended += 8192-(startOfExtended % 8192);

// BUGBUG - reserve space for WinIOT
    startOfExtended += 5000 * 2048;    
//

    int sizeOfDisk = sizeofSDCardInBlocks();
    int sizeOfExtended = sizeOfDisk - startOfExtended;

    partitionTable  = QByteArray::number(startOfOurPartition)+","+QByteArray::number(sizeOfOurPartition)+",0E\n"; /* FAT partition */
    partitionTable += "0,0\n";
    partitionTable += "0,0\n";
    partitionTable += QByteArray::number(startOfExtended)+","+QByteArray::number(sizeOfExtended)+",X\n"; /* Extended partition with all remaining space */
    qDebug() << "Writing partition table" << partitionTable;

    /* Write out extended partition table with settings logical partition */
    memset(&extended_mbr, 0, sizeof extended_mbr);
    extended_mbr.part[0].starting_sector = EBR_PARTITION_OFFSET;
    extended_mbr.part[0].nr_of_sectors = SETTINGS_PARTITION_SIZE;
    extended_mbr.part[0].id = 0x83;

    extended_mbr.signature[0] = 0x55;
    extended_mbr.signature[1] = 0xAA;
    f.open(f.ReadWrite);
    f.seek(((qint64)startOfExtended)*512L);
    f.write((char *) &extended_mbr, sizeof(extended_mbr));
    f.flush();
    f.close();

    /* Let sfdisk write a proper partition table */
    cmd = QString("/sbin/sfdisk -uS /dev/mmcblk0");
    QProcess proc;
    proc.setProcessChannelMode(proc.MergedChannels);
    proc.start(cmd);
    proc.write(partitionTable);
    proc.closeWriteChannel();
    proc.waitForFinished(-1);
    if (proc.exitCode() != 0)
    {
        emit error(tr("Error creating extended partition")+"\n"+proc.readAll());
        return false;
    }
    qDebug() << "sfdisk done, output:" << proc.readAll();
    QThread::msleep(500);

    /* For reasons unknown Linux sometimes
     * only finds /dev/mmcblk0p2 and /dev/mmcblk0p1 goes missing */
    if (!QFile::exists("/dev/mmcblk0p1"))
    {
        /* Probe again */
        QProcess::execute("/usr/sbin/partprobe");
        QThread::msleep(1500);
    }

    QProcess::execute("/sbin/mlabel p:RECOVERY");

    emit statusUpdate(tr("Mounting FAT partition"));
    if (!mountSystemPartition())
    {
        emit error(tr("Error mounting system partition."));
        return false;
    }

    return true;
}
コード例 #29
0
/**
 * generate layout and apply it to the given diagram.
 *
 * @return true if generating succeeded
*/
bool LayoutGenerator::generate(UMLScene *scene, const QString &variant)
{
    QTemporaryFile in;
    QTemporaryFile out;
    QTemporaryFile xdotOut;
    if (!isEnabled()) {
        uWarning() << "Could not apply autolayout because graphviz installation has not been found.";
        return false;
    }

#ifdef LAYOUTGENERATOR_DEBUG
    in.setAutoRemove(false);
    out.setAutoRemove(false);
    xdotOut.setAutoRemove(false);
#endif

    // generate filenames
    in.open();
    in.close();
    out.open();
    out.close();
    xdotOut.open();
    xdotOut.close();

#ifdef LAYOUTGENERATOR_DEBUG
    qDebug() << textViewer() << in.fileName();
    qDebug() << textViewer() << out.fileName();
    qDebug() << textViewer() << xdotOut.fileName();
#endif

    if (!createDotFile(scene, in.fileName(), variant))
        return false;

    QString executable = m_dotPath + QLatin1Char('/') + m_generator;

    QProcess p;
    QStringList args;
    args << QLatin1String("-o") << out.fileName() << QLatin1String("-Tplain-ext") << in.fileName();
    p.start(executable, args);
    p.waitForFinished();

    args.clear();
    args << QLatin1String("-o") << xdotOut.fileName() << QLatin1String("-Txdot") << in.fileName();
    p.start(executable, args);
    p.waitForFinished();

#ifdef LAYOUTGENERATOR_DEBUG
    QTemporaryFile pngFile;
    pngFile.setAutoRemove(false);
    pngFile.setFileTemplate(QDir::tempPath() + QLatin1String("/umbrello-layoutgenerator-XXXXXX.png"));
    pngFile.open();
    pngFile.close();
    qDebug() << pngViewer() << pngFile.fileName();
    args.clear();
    args << QLatin1String("-o") << pngFile.fileName() << QLatin1String("-Tpng") << in.fileName();
    p.start(executable, args);
    p.waitForFinished();
#endif
#ifndef USE_XDOT
    if (!readGeneratedDotFile(out.fileName()))
#else
    if (!readGeneratedDotFile(xdotOut.fileName()))
#endif
        return false;

    return true;
}
コード例 #30
0
ファイル: wmhelper.cpp プロジェクト: claudiutraistaru/octopi
/*
 * Opens a directory based on your DE.
 */
void WMHelper::openDirectory( const QString& dirName ){
  QProcess *p = new QProcess(qApp->activeWindow());
  QStringList s;
  QString dir(dirName);

  //Is it really a directory?
  QFileInfo f(dirName);
  if (!f.isDir())
  {
    dir = f.absolutePath();
    f = QFileInfo(dir);
  }

  if (f.exists())
  {
    LinuxDistro distro = UnixCommand::getLinuxDistro();
    if (distro == ectn_ARCHBANGLINUX && UnixCommand::hasTheExecutable(ctn_ARCHBANG_FILE_MANAGER))
    {
      s << dir;
      p->startDetached( ctn_ARCHBANG_FILE_MANAGER, s );
    }
    else if(isXFCERunning() && UnixCommand::hasTheExecutable(ctn_XFCE_FILE_MANAGER))
    {
      s << dir;
      p->startDetached( ctn_XFCE_FILE_MANAGER, s );
    }
    else if (isKDERunning())
    {
      if (UnixCommand::hasTheExecutable(ctn_KDE4_FILE_MANAGER))
      {
        s << dir;

        if (UnixCommand::isRootRunning())
        {
          p->startDetached( "dbus-launch " + ctn_KDE4_FILE_MANAGER + " " + dir);
        }
        else
        {
          p->startDetached( ctn_KDE4_FILE_MANAGER, s);
        }
      }
      else if (UnixCommand::hasTheExecutable(ctn_KDE_FILE_MANAGER))
      {
        s << "newTab";
        s << dir;
        p->startDetached( ctn_KDE_FILE_MANAGER, s );
      }
    }
    else if (isTDERunning())
    {
      if (UnixCommand::hasTheExecutable(ctn_TDE_FILE_MANAGER))
      {
        s << "newTab";
        s << dir;
        p->startDetached( ctn_TDE_FILE_MANAGER, s );
      }
    }
    else if (isMATERunning() && UnixCommand::hasTheExecutable(ctn_MATE_FILE_MANAGER))
    {
      s << dir;
      p->startDetached( ctn_MATE_FILE_MANAGER, s );
    }
    else if (isCinnamonRunning() && UnixCommand::hasTheExecutable(ctn_CINNAMON_FILE_MANAGER))
    {
      s << dir;
      p->startDetached( ctn_CINNAMON_FILE_MANAGER, s );
    }
    else if (UnixCommand::hasTheExecutable(ctn_XFCE_FILE_MANAGER))
    {
      s << dir;
      p->startDetached( ctn_XFCE_FILE_MANAGER, s );
    }
    else if (UnixCommand::hasTheExecutable(ctn_LXDE_FILE_MANAGER))
    {
      s << dir;
      p->startDetached( ctn_LXDE_FILE_MANAGER, s );
    }
  }
}