static inline bool performPatchApplication(const QString &patch, const QString &workingDirectory,
                                           bool reverse = false)
{
    QProcess process;
    process.setProgram(PATCH);
    process.setWorkingDirectory(workingDirectory);
    process.setStandardInputFile(patch);
    QStringList arguments;
    arguments << P1_FLAG << DRY_RUN_FLAG;
    if (!reverse) {
        arguments << T_FLAG << N_FLAG;
    } else {
        arguments << F_FLAG << R_FLAG;
    }
    process.setArguments(arguments);
    process.start();
    process.waitForFinished(-1);
    if (process.exitCode() != 0) {
        return false;
    }

    arguments.clear();
    arguments << P1_FLAG;
    if (!reverse) {
        arguments << T_FLAG << N_FLAG;
    } else {
        arguments << F_FLAG << R_FLAG;
    }
    process.setArguments(arguments);
    process.start();
    process.waitForFinished(-1);
    return (process.exitCode() == 0);
}
Example #2
0
void TestZot::testZot()
{
    QDir bin(QCoreApplication::applicationDirPath());
    QVERIFY(bin.exists());

    QDir examples(bin.path() + "/../../examples");
    QVERIFY(examples.exists());

    QProcess zot;
    zot.setProgram(bin.path() + QDir::separator() + "zot");

    // reverser
    QStringList args = QStringList()
      << "--file"
      << examples.path() + "/reverser.zot"
      << "--input"
      << "111000";

    zot.setArguments(args);
    zot.start();
    QVERIFY(zot.waitForFinished());
    QCOMPARE(zot.exitStatus(), QProcess::NormalExit);
    QCOMPARE(zot.exitCode(), 0);
    QCOMPARE(zot.state(), QProcess::NotRunning);
    QCOMPARE(zot.readAll(), QByteArray("000111\n"));
}
Calamares::JobResult
ClearMountsJob::exec()
{
    QStringList goodNews;

    QString deviceName = m_device->deviceNode().split( '/' ).last();

    QProcess process;
    process.setProgram( "sh" );
    process.setArguments( {
                              "-c",
                              QString( "echo $(awk '{print $4}' /proc/partitions | sed -e '/name/d' -e '/^$/d' -e '/[1-9]/!d' | grep %1)" )
                                      .arg( deviceName )
                          } );
    process.start();
    process.waitForFinished();

    QString partitions = process.readAllStandardOutput();
    QStringList partitionsList = partitions.simplified().split( ' ' );

    // Build a list of partitions of type 82 (Linux swap / Solaris).
    // We then need to clear them just in case they contain something resumable from a
    // previous suspend-to-disk.
    QStringList swapPartitions;
    process.start( "sfdisk", { "-d", m_device->deviceNode() } );
    process.waitForFinished();
    // Sample output:
    //    % sudo sfdisk -d /dev/sda
    //    label: dos
    //    label-id: 0x000ced89
    //    device: /dev/sda
    //    unit: sectors

    //    /dev/sda1 : start=          63, size=    29329345, type=83, bootable
    //    /dev/sda2 : start=    29331456, size=     2125824, type=82

    swapPartitions = QString::fromLocal8Bit( process.readAllStandardOutput() )
                        .split( '\n' );
    swapPartitions = swapPartitions.filter( "type=82" );
    for ( QStringList::iterator it = swapPartitions.begin();
          it != swapPartitions.end(); ++it )
    {
        *it = (*it).simplified().split( ' ' ).first();
    }

    // First we umount all LVM logical volumes we can find
    process.start( "lvscan", { "-a" } );
    process.waitForFinished();
    if ( process.exitCode() == 0 ) //means LVM2 tools are installed
    {
        QStringList lvscanLines = QString::fromLocal8Bit( process.readAllStandardOutput() ).split( '\n' );
        foreach ( const QString& lvscanLine, lvscanLines )
        {
            QString lvPath = lvscanLine.simplified().split( ' ' ).value( 1 ); //second column
            lvPath = lvPath.replace( '\'', "" );

            QString news = tryUmount( lvPath );
            if ( !news.isEmpty() )
                goodNews.append( news );
        }
Example #4
0
static Result runApp(const QString &execPath, const QStringList &args)
{
//   QString outPipePath = FS::TmpFilePath("pipeOut");
    QProcess app;
    app.setProgram(execPath);
    app.setArguments(args);
    app.start();

    if (!app.waitForStarted()) {
        qWarning() << "Cmd Exec Failed:" << app.errorString();
        return Result(Result::Failed, app.errorString(), "", app.program());
    }

    if (!app.waitForFinished(-1)) {
        qWarning() << "waitForFinished Failed:" << app.errorString();
        return Result(Result::Failed, app.errorString(), "", app.program());
    }

    auto standardError = app.readAllStandardError();

    if (QProcess::NormalExit != app.exitStatus()) {
        qWarning() << "exitStatus error:" << app.exitStatus() << standardError << app.program();
        return Result(Result::Failed, standardError, "", app.program());
    }

    if (0 != app.exitCode()) {
        qWarning() << "exitCode error:" << app.exitCode() << standardError << app.program();
        return Result(Result::Failed, standardError, "", app.program());
    }

    Result rest(Result::Success, standardError, app.readAllStandardOutput());
    return rest;
}
Example #5
0
void recursiveFileOpener(QFileInfo file, int & failures, int & total, int & timeOut, int argc, char *argv[])
{
	const QString jaspExtension(".jasp");

	//std::cout << "recursiveFileOpener in " << file.absoluteFilePath().toStdString() << std::endl;

	if(file.isDir())
	{
		//std::cout << "it is a directory and " << (file.exists() ? "exists" : "does not exist") << std::endl;

		QDir dir(file.absoluteFilePath());

		//std::cout << "QDir dir: " << dir.path().toStdString() << " has " << files.size() << " subfiles!" << std::endl;

		for(QFileInfo subFile : dir.entryInfoList(QDir::Filter::NoDotAndDotDot | QDir::Files | QDir::Dirs))
			recursiveFileOpener(subFile, failures, total, timeOut, argc, argv);

	}
	else if(file.isFile())
	{
		//std::cout << "it is a file" << std::endl;

		if(file.absoluteFilePath().indexOf(jaspExtension) == file.absoluteFilePath().size() - jaspExtension.size())
		{
			//std::cout << "it has the .jasp extension so we will start JASP" << std::endl;
#ifndef SEPARATE_PROCESS
			std::cout << "Found a JASP file (" << file.absoluteFilePath().toStdString() << ") going to start JASP" << std::endl;
#endif

			int result = 1;

			try{
#ifdef SEPARATE_PROCESS
				QProcess subJasp;
				subJasp.setProgram(argv[0]);
				subJasp.setArguments({file.absoluteFilePath(), "--unitTest", QString::fromStdString("--timeOut="+std::to_string(timeOut)), "-platform", "minimal" });
				subJasp.start();

				subJasp.waitForFinished((timeOut * 60000) + 10000);

				std::cerr << subJasp.readAllStandardError().toStdString() << std::endl;

				result = subJasp.exitCode();
#else
				//This seems to crash for some reason
				result = Application(argc, argv, file.absoluteFilePath(), true, timeOut).exec();
#endif
			}
			catch(...) { result = -1; }


			std::cout << "JASP file " << file.absoluteFilePath().toStdString() << (result == 0 ? " succeeded!" : " failed!") << std::endl;

			if(result != 0)
				failures++;

			total++;
		}
	}
}
Example #6
0
 Window() {
    m_layout.addWidget(&m_button);
    m_process.setProgram("sleep");
    m_process.setArguments({"5"});
    connect(&m_button, &QPushButton::clicked, &m_process, [=]{ m_process.start(); });
    connect(&m_process, (void(QProcess::*)(int))&QProcess::finished, [=]{ m_box.show(); });
 }
void MainWidget::setupClicked()
{
	if (ui->setupName->text().isEmpty())
	{
		return;
	}
	QProcess *process = createProcess();
	QStringList args;
	args << "setup";
	if (!ui->setupNem->text().isEmpty())
	{
		args << "--nem" << ui->setupNem->text();
	}
	if (!ui->setupCurse->text().isEmpty())
	{
		args << "--curse" << ui->setupCurse->text();
	}
	if (!ui->setupServer->text().isEmpty())
	{
		args << "--server" << ui->setupServer->text();
	}
	args << ui->setupName->text();
	process->setArguments(args);
	startProcess(process);
}
void KaduExtInfo::openMailComposer(const QString &link)
{
    kdebugf();
    QProcess *browser;
    QStringList args;
    QString mail = link;

    QString mailComposer = mailProgram;
    if (mailProgram.isEmpty())
    {
        /*QMessageBox::warning(0, qApp->translate("@default", QT_TR_NOOP("WWW error")),
            qApp->translate("@default", QT_TR_NOOP("Web browser was not specified. Visit the configuration section")));*/
        kdebugmf(KDEBUG_INFO, "Mail composer NOT specified.\n");
        return;
    }
    if (!mailComposer.contains("%1"))
        mailComposer.append(" \"%1\"");

    mail.replace("mailto:","");
    mailComposer.replace("%1", unicode2latinUrl(mail));

    args=toStringList("sh", "-c", mailComposer);

    CONST_FOREACH(i, args)
        kdebugmf(KDEBUG_INFO, "%s\n", (*i).local8Bit().data());
    browser = new QProcess(qApp);
    browser->setArguments(args);
    QObject::connect(browser, SIGNAL(processExited()), browser, SLOT(deleteLater()));

    if (!browser->start())
        QMessageBox::critical(0, tr("Mail error"), tr("Could not spawn Mail composer process. Check if the Mail program is functional"));

    kdebugf2();
}
void MainWidget::verifyClicked()
{
	if (files().isEmpty())
	{
		return;
	}
	QProcess *process = createProcess();
	process->setArguments(QStringList() << "verify" << files());
	startProcess(process);
}
Example #10
0
bool CodeManager::edit()
{
    QProcess *proc = new QProcess();
    QStringList args
        = QStringList::split(' ', Settings::instance()->editorCmd());
    args.append(filename());

    proc->setArguments(args);
    proc->setWorkingDirectory(QDir(sourcePath()));

    return proc->launch("");
}
void AccountsWorker::setPassword(User *user, const QString &oldpwd, const QString &passwd)
{
    QProcess process;
    process.setProgram("passwd");
    process.setArguments(QStringList() << user->name());
    process.start();
    process.write(QString("%1\n%2\n%3").arg(oldpwd).arg(passwd).arg(passwd).toLatin1());
    process.closeWriteChannel();
    process.waitForFinished();

    qDebug() << Q_FUNC_INFO << process.readAllStandardError() << process.readAllStandardOutput();

    Q_EMIT user->passwordModifyFinished(process.exitCode());
}
Example #12
0
bool PackageJobThread::installDependency(const QUrl &destUrl)
{
    auto handler = resolveHandler(destUrl.scheme());
    if (handler.isEmpty())
        return false;

    QProcess process;
    process.setProgram(handler);
    process.setArguments({ destUrl.toString() });
    process.setProcessChannelMode(QProcess::ForwardedChannels);
    process.start();
    process.waitForFinished();

    return process.exitCode() == 0;
}
Example #13
0
/**
  * Open the location of the path, launch a system file browser to the given directory path. If the path is a file then it will open it's containing directory and select it.
  *
  * An other on Windows is to use 'SHOpenFolderAndSelectItems(..)'.
  */
void Utils::openLocation(const QString& path)
{
#ifdef Q_OS_WIN32
    QProcess explorer;
    if (!QFileInfo(path).isDir())
        explorer.setArguments(QStringList() << "/select,");
    explorer.setNativeArguments("\"" + QDir::toNativeSeparators(path) + "\"");
    explorer.setProgram("explorer");
    explorer.start();
    explorer.waitForFinished(5000);
#else
    QFileInfo fileInfo(path);
    const QString dirPath = fileInfo.isDir() ? path : fileInfo.absolutePath();
    QDesktopServices::openUrl(QUrl("file:///" + dirPath, QUrl::TolerantMode));
#endif
}
Example #14
0
void MainWidget::createIndexClicked()
{
	if (files().isEmpty())
	{
		return;
	}
	QProcess *process = createProcess();
	QStringList args;
	args << "create-index";
	if (!ui->createIndexBaseUrl->text().isEmpty())
	{
		args << "--base" << ui->createIndexBaseUrl->text();
	}
	args << files();
	process->setArguments(args);
	startProcess(process);
}
Example #15
0
void MainWidget::updateClicked()
{
	if (files().isEmpty())
	{
		return;
	}
	QProcess *process = createProcess();
	QStringList args;
	args << "update";
	if (ui->updateNetworkBtn->isChecked())
	{
		args << "--no-network";
	}
	args << files();
	process->setArguments(args);
	startProcess(process);
}
Example #16
0
bool FindPDFImages(QProcess &pdfimagesProcess, const char* imageNames[]) {
   int index = 0;
   bool foundPdfImages = false;
   pdfimagesProcess.setArguments(QStringList("--version"));
   while(imageNames[index] != 0) {
      pdfimagesProcess.setProgram(imageNames[index]);
      pdfimagesProcess.start();
      pdfimagesProcess.waitForFinished(-1);
      if(pdfimagesProcess.error() == QProcess::UnknownError) {
         foundPdfImages = true;
         break;
      }
      qDebug() << "pdfimage executable not found" << imageNames[index];
      index++;
   }
   if(!foundPdfImages) {
      qWarning("pdfimage executable not found");
   }

   return foundPdfImages;
}
Example #17
0
unsigned char * resample( const QString & nrrd )
{
  voxmap_size /= rasterization_scale;
  tile_size /= rasterization_scale;

  QProcess proc;
  proc.setProgram( "unu" );
  proc.setArguments( QStringList()
                     << "resample"
                     << "-k" << "cubic:1,0"
                     << "-i" << nrrd
                     << "-s" << "="
                     << QString::number( voxmap_size.X() )
                     << QString::number( voxmap_size.Y() )
                     << QString::number( voxmap_size.Z() )
                     << "-o" << nrrd + ".resampled" );

  proc.start();
  if( !proc.waitForStarted( -1 ) || !proc.waitForFinished( -1 ) )
    return NULL;

  qint64 bytes =
    voxmap_size.X() * voxmap_size.Y() * voxmap_size.Z() * voxel_size;

  char * voxels = new char[ bytes ];

  QFile nf( nrrd + ".resampled" );
  if( !voxels ||
      !nf.open( QIODevice::ReadOnly ) ||
      nf.size() <= bytes )
    return NULL;

  nf.seek( nf.size() - bytes );
  if( nf.read( voxels, bytes ) != bytes )
    return NULL;

  return reinterpret_cast< unsigned char *>( voxels );
}
Example #18
0
QString runHof(const QString& file,
               const QString& input,
               bool* ok,
               bool verbose = false,
               int msecsToTimeout = 5000,
               Expectation e = Expectation::Normal)
{
    QDir bin(QCoreApplication::applicationDirPath());

    QProcess hof;
    hof.setProgram(bin.path() + QDir::separator() + "hof");

    QStringList args = QStringList()
      << "--file"
      << file
      << "--input"
      << input;

    if (verbose) {
        args.append("--verbose");
        hof.setProcessChannelMode(QProcess::ForwardedErrorChannel);
    }

    hof.setArguments(args);
    hof.start();
    bool finished = hof.waitForFinished(msecsToTimeout);
    if (!finished) {
        hof.kill();
        hof.waitForFinished();
    }

    /* special value used to indicate stack depth exceeded */
    switch (e) {
    case Expectation::Normal:
        {
            *ok = finished && hof.exitStatus() == QProcess::NormalExit &&
                  (hof.exitCode() == EXIT_SUCCESS || hof.exitCode() == 2);
            break;
        }
    case Expectation::NoCrash:
        {
            *ok = !finished || (hof.exitStatus() == QProcess::NormalExit &&
                  (hof.exitCode() == EXIT_SUCCESS || hof.exitCode() == 2));
            break;
        }
    case Expectation::Timeout:
        {
            *ok = !finished;
            break;
        }
    default:
        *ok = false;
        break;
    }

    if (!*ok) {
        qDebug() << "exit status:" << hof.exitStatus()
                 << " code:" << hof.exitCode()
                 << " error:" << hof.error();
    }

    return hof.readAll().trimmed();
}
Example #19
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 #20
0
QByteArray executeJob(const Job& job)
{
  QProcess sox;
  QProcess lame;

  // (1) SoX /////////////////////////////////////////////////////////////////

  sox.setProgram(job.soxExe);

  // Command Line: sox <input1> ... <inputN> -t wav -
#if defined(Q_OS_WIN)
  QString sox_args;
  foreach(const QString& input, job.inputFiles) {
    sox_args += _L1C('"');
    sox_args += input;
    sox_args += _L1C('"');
    sox_args += _L1C(' ');
  }
  sox_args += _L1("-t wav -"); // NOTE: Trailing <SPACE> Above!
  sox.setNativeArguments(sox_args);
#else
  QStringList sox_args;
  sox_args << job.inputFiles << _L1("-t") << _L1("wav") << _L1("-");
  sox.setArguments(sox_args);
#endif

  // (2) LAME ////////////////////////////////////////////////////////////////

  lame.setProgram(job.lameExe);

  // Command Line: lame <options> -S - <output>
#if defined(Q_OS_WIN)
  QString lame_args;
  lame_args += job.lameOptions;
  lame_args += _L1(" -S - ");
  lame_args += _L1C('"');
  lame_args += job.outputFile;
  lame_args += _L1C('"');
  lame.setNativeArguments(lame_args);
#else
  QStringList lame_args;
  lame_args << job.lameOptions << _L1("-S") << _L1("-") << job.outputFile;
  lame.setArguments(lame_args);
#endif

  // (3) Execute /////////////////////////////////////////////////////////////

  sox.setStandardOutputProcess(&lame);

  sox.start();
  lame.start();

  sox.waitForFinished(-1);
  lame.waitForFinished(-1);

  QByteArray result;
  result += sox.readAllStandardError();
  result += '\n';
  result += lame.readAllStandardError();

  if( job.renameInput ) {
    foreach(const QString& input, job.inputFiles) {
      QFile::rename(input, input+_L1(".done"));
    }
  }
Example #21
0
bool QUPDUpdater::isUpdateRequested()
{
    qDebug() << "isUpdateRequested";

    if (QSettings().contains(QUPD_UPDATED_VERSION_KEY)) {

        QFileInfo updatedFile (QSettings().value(QUPD_UPDATED_VERSION_KEY).toString());
        QFileInfo applicationFile ( qApp->applicationFilePath() );

#if defined Q_OS_MAC
        QDir dir = applicationFile.dir();
        dir.cdUp(); dir.cdUp();
        applicationFile = QFileInfo( dir.absolutePath() );

#elif defined Q_OS_WIN
        qt_ntfs_permission_lookup++; // Allow permissions verification os NTFS file system

#endif

        if (!updatedFile.exists()) {
            ; // TODO Error
        } else if (!applicationFile.isWritable()) {
            qDebug() << "Unwritable file, update aborted";
        } else {

#if defined Q_OS_WIN
            ;

#elif defined Q_OS_MAC
            QProcess process;
            process.setProgram("hdiutil");
            process.setArguments(QStringList() << "verify" << updatedFile.absoluteFilePath());
            process.start();
            process.waitForFinished();
            if (process.exitStatus() == QProcess::NormalExit) {
                QString mountPoint = applicationFile.absolutePath() + "/" + applicationFile.baseName();

                // Mount the downloaded dmg
                process.setProgram("hdiutil");
                process.setArguments(QStringList() << "attach" << "-mountpoint" << mountPoint << updatedFile.absoluteFilePath());
                process.start();
                process.waitForFinished(180000);
                qDebug() << process.exitStatus();
                qDebug() << process.readAllStandardError();

                // Replace the Application
                QString newFile(mountPoint + "/" +
                              qApp->applicationName() +".app");
                QString oldFile(applicationFile.absoluteFilePath());

                process.setProgram("rm");
                process.setArguments(QStringList() << "-rf" << oldFile);
                process.start();
                process.waitForFinished();
                process.exitStatus();

                process.setProgram("cp");
                process.setArguments(QStringList() << "-r" << newFile << oldFile);
                process.start();
                process.waitForFinished();

                // Unmount it
                process.setProgram("hdiutil");
                process.setArguments(QStringList() << "detach" << applicationFile.absolutePath() + "/" + applicationFile.baseName());
                process.start();
                process.waitForFinished();
                process.exitCode();
                process.exitStatus();
            }
#endif

        }

#if defined Q_OS_WIN
        qt_ntfs_permission_lookup--;
#endif

        QSettings().remove(QUPD_UPDATED_VERSION_KEY);
    }

    return false;
}
void MainWindowVideos::selected(IVideo * pVideo)
{
	// TODO merge with logic from channel

	QWidget * lPopup = new QWidget(this, Qt::Popup);
	QPushButton * lButton;

	lPopup->setAttribute(Qt::WA_DeleteOnClose);
	lPopup->setLayout(new QBoxLayout(QBoxLayout::TopToBottom, lPopup));

	lButton = new QPushButton(lPopup);
	lButton->setText("Watch!");
	QObject::connect(lButton, &QPushButton::clicked, [pVideo,lPopup]
	{
		lPopup->setEnabled(false);
		QUrl lUrl = pVideo->videoUrl(IVideo::URL_VIDEO_DIRECT);
		lPopup->close();

		if (!lUrl.isValid())
			return;

		QString lProgram;
		QStringList lArguments;
		lProgram = "/usr/bin/mpv";
		if (QFile::exists(lProgram))
		{
			lArguments << "--untimed";
			lArguments << "--quiet";
		}
		else
		{
			lProgram = "C:\\Program Files\\VideoLAN\\VLC\\vlc.exe";
			if (!QFile::exists(lProgram))
				lProgram = "C:\\Program Files\\VLC\\vlc.exe";
			if (!QFile::exists(lProgram))
				lProgram = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe";
			if (!QFile::exists(lProgram))
				lProgram = "C:\\Program Files (x86)\\VLC\\vlc.exe";
		}
		lArguments << lUrl.toString(QUrl::FullyEncoded);

		QProcess * lProcess = new QProcess();
		QObject::connect(lProcess, (void (QProcess::*) (int))&QProcess::finished, [lProcess] (int pExitCode) { lProcess->deleteLater(); });
		lProcess->setProcessChannelMode(QProcess::ForwardedChannels);
		lProcess->setProgram(lProgram);
		lProcess->setArguments(lArguments);
		lProcess->start();
	});
	lPopup->layout()->addWidget(lButton);

	lButton = new QPushButton(lPopup);
	lButton->setText("Open in browser");
	QObject::connect(lButton, &QPushButton::clicked, [pVideo,lPopup]
	{
		lPopup->setEnabled(false);
		QUrl lUrl = pVideo->videoUrl(IVideo::URL_VIDEO_WEBSITE);
		lPopup->close();

		if (!lUrl.isValid())
			return;

		QDesktopServices::openUrl(lUrl);
	});
	lPopup->layout()->addWidget(lButton);

	lButton = new QPushButton(lPopup);
	lButton->setText("Download ...");
	QObject::connect(lButton, &QPushButton::clicked, [pVideo,lPopup]
	{
		lPopup->setEnabled(false);
		IDownloader * lDownloader = pVideo->downloader();
		lPopup->close();

		if (lDownloader == nullptr)
			return;

		DownloadWindow * lWindow = new DownloadWindow(lDownloader);
		lWindow->setAttribute(Qt::WA_DeleteOnClose);
		lWindow->show();
	});
	lPopup->layout()->addWidget(lButton);

	lPopup->move(QCursor::pos() - QPoint(5, 10));
	lPopup->show();
}
Example #23
0
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    app.setApplicationName("ksvg2icns");
    app.setApplicationVersion(KICONTHEMES_VERSION_STRING);
    QCommandLineParser parser;
    parser.setApplicationDescription(app.translate("main", "Creates an icns file from an svg image"));
    parser.addPositionalArgument("iconname", app.translate("main", "The svg icon to convert"));
    parser.addHelpOption();

    parser.process(app);
    if (parser.positionalArguments().isEmpty()) {
        parser.showHelp();
        return 1;
    }

    bool isOk;

    // create a temporary dir to create an iconset
    QTemporaryDir tmpDir("ksvg2icns");
    tmpDir.setAutoRemove(true);

    isOk = tmpDir.isValid();
    EXIT_ON_ERROR(isOk, "Unable to create temporary directory\n");

    isOk = QDir(tmpDir.path()).mkdir("out.iconset");
    EXIT_ON_ERROR(isOk, "Unable to create out.iconset directory\n");

    const QString outPath = tmpDir.path() + "/out.iconset";

    const QStringList &args = app.arguments();
    EXIT_ON_ERROR(args.size() == 2,
                  "Usage: %s svg-image\n",
                  qPrintable(args.value(0)));

    const QString &svgFileName = args.at(1);

    // open the actual svg file
    QSvgRenderer svg;
    isOk = svg.load(svgFileName);
    EXIT_ON_ERROR(isOk, "Unable to load %s\n", qPrintable(svgFileName));

    // The sizes are from:
    // https://developer.apple.com/library/mac/documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/Optimizing/Optimizing.html

    struct OutFiles
    {
        int size;
        QString out1;
        QString out2;
    };

    // create the pngs in various resolutions
    const OutFiles outFiles[] = {
        { 1024, outPath + "/[email protected]", QString() },
        {  512, outPath + "/icon_512x512.png",    outPath + "/[email protected]" },
        {  256, outPath + "/icon_256x256.png",    outPath + "/[email protected]" },
        {  128, outPath + "/icon_128x128.png",    QString() },
        {   64, outPath + "/[email protected]",   QString() },
        {   32, outPath + "/icon_32x32.png",       outPath + "/[email protected]" },
        {   16, outPath + "/icon_16x16.png",       QString() }
    };

    for (size_t i = 0; i < sizeof(outFiles) / sizeof(OutFiles); ++i) {
        isOk = writeImage(svg, outFiles[i].size, outFiles[i].out1, outFiles[i].out2);
        if (!isOk) {
            return 1;
        }
    }

    // convert the iconset to icns using the "iconutil" command

    const QString outIcns = QFileInfo(svgFileName).baseName() + ".icns";

    const QStringList utilArgs = QStringList()
            << "-c" << "icns"
            << "-o" << outIcns
            << outPath;

    QProcess iconUtil;
    iconUtil.setProgram("iconUtil");
    iconUtil.setArguments(utilArgs);

    iconUtil.start("iconutil", utilArgs, QIODevice::ReadOnly);
    isOk = iconUtil.waitForFinished(-1);
    EXIT_ON_ERROR(isOk, "Unable to launch iconutil: %s\n", qPrintable(iconUtil.errorString()));

    EXIT_ON_ERROR(iconUtil.exitStatus() == QProcess::NormalExit, "iconutil crashed!\n");
    EXIT_ON_ERROR(iconUtil.exitCode() == 0, "iconutil returned %d\n", iconUtil.exitCode());

    return 0;
}