Example #1
0
bool Upload::adjustNewstuffFile(const Package &package)
{
    if (m_xml.isNull()) {
        QTemporaryFile tempFile(QDir::tempPath() + "/monav-maps-XXXXXX.xml");
        tempFile.setAutoRemove(false);
        tempFile.open();
        QString monavFilename = tempFile.fileName();
        tempFile.close();
        QProcess wget;
        QStringList const arguments = QStringList() << "http://filesmaster.kde.org/marble/newstuff/maps-monav.xml" << "-O" << monavFilename;
        wget.start("wget", arguments);
        wget.waitForFinished(1000 * 60 * 60 * 12); // wait up to 12 hours for download to complete
        if (wget.exitStatus() != QProcess::NormalExit || wget.exitCode() != 0) {
            qDebug() << "Failed to download newstuff file from filesmaster.kde.org";
            changeStatus( package, "error", "Failed to sync newstuff file: " + wget.readAllStandardError());
            return false;
        }

        QFile file(monavFilename);
        if (!file.open(QFile::ReadOnly)) {
            qDebug() << "Failed to open newstuff file" << monavFilename;
            changeStatus( package, "error", "Failed to open newstuff file.");
            return false;
        }

        if ( !m_xml.setContent( &file ) ) {
            qDebug() << "Cannot parse newstuff xml file.";
            changeStatus( package, "error", "Failed to parse newstuff .xml file.");
            return false;
        }

        QFile::remove(monavFilename);
    }

    QDomElement root = m_xml.documentElement();
    QDomNodeList regions = root.elementsByTagName( "stuff" );
    for ( unsigned int i = 0; i < regions.length(); ++i ) {
        QDomNode node = regions.item( i );
        if (!node.namedItem("payload").isNull()) {
            QUrl url = node.namedItem("payload").toElement().text();
            QFileInfo fileInfo(url.path());
            if (fileInfo.fileName() == package.file.fileName()) {
                QString removeFile;
                QDomNode dateNode = node.namedItem("releasedate");
                if (!dateNode.isNull()) {
                    dateNode.removeChild(dateNode.firstChild());
                    dateNode.appendChild(m_xml.createTextNode(releaseDate()));
                }
                QDomNode versionNode = node.namedItem("version");
                if (!versionNode.isNull()) {
                    double version = versionNode.toElement().text().toDouble();
                    versionNode.removeChild(versionNode.firstChild());
                    versionNode.appendChild(m_xml.createTextNode(QString::number(version+0.1, 'f', 1)));
                }
                QDomNode payloadNode = node.namedItem("payload");
                payloadNode.removeChild(payloadNode.firstChild());
                if (fileInfo.dir().dirName() != targetDir()) {
                    removeFile = QString("/home/marble/web/monav/%1/%2").arg(fileInfo.dir().dirName()).arg(package.file.fileName());
                    qDebug() << "Going to remove the old file " << removeFile;
                }
                QString payload = "http://files.kde.org/marble/monav/%1/%2";
                payload = payload.arg(targetDir()).arg(package.file.fileName());
                payloadNode.appendChild(m_xml.createTextNode(payload));
                return removeFile.isEmpty() ? uploadNewstuff() : (uploadNewstuff() && deleteRemoteFile(removeFile));
            }
        }
    }

    QDomNode stuff = root.appendChild(m_xml.createElement("stuff"));
    stuff.toElement().setAttribute("category", "marble/routing/monav");
    QDomNode nameNode = stuff.appendChild(m_xml.createElement("name"));
    nameNode.toElement().setAttribute("lang", "en");
    QString name = "%1 / %2 (%3)";
    if (package.region.country().isEmpty()) {
        name = name.arg(package.region.continent()).arg(package.region.name());
        name = name.arg(package.transport);
    } else {
        name = "%1 / %2 / %3 (%4)";
        name = name.arg(package.region.continent()).arg(package.region.country());
        name = name.arg(package.region.name()).arg(package.transport);
    }
    nameNode.appendChild(m_xml.createTextNode(name));

    QDomNode authorNode = stuff.appendChild(m_xml.createElement("author"));
    authorNode.appendChild(m_xml.createTextNode("Automatically created from map data assembled by the OpenStreetMap community"));

    QDomNode licenseNode = stuff.appendChild(m_xml.createElement("license"));
    licenseNode.appendChild(m_xml.createTextNode("Creative Commons by-SA 2.0"));

    QDomNode summaryNode = stuff.appendChild(m_xml.createElement("summary"));
    QString summary = "Requires KDE >= 4.6: Offline Routing in %1, %2";
    summary = summary.arg(package.region.name()).arg(package.region.continent());
    summaryNode.appendChild(m_xml.createTextNode(summary));

    QDomNode versionNode = stuff.appendChild(m_xml.createElement("version"));
    versionNode.appendChild(m_xml.createTextNode("0.1"));

    QDomNode dateNode = stuff.appendChild(m_xml.createElement("releasedate"));
    dateNode.appendChild(m_xml.createTextNode(releaseDate()));

    QDomNode previewNode = stuff.appendChild(m_xml.createElement("preview"));
    QString preview = "http://files.kde.org/marble/monav/previews/%1-preview.png";
    preview = preview.arg(package.region.id());
    previewNode.appendChild(m_xml.createTextNode(preview));

    QDomNode payloadNode = stuff.appendChild(m_xml.createElement("payload"));
    payloadNode.toElement().setAttribute("lang", "en");
    QString payload = "http://files.kde.org/marble/monav/%1/%2";
    payload = payload.arg(targetDir()).arg(package.file.fileName());
    payloadNode.appendChild(m_xml.createTextNode(payload));

    return uploadNewstuff();
}
Example #2
0
bool SSHConnectionCLI::executeSCPFrom(const QString& source,
                                      const QString& dest,
                                      const QStringList& args,
                                      QString* stdout_str, QString* stderr_str,
                                      int* ec)
{
  QProcess proc;

  // Start with input args
  QStringList fullArgs(args);

  // Add port number
  fullArgs << "-P" << QString::number(m_port);

  // Add source
  fullArgs << QString("%1%2%3:%4")
                .arg(m_user)
                .arg(m_user.isEmpty() ? "" : "@")
                .arg(m_host)
                .arg(source);

  // Add destination
  fullArgs << dest;

  proc.start("scp", fullArgs);
  int timeout_ms = 60000; // one minute

  if (!proc.waitForStarted(timeout_ms)) {
    qWarning() << QString("Failed to start scp command with args \"%1\" "
                          "after %2 seconds.")
                    .arg(fullArgs.join(","))
                    .arg(timeout_ms / 1000);
    return false;
  }

  proc.closeWriteChannel();
  if (!proc.waitForFinished(timeout_ms)) {
    qWarning() << QString("scp command with args \"%1\" failed to finish "
                          "within %2 seconds.")
                    .arg(fullArgs.join(","))
                    .arg(timeout_ms / 1000);
    return false;
  }

  if (proc.exitCode() != 0) {
    qWarning() << QString("scp command with args \"%1\" failed with an exit "
                          "code of %2.")
                    .arg(fullArgs.join(","))
                    .arg(proc.exitCode())
               << "\nstdout:\n"
               << QString(proc.readAllStandardOutput()) << "\nstderr:\n"
               << QString(proc.readAllStandardError());
    return false;
  }

  if (stdout_str != nullptr)
    *stdout_str = QString(proc.readAllStandardOutput());
  if (stderr_str != nullptr)
    *stderr_str = QString(proc.readAllStandardError());
  if (ec != nullptr)
    *ec = proc.exitCode();

  proc.close();

  return true;
}
Example #3
0
//------------------------------------------------------------------------------
// Name: on_buttonBox_accepted
// Desc:
//------------------------------------------------------------------------------
void DialogAssembler::on_buttonBox_accepted() {

	static const QString mnemonic_regex   = "([a-z][a-z0-9]*)";
	static const QString register_regex   = "((?:(?:e|r)?(?:ax|bx|cx|dx|bp|sp|si|di|ip))|(?:[abcd](?:l|h))|(?:sp|bp|si|di)l|(?:[cdefgs]s)|(?:x?mm[0-7])|r(?:8|9|(?:1[0-5]))[dwb]?)";
	static const QString constant_regex   = "((?:0[0-7]*)|(?:0x[0-9a-f]+)|(?:[1-9][0-9]*))";

	static const QString pointer_regex    = "(?:(t?byte|(?:xmm|[qdf]?)word)(?:\\s+ptr)?)?";
	static const QString segment_regex    = "([csdefg]s)";
	static const QString expression_regex = QString("(%1\\s*(?:\\s+%2\\s*:\\s*)?\\[(\\s*(?:(?:%3(?:\\s*\\+\\s*%3(?:\\s*\\*\\s*%4)?)?(?:\\s*\\+\\s*%4)?)|(?:(?:%3(?:\\s*\\*\\s*%4)?)(?:\\s*\\+\\s*%4)?)|(?:%4)\\s*))\\])").arg(pointer_regex, segment_regex, register_regex, constant_regex);

	static const QString operand_regex    = QString("((?:%1)|(?:%2)|(?:%3))").arg(register_regex, constant_regex, expression_regex);

	static const QString assembly_regex   = QString("%1(?:\\s+%2\\s*(?:\\s*,\\s*%2\\s*(?:\\s*,\\s*%2\\s*)?)?)?").arg(mnemonic_regex, operand_regex);

// [                 OFFSET]
// [     INDEX             ]
// [     INDEX      +OFFSET]
// [     INDEX*SCALE       ]
// [     INDEX*SCALE+OFFSET]
// [BASE                   ]
// [BASE            +OFFSET]
// [BASE+INDEX             ]
// [BASE+INDEX      +OFFSET]
// [BASE+INDEX*SCALE       ]
// [BASE+INDEX*SCALE+OFFSET]
// -------------------------
// [((BASE(\+INDEX(\*SCALE)?)?(\+OFFSET)?)|((INDEX(\*SCALE)?)(\+OFFSET)?)|(OFFSET))]


	const QString assembly = ui->assembly->currentText().trimmed();
	QRegExp regex(assembly_regex, Qt::CaseInsensitive, QRegExp::RegExp2);

	if(regex.exactMatch(assembly)) {
		const QStringList list = regex.capturedTexts();


/*
[0]  -> whole match
[1]  -> mnemonic

[2]  -> whole operand 1
[3]  -> operand 1 (REGISTER)
[4]  -> operand 1 (IMMEDIATE)
[5]  -> operand 1 (EXPRESSION)
[6]  -> operand 1 pointer (EXPRESSION)
[7]  -> operand 1 segment (EXPRESSION)
[8]  -> operand 1 internal expression (EXPRESSION)
[9]  -> operand 1 base (EXPRESSION)
[10] -> operand 1 index (EXPRESSION)
[11] -> operand 1 scale (EXPRESSION)
[12] -> operand 1 displacement (EXPRESSION)
[13] -> operand 1 index (EXPRESSION) (version 2)
[14] -> operand 1 scale (EXPRESSION) (version 2)
[15] -> operand 1 displacement (EXPRESSION) (version 2)
[16] -> operand 1 displacement (EXPRESSION) (version 3)

[17] -> whole operand 2
[18] -> operand 2 (REGISTER)
[19] -> operand 2 (IMMEDIATE)
[20] -> operand 2 (EXPRESSION)
[21] -> operand 2 pointer (EXPRESSION)
[22] -> operand 2 segment (EXPRESSION)
[23] -> operand 2 internal expression (EXPRESSION)
[24] -> operand 2 base (EXPRESSION)
[25] -> operand 2 index (EXPRESSION)
[26] -> operand 2 scale (EXPRESSION)
[27] -> operand 2 displacement (EXPRESSION)
[28] -> operand 2 index (EXPRESSION) (version 2)
[29] -> operand 2 scale (EXPRESSION) (version 2)
[30] -> operand 2 displacement (EXPRESSION) (version 2)
[31] -> operand 2 displacement (EXPRESSION) (version 3)

[32] -> whole operand 3
[33] -> operand 3 (REGISTER)
[34] -> operand 3 (IMMEDIATE)
[35] -> operand 3 (EXPRESSION)
[36] -> operand 3 pointer (EXPRESSION)
[37] -> operand 3 segment (EXPRESSION)
[38] -> operand 3 internal expression (EXPRESSION)
[39] -> operand 3 base (EXPRESSION)
[40] -> operand 3 index (EXPRESSION)
[41] -> operand 3 scale (EXPRESSION)
[42] -> operand 3 displacement (EXPRESSION)
[43] -> operand 3 index (EXPRESSION) (version 2)
[44] -> operand 3 scale (EXPRESSION) (version 2)
[45] -> operand 3 displacement (EXPRESSION) (version 2)
[46] -> operand 3 displacement (EXPRESSION) (version 3)
*/

		int operand_count = 0;
		if(!list[2].isEmpty()) {
			++operand_count;
		}

		if(!list[17].isEmpty()) {
			++operand_count;
		}

		if(!list[32].isEmpty()) {
			++operand_count;
		}

		QStringList operands;

		for(int i = 0; i < operand_count; ++i) {

			int offset = 15 * i;

			if(!list[3 + offset].isEmpty()) {
				operands << list[3 + offset];
			} else if(!list[4 + offset].isEmpty()) {
				operands << list[4 + offset];
			} else if(!list[5 + offset].isEmpty()) {
				if(!list[7 + offset].isEmpty()) {
					operands << QString("%1 [%2:%3]").arg(list[6 + offset], list[7 + offset], list[8 + offset]);
				} else {
					operands << QString("%1 [%2]").arg(list[6 + offset], list[8 + offset]);
				}
			}
		}

		const QString nasm_syntax = list[1] + ' ' + operands.join(",");

		QTemporaryFile source_file(QString("%1/edb_asm_temp_%2_XXXXXX.asm").arg(QDir::tempPath()).arg(getpid()));
		if(!source_file.open()) {
			QMessageBox::critical(this, tr("Error Creating File"), tr("Failed to create temporary source file."));
			return;
		}

		QTemporaryFile output_file(QString("%1/edb_asm_temp_%2_XXXXXX.bin").arg(QDir::tempPath()).arg(getpid()));
		if(!output_file.open()) {
			QMessageBox::critical(this, tr("Error Creating File"), tr("Failed to create temporary object file."));
			return;
		}

		QSettings settings;
		const QString assembler = settings.value("Assembler/helper_application", "/usr/bin/yasm").toString();
		const QFile file(assembler);
		if(assembler.isEmpty() || !file.exists()) {
			QMessageBox::warning(this, tr("Couldn't Find Assembler"), tr("Failed to locate your assembler, please specify one in the options."));
			return;
		}

		const QFileInfo info(assembler);

		QProcess process;
		QStringList arguments;
		QString program(assembler);

		if(info.fileName() == "yasm") {

			switch(edb::v1::debugger_core->cpu_type()) {
			case edb::string_hash<'x', '8', '6'>::value:
				source_file.write("[BITS 32]\n");
				break;
			case edb::string_hash<'x', '8', '6', '-', '6', '4'>::value:
				source_file.write("[BITS 64]\n");
				break;
			default:
				Q_ASSERT(0);
			}

			source_file.write(QString("[SECTION .text vstart=0x%1 valign=1]\n\n").arg(edb::v1::format_pointer(address_)).toLatin1());
			source_file.write(nasm_syntax.toLatin1());
			source_file.write("\n");
			source_file.close();

			arguments << "-o" << output_file.fileName();
			arguments << "-f" << "bin";
			arguments << source_file.fileName();
		} else if(info.fileName() == "nasm") {

			switch(edb::v1::debugger_core->cpu_type()) {
			case edb::string_hash<'x', '8', '6'>::value:
				source_file.write("[BITS 32]\n");
				break;
			case edb::string_hash<'x', '8', '6', '-', '6', '4'>::value:
				source_file.write("[BITS 64]\n");
				break;
			default:
				Q_ASSERT(0);
			}

			source_file.write(QString("ORG 0x%1\n\n").arg(edb::v1::format_pointer(address_)).toLatin1());
			source_file.write(nasm_syntax.toLatin1());
			source_file.write("\n");
			source_file.close();


			arguments << "-o" << output_file.fileName();
			arguments << "-f" << "bin";
			arguments << source_file.fileName();
		}

		process.start(program, arguments);

		if(process.waitForFinished()) {

			const int exit_code = process.exitCode();

			if(exit_code != 0) {
				QMessageBox::warning(this, tr("Error In Code"), process.readAllStandardError());
			} else {
				QByteArray bytes = output_file.readAll();

				if(bytes.size() <= instruction_size_) {
					if(ui->fillWithNOPs->isChecked()) {
						// TODO: get system independent nop-code
						edb::v1::modify_bytes(address_, instruction_size_, bytes, 0x90);
					} else {
						edb::v1::modify_bytes(address_, instruction_size_, bytes, 0x00);
					}
				} else {
					if(ui->keepSize->isChecked()) {
						QMessageBox::warning(this, tr("Error In Code"), tr("New instruction is too big to fit."));
					} else {
						edb::v1::modify_bytes(address_, bytes.size(), bytes, 0x00);
					}
				}
			}
		}
	} else {
		QMessageBox::warning(this, tr("Error In Code"), tr("Failed to assembly the given assemble code."));
	}

}
Example #4
0
  void updateTOPPAS(const String& infile, const String& outfile)
  {
    Int this_instance = getIntOption_("instance");
    INIUpdater updater;
    String tmp_ini_file = File::getTempDirectory() + "/" + File::getUniqueName() + "_INIUpdater.ini";
    tmp_files_.push_back(tmp_ini_file);

    String path = File::getExecutablePath();

    ParamXMLFile paramFile;
    Param p;
    paramFile.load(infile, p);

    // get version of TOPPAS file
    String version = "Unknown";
    if (!p.exists("info:version"))
    {
      writeLog_("No OpenMS version information found in file " + infile + "! Assuming OpenMS 1.8 and below.");
      version = "1.8.0";
    }
    else
    {
      version = p.getValue("info:version");
      // TODO: return on newer version?!
    }

    Int vertices = p.getValue("info:num_vertices");

    // update sections
    writeDebug_("#Vertices: " + String(vertices), 1);
    bool update_success = true;
    for (Int v = 0; v < vertices; ++v)
    {
      String sec_inst = "vertices:" + String(v) + ":";
      // check for default instance
      if (!p.exists(sec_inst + "toppas_type"))
      {
        writeLog_("Update for file " + infile + " failed because the vertex #" + String(v) + " does not have a 'toppas_type' node. Check INI file for corruption!");
        update_success = false;
        break;
      }

      if (p.getValue(sec_inst + "toppas_type") != "tool") // not a tool (but input/output/merge node)
      {
        continue;
      }

      if (!p.exists(sec_inst + "tool_name"))
      {
        writeLog_("Update for file " + infile + " failed because the vertex #" + String(v) + " does not have a 'tool_name' node. Check INI file for corruption!");
        update_success = false;
        break;
      }

      String old_name = p.getValue(sec_inst + "tool_name");
      String new_tool;
      String ttype;
      // find mapping to new tool (might be the same name)
      if (p.exists(sec_inst + "tool_type")) ttype = p.getValue(sec_inst + "tool_type");
      if (!updater.getNewToolName(old_name, ttype, new_tool))
      {
        String type_text = ((ttype == "") ? "" : " with type '" + ttype + "' ");
        writeLog_("Update for file " + infile + " failed because the tool '" + old_name + "'" + type_text + "is unknown. TOPPAS file seems to be corrupted!");
        update_success = false;
        break;
      }

      // set new tool name
      p.setValue(sec_inst + "tool_name", new_tool);
      // delete TOPPAS type
      if (new_tool != "GenericWrapper")
      {
        p.setValue(sec_inst + "tool_type", "");
      }

      // get defaults of new tool by calling it
      QProcess pr;
      QStringList arguments;
      arguments << "-write_ini";
      arguments << tmp_ini_file.toQString();
      arguments << "-instance";
      arguments << String(this_instance).toQString();
      pr.start((path + "/" + new_tool).toQString(), arguments);
      if (!pr.waitForFinished(-1))
      {
        writeLog_("Update for file " + infile + " failed because the tool '" + new_tool + "' returned with an error! Check if the tool works properly.");
        update_success = false;
        break;
      }

      // update defaults with old values
      Param new_param;
      paramFile.load(tmp_ini_file, new_param);
      new_param = new_param.copy(new_tool + ":1", true);
      Param old_param = p.copy(sec_inst + "parameters", true);
      new_param.update(old_param);
      // push back changes
      p.remove(sec_inst + "parameters:");
      p.insert(sec_inst + "parameters", new_param);
    }

    if (!update_success)
    {
      failed_.push_back(infile);
      return;
    }

    paramFile.store(tmp_ini_file, p);

    // update internal structure (e.g. edges format changed from 1.8 to 1.9)
    int argc = 1;
    const char* c = "IniUpdater";
    const char** argv = &c;
    QApplication app(argc, const_cast<char**>(argv), false);
    String tmp_dir = File::getTempDirectory() + "/" + File::getUniqueName();
    QDir d;
    d.mkpath(tmp_dir.toQString());
    TOPPASScene ts(0, tmp_dir.toQString(), false);
    paramFile.store(tmp_ini_file, p);
    ts.load(tmp_ini_file);
    ts.store(tmp_ini_file);
    paramFile.load(tmp_ini_file, p);

    // STORE
    if (outfile.empty()) // create a backup
    {
      QFileInfo fi(infile.toQString());
      String new_name = String(fi.path()) + "/" + fi.completeBaseName() + "_v" + version + ".toppas";
      QFile::rename(infile.toQString(), new_name.toQString());
      // write new file
      paramFile.store(infile, p);
    }
    else
    {
      paramFile.store(outfile, p);
    }
  }
