Ejemplo n.º 1
0
bool NetAccess::download(const KUrl& u, QString & target, QWidget* window)
{
  if (u.isLocalFile()) {
    // file protocol. We do not need the network
    target = u.toLocalFile();
    bool accessible = KStandardDirs::checkAccess(target, R_OK);
    if(!accessible)
    {
        if(!lastErrorMsg)
            lastErrorMsg = new QString;
        *lastErrorMsg = i18n("File '%1' is not readable", target);
        lastErrorCode = ERR_COULD_NOT_READ;
    }
    return accessible;
  }

  if (target.isEmpty())
  {
      KTemporaryFile tmpFile;
      tmpFile.setAutoRemove(false);
      tmpFile.open();
      target = tmpFile.fileName();
      if (!tmpfiles)
          tmpfiles = new QStringList;
      tmpfiles->append(target);
  }

  NetAccess kioNet;
  KUrl dest;
  dest.setPath( target );
  return kioNet.filecopyInternal( u, dest, -1, KIO::Overwrite, window, false /*copy*/);
}
ImageViewer::ImageViewer (const KUrl &url, const QString &capText, QWidget *parent) :
    KDialog( parent ),
    m_ImageUrl(url),
    fileIsImage(false),
    downloadJob(0)
{
    init(url.fileName(), capText);
    // Add save button
    setButtons( KDialog::User2 | KDialog::User1 | KDialog::Close );

    KGuiItem saveButton( i18n("Save"), "document-save", i18n("Save the image to disk") );
    setButtonGuiItem( KDialog::User1, saveButton );

    // FIXME: Add more options, and do this more nicely
    KGuiItem invertButton( i18n("Invert colors"), "", i18n("Reverse colors of the image. This is useful to enhance contrast at times. This affects only the display and not the saving.") );
    setButtonGuiItem( KDialog::User2, invertButton );

    connect( this, SIGNAL( user1Clicked() ), this, SLOT ( saveFileToDisc() ) );
    connect( this, SIGNAL( user2Clicked() ), this, SLOT ( invertColors() ) );
    // check URL
    if (!m_ImageUrl.isValid())
        kDebug() << "URL is malformed: " << m_ImageUrl;
    
    // FIXME: check the logic with temporary files. Races are possible
    {
        KTemporaryFile tempfile;
        tempfile.open();
        file.setFileName( tempfile.fileName() );
    }// we just need the name and delete the tempfile from disc; if we don't do it, a dialog will be show

    loadImageFromURL();
}
void KEduVocDocumentValidatorTest::testDocumentAboutInfo()
{
    KTemporaryFile temp;
    temp.setSuffix(".kvtml");
    temp.open();
    KUrl fileName = KUrl(temp.fileName());
    temp.close();

    const QString generator = QString::fromLatin1( "Validator Unit Tests" );
    const QString author = QString::fromLatin1( "Validator Test" );
    const QString license = QString::fromLatin1( "test license" );
    const QString comment = QString::fromLatin1( "comment" );
    const QString category = QString::fromLatin1( "test document" );
    const QString title = QString::fromLatin1( "Validator Test Title" );

    KEduVocDocument doc;
    doc.setAuthor( author );
    doc.setLicense( license );
    doc.setDocumentComment( comment );
    doc.setCategory( category );
    doc.setTitle( title );

    doc.saveAs(fileName, KEduVocDocument::Kvtml, generator);

    KEduVocDocument docRead;
    docRead.open(fileName);

    QCOMPARE( docRead.generator(), generator );
    QCOMPARE( docRead.author(), author );
    QCOMPARE( docRead.license(), license );
    QCOMPARE( docRead.documentComment(), comment );
    QCOMPARE( docRead.category(), category );
    QCOMPARE( docRead.title(), title );
}
Ejemplo n.º 4
0
void KDesktopFileTest::testActionGroup()
{
    KTemporaryFile file;
    file.setPrefix("test1");
    QVERIFY( file.open() );
    const QString fileName = file.fileName();
    QTextStream ts( &file );
    ts <<
        "[Desktop Entry]\n"
        "Actions=encrypt;\n"
        "[Desktop Action encrypt]\n"
        "Name=Encrypt file\n"
        "\n";
    file.close();
    QVERIFY(QFile::exists(fileName));
    KDesktopFile df(fileName);
    QCOMPARE(df.readType(), QString());
    QCOMPARE(df.fileName(), fileName);
    QCOMPARE(df.readActions(), QStringList() << "encrypt");
    QCOMPARE(df.hasActionGroup("encrypt"), true);
    QCOMPARE(df.hasActionGroup("doesnotexist"), false);
    KConfigGroup cg = df.actionGroup("encrypt");
    QVERIFY(cg.hasKey("Name"));
    QCOMPARE(cg.readEntry("Name"), QString("Encrypt file"));
}
Ejemplo n.º 5
0
bool FileProvider::get( const QString &url, QString &target )
{
  if ( !mFileName.isEmpty() )
    cleanUp();

  if ( target.isEmpty() ) {
    KTemporaryFile tmpFile;
    tmpFile.setAutoRemove(false);
    tmpFile.open();
    target = tmpFile.fileName();
    mFileName = target;
  }

  mData.truncate( 0 );

  qDebug( "Downloading external schema '%s'", qPrintable( url ) );

  KIO::TransferJob* job = KIO::get( KUrl( url ), KIO::NoReload, KIO::HideProgressInfo );
  connect( job, SIGNAL( data( KIO::Job*, const QByteArray& ) ),
           this, SLOT( slotData( KIO::Job*, const QByteArray& ) ) );
  connect( job, SIGNAL( result( KJob* ) ),
           this, SLOT( slotResult( KJob* ) ) );

  mBlocked = true;
  while ( mBlocked ) {
    QCoreApplication::processEvents( QEventLoop::ExcludeUserInputEvents );
    usleep( 500 );
  }

  return true;
}
bool Kleo::SymCryptRunProcessBase::launch( const QByteArray & input, bool block ) {
  connect( this, SIGNAL(readyReadStandardOutput()),
           this, SLOT(slotReadyReadStandardOutput()) );
  connect( this, SIGNAL(readyReadStandardError()),
           this, SLOT(slotReadyReadStandardError()) );
  if ( block ) {
    KTemporaryFile tempfile;
    if ( tempfile.open() )
      tempfile.write( input );
    else
      return false;
    tempfile.flush();
    *this << "--input" << tempfile.fileName();
    addOptions();
    if(KProcess::execute() == -2)
        return false;
  } else {
    addOptions();
    KProcess::start();
    const bool ok = waitForStarted();
    if ( !ok )
      return ok;
    mInput = input;
    write( mInput );
    closeWriteChannel();
  }
  return true;
}
Ejemplo n.º 7
0
void KateFoldingTest::testFolding_py_lang()
{
  KTemporaryFile file;
  file.setSuffix(".py");
  file.open();
  QTextStream stream(&file);
  stream << "if customerName == x\n"
         << "  print x\n"
         << "elif customerName == y\n"
         << "  print y\n"
         << "else print z\n";
  stream << flush;
  file.close();

  KateDocument doc(false, false, false);
  QVERIFY(doc.openUrl(KUrl(file.fileName())));

  KateView* view = new KateView(&doc, 0);

  // is set to allow kate's hl to be called
  view->config()->setDynWordWrap(true);

  QCOMPARE(doc.visibleLines(), 6u);

  QAction* action = view->action("folding_toplevel");
  QVERIFY(action);
  action->trigger();
  QCOMPARE(doc.visibleLines(), 4u);

  action = view->action("folding_expandtoplevel");
  QVERIFY(action);
  action->trigger();
  QCOMPARE(doc.visibleLines(), 6u);
}
Ejemplo n.º 8
0
bool ResourceNet::save( Ticket *ticket )
{
    Q_UNUSED( ticket );
    kDebug();

    if ( d->mIsSaving ) {
        abortAsyncSaving();
    }

    KTemporaryFile tempFile;
    bool ok = tempFile.open();

    if ( ok ) {
        saveToFile( &tempFile );
        tempFile.flush();
    }

    if ( !ok ) {
        addressBook()->error( i18n( "Unable to save file '%1'.", tempFile.fileName() ) );
        return false;
    }

    ok = KIO::NetAccess::upload( tempFile.fileName(), mUrl, 0 );
    if ( !ok ) {
        addressBook()->error( i18n( "Unable to upload to '%1'.", mUrl.prettyUrl() ) );
    }

    return ok;
}
Ejemplo n.º 9
0
void TestM3UPlaylist::testSave()
{
    KTemporaryFile temp;
    temp.setSuffix( ".m3u" );
    QVERIFY( temp.open() );
    QVERIFY( m_testPlaylist->save( temp.fileName(), false ) );
}
Ejemplo n.º 10
0
void KateFoldingTest::testFolding_collapse_dsComments_XML()
{
  KTemporaryFile file;
  file.setSuffix(".xml");
  file.open();
  QTextStream stream(&file);
  stream << "<test1>\n"
         << "</test1>\n"
         << "<!--\n"
         << "<test2>\n"
         << "</test2>\n"
         << "-->\n"
         << "<!--\n"
         << "-->\n";
  stream << flush;
  file.close();

  KateDocument doc(false, false, false);
  QVERIFY(doc.openUrl(KUrl(file.fileName())));

  KateView* view = new KateView(&doc, 0);

  // is set to allow kate's hl to be called
  view->config()->setDynWordWrap(true);

  QCOMPARE(doc.visibleLines(), 9u);

  QAction* action = view->action("folding_collapse_dsComment");
  QVERIFY(action);
  action->trigger();
  QCOMPARE(doc.visibleLines(), 5u);
}
Ejemplo n.º 11
0
static KTemporaryFile *generateTestFile(const QString &content)
{
    KTemporaryFile *file = new KTemporaryFile;
    Q_ASSERT(file->open());
    file->write(content.toUtf8());
    file->flush();
    return file;
}
Ejemplo n.º 12
0
Status SetAuthentication (int count, IceListenObj *listenObjs,
                          IceAuthDataEntry **authDataEntries)
{
    KTemporaryFile addTempFile;
    remTempFile = new KTemporaryFile;

    if (!addTempFile.open() || !remTempFile->open())
        return 0;

    if ((*authDataEntries = (IceAuthDataEntry *) malloc (
                         count * 2 * sizeof (IceAuthDataEntry))) == NULL)
        return 0;

    FILE *addAuthFile = fopen(QFile::encodeName(addTempFile.fileName()), "r+");
    FILE *remAuthFile = fopen(QFile::encodeName(remTempFile->fileName()), "r+");

    for (int i = 0; i < numTransports * 2; i += 2) {
        (*authDataEntries)[i].network_id =
            IceGetListenConnectionString (listenObjs[i/2]);
        (*authDataEntries)[i].protocol_name = (char *) "ICE";
        (*authDataEntries)[i].auth_name = (char *) "MIT-MAGIC-COOKIE-1";

        (*authDataEntries)[i].auth_data =
            IceGenerateMagicCookie (MAGIC_COOKIE_LEN);
        (*authDataEntries)[i].auth_data_length = MAGIC_COOKIE_LEN;

        (*authDataEntries)[i+1].network_id =
            IceGetListenConnectionString (listenObjs[i/2]);
        (*authDataEntries)[i+1].protocol_name = (char *) "XSMP";
        (*authDataEntries)[i+1].auth_name = (char *) "MIT-MAGIC-COOKIE-1";

        (*authDataEntries)[i+1].auth_data =
            IceGenerateMagicCookie (MAGIC_COOKIE_LEN);
        (*authDataEntries)[i+1].auth_data_length = MAGIC_COOKIE_LEN;

        write_iceauth (addAuthFile, remAuthFile, &(*authDataEntries)[i]);
        write_iceauth (addAuthFile, remAuthFile, &(*authDataEntries)[i+1]);

        IceSetPaAuthData (2, &(*authDataEntries)[i]);

        IceSetHostBasedAuthProc (listenObjs[i/2], HostBasedAuthProc);
    }
    fclose(addAuthFile);
    fclose(remAuthFile);

    QString iceAuth = KGlobal::dirs()->findExe("iceauth");
    if (iceAuth.isEmpty())
    {
        qWarning("KSMServer: could not find iceauth");
        return 0;
    }

    KProcess p;
    p << iceAuth << "source" << addTempFile.fileName();
    p.execute();

    return (1);
}
QString KCheckGmailTray::takeScreenshotOfTrayIcon()
{
    // Process the events else the icon will not be there and the screenie will fail!
    kapp->processEvents();

    // Taken from Akregator TrayIcon::takeScreenshot()
    const QRect rect = geometry();
    const QPoint g = rect.topLeft();
    int desktopWidth  = kapp->desktop()->width();
    int desktopHeight = kapp->desktop()->height();
    int tw = rect.width();
    int th = rect.height();
    int w = desktopWidth / 4;
    int h = desktopHeight / 9;
    int x = g.x() + tw/2 - w/2; // Center the rectange in the systray icon
    int y = g.y() + th/2 - h/2;
    if (x < 0)
        x = 0; // Move the rectangle to stay in the desktop limits
    if (y < 0)
        y = 0;
    if (x + w > desktopWidth)
        x = desktopWidth - w;
    if (y + h > desktopHeight)
        y = desktopHeight - h;

    // Grab the desktop and draw a circle around the icon:
    QPixmap shot = QPixmap::grabWindow(QApplication::desktop()->winId(), x, y, w, h);
    QPainter painter(&shot);
    painter.setRenderHint( QPainter::Antialiasing );
    const int MARGINS = 6;
    const int WIDTH   = 3;
    int ax = g.x() - x - MARGINS -1;
    int ay = g.y() - y - MARGINS -1;
    painter.setPen( QPen(Qt::red/*KApplication::palette().active().highlight()*/, WIDTH) );
    painter.drawArc(ax, ay, tw + 2*MARGINS, th + 2*MARGINS, 0, 16*360);
    painter.end();

    // Paint the border
    const int BORDER = 1;
    QPixmap finalShot(w + 2*BORDER, h + 2*BORDER);
    finalShot.fill( KApplication::palette().color( QPalette::Foreground ));
    painter.begin(&finalShot);
    painter.drawPixmap(BORDER, BORDER, shot);
    painter.end();
//	return shot; // not finalShot?? -fo

    // End of Taken from Akregator

    QString filename;
    KTemporaryFile* tmpfile = new KTemporaryFile;
    tmpfile->setAutoRemove(false);
    if (tmpfile->open()) {
        filename = tmpfile->fileName();
        shot.save(tmpfile, "png");
        tmpfile->close();
    }
    return filename;
}
Ejemplo n.º 14
0
void ExportImageDialog::exportImage()
{
    //If the filename string contains no "/" separators, assume the
    //user wanted to place a file in their home directory.
    KUrl fileURL;
    if(!m_Url.contains("/"))
    {
        fileURL = QDir::homePath() + '/' + m_Url;
    }

    else
    {
        fileURL = m_Url;
    }

    if(fileURL.isValid())
    {
        KTemporaryFile tmpfile;
        QString fname;
        bool isLocalFile = fileURL.isLocalFile();

        if(isLocalFile)
        {
            fname = fileURL.toLocalFile();
        }

        else
        {
            tmpfile.open();
            fname = tmpfile.fileName();
        }

        //Determine desired image format from filename extension
        QString ext = fname.mid(fname.lastIndexOf(".") + 1);
        if(ext.toLower() == "svg")
        {
            exportSvg(fname);
        }

        else
        {
            exportRasterGraphics(fname);
        }

        if(!isLocalFile)
        {
            //attempt to upload image to remote location
            if(!KIO::NetAccess::upload(tmpfile.fileName(), fileURL, this))
            {
                QString message = i18n( "Could not upload image to remote location: %1", fileURL.prettyUrl() );
                KMessageBox::sorry( 0, message, i18n( "Could not upload file" ) );
            }
        }
    }
}
Ejemplo n.º 15
0
void KateFoldingTest::testFolding_collapse_expand_local()
{
  KTemporaryFile file;
  file.setSuffix(".c");
  file.open();
  QTextStream stream(&file);
  stream << "if () {\n"
         << "  if () {\n"
         << "     if () {\n"
         << "        if () {\n"
         << "              }\n"
         << "           }\n"
         << "        }\n"
         << "  if () {\n"
         << "     foo()\n"
         << "        }\n"
         << " }\n";
  stream << flush;
  file.close();

  KateDocument doc(false, false, false);
  QVERIFY(doc.openUrl(KUrl(file.fileName())));

  KateView* view = new KateView(&doc, 0);

  // is set to allow kate's hl to be called
  view->config()->setDynWordWrap(true);

  QCOMPARE(doc.visibleLines(), 12u);

  view->setCursorPosition(KTextEditor::Cursor(2,12));

  QAction* action = view->action("folding_collapselocal");
  QVERIFY(action);
  action->trigger();
  QCOMPARE(doc.visibleLines(), 9u);

  view->setCursorPosition(KTextEditor::Cursor(2,11));

  action = view->action("folding_collapselocal");
  QVERIFY(action);
  action->trigger();
  QCOMPARE(doc.visibleLines(), 7u);

  view->setCursorPosition(KTextEditor::Cursor(1,9));

  action = view->action("folding_expandlocal");
  QVERIFY(action);
  action->trigger();
  QCOMPARE(doc.visibleLines(), 9u);

}
Ejemplo n.º 16
0
void Serialization::writeFile(const QString& data, const KUrl& url)
throw (IOException) {
    KTemporaryFile temporaryFile;
    temporaryFile.open();
    QTextStream out(&temporaryFile);
    out << data;
    out.flush();
    temporaryFile.close();

    if (!KIO::NetAccess::upload(temporaryFile.fileName(), url, mWindow)) {
        throw IOException(KIO::NetAccess::lastErrorString());
    }
}
void KTNEFMain::slotShowMessageText()
{
  if ( !mParser->message() ) {
    return;
  }

  QString rtf = mParser->message()->rtfString();
  if ( !rtf.isEmpty() ) {
    KTemporaryFile *tmpFile = new KTemporaryFile();
    tmpFile->setPrefix( KGlobal::dirs()->localkdedir() + "/share/apps/ktnef/tmp/" );
    tmpFile->setSuffix( QLatin1String( ".rtf" ) );
    tmpFile->open();
    tmpFile->setPermissions( QFile::ReadUser );
    tmpFile->write( rtf.toLocal8Bit() );
    tmpFile->close();

    KRun::runUrl( KUrl( tmpFile->fileName() ), "text/rtf", this, true );
    delete tmpFile;
  } else {
      KMessageBox::error(
        this,
        i18nc( "@info",
               "The message does not contain any Rich Text data." ) );
  }
}
Ejemplo n.º 18
0
void BinaryWidget::save()
{
  KUrl url = KFileDialog::getSaveUrl( QString(), QString(), this );
  if ( url.isEmpty() )
    return;

  KTemporaryFile tempFile;
  tempFile.open();
  tempFile.write( mData );
  tempFile.flush();

  if ( !KIO::NetAccess::upload( tempFile.fileName(), url, this ) )
    KMessageBox::error( this, KIO::NetAccess::lastErrorString() );
}
Ejemplo n.º 19
0
Rules::Rules(const QString& str, bool temporary)
    : temporary_state(temporary ? 2 : 0)
{
    KTemporaryFile file;
    if (file.open()) {
        QByteArray s = str.toUtf8();
        file.write(s.data(), s.length());
    }
    file.flush();
    KConfig cfg(file.fileName(), KConfig::SimpleConfig);
    readFromCfg(cfg.group(QString()));
    if (description.isEmpty())
        description = "temporary";
}
Ejemplo n.º 20
0
//static
void DrKonqi::saveReport(const QString & reportText, QWidget *parent)
{
    if (KCmdLineArgs::parsedArgs()->isSet("safer")) {
        KTemporaryFile tf;
        tf.setSuffix(".kcrash.txt");
        tf.setAutoRemove(false);

        if (tf.open()) {
            QTextStream textStream(&tf);
            textStream << reportText;
            textStream.flush();
            KMessageBox::information(parent, i18nc("@info",
                                                   "Report saved to <filename>%1</filename>.",
                                                   tf.fileName()));
        } else {
            KMessageBox::sorry(parent, i18nc("@info","Could not create a file in which to save the report."));
        }
    } else {
        QString defname = getSuggestedKCrashFilename(crashedApplication());

        QWeakPointer<KFileDialog> dlg = new KFileDialog(defname, QString(), parent);
        dlg.data()->setSelection(defname);
        dlg.data()->setCaption(i18nc("@title:window","Select Filename"));
        dlg.data()->setOperationMode(KFileDialog::Saving);
        dlg.data()->setMode(KFile::File);
        dlg.data()->setConfirmOverwrite(true);
        dlg.data()->exec();

        if (dlg.isNull()) {
            //Dialog is invalid, it was probably deleted (ex. via DBus call)
            //return and do not crash
            return;
        }

        KUrl fileUrl = dlg.data()->selectedUrl();
        delete dlg.data();

        if (fileUrl.isValid()) {
            KTemporaryFile tf;
            if (tf.open()) {
                QTextStream ts(&tf);
                ts << reportText;
                ts.flush();
            } else {
                KMessageBox::sorry(parent, i18nc("@info","Cannot open file <filename>%1</filename> "
                                                         "for writing.", tf.fileName()));
                return;
            }

            if (!KIO::NetAccess::upload(tf.fileName(), fileUrl, parent)) {
                KMessageBox::sorry(parent, KIO::NetAccess::lastErrorString());
            }
        }
    }
}
Ejemplo n.º 21
0
bool SocketConnectionBackend::listenForRemote()
{
    Q_ASSERT(state == Idle);
    Q_ASSERT(!socket);
    Q_ASSERT(!localServer);     // !tcpServer as well

    if (mode == LocalSocketMode) {
        QString prefix = KStandardDirs::locateLocal("socket", KGlobal::mainComponent().componentName());
        KTemporaryFile *socketfile = new KTemporaryFile();
        socketfile->setPrefix(prefix);
        socketfile->setSuffix(QLatin1String(".slave-socket"));
        if (!socketfile->open())
        {
            errorString = i18n("Unable to create io-slave: %1", strerror(errno));
            delete socketfile;
            return false;
        }

        QString sockname = socketfile->fileName();
        KUrl addressUrl(sockname);
        addressUrl.setProtocol("local");
        address = addressUrl.url();
        delete socketfile; // can't bind if there is such a file

        localServer = new KLocalSocketServer(this);
        if (!localServer->listen(sockname, KLocalSocket::UnixSocket)) {
            errorString = localServer->errorString();
            delete localServer;
            localServer = 0;
            return false;
        }

        connect(localServer, SIGNAL(newConnection()), SIGNAL(newConnection()));
    } else {
        tcpServer = new QTcpServer(this);
        tcpServer->listen(QHostAddress::LocalHost);
        if (!tcpServer->isListening()) {
            errorString = tcpServer->errorString();
            delete tcpServer;
            tcpServer = 0;
            return false;
        }

        address = "tcp://127.0.0.1:" + QString::number(tcpServer->serverPort());
        connect(tcpServer, SIGNAL(newConnection()), SIGNAL(newConnection()));
    }

    state = Listening;
    return true;
}
Ejemplo n.º 22
0
void KDesktopFileTest::testUnsuccessfulTryExec()
{
    KTemporaryFile file;
    file.setPrefix("test1");
    QVERIFY( file.open() );
    const QString fileName = file.fileName();
    QTextStream ts( &file );
    ts <<
        "[Desktop Entry]\n"
        "TryExec=/does/not/exist\n"
        "\n";
    file.close();
    QVERIFY(QFile::exists(fileName));
    KDesktopFile df(fileName);
    QCOMPARE(df.tryExec(), false);
}
Ejemplo n.º 23
0
	void testMMap()
	{
		KTemporaryFile tmp;
		QVERIFY(tmp.open());
		int fd = tmp.handle();
		try
		{
			TruncateFile(fd, 4096, true);
		}
		catch (bt::Error & err)
		{
			QString msg = QString("Exception thrown: %s").arg(err.toString());
			QFAIL(msg.toLocal8Bit());
		}
		
		
		char* ptr = (char*)mmap(0, 4096, PROT_WRITE, MAP_SHARED, fd, 0);
		QVERIFY(ptr);
		
		// First try a write which should not fail
		try
		{
			BUS_ERROR_WPROTECT();
			memcpy(ptr,"Testing",7);
		}
		catch (bt::BusError & e)
		{
			QString msg = QString("Caught signal: %s").arg(e.toString());
			QFAIL(msg.toLocal8Bit());
		}
		
		// Lets try one which should fail
		try
		{
			BUS_ERROR_WPROTECT();
			TruncateFile(fd, 0, true);
			memcpy(ptr,"Testing",7);
			QFAIL("Didn't catch SIGBUS");
		}
		catch (bt::BusError & e)
		{
			Out(SYS_GEN|LOG_DEBUG) << QString("Caught signal: %1").arg(e.toString()) << endl;
		}
	}
