Calamares::JobResult
CreatePartitionTableJob::exec()
{
    Report report( 0 );
    QString message = tr( "The installer failed to create a partition table on %1." ).arg( m_device->name() );

    CoreBackend* backend = CoreBackendManager::self()->backend();
    QScopedPointer< CoreBackendDevice > backendDevice( backend->openDevice( m_device->deviceNode() ) );
    if ( !backendDevice.data() )
    {
        return Calamares::JobResult::error(
                   message,
                   tr( "Could not open device %1." ).arg( m_device->deviceNode() )
               );
    }

    QScopedPointer< PartitionTable > table( createTable() );
    cDebug() << "Creating new partition table of type" << table->typeName()
             << ", uncommitted yet:\n" << table;

    QProcess lsblk;
    lsblk.setProgram( "lsblk" );
    lsblk.setProcessChannelMode( QProcess::MergedChannels );
    lsblk.start();
    lsblk.waitForFinished();
    cDebug() << "lsblk:\n" << lsblk.readAllStandardOutput();

    QProcess mount;
    mount.setProgram( "mount" );
    mount.setProcessChannelMode( QProcess::MergedChannels );
    mount.start();
    mount.waitForFinished();
    cDebug() << "mount:\n" << mount.readAllStandardOutput();

    bool ok = backendDevice->createPartitionTable( report, *table );
    if ( !ok )
    {
        return Calamares::JobResult::error(
                    message,
                    QString( "Text: %1\nCommand: %2\nOutput: %3\nStatus: %4" )
                        .arg( report.toText() )
                        .arg( report.command() )
                        .arg( report.output() )
                        .arg( report.status() )
               );
    }

    return Calamares::JobResult::ok();
}
Example #2
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 #3
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;
}
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 #5
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(); });
 }
Example #6
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 );
        }
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
0
QProcess *MainWidget::createProcess()
{
	QProcess *process = new QProcess(this);
	process->setProgram(qApp->applicationFilePath());
	return process;
}
Example #17
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;
}
Example #18
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;
}
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 #20
0
OsproberEntryList
runOsprober( PartitionCoreModule* core )
{
    QString osproberOutput;
    QProcess osprober;
    osprober.setProgram( "os-prober" );
    osprober.setProcessChannelMode( QProcess::SeparateChannels );
    osprober.start();
    if ( !osprober.waitForStarted() )
    {
        cDebug() << "ERROR: os-prober cannot start.";
    }
    else if ( !osprober.waitForFinished( 60000 ) )
    {
        cDebug() << "ERROR: os-prober timed out.";
    }
    else
    {
        osproberOutput.append(
            QString::fromLocal8Bit(
                osprober.readAllStandardOutput() ).trimmed() );
    }

    QString osProberReport( "Osprober lines, clean:\n" );
    QStringList osproberCleanLines;
    OsproberEntryList osproberEntries;
    const auto lines = osproberOutput.split( '\n' );
    for ( const QString& line : lines )
    {
        if ( !line.simplified().isEmpty() )
        {
            QStringList lineColumns = line.split( ':' );
            QString prettyName;
            if ( !lineColumns.value( 1 ).simplified().isEmpty() )
                prettyName = lineColumns.value( 1 ).simplified();
            else if ( !lineColumns.value( 2 ).simplified().isEmpty() )
                prettyName = lineColumns.value( 2 ).simplified();

            QString path = lineColumns.value( 0 ).simplified();
            if ( !path.startsWith( "/dev/" ) ) //basic sanity check
                continue;

            FstabEntryList fstabEntries = lookForFstabEntries( path );
            QString homePath = findPartitionPathForMountPoint( fstabEntries, "/home" );

            osproberEntries.append( { prettyName,
                                      path,
                                      QString(),
                                      canBeResized( core, path ),
                                      lineColumns,
                                      fstabEntries,
                                      homePath } );
            osproberCleanLines.append( line );
        }
    }
    osProberReport.append( osproberCleanLines.join( '\n' ) );
    cDebug() << osProberReport;

    Calamares::JobQueue::instance()->globalStorage()->insert( "osproberLines", osproberCleanLines );

    return osproberEntries;
}