Example #5
0
File: main.cpp Project: KDE/zanshin
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    App::initializeDependencies();

    auto aboutData = App::getAboutData();
    QCommandLineParser parser;
    KAboutData::setApplicationData(aboutData);
    parser.addVersionOption();
    parser.addHelpOption();
    aboutData.setupCommandLine(&parser);
    parser.process(app);
    aboutData.processCommandLine(&parser);

    KSharedConfig::Ptr config = KSharedConfig::openConfig(QStringLiteral("zanshin-migratorrc"));
    KConfigGroup group = config->group("Migrations");
    if (!group.readEntry("Migrated021Projects", false)) {
        std::cerr << "Migrating data from zanshin 0.2, please wait..." << std::endl;
        QProcess proc;
        proc.start(QStringLiteral("zanshin-migrator"));
        proc.waitForFinished(-1);
        if (proc.exitStatus() == QProcess::CrashExit) {
            std::cerr << "Migrator crashed!" << std::endl;
        } else if (proc.exitCode() == 0) {
            std::cerr << "Migration done" << std::endl;
        } else {
            std::cerr << "Migration error, code" << proc.exitCode() << std::endl;
        }
    }

    auto widget = new QWidget;
    auto components = new Widgets::ApplicationComponents(widget);
    components->setModel(Presentation::ApplicationModel::Ptr::create());

    auto layout = new QVBoxLayout;
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(components->pageView());
    widget->setLayout(layout);

    auto sourcesDock = new QDockWidget(QObject::tr("Sources"));
    sourcesDock->setObjectName(QStringLiteral("sourcesDock"));
    sourcesDock->setWidget(components->availableSourcesView());

    auto pagesDock = new QDockWidget(QObject::tr("Pages"));
    pagesDock->setObjectName(QStringLiteral("pagesDock"));
    pagesDock->setWidget(components->availablePagesView());

    auto editorDock = new QDockWidget(QObject::tr("Editor"));
    editorDock->setObjectName(QStringLiteral("editorDock"));
    editorDock->setWidget(components->editorView());

    auto window = new KXmlGuiWindow;
    window->setCentralWidget(widget);

    window->addDockWidget(Qt::RightDockWidgetArea, editorDock);
    window->addDockWidget(Qt::LeftDockWidgetArea, pagesDock);
    window->addDockWidget(Qt::LeftDockWidgetArea, sourcesDock);

    auto actions = components->globalActions();
    actions.insert(QStringLiteral("dock_sources"), sourcesDock->toggleViewAction());
    actions.insert(QStringLiteral("dock_pages"), pagesDock->toggleViewAction());
    actions.insert(QStringLiteral("dock_editor"), editorDock->toggleViewAction());

    auto ac = window->actionCollection();
    ac->addAction(KStandardAction::Quit, window, SLOT(close()));
    for (auto it = actions.constBegin(); it != actions.constEnd(); ++it) {
        auto shortcut = it.value()->shortcut();
        if (!shortcut.isEmpty()) {
            ac->setDefaultShortcut(it.value(), shortcut);
        }
        ac->addAction(it.key(), it.value());
    }

    window->setupGUI(QSize(1024, 600),
                     KXmlGuiWindow::ToolBar
                   | KXmlGuiWindow::Keys
                   | KXmlGuiWindow::Save
                   | KXmlGuiWindow::Create);
    window->show();

    return app.exec();
}
void AndroidRunner::asyncStart()
{
    QMutexLocker locker(&m_mutex);
    forceStop();

    if (m_useCppDebugger) {
        // Remove pong file.
        QProcess adb;
        adb.start(m_adb, selector() << _("shell") << _("rm") << m_pongFile);
        adb.waitForFinished();
    }

    QStringList args = selector();
    args << _("shell") << _("am") << _("start") << _("-n") << m_intentName;

    if (m_useCppDebugger) {
        QProcess adb;
        adb.start(m_adb, selector() << _("forward")
                  << QString::fromLatin1("tcp:%1").arg(m_localGdbServerPort)
                  << _("localfilesystem:") + m_gdbserverSocket);
        if (!adb.waitForStarted()) {
            emit remoteProcessFinished(tr("Failed to forward C++ debugging ports. Reason: %1.").arg(adb.errorString()));
            return;
        }
        if (!adb.waitForFinished(5000)) {
            emit remoteProcessFinished(tr("Failed to forward C++ debugging ports."));
            return;
        }

        args << _("-e") << _("debug_ping") << _("true");
        args << _("-e") << _("ping_file") << m_pingFile;
        args << _("-e") << _("pong_file") << m_pongFile;
        args << _("-e") << _("gdbserver_command") << m_gdbserverCommand;
        args << _("-e") << _("gdbserver_socket") << m_gdbserverSocket;
    }

    if (m_useQmlDebugger || m_useQmlProfiler) {
        // currently forward to same port on device and host
        const QString port = QString::fromLatin1("tcp:%1").arg(m_qmlPort);
        QProcess adb;
        adb.start(m_adb, selector() << _("forward") << port << port);
        if (!adb.waitForStarted()) {
            emit remoteProcessFinished(tr("Failed to forward QML debugging ports. Reason: %1.").arg(adb.errorString()));
            return;
        }
        if (!adb.waitForFinished()) {
            emit remoteProcessFinished(tr("Failed to forward QML debugging ports."));
            return;
        }
        args << _("-e") << _("qml_debug") << _("true");
        args << _("-e") << _("qmljsdebugger") << QString::fromLatin1("port:%1,block").arg(m_qmlPort);
    }
    if (m_useLocalQtLibs) {
        args << _("-e") << _("use_local_qt_libs") << _("true");
        args << _("-e") << _("libs_prefix") << _("/data/local/tmp/qt/");
        args << _("-e") << _("load_local_libs") << m_localLibs;
        args << _("-e") << _("load_local_jars") << m_localJars;
        if (!m_localJarsInitClasses.isEmpty())
            args << _("-e") << _("static_init_classes") << m_localJarsInitClasses;
    }

    QProcess adb;
    adb.start(m_adb, args);
    if (!adb.waitForStarted()) {
        emit remoteProcessFinished(tr("Failed to start the activity. Reason: %1.").arg(adb.errorString()));
        return;
    }
    if (!adb.waitForFinished(5000)) {
        adb.terminate();
        emit remoteProcessFinished(tr("Unable to start '%1'.").arg(m_packageName));
        return;
    }

    if (m_useCppDebugger) {

        // Handling ping.
        for (int i = 0; ; ++i) {
            QTemporaryFile tmp(_("pingpong"));
            tmp.open();
            tmp.close();

            QProcess process;
            process.start(m_adb, selector() << _("pull") << m_pingFile << tmp.fileName());
            process.waitForFinished();

            QFile res(tmp.fileName());
            const bool doBreak = res.size();
            res.remove();
            if (doBreak)
                break;

            if (i == 20) {
                emit remoteProcessFinished(tr("Unable to start '%1'.").arg(m_packageName));
                return;
            }
            qDebug() << "WAITING FOR " << tmp.fileName();
            QThread::msleep(500);
        }

    }

    m_tries = 0;
    m_wasStarted = false;
    QMetaObject::invokeMethod(&m_checkPIDTimer, "start");
}
Example #7
0
void MetaEditorSupportPlugin::loadNewEditor(QString const &directoryName
		, QPair<QString, QString> const &metamodelNames
		, QString const &commandFirst
		, QString const &commandSecond
		, QString const &extension
		, QString const &prefix
		, QString const &buildConfiguration
		)
{
	int const progressBarWidth = 240;
	int const progressBarHeight = 20;

	QString const metamodelName = metamodelNames.first;
	QString const normalizerMetamodelName = metamodelNames.second;

	if ((commandFirst == "") || (commandSecond == "") || (extension == "")) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("please, fill compiler settings"));
		return;
	}

	QString const normalizeDirName = metamodelName.at(0).toUpper() + metamodelName.mid(1);

	QProgressBar * const progress = new QProgressBar(mMainWindowInterface->windowWidget());
	progress->show();

	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);
	progress->setValue(5);

	const bool stateOfLoad = mMainWindowInterface->pluginLoaded(normalizeDirName);
	if (!mMainWindowInterface->unloadPlugin(normalizeDirName)) {
		progress->close();
		delete progress;
		return;
	}

	progress->setValue(20);
	QStringList qmakeArgs;
	qmakeArgs.append("CONFIG+=" + buildConfiguration);
	qmakeArgs.append(metamodelName + ".pro");

	QProcess builder;
	builder.setWorkingDirectory(directoryName);
	const QStringList environment = QProcess::systemEnvironment();
	builder.setEnvironment(environment);
	builder.start(commandFirst, qmakeArgs);

	if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
		progress->setValue(60);
		builder.start(commandSecond);

		if (builder.waitForFinished(60000) && (builder.exitCode() == 0)) {
			progress->setValue(80);

			if (stateOfLoad) {
				QMessageBox::warning(mMainWindowInterface->windowWidget()
						, tr("Attention!"), tr("Please restart QReal."));
				progress->close();
				delete progress;
				return;
			} else if (buildConfiguration == "debug") {
				if (mMainWindowInterface->loadPlugin(prefix + metamodelName
						+ "-d"+ "." + extension, normalizeDirName))
				{
					progress->setValue(100);
				}
			} else {
				if (mMainWindowInterface->loadPlugin(prefix + metamodelName + "." + extension, normalizeDirName)) {
					progress->setValue(100);
				}
			}
		}
	}

	if (progress->value() == 20) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot qmake new editor"));
	} else if (progress->value() == 60) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot make new editor"));
	}

	progress->setValue(100);
	progress->close();
	delete progress;
}
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;
	QPair<quint32, quint32> id_val(UINT_MAX, UINT_MAX);
	quint32 coverType = UINT_MAX;
	QByteArray coverData;

	QStringList params;
	params << QString("--Inform=file://%1").arg(QDir::toNativeSeparators(m_templateFile));
	params << QDir::toNativeSeparators(filePath);
	
	QProcess process;
	MUtils::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", MUTILS_UTF8(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 != UINT_MAX) && (!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;
}
bool AnalyzeTask::analyzeAvisynthFile(const QString &filePath, AudioFileModel &info)
{
	QProcess process;
	MUtils::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;
	}
}
Example #10
0
  ExitCodes main_(int, const char**) override
  {
    String tmp_dir = QDir::toNativeSeparators((File::getTempDirectory() + "/" + File::getUniqueName() + "/").toQString()); // body for the tmp files
    {
      QDir d;
      d.mkpath(tmp_dir.toQString());
    }
    String logfile(getStringOption_("log"));
    String myrimatch_executable(getStringOption_("myrimatch_executable"));

    //-------------------------------------------------------------
    // get version of MyriMatch
    //-------------------------------------------------------------

    QProcess qp;
    String myrimatch_version;
    MyriMatchVersion myrimatch_version_i;

    // we invoke myrimatch w/o arguments. that yields a return code != 0. but
    // there is no other way for version 2.1 to get the version number
    qp.start(myrimatch_executable.toQString(), QStringList(), QIODevice::ReadOnly); // does automatic escaping etc...
    qp.waitForFinished();
    String output(QString(qp.readAllStandardOutput()));

    vector<String> lines;
    vector<String> version_split;
    output.split('\n', lines);

    // the version number is expected to be in the second line
    if (lines.size() < 2)
    {
      writeLog_("Warning: MyriMatch version output (" + output + ") not formatted as expected!");
      return EXTERNAL_PROGRAM_ERROR;
    }

    // the version is expected to be something like:
    // MyriMatch 2.1.111 (2011-12-27)
    lines[1].split(' ', version_split);
    if (version_split.size() == 3 && getVersion_(version_split[1], myrimatch_version_i))
    {
      myrimatch_version = version_split[1].removeWhitespaces();
      writeDebug_("Setting MyriMatch version to " + myrimatch_version, 1);
    }
    else
    {
      writeLog_("Warning: MyriMatch version output (" + output + ") not formatted as expected!");
      return EXTERNAL_PROGRAM_ERROR;
    }
    if (! (   (myrimatch_version_i.myrimatch_major == 2) &&  // major must be 2
              (myrimatch_version_i.myrimatch_minor == 1 || myrimatch_version_i.myrimatch_minor == 2) // minor .1 or .2
          ))
    {
      writeLog_("Warning: unsupported MyriMatch version (" + myrimatch_version + "). Tested only for MyriMatch 2.1.x and 2.2.x."
                "\nIf you encounter parameter errors, you can try the flag 'ignoreConfigErrors', but be aware that MyriMatch might be misconfigured.");
    }

    //-------------------------------------------------------------
    // parsing parameters
    //-------------------------------------------------------------

    String inputfile_name = File::absolutePath(getStringOption_("in"));
    String outputfile_name = getStringOption_("out");
    String db_name = File::absolutePath(String(getStringOption_("database")));

    // building parameter String
    StringList parameters;

    if (getFlag_("ignoreConfigErrors")) parameters << "-ignoreConfigErrors";

    // Common Identification engine options
    StringList static_mod_list;
    StringList dynamic_mod_list;
    translateModifications(static_mod_list, dynamic_mod_list);
    if (!static_mod_list.empty())
      parameters << "-StaticMods" << ListUtils::concatenate(static_mod_list, " ");
    if (!dynamic_mod_list.empty())
      parameters << "-DynamicMods" << ListUtils::concatenate(dynamic_mod_list, " ");

    parameters << "-ProteinDatabase"  << File::absolutePath(db_name);

    if (getFlag_("precursor_mass_tolerance_avg"))
    {
      parameters << "-AvgPrecursorMzTolerance";
    }
    else
    {
      parameters << "-MonoPrecursorMzTolerance";
    }
    String precursor_mass_tolerance_unit = getStringOption_("precursor_mass_tolerance_unit") == "Da" ? " m/z" : " ppm";
    parameters << String(getDoubleOption_("precursor_mass_tolerance")) + precursor_mass_tolerance_unit;

    String fragment_mass_tolerance_unit = getStringOption_("fragment_mass_tolerance_unit");
    if (fragment_mass_tolerance_unit == "Da")
    {
      fragment_mass_tolerance_unit = "m/z";
    }

    parameters << "-FragmentMzTolerance" << String(getDoubleOption_("fragment_mass_tolerance")) + " " + fragment_mass_tolerance_unit;

    StringList slf = getStringList_("SpectrumListFilters");
    if (slf.size() > 0) 
    {
      if (myrimatch_version_i.myrimatch_minor <= 1)
      { // use quotes around the slf arguments (will be added automatically by Qt during call), i.e. "-SpectrumListFilters" "peakPicking false 2-"
        parameters << "-SpectrumListFilters" << ListUtils::concatenate(slf, ";") << "";
      }
      else
      { // no quotes -- pass a single argument, i.e. "-SpectrumListFilters peakPicking false 2-"
        parameters << "-SpectrumListFilters " + ListUtils::concatenate(slf, ";") << "";
      }
      
    }
    //parameters << "-ThreadCountMultiplier" << String(getIntOption_("threads")); // MyriMatch does not recognise this, even though it's in the manual.

    // MyriMatch specific parameters
    parameters << "-NumChargeStates" << getIntOption_("NumChargeStates");
    parameters << "-TicCutoffPercentage" << String(getDoubleOption_("TicCutoffPercentage"));
    parameters << "-MaxDynamicMods" << getIntOption_("MaxDynamicMods");
    parameters << "-MaxResultRank" << getIntOption_("MaxResultRank");
    parameters << "-MinTerminiCleavages" << getIntOption_("MinTerminiCleavages");
    parameters << "-MaxMissedCleavages" << getIntOption_("MaxMissedCleavages");
    String cleavage_rule = getStringOption_("CleavageRules");
    if (cleavage_rule.empty())
    {
      cleavage_rule = "Trypsin/P";
    }
    parameters << "-CleavageRules" << cleavage_rule;

    // advanced parameters
    parameters << "-MinPeptideMass"   << getDoubleOption_("MinPeptideMass");
    parameters << "-MaxPeptideMass"   << getDoubleOption_("MaxPeptideMass");
    parameters << "-MinPeptideLength" << getIntOption_("MinPeptideLength");
    parameters << "-MaxPeptideLength" << getIntOption_("MaxPeptideLength");
    parameters << "-NumIntensityClasses" << getIntOption_("NumIntensityClasses");
    parameters << "-ClassSizeMultiplier" << getDoubleOption_("ClassSizeMultiplier");
    parameters << "-MonoisotopeAdjustmentSet" << getStringOption_("MonoisotopeAdjustmentSet");
    parameters << "-cpus" << getIntOption_("threads");


    // Constant parameters

    // DecoyPrefix worked only when set through the config file
    String cfg_file = tmp_dir + "myrimatch.cfg";
    ofstream f(cfg_file.c_str());
    f << "DecoyPrefix=\"\"\n";
    f.close();
    parameters << "-cfg" << cfg_file;

    // path to input file must be the last parameter
    parameters << inputfile_name;

    //-------------------------------------------------------------
    // calculations
    //-------------------------------------------------------------
    QStringList qparam;
    writeDebug_("MyriMatch arguments:", 1);
    writeDebug_(String("\"") + ListUtils::concatenate(parameters, "\" \"") + "\"", 1);
    for (Size i = 0; i < parameters.size(); ++i)
    {
      qparam << parameters[i].toQString();
    }
    QProcess process;

    // Bad style, because it breaks relative paths?
    process.setWorkingDirectory(tmp_dir.toQString());

    process.start(myrimatch_executable.toQString(), qparam, QIODevice::ReadOnly);
    bool success = process.waitForFinished(-1);
    String myri_msg(QString(process.readAllStandardOutput()));
    String myri_err(QString(process.readAllStandardError()));
    writeDebug_(myri_msg, 1);
    writeDebug_(myri_err, 0);
    if (!success || process.exitStatus() != 0 || process.exitCode() != 0)
    {
      writeLog_("Error: MyriMatch problem! (Details can be seen in the logfile: \"" + logfile + "\")");
      writeLog_("Note: This message can also be triggered if you run out of space in your tmp directory");
      return EXTERNAL_PROGRAM_ERROR;
    }

    //-------------------------------------------------------------
    // reading MyriMatch output
    //-------------------------------------------------------------

    writeDebug_("Reading output of MyriMatch", 5);
    String exp_name = File::basename(inputfile_name);
    String pep_file = tmp_dir + File::removeExtension(exp_name) + ".pepXML";

    vector<ProteinIdentification> protein_identifications;
    vector<PeptideIdentification> peptide_identifications;

    PeakMap exp;
    if (File::exists(pep_file))
    {
      MzMLFile fh;
      fh.load(inputfile_name, exp);

      SpectrumMetaDataLookup lookup;
      lookup.readSpectra(exp.getSpectra());
      PepXMLFile().load(pep_file, protein_identifications,
                        peptide_identifications, exp_name, lookup);
    }
    else
    {
      writeLog_("Error: MyriMatch problem! No pepXML output file (expected as '" + pep_file + "') was generated by MyriMatch.");
      writeLog_("Note: This message can be triggered if no MS2 spectra were found or no identifications were made.");
      writeLog_("      Myrimatch expects MS2 spectra in mzML files to contain the MSn tag. MSSpectrum with MS level 2 is not sufficient. You can use FileConverter to create such an mzML file by converting from mzML --> mzXML --> mzML.");
      return EXTERNAL_PROGRAM_ERROR;
    }

    if (debug_level_ == 0)
    {
      QFile(pep_file.toQString()).remove();
      QFile(cfg_file.toQString()).remove();
    }
    else
    {
      writeDebug_(String("Not removing '") + pep_file + "' for debugging purposes. Please delete manually!", 1);
      writeDebug_(String("Not removing '") + cfg_file + "' for debugging purposes. Please delete manually!", 1);
    }
    //-------------------------------------------------------------
    // writing results
    //-------------------------------------------------------------
    ProteinIdentification::SearchParameters search_parameters;
    search_parameters.db = getStringOption_("database");
    ProteinIdentification::PeakMassType mass_type = getFlag_("precursor_mass_tolerance_avg") == true ? ProteinIdentification::AVERAGE : ProteinIdentification::MONOISOTOPIC;
    search_parameters.mass_type = mass_type;
    search_parameters.fixed_modifications = getStringList_("fixed_modifications");
    search_parameters.variable_modifications = getStringList_("variable_modifications");
    search_parameters.missed_cleavages = getIntOption_("MaxMissedCleavages");
    search_parameters.fragment_mass_tolerance = getDoubleOption_("fragment_mass_tolerance");
    search_parameters.precursor_mass_tolerance = getDoubleOption_("precursor_mass_tolerance");
    search_parameters.precursor_mass_tolerance_ppm = getStringOption_("precursor_mass_tolerance_unit") == "ppm" ? true : false;
    search_parameters.fragment_mass_tolerance_ppm = getStringOption_("fragment_mass_tolerance_unit") == "ppm" ? true : false;
    protein_identifications[0].setSearchParameters(search_parameters);
    protein_identifications[0].setSearchEngineVersion(myrimatch_version);
    protein_identifications[0].setSearchEngine("MyriMatch");

    if (!protein_identifications.empty())
    {
      StringList ms_runs;
      exp.getPrimaryMSRunPath(ms_runs);
      protein_identifications[0].setPrimaryMSRunPath(ms_runs);
    }
    IdXMLFile().store(outputfile_name, protein_identifications, peptide_identifications);
    return EXECUTION_OK;
  }
