Ejemplo n.º 1
0
bool KFileShare::setShared(const QString &path, bool shared)
{
    if(!KFileShare::sharingEnabled() || KFileShare::shareMode() == Advanced)
        return false;

    kdDebug(7000) << "KFileShare::setShared " << path << "," << shared << endl;
    QString exe = KFileShare::findExe("fileshareset");
    if(exe.isEmpty())
        return false;

    KProcess proc;
    proc << exe;
    if(shared)
        proc << "--add";
    else
        proc << "--remove";
    proc << path;
    proc.start(KProcess::Block); // should be ok, the perl script terminates fast
    bool ok = proc.normalExit() && (proc.exitStatus() == 0);
    kdDebug(7000) << "KFileSharePropsPlugin::setShared normalExit=" << proc.normalExit() << endl;
    kdDebug(7000) << "KFileSharePropsPlugin::setShared exitStatus=" << proc.exitStatus() << endl;
    if(proc.normalExit())
    {
        switch(proc.exitStatus())
        {
            case 1:
                // User is not authorized
                break;
            case 3:
                // Called script with --add, but path was already shared before.
                // Result is nevertheless what the client wanted, so
                // this is alright.
                ok = true;
                break;
            case 4:
                // Invalid mount point
                break;
            case 5:
                // Called script with --remove, but path was not shared before.
                // Result is nevertheless what the client wanted, so
                // this is alright.
                ok = true;
                break;
            case 6:
                // There is no export method
                break;
            case 7:
                // file sharing is disabled
                break;
            case 8:
                // advanced sharing is enabled
                break;
            case 255:
                // Abitrary error
                break;
        }
    }

    return ok;
}
Ejemplo n.º 2
0
bool K3b::mount( K3bDevice::Device* dev )
{
  if( !dev )
    return false;

  QString mntDev = dev->blockDeviceName();

#if KDE_IS_VERSION(3,4,0)
  // first try to mount it the standard way
  if( KIO::NetAccess::synchronousRun( KIO::mount( true, 0, mntDev, false ), 0 ) )
    return true;
#endif

#ifdef HAVE_HAL
  if( !K3bDevice::HalConnection::instance()->mount( dev ) )
    return true;
#endif

  // now try pmount
  QString pmountBin = K3b::findExe( "pmount" );
  if( !pmountBin.isEmpty() ) {
    KProcess p;
    p << pmountBin;
    p << mntDev;
    p.start( KProcess::Block );
    return !p.exitStatus();
  }
  return false;
}
Ejemplo n.º 3
0
bool EncoderLame::init(){
	// Determine if lame is installed on the system or not.
	if ( KStandardDirs::findExe( "lame" ).isEmpty() )
		return false;

	// Ask lame for the list of genres it knows; otherwise it barfs when doing
	// e.g. lame --tg 'Vocal Jazz'
	KProcess proc;
	proc.setOutputChannelMode(KProcess::MergedChannels);
	proc << "lame" << "--genre-list";
	proc.execute();

	if(proc.exitStatus() != QProcess::NormalExit)
		return false;

	QByteArray array = proc.readAll();
	QString str = QString::fromLocal8Bit( array );
	d->genreList = str.split( '\n', QString::SkipEmptyParts );
	// Remove the numbers in front of every genre
	for( QStringList::Iterator it = d->genreList.begin(); it != d->genreList.end(); ++it ) {
		QString& genre = *it;
		int i = 0;
		while ( i < genre.length() && ( genre[i].isSpace() || genre[i].isDigit() ) )
			++i;
		genre = genre.mid( i );

	}
	//kDebug(7117) << "Available genres:" << d->genreList;

	return true;
}
Ejemplo n.º 4
0
// if it's e.g. just 'www', try if it's a hostname in the local search domain
bool LocalDomainURIFilter::isLocalDomainHost( QString& cmd ) const
{
    // find() returns -1 when no match -> left()/truncate() are noops then
    QString host( cmd.left( cmd.find( '/' ) ) );
    host.truncate( host.find( ':' ) ); // Remove port number

    if( !(host == last_host && last_time > time( NULL ) - 5 ) ) {

        QString helper = KStandardDirs::findExe(QString::fromLatin1( "klocaldomainurifilterhelper" ));
        if( helper.isEmpty())
            return last_result = false;

        m_fullname = QString::null;

        KProcess proc;
        proc << helper << host;
        connect( &proc, SIGNAL(receivedStdout(KProcess *, char *, int)),
                 SLOT(receiveOutput(KProcess *, char *, int)) );
        if( !proc.start( KProcess::NotifyOnExit, KProcess::Stdout ))
            return last_result = false;

        last_host = host;
        last_time = time( (time_t *)0 );

        last_result = proc.wait( 1 ) && proc.normalExit() && !proc.exitStatus();

        if( !m_fullname.isEmpty() )
            cmd.replace( 0, host.length(), m_fullname );
    }
Ejemplo n.º 5
0
bool ValgrindDialog::isNewValgrindVersion( ) const
{
  KProcess *proc = new KProcess;
  proc->setUseShell(true);
  *proc << "test \"valgrind-20\" == `valgrind --version | awk -F \\. '{print $1$2}'`";
  proc->start(KProcess::Block);
  if (proc->normalExit())
    return proc->exitStatus();
  return true;
}
Ejemplo n.º 6
0
bool K3b::unmount( K3bDevice::Device* dev )
{
  if( !dev )
    return false;

  QString mntDev = dev->blockDeviceName();

#if KDE_IS_VERSION(3,4,0)
  // first try to unmount it the standard way
  if( KIO::NetAccess::synchronousRun( KIO::unmount( mntDev, false ), 0 ) )
    return true;
#endif

  QString umountBin = K3b::findExe( "umount" );
  if( !umountBin.isEmpty() ) {
    KProcess p;
    p << umountBin;
    p << "-l"; // lazy unmount
    p << dev->blockDeviceName();
    p.start( KProcess::Block );
    if( !p.exitStatus() )
      return true;
  }

  // now try pmount
  QString pumountBin = K3b::findExe( "pumount" );
  if( !pumountBin.isEmpty() ) {
    KProcess p;
    p << pumountBin;
    p << "-l"; // lazy unmount
    p << dev->blockDeviceName();
    p.start( KProcess::Block );
    return !p.exitStatus();
  }
  else {
#ifdef HAVE_HAL
    return !K3bDevice::HalConnection::instance()->unmount( dev );
#else
    return false;
#endif
  }
}
Ejemplo n.º 7
0
void SqlBackendTest::allTests()
{
	QString dbname = "test";

	Classes::setup();

	// Drop the database if already exists
	KProcess *proc = new KProcess;
	*proc << "dropdb";
	*proc << dbname;
	proc->start();
	proc->wait();
	delete proc;

	// Create the database
	proc = new KProcess;
	*proc << "createdb";
	*proc << dbname;
	CHECK( proc->start(), true );
	proc->wait();
	if ( ! proc->normalExit() || proc->exitStatus() != 0 ) {
		CHECK( true, false );
		delete proc;
		return;
	}
	delete proc;

	QSqlDatabase *db = QSqlDatabase::addDatabase( "QPSQL7" );
	db->setDatabaseName( dbname );
	db->setUserName( "albert" );
	db->setPassword( "" );
	db->setHostName( "localhost" );
	if ( ! db->open() ) {
		kdDebug() << "Failed to open database: " << db->lastError().text() << endl;
		return;
	}
	DbBackendIface *backend = new SqlDbBackend( db );

	m_manager = new Manager( backend );
	m_manager->createSchema();

	transactions();
	collections();
	cache();
	freeing();
	testRelations();

	delete m_manager;
}
Ejemplo n.º 8
0
//Warning: This assumes that both files are CLOSED
bool IndexedEdictFile::buildIndex()
{
  KProcess proc;
  proc << QStandardPaths::findExecutable("kitengen") << m_dictFile.fileName() << m_indexFile.fileName();
  proc.start();
  proc.waitForStarted();

  do
  {
    QApplication::processEvents();
  } while( proc.waitForFinished( 5000 ) ); //FIXME: This just cuts the index generator off after 5 sec

  //FIXME: Check for the result of this operation
  return proc.exitStatus() == QProcess::NormalExit && proc.exitCode() == 0;
}
void MultipleBackendsTest::xml2sql()
{
	QString dbname = "testmultiple";
	// Drop the database if already exists
	KProcess *proc = new KProcess;
	*proc << "dropdb";
	*proc << dbname;
	proc->start();
	proc->wait();
	delete proc;

	// Create the database
	proc = new KProcess;
	*proc << "createdb";
	*proc << dbname;
	CHECK( proc->start(), true );
	proc->wait();
	if ( ! proc->normalExit() || proc->exitStatus() != 0 ) {
		CHECK( true, false );
		delete proc;
		return;
	}
	delete proc;

	DbBackendIface *backend1 = new XmlDbBackend( "database.xml" );
	Manager *manager1 = new Manager( backend1 );
	manager1->createSchema();

	QSqlDatabase *db = QSqlDatabase::addDatabase( "QPSQL7" );
	db->setDatabaseName( dbname );
	db->setUserName( "ak213" );
	db->setPassword( "ak" );
	db->setHostName( "localhost" );
	if ( ! db->open() ) {
		kdDebug() << "Failed to open database: " << db->lastError().text() << endl;
		return;
	}
	DbBackendIface *backend2 = new SqlDbBackend( db );
	Manager *manager2 = new Manager( backend2 );
	manager2->createSchema();
	manager1->copyTo( manager2 );
	manager2->commit();
	delete manager2;
	delete manager1;
	QSqlDatabase::removeDatabase( db );
}
Ejemplo n.º 10
0
bool KGVDocument::convertFromPDF( const QString& saveFileName, 
                                    unsigned int firstPage,
                                    unsigned int lastPage )
{
    // TODO -- timeout/fail on this conversion (it can hang on a bad pdf)
    // TODO -- use output from gs (leave out -q) to drive a progress bar
    KProcess process;
    process << _interpreterPath
            << "-q"
            << "-dNOPAUSE"
            << "-dBATCH"
            << "-dSAFER"
            << "-dPARANOIDSAFER"
            << "-sDEVICE=pswrite"
            << ( QCString("-sOutputFile=")+QFile::encodeName(saveFileName) )
            << ( QString("-dFirstPage=")+QString::number( firstPage ) )
            << ( QString("-dLastPage=")+QString::number( lastPage ) )
            << "-c"
            << "save"
            << "pop"
            << "-f"
            << QFile::encodeName(_fileName);

    /*QValueList<QCString> args = process.args();
    QValueList<QCString>::Iterator it = args.begin();
    for ( ; it != args.end() ; ++it )
        kdDebug(4500) << ( *it ) << endl;*/

    if( !process.start( KProcess::Block ) )
    {
	kdError() << "convertFromPDF: Couldn't start gs process" << endl;
	// TODO -- error message (gs not found?)
	return false;
    }
    if ( !process.normalExit() || process.exitStatus() != 0 )
    {
	kdError() << "convertFromPDF: normalExit=" << process.normalExit() << " exitStatus=" << process.exitStatus() << endl;
	// TODO -- error message (can't open, strerr())
	return false;
    }

    return true;
}
void QGpgMECryptoConfigComponent::runGpgConf()
{
  const QString gpgconf = QGpgMECryptoConfig::gpgConfPath();
  if ( gpgconf.isEmpty() ) {
      kWarning(5150) << "Can't get path to gpgconf executable...";
      return;
  }

  // Run gpgconf --list-options <component>, and create all groups and entries for that component
  KProcess proc;
  proc << gpgconf;
  proc << "--list-options";
  proc << mName;

  //kDebug(5150) <<"Running gpgconf --list-options" << mName;

  connect( &proc, SIGNAL(readyReadStandardOutput()),
           this, SLOT(slotCollectStdOut()) );
  mCurrentGroup = 0;

  // run the process:
  int rc = 0;
  proc.setOutputChannelMode( KProcess::OnlyStdoutChannel );
  proc.start();
  if ( !proc.waitForFinished() )
    rc = -2;
  else if ( proc.exitStatus() == QProcess::NormalExit )
    rc = proc.exitCode();
  else
    rc = -1;

  if( rc != 0 ) // can happen when using the wrong version of gpg...
    kWarning(5150) <<"Running 'gpgconf --list-options" << mName <<"' failed." << strerror( rc ) <<", but try that command to see the real output";
  else {
    if ( mCurrentGroup && !mCurrentGroup->mEntriesNaturalOrder.empty() ) { // only add non-empty groups
      mGroupsByName.insert( mCurrentGroupName, mCurrentGroup );
      mGroupsNaturalOrder.push_back( std::make_pair( mCurrentGroupName, mCurrentGroup ) );
    }
  }
}
void QGpgMECryptoConfig::runGpgConf( bool showErrors )
{
  // Run gpgconf --list-components to make the list of components
  KProcess process;

  process << gpgConfPath();
  process << "--list-components";


  connect( &process, SIGNAL(readyReadStandardOutput()),
           this, SLOT(slotCollectStdOut()) );

  // run the process:
  int rc = 0;
  process.setOutputChannelMode( KProcess::OnlyStdoutChannel );
  process.start();
  if ( !process.waitForFinished() )
    rc = -2;
  else if ( process.exitStatus() == QProcess::NormalExit )
    rc = process.exitCode();
  else
    rc = -1;

  // handle errors, if any (and if requested)
  if ( showErrors && rc != 0 ) {
    QString reason;
    if ( rc == -1 )
        reason = i18n( "program terminated unexpectedly" );
    else if ( rc == -2 )
        reason = i18n( "program not found or cannot be started" );
    else
      reason = QString::fromLocal8Bit( strerror(rc) ); // XXX errno as an exit code?
    QString wmsg = i18n("<qt>Failed to execute gpgconf:<p>%1</p></qt>", reason);
    kWarning(5150) << wmsg; // to see it from test_cryptoconfig.cpp
    KMessageBox::error(0, wmsg);
  }
  mParsed = true;
}
Ejemplo n.º 13
0
bool ImageGrayScale::image2GrayScaleImageMagick(const QString& src, const QString& dest, QString& err)
{
    KProcess process;
    process.clearProgram();
    process << "convert";
    process << "-type" << "Grayscale";
    process << src + QString("[0]") << dest;

    kDebug( 51000 ) << "ImageMagick Command line: " << process.program() << endl;

    process.start();

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

    if (process.exitStatus() != QProcess::NormalExit)
        return false;

    switch (process.exitCode())
    {
        case 0:  // Process finished successfully !
        {
            return true;
            break;
        }
        case 15: //  process aborted !
        {
            return false;
            break;
        }
    }

    // Processing error !
    m_stdErr = process.readAllStandardError();
    err      = i18n("Cannot convert to gray scale: %1", m_stdErr.replace('\n', ' '));
    return false;
}
Ejemplo n.º 14
0
CreateChecksumDlg::CreateChecksumDlg(const QStringList& files, bool containFolders, const QString& path)
    : QDialog(krApp)
{
    setWindowModality(Qt::WindowModal);
    setWindowTitle(i18n("Create Checksum"));

    QVBoxLayout *mainLayout = new QVBoxLayout;
    setLayout(mainLayout);

    QList<CS_Tool *> tools = getTools(containFolders);

    if (tools.count() == 0) { // nothing was suggested?!
        QString error = i18n("<qt>Cannot calculate checksum since no supported tool was found. "
                             "Please check the <b>Dependencies</b> page in Krusader's settings.</qt>");
        if (containFolders)
            error += i18n("<qt><b>Note</b>: you have selected folders, and probably have no recursive checksum tool installed."
                          " Krusader currently supports <i>md5deep, sha1deep, sha256deep, tigerdeep and cfv</i></qt>");
        KMessageBox::error(0, error);
        return;
    }

    QWidget * widget = new QWidget(this);
    QGridLayout *layout = new QGridLayout(widget);

    int row = 0;

    // title (icon+text)
    QHBoxLayout *hlayout = new QHBoxLayout;
    QLabel *p = new QLabel(widget);
    p->setPixmap(krLoader->loadIcon("document-edit-sign", KIconLoader::Desktop, 32));
    hlayout->addWidget(p);
    QLabel *l1 = new QLabel(widget);

    if (containFolders)
        l1->setText(i18n("About to calculate checksum for the following files and folders:"));
    else
        l1->setText(i18n("About to calculate checksum for the following files:"));

    hlayout->addWidget(l1);
    layout->addLayout(hlayout, row, 0, 1, 2, Qt::AlignLeft);
    ++row;

    // file list
    KrListWidget *lb = new KrListWidget(widget);
    lb->addItems(files);
    layout->addWidget(lb, row, 0, 1, 2);
    ++row;

    // checksum method
    QHBoxLayout *hlayout2 = new QHBoxLayout;
    QLabel *l2 = new QLabel(i18n("Select the checksum method:"), widget);
    hlayout2->addWidget(l2);
    KComboBox *method = new KComboBox(widget);
    // -- fill the combo with available methods
    int i;
    for (i = 0; i < tools.count(); ++i)
        method->addItem(cs_typeToText[tools.at(i)->type], i);
    method->setFocus();
    hlayout2->addWidget(method);
    layout->addLayout(hlayout2, row, 0, 1, 2, Qt::AlignLeft);
    ++row;
    mainLayout->addWidget(widget);

    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
    mainLayout->addWidget(buttonBox);

    QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok);
    okButton->setDefault(true);
    okButton->setShortcut(Qt::CTRL | Qt::Key_Return);
    connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));

    if (exec() != Accepted) return;
    // else implied: run the process
    QTemporaryFile tmpOut(QDir::tempPath() + QLatin1String("/krusader_XXXXXX.stdout"));
    tmpOut.open(); // necessary to create the filename
    QTemporaryFile tmpErr(QDir::tempPath() + QLatin1String("/krusader_XXXXXX.stderr"));
    tmpErr.open(); // necessary to create the filename
    KProcess proc;
    CS_Tool *mytool = tools.at(method->currentIndex());
    mytool->create(proc, mytool, files, QString(), containFolders, method->currentText());
    proc.setOutputChannelMode(KProcess::SeparateChannels); // without this the next 2 lines have no effect!
    proc.setStandardOutputFile(tmpOut.fileName());
    proc.setStandardErrorFile(tmpErr.fileName());
    proc.setWorkingDirectory(path);

    krApp->startWaiting(i18n("Calculating checksums..."), 0, true);
    QApplication::setOverrideCursor(Qt::WaitCursor);
    proc.start();
    // TODO make use of asynchronous process starting. waitForStarted(int msec = 30000) is blocking
    // it would be better to connect to started(), error() and finished()
    if (proc.waitForStarted())
        while (proc.state() == QProcess::Running) {
            usleep(500);
            qApp->processEvents();
            if (krApp->wasWaitingCancelled()) { // user cancelled
                proc.kill();
                QApplication::restoreOverrideCursor();
                return;
            }
        };
    krApp->stopWait();
    QApplication::restoreOverrideCursor();
    if (proc.exitStatus() != QProcess::NormalExit) {
        KMessageBox::error(0, i18n("<qt>There was an error while running <b>%1</b>.</qt>", mytool->binary));
        return;
    }

    // suggest a filename
    QString suggestedFilename = path + '/';
    if (files.count() > 1) suggestedFilename += ("checksum." + cs_typeToText[mytool->type]);
    else suggestedFilename += (files[0] + '.' + cs_typeToText[mytool->type]);
    // send both stdout and stderr
    QStringList stdOut, stdErr;
    if (!KrServices::fileToStringList(&tmpOut, stdOut) ||
            !KrServices::fileToStringList(&tmpErr, stdErr)) {
        KMessageBox::error(krApp, i18n("Error reading stdout or stderr"));
        return;
    }

    ChecksumResultsDlg dlg(stdOut, stdErr, suggestedFilename, mytool->standardFormat);
}
Ejemplo n.º 15
0
MatchChecksumDlg::MatchChecksumDlg(const QStringList& files, bool containFolders,
                                   const QString& path, const QString& checksumFile)
    : QDialog(krApp)
{
    setWindowTitle(i18n("Verify Checksum"));
    setWindowModality(Qt::WindowModal);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    setLayout(mainLayout);

    QList<CS_Tool *> tools = getTools(containFolders);

    if (tools.count() == 0) { // nothing was suggested?!
        QString error = i18n("<qt>Cannot verify checksum since no supported tool was found. "
                             "Please check the <b>Dependencies</b> page in Krusader's settings.</qt>");
        if (containFolders)
            error += i18n("<qt><b>Note</b>: you have selected folders, and probably have no recursive checksum tool installed."
                          " Krusader currently supports <i>md5deep, sha1deep, sha256deep, tigerdeep and cfv</i></qt>");
        KMessageBox::error(0, error);
        return;
    }

    QWidget * widget = new QWidget(this);
    QGridLayout *layout = new QGridLayout(widget);

    int row = 0;

    // title (icon+text)
    QHBoxLayout *hlayout = new QHBoxLayout;
    QLabel *p = new QLabel(widget);
    p->setPixmap(krLoader->loadIcon("document-edit-decrypt-verify", KIconLoader::Desktop, 32));
    hlayout->addWidget(p);
    QLabel *l1 = new QLabel(widget);

    if (containFolders)
        l1->setText(i18n("About to verify checksum for the following files and folders:"));
    else
        l1->setText(i18n("About to verify checksum for the following files:"));

    hlayout->addWidget(l1);
    layout->addLayout(hlayout, row, 0, 1, 2, Qt::AlignLeft);
    ++row;

    // file list
    KrListWidget *lb = new KrListWidget(widget);
    lb->addItems(files);
    layout->addWidget(lb, row, 0, 1, 2);
    ++row;

    // checksum file
    QHBoxLayout *hlayout2 = new QHBoxLayout;
    QLabel *l2 = new QLabel(i18n("Checksum file:"), widget);
    hlayout2->addWidget(l2);
    KUrlRequester *checksumFileReq = new KUrlRequester(widget);
    checksumFileReq->setUrl(QUrl::fromLocalFile(path));
    if (!checksumFile.isEmpty())
        checksumFileReq->setUrl(QUrl::fromLocalFile(checksumFile));
    checksumFileReq->setFocus();
    hlayout2->addWidget(checksumFileReq);
    layout->addLayout(hlayout2, row, 0, 1, 2, Qt::AlignLeft);
    mainLayout->addWidget(widget);

    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
    mainLayout->addWidget(buttonBox);

    QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok);
    okButton->setDefault(true);
    okButton->setShortcut(Qt::CTRL | Qt::Key_Return);
    connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));

    if (exec() != Accepted) return;
    QString file = checksumFileReq->url().toDisplayString(QUrl::PreferLocalFile);
    QString extension;
    if (!verifyChecksumFile(file, extension)) {
        KMessageBox::error(0, i18n("<qt>Error reading checksum file <i>%1</i>.<br />Please specify a valid checksum file.</qt>", file));
        return;
    }

    // do we have a tool for that extension?
    int i;
    CS_Tool *mytool = 0;
    for (i = 0; i < tools.count(); ++i)
        if (cs_typeToText[tools.at(i)->type] == extension.toLower()) {
            mytool = tools.at(i);
            break;
        }
    if (!mytool) {
        KMessageBox::error(0, i18n("<qt>Krusader cannot find a checksum tool that handles %1 on your system. Please check the <b>Dependencies</b> page in Krusader's settings.</qt>", extension));
        return;
    }

    // else implied: run the process
    QTemporaryFile tmpOut(QDir::tempPath() + QLatin1String("/krusader_XXXXXX.stdout"));
    tmpOut.open(); // necessary to create the filename
    QTemporaryFile tmpErr(QDir::tempPath() + QLatin1String("/krusader_XXXXXX.stderr"));
    tmpErr.open(); // necessary to create the filename
    KProcess proc;
    mytool->verify(proc, mytool, files, file, containFolders, extension);
    proc.setOutputChannelMode(KProcess::SeparateChannels); // without this the next 2 lines have no effect!
    proc.setStandardOutputFile(tmpOut.fileName());
    proc.setStandardErrorFile(tmpErr.fileName());
    proc.setWorkingDirectory(path);

    krApp->startWaiting(i18n("Verifying checksums..."), 0, true);
    QApplication::setOverrideCursor(Qt::WaitCursor);
    proc.start();
    // TODO make use of asynchronous process starting. waitForStarted(int msec = 30000) is blocking
    // it would be better to connect to started(), error() and finished()
    if (proc.waitForStarted())
        while (proc.state() == QProcess::Running) {
            usleep(500);
            qApp->processEvents();
            if (krApp->wasWaitingCancelled()) { // user cancelled
                proc.kill();
                QApplication::restoreOverrideCursor();
                return;
            }
        };
    if (proc.exitStatus() != QProcess::NormalExit) {
        KMessageBox::error(0, i18n("<qt>There was an error while running <b>%1</b>.</qt>", mytool->binary));
        return;
    }
    QApplication::restoreOverrideCursor();
    krApp->stopWait();
    // send both stdout and stderr
    QStringList stdOut, stdErr;
    if (!KrServices::fileToStringList(&tmpOut, stdOut) ||
            !KrServices::fileToStringList(&tmpErr, stdErr)) {
        KMessageBox::error(krApp, i18n("Error reading stdout or stderr"));
        return;
    }
    VerifyResultDlg dlg(mytool->failed(stdOut, stdErr));
}
bool ImageRotate::rotateImageMagick(const QString& src, const QString& dest, 
                                    RotateAction angle, QString& err)
{
    KProcess process;
    process.clearProgram();
    process << "convert";
    process << "-rotate";

    switch(angle)
    {
        case (Rot90):
        {
            process << "90";
            break;
        }
        case (Rot180):
        {
            process << "180";
            break;
        }
        case (Rot270):
        {
            process << "270";
            break;
        }
        case (Rot0):
        {
            break;
        }
        default:
        {
            kError() << "ImageRotate: Nonstandard rotation angle";
            err = i18n("Nonstandard rotation angle");
            return false;
        }
    }

    process << src + QString("[0]") << dest;

    kDebug() << "ImageMagick Command line: " << process.program();

    process.start();

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

    if (process.exitStatus() != QProcess::NormalExit)
        return false;

    switch (process.exitCode())
    {
        case 0:  // Process finished successfully !
        {
            return true;
            break;
        }
        case 15: //  process aborted !
        {
            return false;
            break;
        }
    }

    // Processing error !
    m_stdErr = process.readAllStandardError();
    err      = i18n("Cannot rotate: %1", m_stdErr.replace('\n', ' '));
    return false;
}
Ejemplo n.º 17
0
bool Utils::updateMetadataImageMagick(const QString& src, QString& err)
{
    QFileInfo finfo(src);
    if (src.isEmpty() || !finfo.isReadable())
    {
        err = i18n("unable to open source file");
        return false;
    }

    QImage img(src);
    QImage iptcPreview   = img.scaled(1280, 1024, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QImage exifThumbnail = iptcPreview.scaled(160, 120, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    KExiv2Iface::KExiv2 meta;
    meta.load(src);
    meta.setImageOrientation(KExiv2Iface::KExiv2::ORIENTATION_NORMAL);
    meta.setImageProgramId(QString("Kipi-plugins"), QString(kipiplugins_version));
    meta.setImageDimensions(img.size());
    meta.setExifThumbnail(exifThumbnail);
    meta.setImagePreview(iptcPreview);

#if KEXIV2_VERSION >= 0x010000
    QByteArray exifData = meta.getExifEncoded(true);
#else
    QByteArray exifData = meta.getExif(true);
#endif

    QByteArray iptcData = meta.getIptc(true);
    QByteArray xmpData  = meta.getXmp();

    KTemporaryFile exifTemp;
    exifTemp.setSuffix(QString("kipipluginsexif.app1"));
    exifTemp.setAutoRemove(true);
    if ( !exifTemp.open() )
    {
        err = i18n("unable to open temp file");
        return false;
    }
    QString exifFile = exifTemp.fileName();
    QDataStream streamExif( &exifTemp );
    streamExif.writeRawData(exifData.data(), exifData.size());
    exifTemp.close();

    KTemporaryFile iptcTemp;
    iptcTemp.setSuffix(QString("kipipluginsiptc.8bim"));
    iptcTemp.setAutoRemove(true);
    iptcTemp.open();
    if ( !iptcTemp.open() )
    {
        err = i18n("Cannot rotate: unable to open temp file");
        return false;
    }
    QString iptcFile = iptcTemp.fileName();
    QDataStream streamIptc( &iptcTemp );
    streamIptc.writeRawData(iptcData.data(), iptcData.size());
    iptcTemp.close();

    KTemporaryFile xmpTemp;
    xmpTemp.setSuffix(QString("kipipluginsxmp.xmp"));
    xmpTemp.setAutoRemove(true);
    if ( !xmpTemp.open() )
    {
        err = i18n("unable to open temp file");
        return false;
    }
    QString xmpFile = xmpTemp.fileName();
    QDataStream streamXmp( &xmpTemp );
    streamXmp.writeRawData(xmpData.data(), xmpData.size());
    xmpTemp.close();

    KProcess process;
    process.clearProgram();
    process << "mogrify";

    process << "-profile";
    process << exifFile;

    process << "-profile";
    process << iptcFile;

    process << "-profile";
    process << xmpFile;

    process << src + QString("[0]");

    kDebug() << "ImageMagick Command line: " << process.program();

    process.start();

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

    if (process.exitStatus() != QProcess::NormalExit)
        return false;

    switch (process.exitCode())
    {
        case 0:  // Process finished successfully !
        {
            return true;
            break;
        }
        case 15: //  process aborted !
        {
            return false;
            break;
        }
    }

    // Processing error !
    m_stdErr = process.readAllStandardError();
    err      = i18n("Cannot update metadata: %1", m_stdErr.replace('\n', ' '));
    return false;
}
void DynamicObjectsTest::allTests()
{
	QString dbname = "testdynamic";
	
	Classes::setup();

	Classes::addClass( "Test", DynamicObject::createInstance, 0 );
	ClassInfo *ci = Classes::classInfo( "Test" );
	ci->addObject( "Customer", "Customer_Test", &Customer::createInstance );
	ci->addCollection( "Article", "Article_Test" );

	PropertyInfo *p;
	
	p = new PropertyInfo();
	p->setName( "Property1" );
	p->setType( QVariant::String );
	ci->addProperty( p );
	
	p = new PropertyInfo();
	p->setName( "Property2" );
	p->setType( QVariant::ULongLong );
	ci->addProperty( p );

	Classes::setupRelations();

	// Drop the database if already exists
	KProcess *proc = new KProcess;
	*proc << "dropdb";
	*proc << dbname;
	proc->start();
	proc->wait();
	delete proc;

	// Create the database
	proc = new KProcess;
	*proc << "createdb";
	*proc << dbname;
	CHECK( proc->start(), true );
	proc->wait();
	if ( ! proc->normalExit() || proc->exitStatus() != 0 ) {
		CHECK( true, false );
		delete proc;
		return;
	}
	delete proc;

	QSqlDatabase *db = QSqlDatabase::addDatabase( "QPSQL7" );
	db->setDatabaseName( dbname );
	db->setUserName( "ak213" );
	db->setPassword( "ak" );
	db->setHostName( "localhost" );
	if ( ! db->open() ) {
		kdDebug() << "Failed to open database: " << db->lastError().text() << endl;
		return;
	}
	DbBackendIface *backend = new SqlDbBackend( db );

	m_manager = new Manager( backend );
	m_manager->setMaxObjects( 1 );
	m_manager->createSchema();


	ObjectRef<Customer> customer = Customer::create();
	customer->setCustomerName( "Name of the customer" );

	ObjectRef<Article> a1 = Article::create();
	a1->setCode( "00001" );
	ObjectRef<Article> a2 = Article::create();
	a2->setCode( "00002" );

	ObjectRef<Object> obj = Classes::classInfo( "Test" )->create();
	CHECK( obj->property( "Property1" ).type(), QVariant::String );
	CHECK( obj->property( "Property2" ).type(), QVariant::ULongLong );
	CHECK( obj->containsObject( "Customer_Test" ), true );
	CHECK( obj->containsCollection( "Article_Test" ), true );
	obj->setProperty( "Property1", "Property number one" );
	obj->setProperty( "Property2", 2 );
	CHECK( obj->property( QString( "Property1" ) ).value().toString(), QString( "Property number one" ) );
	CHECK( obj->property( QString( "Property2" ) ).value().toULongLong(), 2 );
	
	obj->setObject( "Customer_Test", customer );
	obj->collection( "Article_Test" )->add( a1 );
	obj->collection( "Article_Test" )->add( a2 );

	m_manager->commit();

	CHECK( obj->property( "Property1" ).value().toString(), QString( "Property number one" ) );

	delete m_manager;
}