Ejemplo n.º 24
0
QString NetAccess::fish_executeInternal(const KUrl & url, const QString &command, QWidget* window)
{
  QString target, remoteTempFileName, resultData;
  KUrl tempPathUrl;
  KTemporaryFile tmpFile;
  tmpFile.open();

  if( url.protocol() == "fish" )
  {
    // construct remote temp filename
    tempPathUrl = url;
    remoteTempFileName = tmpFile.fileName();
    // only need the filename KTempFile adds some KDE specific dirs
    // that probably does not exist on the remote side
    int pos = remoteTempFileName.lastIndexOf('/');
    remoteTempFileName = "/tmp/fishexec_" + remoteTempFileName.mid(pos + 1);
    tempPathUrl.setPath( remoteTempFileName );
    d->bJobOK = true; // success unless further error occurs
    QByteArray packedArgs;
    QDataStream stream( &packedArgs, QIODevice::WriteOnly );

    stream << int('X') << tempPathUrl << command;

    KIO::Job * job = KIO::special( tempPathUrl, packedArgs );
    job->ui()->setWindow( window );
    connect( job, SIGNAL( result (KJob *) ),
             this, SLOT( slotResult (KJob *) ) );
    enter_loop();

    // since the KIO::special does not provide feedback we need to download the result
    if( NetAccess::download( tempPathUrl, target, window ) )
    {
      QFile resultFile( target );

      if (resultFile.open( QIODevice::ReadOnly ))
      {
        QTextStream ts( &resultFile ); // default encoding is Locale
        resultData = ts.readAll();
        resultFile.close();
        NetAccess::del( tempPathUrl, window );
      }
    }
  }
Ejemplo n.º 25
0
void KateFoldingTest::testFoldingReload()
{
  KTemporaryFile file;
  file.setSuffix(".cpp");
  file.open();
  QTextStream stream(&file);
  stream << "int main() {\n"
         << "  asdf;\n"
         << "}\n";
  stream << flush;
  file.close();

  KateDocument doc(false, false, false);
  QVERIFY(doc.openUrl(KUrl(file.fileName())));

  KateView* view = new KateView(&doc, 0);

  // is set to allow kate's hl to be called
  view->config()->setDynWordWrap(true);

  QCOMPARE(doc.visibleLines(), 4u);

  QAction* action = view->action("folding_toplevel");
  QVERIFY(action);
  action->trigger();

  doc.foldingTree()->saveFoldingState();

  QList<int> hiddenLines(doc.foldingTree()->m_hiddenLines);
  QList<int> hiddenColumns(doc.foldingTree()->m_hiddenColumns);

  QCOMPARE(doc.visibleLines(), 2u);

  action = view->action("file_reload");
  QVERIFY(action);
  action->trigger();

  QCOMPARE(doc.visibleLines(), 2u);

  QCOMPARE(hiddenLines,doc.foldingTree()->m_hiddenLines);
  QCOMPARE(hiddenColumns,doc.foldingTree()->m_hiddenColumns);
}
Ejemplo n.º 26
0
void KateFoldingTest::testFolding()
{
  QFETCH(QString, text);
  QFETCH(QString, fileExt);
  QFETCH(QString, firstActionName);
  QFETCH(QString, secondActionName);

  QFETCH(unsigned int, initValue);
  QFETCH(unsigned int, firstResult);
  QFETCH(unsigned int, secondResult);

  KTemporaryFile file;
  file.setSuffix("." + fileExt);
  file.open();
  QTextStream stream(&file);

  stream << text;
  stream << flush;
  file.close();

  KateDocument doc(false, false, false);
  QVERIFY(doc.openUrl(KUrl(file.fileName())));

  KateView* view = new KateView(&doc, 0);

  QAction* firstAction = view->action(qPrintable(firstActionName));
  QVERIFY(firstAction);

  QAction* secondAction = view->action(qPrintable(secondActionName));
  QVERIFY(secondAction);

  // is set to allow kate's hl to be called
  view->config()->setDynWordWrap(true);

  QCOMPARE(doc.visibleLines(), initValue);

  firstAction->trigger();
  QCOMPARE(doc.visibleLines(), firstResult);

  secondAction->trigger();
  QCOMPARE(doc.visibleLines(), secondResult);
}
Ejemplo n.º 27
0
QString KNArticleManager::saveContentToTemp(KMime::Content *c)
{
  QString path;
  KTemporaryFile* tmpFile;
  KMime::Headers::Base *pathHdr=c->headerByType("X-KNode-Tempfile");  // check for existing temp file

  if(pathHdr) {
    path = pathHdr->asUnicodeString();
    bool found=false;

    // lets see if the tempfile-path is still valid...
    for ( QList<KTemporaryFile*>::Iterator it = mTempFiles.begin(); it != mTempFiles.end(); ++it ) {
      if ( (*it)->fileName() == path ) {
        found = true;
        break;
      }
    }

    if (found)
      return path;
    else
      c->removeHeader("X-KNode-Tempfile");
  }

  tmpFile=new KTemporaryFile();
  if (!tmpFile->open()) {
    KNHelper::displayTempFileError();
    delete tmpFile;
    return QString();
  }

  mTempFiles.append(tmpFile);
  QByteArray data=c->decodedContent();
  tmpFile->write(data.data(), data.size());
  tmpFile->flush();
  path=tmpFile->fileName();
  pathHdr=new KMime::Headers::Generic("X-KNode-Tempfile", c, path, "UTF-8");
  c->setHeader(pathHdr);

  return path;
}
Ejemplo n.º 28
0
void GlobalIgnoreList::retrieveServerIgnoreList(OrgKdeCervisiaCvsserviceCvsserviceInterface* cvsService,
                                                const QString& repository)
{
    KTemporaryFile tmpFile;
    tmpFile.open();

    // clear old ignore list
    m_stringMatcher.clear();
    
    // now set it up again
    setup();
    
    QDBusReply<QDBusObjectPath> ref = cvsService->downloadCvsIgnoreFile(repository, 
                                                    tmpFile.fileName());
      
    ProgressDialog dlg(0, "Edit", cvsService->service(),ref, "checkout", "CVS Edit");
    if( !dlg.execute() )
        return;
    
    addEntriesFromFile(tmpFile.fileName());
}
Ejemplo n.º 29
0
void BinaryWidget::setData( const QByteArray &data )
{
  delete mMainWidget;

  QString mimetype;
  KMimeType::Ptr mime = KMimeType::findByContent( data );
  if ( mime && !mime->isDefault() )
    mimetype = mime->name();

  if ( !mimetype.isEmpty() ) {
    KParts::ReadOnlyPart *part = KParts::ComponentFactory::createPartInstanceFromQuery<KParts::ReadOnlyPart>( mimetype, QString(), this, this );
    if ( part ) {
      KTemporaryFile file;
      file.setAutoRemove(false);
      file.open();
      file.write( data );
      file.flush();
      part->openUrl( KUrl( file.fileName() ) );
      mMainWidget = part->widget();
    } else {
      mMainWidget = new QLabel( i18n( "No part found for visualization of mimetype %1", mimetype ), this );
    }

    mData = data;
    mSaveButton->setEnabled( true );
  } else {
    mMainWidget = new QLabel( i18n( "Got data of unknown mimetype" ), this );
  }

  mLayout->addWidget( mMainWidget, 0, 0, 3, 1);
  mMainWidget->show();
}
Ejemplo n.º 30
0
void ReportGenerator::slotConvertTemplate( const QString& templ )
{
  // kDebug() << "Report BASE:\n" << templ;

  if ( ! templ.isEmpty() ) {
    KTemporaryFile temp;
    temp.setSuffix( ".trml" );
    temp.setAutoRemove( false );

    if ( temp.open() ) {
      QTextStream s(&temp);

      // The following explicit coding settings were needed for Qt 4.7.3, former Qt versions
      // seemed to default on UTF-8. Try to comment the following two lines for older Qt versions
      // if needed and see if the trml file on the disk still is UTF-8 encoded.
      QTextCodec *codec = QTextCodec::codecForName("UTF-8");
      s.setCodec( codec );

      s << templ;
    } else {
      kDebug() << "ERROR: Could not open temporar file";
    }

    kDebug() << "Wrote rml to " << temp.fileName();

    QString dId( mDocId );

    if ( mDocId.isEmpty() ) {
      dId = ArchiveMan::self()->documentID( mArchId );
    }
    runTrml2Pdf( temp.fileName(), dId, mArchId.toString() );
  }
}