bool CommandLineExporter::executeCommand
(
    const QString& command,
    const QString& inputFilePath,
    const QString& textInput,
    const QString& outputFilePath,
    QString& stdoutOutput,
    QString& stderrOutput
)
{
    QProcess process;
    process.setReadChannel(QProcess::StandardOutput);

    QString expandedCommand = command + QString(" ");

    if (!outputFilePath.isNull() && !outputFilePath.isEmpty())
    {
        // Redirect stdout to the output file path if the path variable wasn't
        // set in the command string.
        //
        if (!expandedCommand.contains(OUTPUT_FILE_PATH_VAR))
        {
            process.setStandardOutputFile(outputFilePath);
        }
        else
        {
            // Surround file path with quotes in case there are spaces in the
            // path.
            //
            QString outputFilePathWithQuotes = QString('\"') +
                outputFilePath + '\"';
            expandedCommand.replace(OUTPUT_FILE_PATH_VAR, outputFilePathWithQuotes);
        }
    }

    if
    (
        this->getSmartTypographyEnabled() &&
        !this->smartTypographyOnArgument.isNull()
    )
    {
        expandedCommand.replace
        (
            SMART_TYPOGRAPHY_ARG,
            smartTypographyOnArgument
        );
    }
    else if
    (
        !this->getSmartTypographyEnabled() &&
        !this->smartTypographyOffArgument.isNull()
    )
    {
        expandedCommand.replace
        (
            SMART_TYPOGRAPHY_ARG,
            smartTypographyOffArgument
        );
    }

    if (!inputFilePath.isNull() && !inputFilePath.isEmpty())
    {
        process.setWorkingDirectory(QFileInfo(inputFilePath).dir().path());
    }

    process.start(expandedCommand);

    if (!process.waitForStarted())
    {
        return false;
    }
    else
    {
        if (!textInput.isNull() && !textInput.isEmpty())
        {
            process.write(textInput.toUtf8());
            process.closeWriteChannel();
        }

        if (!process.waitForFinished())
        {
            return false;
        }
        else
        {
            stdoutOutput = QString::fromUtf8(process.readAllStandardOutput().data());
            stderrOutput = QString::fromUtf8(process.readAllStandardError().data());
        }
    }

    return true;
}
Example #12
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_XP)
	{
		MEMORYSTATUSEX statex;
		statex.dwLength = sizeof (statex);
		GlobalMemoryStatusEx(&statex);
		writeLog(QString("Total physical memory: %1 MB").arg(statex.ullTotalPhys/(1024<<10)));
		writeLog(QString("Available physical memory: %1 MB").arg(statex.ullAvailPhys/(1024<<10)));
		writeLog(QString("Physical memory in use: %1%").arg(statex.dwMemoryLoad));
		#ifndef _WIN64
		// This always reports about 8TB on Win64, not really useful to show.
		writeLog(QString("Total virtual memory: %1 MB").arg(statex.ullTotalVirtual/(1024<<10)));
		writeLog(QString("Available virtual memory: %1 MB").arg(statex.ullAvailVirtual/(1024<<10)));
		#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
}
Example #13
0
/**************************************************************************************************
*   inicia o pserve para receber as imagens e plota na ui
**************************************************************************************************/
void MainWindow::start_pserve()
{
    contagem=0;
    pixeis_lidos=0;
    QProcess *myProcess = new QProcess;
    QStringList arguments_pserve;
    process_pserve = Current_Path+"/pserve";
    arguments_pserve<<Count_L<<NImage<<Save_Path;
    myProcess->setProcessChannelMode(QProcess::MergedChannels);
    myProcess->start(process_pserve,arguments_pserve);
    myProcess->waitForStarted();
    QPixmap pixmap;
    float contagem_anterior;
    /**************************************************************************************************
    *   le uma imagem
    **************************************************************************************************/
    if(NImage.toInt()==1)
    {
        if(Count_L.toInt()==0) // 1 bit
        {
            contagem=0;
            pixeis_lidos=0;
            myProcess->waitForFinished((Time.toFloat()*1000)+100);
            QImage image(256,256,QImage::Format_Indexed8);
            if(image.load(Save_Path+"1.ppm","pbm")==true)
            {
                image.invertPixels();
                for(int a=0;a<=255;a++)
                {
                    for(int b=0;b<=255;b++)
                    {
                        contagem=contagem+(1-image.pixelIndex(b,a));
                        pixeis_lidos=contagem;
                    }
                }
            }
            else
            {
                image.fill(Qt::black);
                ui->textBrowser->append("Error Reading Image!!!");
            }
            pixmap = QPixmap::fromImage(image,Qt::ColorOnly);
        }
        else if(Count_L.toInt()==1) // 12 bits
        {
            contagem=0;
            pixeis_lidos=0;
            myProcess->waitForFinished((Time.toFloat()*1000)+1000);
            QImage image(256,256,QImage::Format_RGB16);
            QByteArray teste;
            QFile filestr(Save_Path+"1.ppm");
            if(filestr.open(QIODevice::ReadOnly)==true)
            {
                teste=filestr.readAll();
                QString colorstr(teste);
                QStringList colors = colorstr.split(QRegExp("\\s+"));
                colors.removeLast();
                colors.removeFirst();
                colors.removeFirst();
                colors.removeFirst();
                colors.removeFirst();
                QVector<QRgb> colortable;
                Lookup_Tables ctable;
                colortable=ctable.colorPalete1280();
                image.setColorTable(colortable);
                int cont=0;
                for(int a=0;a<=255;a++)
                {
                    for(int b=0;b<=255;b++)
                    {
                        if(qCeil(colors.at(cont).toInt()/3.2)>=1280)
                        {
                            image.setPixel(b,a, image.colorTable().at(1279));
                        }
                        else
                        {
                            image.setPixel(b,a, image.colorTable().at(qCeil(colors.at(cont).toUInt()/3.2)));
                        }
                        contagem_anterior=contagem;
                        contagem=contagem+colors.at(cont).toFloat();
                        cont++;
                        if(contagem_anterior!=contagem)
                        {
                            pixeis_lidos++;
                        }
                    }
                }
            }
            else
            {
                image.fill(Qt::black);
                ui->textBrowser->append("Error Reading Image!!!");
            }
            pixmap = QPixmap::fromImage(image,Qt::ColorOnly);
        }
        else if(Count_L.toInt()==2) // 6 bits
        {
            contagem=0;
            pixeis_lidos=0;
            myProcess->waitForFinished((Time.toFloat()*1000)+500);
            QImage image(256,256,QImage::Format_Indexed8);
            if(image.load(Save_Path+"1.ppm","pbm")==true)
            {
                QVector<QRgb> colortable;
                Lookup_Tables ctable;
                colortable=ctable.colorPalete64();
                image.setColorTable(colortable);
            }
            else
            {
                image.fill(Qt::black);
                ui->textBrowser->append("Error Reading Image!!!");
            }
            pixmap = QPixmap::fromImage(image,Qt::ColorOnly);

            for(int a=0;a<=255;a++)
            {
                for(int b=0;b<=255;b++)
                {
                    contagem_anterior=contagem;
                    contagem=contagem+image.pixelIndex(b,a);
                    if(contagem_anterior!=contagem)
                    {
                        pixeis_lidos++;
                    }
                }
            }
        }
        else if(Count_L.toInt()==3) // 24 bits
        {
            contagem=0;
            pixeis_lidos=0;
            myProcess->waitForFinished((Time.toFloat()*1000)+1500);
            QImage image(256,256,QImage::Format_RGB32);
            QByteArray teste;
            QFile filestr(Save_Path+"1.ppm");
            if(filestr.open(QIODevice::ReadOnly)==true)
            {
                teste=filestr.readAll();
                QString colorstr(teste);
                QStringList colors = colorstr.split(QRegExp("\\s+"));
                colors.removeLast();
                colors.removeFirst();
                colors.removeFirst();
                colors.removeFirst();
                colors.removeFirst();
                QVector<QRgb> colortable;
                Lookup_Tables ctable;
                colortable=ctable.colorPalete1280();
                image.setColorTable(colortable);
                int cont=0;
                for(int a=0;a<=255;a++)
                {
                    for(int b=0;b<=255;b++)
                    {
                        if(qCeil(colors.at(cont).toInt()/100)>=1536)
                        {
                            image.setPixel(b,a, image.colorTable().at(1535));
                        }
                        else
                        {
                            image.setPixel(b,a, image.colorTable().at(qCeil(colors.at(cont).toUInt()/100)));
                        }
                        contagem_anterior=contagem;
                        contagem=contagem+colors.at(cont).toFloat();
                        cont++;
                        if(contagem_anterior!=contagem)
                        {
                            pixeis_lidos++;
                        }
                    }
                }
            }
            else
            {
                image.fill(Qt::black);
                ui->textBrowser->append("Error Reading Image!!!");
            }
            pixmap = QPixmap::fromImage(image,Qt::ColorOnly);
        }
        pixmap=pixmap.scaled(512,512);
        scene= new QGraphicsScene(this);
        scene->addPixmap(pixmap);
        ui->Plot_Window->setScene(scene);
        QByteArray text_response=myProcess->readAll();
        QString mystr(text_response);
        ui->textBrowser->setText(mystr);
        ui->textBrowser->append("Total Count = "+QString::number(contagem));
        ui->textBrowser->append("Pixel Read = "+QString::number(pixeis_lidos));
    }
    /**************************************************************************************************
    *   le +1 imagem
    **************************************************************************************************/
    else
    {
        Save_Dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
        Save_Dir.setSorting(QDir::Time);
        QString lee(Image_Name);
        int cont =0;
        lee.append(QString::number(cont));
        for(int a=0;a<=(NImage.toInt()-1);a++)
        {
            if(Count_L.toInt()==0) // 1 bit
            {
                if(a==(NImage.toInt()-1))
                {
                    myProcess->waitForFinished(NImage.toInt()*((Gap.toInt()*1000)+(Time.toFloat()*1000)+300));
                }
                else if(a==0)
                {
                    QThread::msleep((Time.toFloat()*1000)+300);
                }
                else
                {
                    QThread::msleep((Gap.toInt()*1000)+(Time.toFloat()*1000)+300);
                }
                cont++;
                lee.replace(lee.size()-1,1,QString::number(cont));
                QImage image(256,256,QImage::Format_Indexed8);
                image.load(Save_Dir.absolutePath()+"/"+lee+".ppm","pbm");
                image.invertPixels();
                pixmap = QPixmap::fromImage(image,Qt::ColorOnly);
                pixmap=pixmap.scaled(512,512);
                scene= new QGraphicsScene(this);
                scene->addPixmap(pixmap);
                scene->update();
                ui->Plot_Window->setScene(scene);
                ui->Plot_Window->update();
                QByteArray text_response=myProcess->readAll();
                QString mystr(text_response);
                ui->textBrowser->setText(mystr);
                ui->textBrowser->update();
                QCoreApplication::processEvents(QEventLoop::AllEvents);
            }
            else if(Count_L.toInt()==1) // 12 bits
            {
                if(a==(NImage.toInt()-1))
                {
                    myProcess->waitForFinished(NImage.toInt()*((Gap.toInt()*1000)+(Time.toFloat()*1000)+1000));
                }
                else if(a==0)
                {
                    QThread::msleep((Time.toFloat()*1000)+1000);
                }
                else
                {
                    QThread::msleep((Gap.toInt()*1000)+(Time.toFloat()*1000)+1000);
                }
                QByteArray text_response=myProcess->readAll();
                QString mystr(text_response);
                ui->textBrowser->setText(mystr);
                cont++;
                lee.replace(lee.size()-1,1,QString::number(cont));
                QImage image(256,256,QImage::Format_RGB16);
                QByteArray teste;
                QFile filestr(Save_Dir.absolutePath()+"/"+lee+".ppm");
                filestr.open(QIODevice::ReadOnly);
                teste=filestr.readAll();
                QString colorstr(teste);
                QStringList colors = colorstr.split(QRegExp("\\s+"));
                colors.removeLast();
                colors.removeFirst();
                colors.removeFirst();
                colors.removeFirst();
                colors.removeFirst();
                QVector<QRgb> colortable;
                Lookup_Tables ctable;
                colortable=ctable.colorPalete1280();
                image.setColorTable(colortable);
                int cont=0;
                for(int a=0;a<=255;a++)
                {
                    for(int b=0;b<=255;b++)
                    {
                        if(qCeil(colors.at(cont).toInt()/3.2)>=1280)
                        {
                            image.setPixel(b,a, image.colorTable().at(1279));
                        }
                        else
                        {
                            image.setPixel(b,a, image.colorTable().at(qCeil(colors.at(cont).toUInt()/3.2)));
                        }
                        cont++;
                    }
                }
                pixmap = QPixmap::fromImage(image,Qt::ColorOnly);
                pixmap=pixmap.scaled(512,512);
                scene= new QGraphicsScene(this);
                scene->addPixmap(pixmap);
                scene->update();
                ui->Plot_Window->setScene(scene);
                ui->Plot_Window->update();
                QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
            }
            else if(Count_L.toInt()==2) // 6 bits
            {
                if(a==(NImage.toInt()-1))
                {
                    myProcess->waitForFinished(NImage.toInt()*((Gap.toInt()*1000)+(Time.toFloat()*1000)+500));
                }
                else if(a==0)
                {
                    QThread::msleep((Time.toFloat()*1000)+500);
                }
                else
                {
                    QThread::msleep((Gap.toInt()*1000)+(Time.toFloat()*1000)+500);
                }
                QByteArray text_response=myProcess->readAll();
                QString mystr(text_response);
                ui->textBrowser->setText(mystr);
                cont++;
                //QFileInfoList list = Save_Dir.entryInfoList();
                //QFileInfo fileinfo = list.at(0);
                //image1 = fileinfo.fileName();
                lee.replace(lee.size()-1,1,QString::number(cont));
                //qDebug()<<Save_Dir.absolutePath()+"/"+lee+".ppm";
                QImage image(256,256,QImage::Format_Indexed8);
                image.load(Save_Dir.absolutePath()+"/"+lee+".ppm","pgm");
                QVector<QRgb> colortable;
                Lookup_Tables ctable;
                colortable=ctable.colorPalete64();
                image.setColorTable(colortable);
                pixmap=pixmap.scaled(512,512);
                pixmap = QPixmap::fromImage(image,Qt::ColorOnly);
                scene= new QGraphicsScene(this);
                scene->addPixmap(pixmap);
                scene->update();
                ui->Plot_Window->setScene(scene);
                ui->Plot_Window->update();
                QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
            }
            else if(Count_L.toInt()==3) // 24 bits
            {
                if(a==(NImage.toInt()-1))
                {
                    myProcess->waitForFinished(NImage.toInt()*((Gap.toInt()*1000)+(Time.toFloat()*1000)+1500));
                }
                else if(a==0)
                {
                    QThread::msleep((Time.toFloat()*1000)+1500);
                }
                else
                {
                    QThread::msleep((NImage.toInt()*1000)+(Time.toFloat()*1000)+1500);
                }
                QByteArray text_response=myProcess->readAll();
                QString mystr(text_response);
                ui->textBrowser->setText(mystr);
                cont++;
                lee.replace(lee.size()-1,1,QString::number(cont));
                QImage image(256,256,QImage::Format_RGB32);
                QByteArray teste;
                QFile filestr(Save_Dir.absolutePath()+"/"+lee+".ppm");
                filestr.open(QIODevice::ReadOnly);
                teste=filestr.readAll();
                QString colorstr(teste);
                QStringList colors = colorstr.split(QRegExp("\\s+"));
                colors.removeLast();
                colors.removeFirst();
                colors.removeFirst();
                colors.removeFirst();
                colors.removeFirst();
                QVector<QRgb> colortable;
                Lookup_Tables ctable;
                colortable=ctable.colorPalete1280();
                image.setColorTable(colortable);
                int cont=0;
                for(int a=0;a<=255;a++)
                {
                    for(int b=0;b<=255;b++)
                    {
                        if(qCeil(colors.at(cont).toInt()/100)>=1536)
                        {
                            image.setPixel(b,a, image.colorTable().at(1535));
                        }
                        else
                        {
                            image.setPixel(b,a, image.colorTable().at(qCeil(colors.at(cont).toUInt()/100)));
                        }
                        cont++;
                    }
                }
                pixmap = QPixmap::fromImage(image,Qt::ColorOnly);
                pixmap=pixmap.scaled(512,512);
                scene= new QGraphicsScene(this);
                scene->addPixmap(pixmap);
                scene->update();
                ui->Plot_Window->setScene(scene);
                ui->Plot_Window->update();
                QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
            }
        }
    }
}
TemplateCore::GenerationResult FlashCardCore::generateMobileApplication(const QString &input_apk_file, QString &output_file) {
  emit generationProgress(5, tr("Preparing workspace..."));

  qApp->templateManager()->generator()->cleanWorkspace();

  emit generationProgress(10, tr("Extracting raw data from editor..."));

  // We need data which will be imported into apk/zip file.
  QString quiz_data = editor()->generateBundleData();

  if (quiz_data.isEmpty()) {
    // No date received, this is big problem.
    return BundleProblem;
  }

  QString temp_folder = qApp->templateManager()->tempDirectory();
  QDir temp_directory(temp_folder);
  QString base_folder = temp_folder + "/" + APP_LOW_NAME;
  QDir base_directory(base_folder);

  // Preparation of target bundle file
  emit generationProgress(20, tr("Creating base temporary folder..."));

  temp_directory.mkdir(APP_LOW_NAME);
  base_directory.mkdir("assets");

  QFile index_file(base_folder + "/assets/flash_content.xml");
  index_file.open(QIODevice::WriteOnly | QIODevice::Text);

  emit generationProgress(30, tr("Writting info data into file..."));

  QTextStream out(&index_file);
  out << quiz_data;

  out.flush();
  index_file.close();

  emit generationProgress(40, tr("Copying template apk file..."));

  // Copying of target apk file.
  QString new_apk_name = input_apk_file;

  if (!QFile::copy(APP_TEMPLATES_PATH + "/" + entryPoint()->baseFolder() + "/" + entryPoint()->mobileApplicationApkFile(),
                   base_folder + "/" + new_apk_name)) {
    qApp->templateManager()->generator()->cleanWorkspace();
    return CopyProblem;
  }

  emit generationProgress(60, tr("Inserting data into apk file..."));

  // Inserting bundle file into apk file.
  QProcess zip;

  zip.setWorkingDirectory(base_folder);
  zip.start(qApp->zipUtilityPath(), QStringList() << "-m" << "-r" << new_apk_name << "assets");
  zip.waitForFinished();

  if (zip.exitCode() != EXIT_STATUS_ZIP_NORMAL) {
    // Error during inserting quiz data via zip.
    qApp->templateManager()->generator()->cleanWorkspace();
    return ZipProblem;
  }

  emit generationProgress(70, tr("Signing apk file..."));

  // Signing and renaming target file.
  QString pem_certificate = QDir::toNativeSeparators(APP_CERT_PATH + "/" + CERTIFICATE_PATH);
  QString pk_certificate = QDir::toNativeSeparators(APP_CERT_PATH + "/" + KEY_PATH);
  QProcess signapk;

  signapk.setWorkingDirectory(base_folder);
  signapk.start(qApp->javaInterpreterPath(), QStringList() << "-jar" << qApp->signApkUtlityPath() <<
                pem_certificate << pk_certificate << new_apk_name <<
                QDir::toNativeSeparators(new_apk_name + ".new"));
  signapk.waitForFinished();

  if (signapk.exitCode() != EXIT_STATUS_SIGNAPK_WORKING) {
    qApp->templateManager()->generator()->cleanWorkspace();
    return SignApkProblem;
  }

  emit generationProgress(90, tr("Copying final apk file to output directory..."));

  // Now, our file is created. We need to move it to target directory.
  if (!IOFactory::copyFile(base_folder + "/" + new_apk_name + ".new",
                           qApp->templateManager()->outputDirectory() + "/" + new_apk_name)) {
    qApp->templateManager()->generator()->cleanWorkspace();
    return CopyProblem;
  }

  output_file = QDir(qApp->templateManager()->outputDirectory()).filePath(new_apk_name);

  // Removing temporary files and exit.
  qApp->templateManager()->generator()->cleanWorkspace();
  return Success;
}
Example #15
0
void UdpManager::readUDP()
{
    QByteArray Temp;
    Temp.resize(socket->pendingDatagramSize());

    QHostAddress sender;
    quint16 senderPort;
    socket->readDatagram(Temp.data(),Temp.size(),&sender,&senderPort);

    QString debugMessage = "Got \"" + QString(Temp.data()) + "\" from " + sender.toString() + ":"+ QString::number(senderPort) + " (UDP)";
    emit updateClientGUIConsole(debugMessage);

    QString compareString = "BLENDER";
    QString message;
    if(Temp.data() == compareString)
    {
        if (workerIsBusy)
            message = "BLENDER0";       //is busy
        else{
            if (isGPUWorker)
                message = "BLENDER2";   // is available GPU-Worker
            else
                message = "BLENDER1";   // is available CPU-Worker
        }
        writeUDP(message, sender);
    }
    else if( QString(Temp.data()).at(0) == '#' && !workerIsBusy )
    {
        message = "";

        QString filepathToBlend = QDir::currentPath() + "/awesome.blend";

        QByteArray fileData;

        QFile file( filepathToBlend ); //e.g.: /.../build/awesome.blend
        if( file.open(QIODevice::ReadOnly) )
        {
            fileData = file.readAll();
            file.close();

            //Generate MD5 Hash
            QByteArray hashData = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
            file_hash = hashData.toHex();

            qDebug() << "Hex-Hash: " << hashData.toHex();

        }
        else
        {
            //Error
            file_hash = "Th15I5Th3DummymD5HasH0fGSORF.0RG";
        }

        //Send UDP Response
        writeUDP( "#" + file_hash, sender );
        if(file_hash==QString(Temp.data()).remove('#') )
        {
            emit setFileCached(true);
        }
        else
        {
            emit setFileCached(false);
        }
    }
    else if( QString(Temp.data()).startsWith("killall"))
    {
    qDebug()<<"Bye Bye Blender";
    QProcess *myProcess = new QProcess(this);
    myProcess->start("killall blender");
    myProcess->waitForFinished();
    }


    emit setServerAddress(sender);

}
Example #16
0
bool ALACDecoder::decode(const QString &sourceFile, const QString &outputFile, volatile bool *abortFlag)
{
    QProcess process;
    QStringList args;

    args << "--decode";
    args << "-o" << QDir::toNativeSeparators(outputFile);
    args << QDir::toNativeSeparators(sourceFile);

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

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

    //The ALAC Decoder doesn't actually send any status updates :-[
    //emit statusUpdated(20 + (QUuid::createUuid().data1 % 60));
    QRegExp regExp("\\[(\\d+)\\.(\\d)%\\]");

    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("ALAC 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[2] = {false, false};
                int intVal[2] = {0, 0};
                intVal[0] = regExp.cap(1).toInt(&ok[0]);
                intVal[1] = regExp.cap(2).toInt(&ok[1]);
                if(ok[0] && ok[1])
                {
                    int progress = qRound(static_cast<double>(intVal[0]) + (static_cast<double>(intVal[1]) / 10.0));
                    if(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 || QFileInfo(outputFile).size() == 0)
    {
        return false;
    }

    return true;
}
Example #17
0
// Index any PDFs that are attached.  Basically it turns the PDF into text and adds it the same
// way as a note's body
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->conn);
    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(".");
        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->conn);
        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();
        txtFile.close();
    }
    QDir dir;
    dir.remove(outDir+QString::number(reslid) +".txt");
}
void MainWindow::downloadFinished(QNetworkReply *reply)
{
    QScrollBar *sb = ui->textBrowser->verticalScrollBar();
    QUrl url = reply->url();

    if (reply->error()) {
      if ( !url.toString().contains("hgt.zip") ) {
        ui->textBrowser->append("Download of " + QString(url.toEncoded().constData()) + " failed: " + QString(reply->errorString()));
        sb->setValue(sb->maximum()); // get the info shown
      }

        QString fileUrl = url.toEncoded().constData();
    } else {
        QString path = url.path();
        QString fileName = QFileInfo(path).fileName();
        if (fileName.isEmpty()) fileName = "download";

        QDir dir(dataDirectory);
        dir.mkpath(dataDirectory);
        QFile file(dataDirectory+"/"+fileName);

        if (fileName.contains("dl")) {
            // obtain url
            QFile file(dataDirectory+"/"+fileName);
        } else if (fileName.contains("hgt")) {
            // obtain elevation files
            dir.mkpath(dataDirectory+"/SRTM-3/");
            file.setFileName(dataDirectory+"/SRTM-3/"+fileName);
            GUILog( url.toString() + "\n", "download" );
        }

        if (file.open(QIODevice::WriteOnly)) {
            file.write(reply->readAll());
            file.close();
        }

        // download actual shapefile package
        if (fileName.contains("dl")) {
            QFile dlFile(dataDirectory+"/"+fileName);
            if (!dlFile.open(QIODevice::ReadOnly | QIODevice::Text))
                return;
            QTextStream textStream( &dlFile);
            QString dlUrl = textStream.readAll();
            dlUrl.remove("<p>The document has moved <a href=\"");
            dlUrl.remove("\">here</a></p>\n");
            QNetworkReply *r = _manager->get(QNetworkRequest("http://mapserver.flightgear.org"+dlUrl));
            connect(r, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(downloadShapefilesProgressBar(qint64, qint64)));
        }

        ui->textBrowser->append("Download of "+QString(url.toEncoded().constData())+" succeded saved to: "+QString(fileName));
        sb->setValue(sb->maximum()); // get the info shown

        // unzip shapefile package
        if (fileName.contains("-")) {
            // unpack zip
            QString arguments;
#ifdef Q_OS_WIN
            arguments += "7z.exe x \""+dataDirectory+"/"+fileName+"\" -o\""+dataDirectory+"\" -aoa";
#endif
#ifdef Q_OS_UNIX
            arguments += "unzip -o "+dataDirectory+"/"+fileName+" -d "+dataDirectory;
#endif
            //ui->textBrowser->append(arguments);
            GUILog( arguments + "\n", "download" );
            QProcess proc;
            proc.start(arguments, QIODevice::ReadWrite);
            proc.waitForReadyRead();
            proc.waitForFinished(-1);

            // delete temporary files
            QFile shapeFile(dataDirectory+"/"+fileName);
            shapeFile.remove();
            QFile dlshpFile(dataDirectory+"/dlshp");
            dlshpFile.remove();

            // re-enable download button
            ui->downloadShapefilesButton->setText("Download shapefiles");
            ui->downloadShapefilesButton->setEnabled(1);
        }

        if (fileName.contains(".hgt.zip")){
            // adjust progress bar
            ui->downloadElevationProgressBar->setValue(ui->downloadElevationProgressBar->value()+1);
        }
    }
    // re-enable download button
    if (ui->downloadElevationProgressBar->value() == ui->downloadElevationProgressBar->maximum()) {
        ui->downloadElevationButton->setEnabled(1);
    }
}
Example #19
0
void MetaEditorSupportPlugin::generateEditorWithQrmc()
{
	qrmc::MetaCompiler metaCompiler(*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();

	for (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);

			const QString normalizedName = nameOfMetamodel.at(0).toUpper() + nameOfMetamodel.mid(1);
			const bool stateOfLoad = mMainWindowInterface->pluginLoaded(normalizedName);
			if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
				progress->close();
				delete progress;
				return;
			}

			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);

			QStringList qmakeArgs;
			qmakeArgs.append("CONFIG+=" + mLogicalRepoApi->stringProperty(key, "buildConfiguration"));
			qmakeArgs.append(nameOfMetamodel + ".pro");

			QProcess builder;
			builder.setWorkingDirectory(nameOfTheDirectory);
			const QStringList environment = QProcess::systemEnvironment();
			builder.setEnvironment(environment);
			builder.start(SettingsManager::value("pathToQmake").toString(), qmakeArgs);

			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)) {
					if (stateOfLoad) {
						QMessageBox::warning(mMainWindowInterface->windowWidget()
								, tr("Attention!"), tr("Please restart QReal."));
						progress->close();
						delete progress;
						return;
					}
					qDebug()  << "make ok";
					progress->setValue(progress->value() + forEditor / 2);

					if (!nameOfMetamodel.isEmpty()) {
						if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
							QMessageBox::warning(mMainWindowInterface->windowWidget()
									, tr("error")
									, tr("cannot unload plugin ") + normalizedName);
							progress->close();
							delete progress;
							continue;
						}
					}

					QString suffix = "";
					if (mLogicalRepoApi->stringProperty(key, "buildConfiguration") == "debug") {
						suffix = "-d";
					}

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

					if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) {
						progress->setValue(progress->value() + forEditor / 2);
					}
				}
				progress->setValue(100);
			}
		}
	}
	if (progress->value() != 100) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot load new editor"));
	}
	progress->setValue(100);
	progress->close();
	delete progress;
}
Example #20
0
void Wizard::checkMltComponents()
{
    m_mltCheck.programList->setColumnCount(2);
    m_mltCheck.programList->setRootIsDecorated(false);
    m_mltCheck.programList->setHeaderHidden(true);
    QSize itemSize(20, fontMetrics().height() * 2.5);
    m_mltCheck.programList->setColumnWidth(0, 30);
    m_mltCheck.programList->setIconSize(QSize(24, 24));


    QTreeWidgetItem *mltitem = new QTreeWidgetItem(m_mltCheck.programList);

    QTreeWidgetItem *meltitem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("Melt") + " (" + KdenliveSettings::rendererpath() + ')');
    meltitem->setData(1, Qt::UserRole, i18n("Required for rendering (part of MLT package)"));
    meltitem->setSizeHint(0, itemSize);
    meltitem->setIcon(0, m_okIcon);

    // Check MLT's installed producers
    QProcess checkProcess;
    checkProcess.start(KdenliveSettings::rendererpath(), QStringList() << "-query" << "producer");
    if (!checkProcess.waitForStarted()) {
        meltitem->setIcon(0, m_badIcon);
        meltitem->setData(1, Qt::UserRole, i18n("Error starting MLT's command line player (melt)"));
        button(QWizard::NextButton)->setEnabled(false);
    } else {
        checkProcess.waitForFinished();
        QByteArray result = checkProcess.readAllStandardError();

        // Check MLT avformat module
        QTreeWidgetItem *avformatItem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("Avformat module (FFmpeg)"));
        avformatItem->setData(1, Qt::UserRole, i18n("Required to work with various video formats (hdv, mpeg, flash, ...)"));
        avformatItem->setSizeHint(0, itemSize);
        if (!result.contains("- avformat")) {
            avformatItem->setIcon(0, m_badIcon);
            m_mltCheck.tabWidget->setTabEnabled(1, false);
        } else {
            avformatItem->setIcon(0, m_okIcon);
            // Make sure we have MLT > 0.3.4
            bool recentMlt = false;
            int version = 0;
            QString mltVersion;
            QString exepath = KStandardDirs::findExe("pkg-config");
            if (!exepath.isEmpty()) {
                checkProcess.start(exepath, QStringList() << "--variable=version" << "mlt++");
                if (!checkProcess.waitForStarted()) {
                    kDebug() << "// Error querying MLT's version";
                } else {
                    checkProcess.waitForFinished();
                    mltVersion = checkProcess.readAllStandardOutput();
                    version = 100 * mltVersion.section('.', 0, 0).toInt() + 10 * mltVersion.section('.', 1, 1).toInt() + mltVersion.section('.', 2, 2).toInt();
                    kDebug() << "// FOUND MLT's pkgconfig version: " << version;
                    if (version > 34) recentMlt = true;
                }
            }
            if (version == 0) {
                checkProcess.start(KdenliveSettings::rendererpath(), QStringList() << "--version");
                if (!checkProcess.waitForStarted()) {
                    kDebug() << "// Error querying MLT's version";
                } else {
                    checkProcess.waitForFinished();
                    mltVersion = checkProcess.readAllStandardError();
                    mltVersion = mltVersion.section('\n', 0, 0).simplified();
                    mltVersion = mltVersion.section(' ', -1).simplified();
                    version = 100 * mltVersion.section('.', 0, 0).toInt() + 10 * mltVersion.section('.', 1, 1).toInt() + mltVersion.section('.', 2, 2).toInt();
                    kDebug() << "// FOUND MLT version: " << version;
                    if (version >= 40) recentMlt = true;
                }
            }

            mltitem->setText(1, i18n("MLT version: %1", mltVersion.simplified()));
            mltitem->setSizeHint(0, itemSize);
            if (version < recommendedMltVersion) {
                mltitem->setData(1, Qt::UserRole, i18n("Please upgrade to the latest MLT version"));
                mltitem->setIcon(0, m_badIcon);
            } else {
                mltitem->setData(1, Qt::UserRole, i18n("MLT version is correct"));
                mltitem->setIcon(0, m_okIcon);
            }

            if (recentMlt) {
                // Check installed audio codecs
                QProcess checkProcess2;
                checkProcess2.start(KdenliveSettings::rendererpath(), QStringList() << "noise:" << "-consumer" << "avformat" << "acodec=list");
                if (!checkProcess2.waitForStarted()) {
                    m_mltCheck.tabWidget->setTabEnabled(1, false);
                    kDebug() << "// Error parsing MLT's avformat codecs";
                } else {
                    checkProcess2.waitForFinished();
                    QByteArray codecList = checkProcess2.readAllStandardError();
                    QString acodecList(codecList);
                    QStringList result;
                    QStringList alist = acodecList.split('\n', QString::SkipEmptyParts);
                    for (int i = 0; i < alist.count(); i++) {
                        if (alist.at(i).contains("- ")) result.append(alist.at(i).section("- ", 1).simplified().toLower());
                    }
                    m_mltCheck.acodecs_list->addItems(result);
                    KdenliveSettings::setAudiocodecs(result);
                    //kDebug()<<"// FOUND LIST:\n\n"<<m_audioCodecs<<"\n\n++++++++++++++++++++";
                }
                // Check video codecs
                checkProcess2.start(KdenliveSettings::rendererpath(), QStringList() << "noise:" << "-consumer" << "avformat" << "vcodec=list");
                if (!checkProcess2.waitForStarted()) {
                    kDebug() << "// Error parsing MLT's avformat codecs";
                } else {
                    checkProcess2.waitForFinished();
                    QByteArray codecList = checkProcess2.readAllStandardError();
                    QString vcodecList(codecList);
                    QStringList result;
                    QStringList vlist = vcodecList.split('\n', QString::SkipEmptyParts);
                    for (int i = 0; i < vlist.count(); i++) {
                        if (vlist.at(i).contains("- ")) result.append(vlist.at(i).section("- ", 1).simplified().toLower());
                    }
                    m_mltCheck.vcodecs_list->addItems(result);
                    KdenliveSettings::setVideocodecs(result);
                    //kDebug()<<"// FOUND LIST:\n\n"<<m_videoCodecs<<"\n\n++++++++++++++++++++";
                }
                // Check formats
                checkProcess2.start(KdenliveSettings::rendererpath(), QStringList() << "noise:" << "-consumer" << "avformat" << "f=list");
                if (!checkProcess2.waitForStarted()) {
                    kDebug() << "// Error parsing MLT's avformat codecs";
                } else {
                    checkProcess2.waitForFinished();
                    QByteArray codecList = checkProcess2.readAllStandardError();
                    QString vcodecList(codecList);
                    QStringList result;
                    QStringList vlist = vcodecList.split('\n', QString::SkipEmptyParts);
                    for (int i = 0; i < vlist.count(); i++) {
                        if (vlist.at(i).contains("- ")) {
                            QString format = vlist.at(i).section("- ", 1).simplified().toLower();
                            if (format.contains(',')) {
                                QStringList sub = format.split(',', QString::SkipEmptyParts);
                                for (int j = 0; j < sub.count(); j++)
                                    result.append(sub.at(j));
                            } else result.append(format);
                        }
                    }
                    m_mltCheck.formats_list->addItems(result);
                    KdenliveSettings::setSupportedformats(result);
                    //kDebug()<<"// FOUND LIST:\n\n"<<m_videoCodecs<<"\n\n++++++++++++++++++++";
                }
            }

        }

        // Check MLT dv module
        QTreeWidgetItem *dvItem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("DV module (libdv)"));
        dvItem->setData(1, Qt::UserRole, i18n("Required to work with dv files if avformat module is not installed"));
        dvItem->setSizeHint(0, itemSize);
        if (!result.contains("- libdv")) {
            dvItem->setIcon(0, m_badIcon);
        } else {
            dvItem->setIcon(0, m_okIcon);
        }

        // Check MLT image format module
        QTreeWidgetItem *imageItem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("QImage module"));
        imageItem->setData(1, Qt::UserRole, i18n("Required to work with images"));
        imageItem->setSizeHint(0, itemSize);
        if (!result.contains("- qimage")) {
            imageItem->setIcon(0, m_badIcon);
            imageItem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("Pixbuf module"));
            imageItem->setData(1, Qt::UserRole, i18n("Required to work with images"));
            imageItem->setSizeHint(0, itemSize);
            if (!result.contains("- pixbuf")) imageItem->setIcon(0, m_badIcon);
            else imageItem->setIcon(0, m_okIcon);
        } else {
            imageItem->setIcon(0, m_okIcon);
        }
    }
}
Example #21
0
    foreach (const TestConfiguration *testConfiguration, selectedTests) {
        QScopedPointer<TestOutputReader> outputReader;
        switch (testConfiguration->testType()) {
        case TestTypeQt:
            outputReader.reset(new QtTestOutputReader(futureInterface, &testProcess,
                                                      testConfiguration->buildDirectory()));
            break;
        case TestTypeGTest:
            outputReader.reset(new GTestOutputReader(futureInterface, &testProcess,
                                                     testConfiguration->buildDirectory()));
            break;
        }
        if (futureInterface.isCanceled())
            break;

        if (!testConfiguration->project())
            continue;

        QProcessEnvironment environment = testConfiguration->environment().toProcessEnvironment();
        QString commandFilePath = executableFilePath(testConfiguration->targetFile(), environment);
        if (commandFilePath.isEmpty()) {
            futureInterface.reportResult(TestResultPtr(new FaultyTestResult(Result::MessageFatal,
                QObject::tr("Could not find command \"%1\". (%2)")
                                                   .arg(testConfiguration->targetFile())
                                                   .arg(testConfiguration->displayName()))));
            continue;
        }

        if (testConfiguration->testType() == TestTypeQt) {
            QStringList argumentList(QLatin1String("-xml"));
            if (!metricsOption.isEmpty())
                argumentList << metricsOption;
            if (testConfiguration->testCases().count())
                argumentList << testConfiguration->testCases();
            testProcess.setArguments(argumentList);
        } else { // TestTypeGTest
            QStringList argumentList;
            const QStringList &testSets = testConfiguration->testCases();
            if (testSets.size()) {
                argumentList << QLatin1String("--gtest_filter=")
                                + testSets.join(QLatin1Char(':'));
            }
            if (settings.gtestRunDisabled)
                argumentList << QLatin1String("--gtest_also_run_disabled_tests");
            if (settings.gtestRepeat)
                argumentList << QString::fromLatin1("--gtest_repeat=%1").arg(settings.gtestIterations);
            if (settings.gtestShuffle) {
                argumentList << QLatin1String("--gtest_shuffle");
                argumentList << QString::fromLatin1("--gtest_random_seed=%1").arg(settings.gtestSeed);
            }
            testProcess.setArguments(argumentList);
        }

        testProcess.setWorkingDirectory(testConfiguration->workingDirectory());
        if (Utils::HostOsInfo::isWindowsHost())
            environment.insert(QLatin1String("QT_LOGGING_TO_CONSOLE"), QLatin1String("1"));
        testProcess.setProcessEnvironment(environment);
        testProcess.setProgram(commandFilePath);
        testProcess.start();

        bool ok = testProcess.waitForStarted();
        QTime executionTimer;
        executionTimer.start();
        bool canceledByTimeout = false;
        if (ok) {
            while (testProcess.state() == QProcess::Running) {
                if (executionTimer.elapsed() >= timeout) {
                    canceledByTimeout = true;
                    break;
                }
                if (futureInterface.isCanceled()) {
                    testProcess.kill();
                    testProcess.waitForFinished();
                    return;
                }
                eventLoop.processEvents();
            }
        }

        if (canceledByTimeout) {
            if (testProcess.state() != QProcess::NotRunning) {
                testProcess.kill();
                testProcess.waitForFinished();
            }
            futureInterface.reportResult(TestResultPtr(
                    new FaultyTestResult(Result::MessageFatal, QObject::tr(
                    "Test case canceled due to timeout. \nMaybe raise the timeout?"))));
        }
    }
Example #22
0
void TestAusmt::initTestCase()
{
    // Dirs
    QDir srcDir (QStandardPaths::writableLocation(QStandardPaths::TempLocation));
    if (!srcDir.exists(AUSMTSRC_SUBDIR)) {
        QVERIFY(srcDir.mkdir(AUSMTSRC_SUBDIR));
    }
    QVERIFY(srcDir.cd(AUSMTSRC_SUBDIR));

    GET_DIR;
    GET_VAR_DIR;
    GET_FILES_DIR;
    GET_PATCHES_DIR;

    // Dump AUSMT into src dir
    QDir ausmtResDir (":/ausmtsrc/");
    foreach (const QString &fileName, ausmtResDir.entryList(QDir::Files)) {
        QFile file (ausmtResDir.absoluteFilePath(fileName));
        if (srcDir.exists(fileName)) {
            QVERIFY(QFileInfo(srcDir.absoluteFilePath(fileName)).isFile());
            QVERIFY(srcDir.remove(fileName));
        }
        QVERIFY(file.copy(srcDir.absoluteFilePath(fileName)));
    }

    QDir ausmtTestResDir (":/ausmtsrc-test/");
    foreach (const QString &fileName, ausmtTestResDir.entryList(QDir::Files)) {
        QFile file (ausmtTestResDir.absoluteFilePath(fileName));
        if (srcDir.exists(fileName)) {
            QVERIFY(QFileInfo(srcDir.absoluteFilePath(fileName)).isFile());
            QVERIFY(srcDir.remove(fileName));
        }
        QVERIFY(file.copy(srcDir.absoluteFilePath(fileName)));
    }

    // Make a better constants_root.sh
    QFile constantsRoot (srcDir.absoluteFilePath(CONSTANTS_ROOT_SH));
    QVERIFY(constantsRoot.open(QIODevice::WriteOnly));
    QTextStream constantsRootStream (&constantsRoot);
    constantsRootStream << QString("AUSMT_VAR_DIR=%1\n").arg(varDir.absolutePath());
    constantsRootStream << QString("PATCH_ROOT_DIR=%1\n").arg(patchesDir.absolutePath());
    constantsRootStream << QString("FILES_DIR=%1\n").arg(filesDir.absolutePath());
    constantsRootStream << QString("NOTIFY_WRAPPER_EXEC=echo\n");
    constantsRoot.close();

    // Build AUSMT
    QString buildName = srcDir.absoluteFilePath(BUILD_SH);
    QFile build (buildName);
    QVERIFY(build.exists());
    QVERIFY(build.setPermissions(QFileDevice::ReadUser | QFileDevice::WriteUser | QFileDevice::ExeUser));
    QProcess buildProcess;
    buildProcess.setWorkingDirectory(srcDir.absolutePath());
    buildProcess.start(PYTHON, QStringList() << buildName);
    buildProcess.waitForFinished(-1);
    QCOMPARE(buildProcess.exitCode(), 0);

    foreach (const QString &fileName, dir.entryList(QDir::Files)) {
        QFile file (dir.absoluteFilePath(fileName));
        QVERIFY(file.setPermissions(QFileDevice::ReadUser | QFileDevice::WriteUser | QFileDevice::ExeUser));
    }

    // Remove src
    QVERIFY(srcDir.removeRecursively());

    // Prepare patches
    preparePatches();
}
Example #23
0
  void updateINI(const String& infile, const String& outfile)
  {
    Int this_instance = getIntOption_("instance");
    INIUpdater updater;
    String tmp_ini_file = File::getTempDirectory() + "/" + File::getUniqueName() + "_INIUpdater.ini";
    tmp_files_.push_back(tmp_ini_file);

    String path = File::getExecutablePath();

    Param p;
    ParamXMLFile paramFile;
    paramFile.load(infile, p);
    // get sections (usually there is only one - or the user has merged INI files manually)
    StringList sections = updater.getToolNamesFromINI(p);

    if (sections.empty())
    {
      writeLog_("Update for file " + infile + " failed because tool section does not exist. Check INI file for corruption!");
      failed_.push_back(infile);
      return;
    }

    // get version of first section
    String version_old = "Unknown";
    if (!p.exists(sections[0] + ":version"))
    {
      writeLog_("No OpenMS version information found in file " + infile + "! Cannot update!");
      failed_.push_back(infile);
      return;
    }
    else
    {
      version_old = p.getValue(sections[0] + ":version");
      // TODO: return on newer version?!
    }


    // update sections
    writeDebug_("Section names: " + ListUtils::concatenate(sections, ", "), 1);
    bool update_success = true;
    for (Size s = 0; s < sections.size(); ++s)
    {
      String sec_inst = sections[s] + ":" + String(this_instance) + ":";
      // check for default instance
      if (!p.exists(sec_inst + "debug"))
      {
        writeLog_("Update for file '" + infile + "' failed because the instance section '" + sec_inst + "' does not exist. Use -instance or check INI file for corruption!");
        update_success = false;
        break;
      }
      String new_tool;
      String ttype;
      // find mapping to new tool (might be the same name)
      if (p.exists(sec_inst + "type")) ttype = p.getValue(sec_inst + "type");
      if (!updater.getNewToolName(sections[s], ttype, new_tool))
      {
        String type_text = ((ttype == "") ? "" : " with type '" + ttype + "' ");
        writeLog_("Update for file '" + infile + "' failed because the tool '" + sections[s] + "'" + type_text + "is unknown. TOPPAS file seems to be corrupted!");
        update_success = false;
        break;
      }
      // get defaults of new tool by calling it
      QProcess pr;
      QStringList arguments;
      arguments << "-write_ini";
      arguments << tmp_ini_file.toQString();
      arguments << "-instance";
      arguments << String(this_instance).toQString();
      pr.start((path + "/" + new_tool).toQString(), arguments);
      if (!pr.waitForFinished(-1))
      {
        writeLog_("Update for file '" + infile + "' failed because the tool '" + new_tool + "' returned with an error! Check if the tool works properly.");
        update_success = false;
        break;
      }

      // update defaults with old values
      Param new_param;
      paramFile.load(tmp_ini_file, new_param);
      new_param = new_param.copy(new_tool, true);
      Param old_param = p.copy(sections[s], true);
      new_param.update(old_param);
      // push back changes
      p.remove(sections[s] + ":");
      p.insert(new_tool, new_param);
    }

    if (!update_success)
    {
      failed_.push_back(infile);
      return;
    }

    // STORE
    if (outfile.empty()) // create a backup
    {
      QFileInfo fi(infile.toQString());
      String backup_filename = String(fi.path()) + "/" + fi.completeBaseName() + "_v" + version_old + ".ini";
      QFile::rename(infile.toQString(), backup_filename.toQString());
      std::cout << "Backup of input file created: " << backup_filename << std::endl;
      // write updated/new file
      paramFile.store(infile, p);
    }
    else
    {
      paramFile.store(outfile, p);
    }
  }
const AudioFileModel& AnalyzeTask::analyzeMediaFile(const QString &filePath, AudioFileModel &audioFile)
{
	//bool skipNext = false;
	QPair<quint32, quint32> id_val(UINT_MAX, UINT_MAX);
	quint32 coverType = UINT_MAX;
	QByteArray coverData;

	QStringList params;
	params << L1S("--Language=raw") << L1S("--Output=XML") << L1S("--Full") << L1S("--Cover_Data=base64");
	params << QDir::toNativeSeparators(filePath);

	QProcess process;
	MUtils::init_process(process, QFileInfo(m_mediaInfoBin).absolutePath());
	process.start(m_mediaInfoBin, params);

	QByteArray data;
	data.reserve(16384);

	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(MUTILS_BOOLIFY(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 the process now!");
				process.kill();
				process.waitForFinished(-1);
				break;
			}
		}

		forever
		{
			const QByteArray dataNext = process.readAll();
			if (dataNext.isEmpty()) {
				break; /*no more input data*/
			}
			data += dataNext.trimmed();
		}
	}

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

	while (!process.atEnd())
	{
		const QByteArray dataNext = process.readAll();
		if (dataNext.isEmpty()) {
			break; /*no more input data*/
		}
		data += dataNext.trimmed();
	}

#if MUTILS_DEBUG
	qDebug("-----BEGIN MEDIAINFO-----\n%s\n-----END MEDIAINFO-----", data.constData());
#endif //MUTILS_DEBUG

	return parseMediaInfo(data, audioFile);
}
Example #25
0
bool SSHConnectionCLI::executeSSH(const QString& command,
                                  const QStringList& args, QString* stdout_str,
                                  QString* stderr_str, int* ec)
{
  QProcess proc;

  QStringList fullArgs;

  // Add username
  if (!m_user.isEmpty())
    fullArgs << "-l" << m_user;

  // Add port number
  fullArgs << "-p" << QString::number(m_port);

  // Add hostname
  fullArgs << m_host;

  // Add command and original arguments
  fullArgs << command;
  fullArgs << args;

  proc.start("ssh", fullArgs);
  int timeout_ms = 60000; // one minute

  if (!proc.waitForStarted(timeout_ms)) {
    qWarning() << QString("Failed to start ssh command with args \"%1\" "
                          "after %2 seconds.")
                    .arg(fullArgs.join(","))
                    .arg(timeout_ms / 1000);
    return false;
  }

  proc.closeWriteChannel();
  if (!proc.waitForFinished(timeout_ms)) {
    qWarning() << QString("ssh command with args \"%1\" failed to finish "
                          "within %2 seconds.")
                    .arg(fullArgs.join(","))
                    .arg(timeout_ms / 1000);
    return false;
  }

  if (proc.exitCode() == 255) {
    qWarning() << QString("ssh command with args \"%1\" returned an exit "
                          "code of 255. This usually means that ssh failed "
                          "to connect, but it may also be a valid exit code"
                          " for the command which was run. Assuming that "
                          "ssh has errored. Contact the development team "
                          "if you believe this is an error.")
                    .arg(fullArgs.join(","))
               << "\nstdout:\n"
               << QString(proc.readAllStandardOutput()) << "\nstderr:\n"
               << QString(proc.readAllStandardError());
    return false;
  }

  if (stdout_str != nullptr)
    *stdout_str = QString(proc.readAllStandardOutput());
  if (stderr_str != nullptr)
    *stderr_str = QString(proc.readAllStandardError());
  if (ec != nullptr)
    *ec = proc.exitCode();

  proc.close();

  return true;
}
bool AnalyzeTask::analyzeAvisynthFile(const QString &filePath, AudioFileModel &info)
{
	QProcess process;
	MUtils::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(MUTILS_BOOLIFY(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;
			}
		}

		while(process.canReadLine())
		{
			const QString line = QString::fromUtf8(process.readLine().constData()).simplified();
			if(!line.isEmpty())
			{
				if(bInfoHeaderFound)
				{
					const qint32 index = line.indexOf(':');
					if (index > 0)
					{
						const QString key = line.left(index).trimmed();
						const QString val = line.mid(index + 1).trimmed();
						if (!(key.isEmpty() || val.isEmpty()))
						{
							switch (m_avisynthIdx.value(key.toLower(), MI_propertyId_t(-1)))
							{
								case propertyId_duration:     SET_OPTIONAL(quint32, parseUnsigned(val, _tmp), info.techInfo().setDuration(_tmp));        break;
								case propertyId_samplingrate: SET_OPTIONAL(quint32, parseUnsigned(val, _tmp), info.techInfo().setAudioSamplerate(_tmp)); break;
								case propertyId_channel_s_:   SET_OPTIONAL(quint32, parseUnsigned(val, _tmp), info.techInfo().setAudioChannels(_tmp));   break;
								case propertyId_bitdepth:     SET_OPTIONAL(quint32, parseUnsigned(val, _tmp), info.techInfo().setAudioBitdepth(_tmp));   break;
							}
						}
					}
				}
				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;
	}
}
Example #27
0
void QgsGPSPlugin::importGPSFile( const QString &inputFileName, QgsBabelFormat *importer,
                                  bool importWaypoints, bool importRoutes,
                                  bool importTracks, const QString &outputFileName,
                                  const QString &layerName )
{
  // what features does the user want to import?
  QString typeArg;
  if ( importWaypoints )
    typeArg = QStringLiteral( "-w" );
  else if ( importRoutes )
    typeArg = QStringLiteral( "-r" );
  else if ( importTracks )
    typeArg = QStringLiteral( "-t" );

  // try to start the gpsbabel process
  QStringList babelArgs =
    importer->importCommand( mBabelPath, typeArg,
                             inputFileName, outputFileName );

  QgsDebugMsg( QString( "Import command: " ) + babelArgs.join( "|" ) );

  QProcess babelProcess;
  babelProcess.start( babelArgs.join( QStringLiteral( " " ) ) );
  if ( !babelProcess.waitForStarted() )
  {
    QMessageBox::warning( nullptr, tr( "Could not start process" ),
                          tr( "Could not start GPSBabel!" ) );
    return;
  }

  // wait for gpsbabel to finish (or the user to cancel)
  QProgressDialog progressDialog( tr( "Importing data..." ), tr( "Cancel" ), 0, 0 );
  progressDialog.setWindowModality( Qt::WindowModal );
  for ( int i = 0; babelProcess.state() == QProcess::Running; ++i )
  {
    progressDialog.setValue( i / 64 );
    if ( progressDialog.wasCanceled() )
      return;
  }

  babelProcess.waitForFinished();

  // did we get any data?
  if ( babelProcess.exitCode() != 0 )
  {
    QString babelError( babelProcess.readAllStandardError() );
    QString errorMsg( tr( "Could not import data from %1!\n\n" )
                      .arg( inputFileName ) );
    errorMsg += babelError;
    QMessageBox::warning( nullptr, tr( "Error importing data" ), errorMsg );
    return;
  }

  // add the layer
  if ( importTracks )
    emit drawVectorLayer( outputFileName + "?type=track",
                          layerName, QStringLiteral( "gpx" ) );
  if ( importRoutes )
    emit drawVectorLayer( outputFileName + "?type=route",
                          layerName, QStringLiteral( "gpx" ) );
  if ( importWaypoints )
    emit drawVectorLayer( outputFileName + "?type=waypoint",
                          layerName, QStringLiteral( "gpx" ) );

  emit closeGui();
}
Example #28
0
// 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();
}
Example #29
0
/**
 * Starting point for the retracing thread.
 *
 * Overrides QThread::run().
 */
void Retracer::run()
{
    QString msg = QLatin1String("Replay finished!");

    /*
     * Construct command line
     */

    QString prog;
    QStringList arguments;

    switch (m_api) {
    case trace::API_GL:
        prog = QLatin1String("glretrace");
        break;
    case trace::API_EGL:
        prog = QLatin1String("eglretrace");
        break;
    case trace::API_DX:
    case trace::API_D3D7:
    case trace::API_D3D8:
    case trace::API_D3D9:
    case trace::API_DXGI:
#ifdef Q_OS_WIN
        prog = QLatin1String("d3dretrace");
#else
        prog = QLatin1String("wine");
        arguments << QLatin1String("d3dretrace.exe");
#endif
        break;
    default:
        emit finished(QLatin1String("Unsupported API"));
        return;
    }

    if (m_singlethread) {
        arguments << QLatin1String("--singlethread");
    }

    if (m_captureState) {
        arguments << QLatin1String("-D");
        arguments << QString::number(m_captureCall);
    } else if (m_captureThumbnails) {
        arguments << QLatin1String("-s"); // emit snapshots
        arguments << QLatin1String("-"); // emit to stdout
    } else if (isProfiling()) {
        if (m_profileGpu) {
            arguments << QLatin1String("--pgpu");
        }

        if (m_profileCpu) {
            arguments << QLatin1String("--pcpu");
        }

        if (m_profilePixels) {
            arguments << QLatin1String("--ppd");
        }
    } else {
        if (m_doubleBuffered) {
            arguments << QLatin1String("--db");
        } else {
            arguments << QLatin1String("--sb");
        }

        if (m_benchmarking) {
            arguments << QLatin1String("-b");
        }
    }

    arguments << m_fileName;

    /*
     * Support remote execution on a separate target.
     */

    if (m_remoteTarget.length() != 0) {
        arguments.prepend(prog);
        arguments.prepend(m_remoteTarget);
        prog = QLatin1String("ssh");
    }

    /*
     * Start the process.
     */

    QProcess process;

    process.start(prog, arguments, QIODevice::ReadOnly);
    if (!process.waitForStarted(-1)) {
        emit finished(QLatin1String("Could not start process"));
        return;
    }

    /*
     * Process standard output
     */

    QList<QImage> thumbnails;
    QVariantMap parsedJson;
    trace::Profile* profile = NULL;

    process.setReadChannel(QProcess::StandardOutput);
    if (process.waitForReadyRead(-1)) {
        BlockingIODevice io(&process);

        if (m_captureState) {
            /*
             * Parse JSON from the output.
             *
             * XXX: QJSON's scanner is inneficient as it abuses single
             * character QIODevice::peek (not cheap), instead of maintaining a
             * lookahead character on its own.
             */

            bool ok = false;
            QJson::Parser jsonParser;

            // Allow Nan/Infinity
            jsonParser.allowSpecialNumbers(true);
#if 0
            parsedJson = jsonParser.parse(&io, &ok).toMap();
#else
            /*
             * XXX: QJSON expects blocking IO, and it looks like
             * BlockingIODevice does not work reliably in all cases.
             */
            process.waitForFinished(-1);
            parsedJson = jsonParser.parse(&process, &ok).toMap();
#endif
            if (!ok) {
                msg = QLatin1String("failed to parse JSON");
            }
        } else if (m_captureThumbnails) {
            /*
             * Parse concatenated PNM images from output.
             */

            while (!io.atEnd()) {
                image::PNMInfo info;

                char header[512];
                qint64 headerSize = 0;
                int headerLines = 3; // assume no optional comment line

                for (int headerLine = 0; headerLine < headerLines; ++headerLine) {
                    qint64 headerRead = io.readLine(&header[headerSize], sizeof(header) - headerSize);

                    // if header actually contains optional comment line, ...
                    if (headerLine == 1 && header[headerSize] == '#') {
                        ++headerLines;
                    }

                    headerSize += headerRead;
                }

                const char *headerEnd = image::readPNMHeader(header, headerSize, info);

                // if invalid PNM header was encountered, ...
                if (headerEnd == NULL ||
                    info.channelType != image::TYPE_UNORM8) {
                    qDebug() << "error: invalid snapshot stream encountered";
                    break;
                }

                unsigned channels = info.channels;
                unsigned width = info.width;
                unsigned height = info.height;

                // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height";

                QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888);

                int rowBytes = channels * width;
                for (int y = 0; y < height; ++y) {
                    unsigned char *scanLine = snapshot.scanLine(y);
                    qint64 readBytes = io.read((char *) scanLine, rowBytes);
                    Q_ASSERT(readBytes == rowBytes);
                    (void)readBytes;
                }

                QImage thumb = thumbnail(snapshot);
                thumbnails.append(thumb);
            }

            Q_ASSERT(process.state() != QProcess::Running);
        } else if (isProfiling()) {
            profile = new trace::Profile();

            while (!io.atEnd()) {
                char line[256];
                qint64 lineLength;

                lineLength = io.readLine(line, 256);

                if (lineLength == -1)
                    break;

                trace::Profiler::parseLine(line, profile);
            }
        } else {
            QByteArray output;
            output = process.readAllStandardOutput();
            if (output.length() < 80) {
                msg = QString::fromUtf8(output);
            }
        }
    }

    /*
     * Wait for process termination
     */

    process.waitForFinished(-1);

    if (process.exitStatus() != QProcess::NormalExit) {
        msg = QLatin1String("Process crashed");
    } else if (process.exitCode() != 0) {
        msg = QLatin1String("Process exited with non zero exit code");
    }

    /*
     * Parse errors.
     */

    QList<ApiTraceError> errors;
    process.setReadChannel(QProcess::StandardError);
    QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$");
    while (!process.atEnd()) {
        QString line = process.readLine();
        if (regexp.indexIn(line) != -1) {
            ApiTraceError error;
            error.callIndex = regexp.cap(1).toInt();
            error.type = regexp.cap(2);
            error.message = regexp.cap(3);
            errors.append(error);
        } else if (!errors.isEmpty()) {
            // Probably a multiligne message
            ApiTraceError &previous = errors.last();
            if (line.endsWith("\n")) {
                line.chop(1);
            }
            previous.message.append('\n');
            previous.message.append(line);
        }
    }

    /*
     * Emit signals
     */

    if (m_captureState) {
        ApiTraceState *state = new ApiTraceState(parsedJson);
        emit foundState(state);
    }

    if (m_captureThumbnails && !thumbnails.isEmpty()) {
        emit foundThumbnails(thumbnails);
    }

    if (isProfiling() && profile) {
        emit foundProfile(profile);
    }

    if (!errors.isEmpty()) {
        emit retraceErrors(errors);
    }

    emit finished(msg);
}
Example #30
0
/** ***************************************************************************/
bool Applications::Application::readDesktopEntry() {
    // TYPES http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s05.html
    map<QString,map<QString,QString>> values;

    // Read the file
    QFile desktopFile(_path);
    if (desktopFile.open(QIODevice::ReadOnly| QIODevice::Text)) {
        QTextStream stream(&desktopFile);
        QString key;
        QString value;
        QString currentGroup;
        for (QString line=stream.readLine(); !line.isNull(); line=stream.readLine()) {
            line = line.trimmed();

            if (line.startsWith('#') || line.isEmpty())
                continue;

            // Check for groups
            if (line.startsWith("[")){
                currentGroup = line.mid(1,line.size()-2);
                continue;
            }

            key = line.section('=', 0,0).trimmed();
            value = line.section('=', 1, -1).trimmed();
            values[currentGroup][key]=value;
        }
        desktopFile.close();
    } else return false;


    if (values["Desktop Entry"]["NoDisplay"] == "true")
        return false;


    // Try to get the (localized name)
    QString locale = QLocale().name();
    QString shortLocale = locale.left(2);
    if (values["Desktop Entry"].count(QString("Name[%1]").arg(locale)))
        _name = values["Desktop Entry"][QString("Name[%1]").arg(locale)];
    else if (values["Desktop Entry"].count(QString("Name[%1]").arg(shortLocale)))
        _name = values["Desktop Entry"][QString("Name[%1]").arg(shortLocale)];
    else if (values["Desktop Entry"].count("Name"))
        _name = values["Desktop Entry"]["Name"];
    else return false;


    // Try to get the command
    if (values["Desktop Entry"].count("Exec"))
        _exec = values["Desktop Entry"]["Exec"];
    else return false;
    _exec.replace("%c", _name);
    _exec.remove(QRegExp("%.")); // Todo standard conform http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html

    _term = values["Desktop Entry"]["Terminal"] == "true";

    // Try to get the icon
    if (values["Desktop Entry"].count("Icon"))
        _icon = getIcon(values["Desktop Entry"]["Icon"]);
    else {
        qWarning() << "No icon specified in " << _path;
        _icon = QIcon::fromTheme("exec");
    }


    // Try to get any [localized] secondary information comment
    if (values["Desktop Entry"].count(QString("Comment[%1]").arg(locale)))
        _altName = values["Desktop Entry"][QString("Comment[%1]").arg(locale)];
    else if (values["Desktop Entry"].count(QString("Comment[%1]").arg(shortLocale)))
        _altName = values["Desktop Entry"][QString("Comment[%1]").arg(shortLocale)];
    else if (values["Desktop Entry"].count("Comment"))
        _altName = values["Desktop Entry"]["Comment"];
    else if (values["Desktop Entry"].count(QString("GenericName[%1]").arg(locale)))
        _altName = values["Desktop Entry"][QString("GenericName[%1]").arg(locale)];
    else if (values["Desktop Entry"].count(QString("GenericName[%1]").arg(shortLocale)))
        _altName = values["Desktop Entry"][QString("GenericName[%1]").arg(shortLocale)];
    else if (values["Desktop Entry"].count("GenericName"))
        _altName = values["Desktop Entry"]["GenericName"];
    else
        _altName = _exec;

    // No additional actions for terminal apps
    if(_term)
        return true;

    // Root actions
    QStringList graphicalSudos({"gksu", "kdesu"});
    for (const QString &s : graphicalSudos){
        QProcess p;
        p.start("which", {s});
        p.waitForFinished(-1);
        if (p.exitCode() == 0)
            _actions.push_back(std::make_shared<DesktopAction>(this,
                                                               QString("Run %1 as root").arg(_name),
                                                               QString("%1 \"%2\"").arg(s, _exec),
                                                               _icon));
    }


    // Desktop entry actions
    if (values["Desktop Entry"].count("Actions")){
        QString actionsString = values["Desktop Entry"]["Actions"];
        QStringList actionStrings = actionsString.split(';',QString::SkipEmptyParts);
        QString name;
        QString exec;
        QString group;
        for (const QString &actionString: actionStrings){
            // Get the name
            group = QString("Desktop Action %1").arg(actionString);
            if (!values[group].count("Name")) continue;
            name = values[group]["Name"];

            // Get the command
            group = QString("Desktop Action %1").arg(actionString);
            if (!values[group].count("Exec")) continue;
            exec = values[group]["Exec"];

            // Try to get an icon
            group = QString("Desktop Action %1").arg(actionString);
            if (values[group].count("Icon"))
                _actions.push_back(std::make_shared<DesktopAction>(this, name, exec, getIcon(values[group]["Icon"])));
            else
                _actions.push_back(std::make_shared<DesktopAction>(this, name, exec, _icon));

        }
    }
    return true;
}