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() );
  }
}
Example #2
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;
}
KJotsBook* KnowItImporter::importFromUrl( KUrl url )
{
  KJotsBook *book = new KJotsBook();
  buildNoteTree(url);

//   foreach ()
//   kDebug();
  buildDomDocument();


  KTemporaryFile file;
  file.setPrefix( KStandardDirs::locateLocal( "data", "kjots/" ) );
  file.setSuffix( ".book" );
  file.setAutoRemove( false );

  if ( file.open() ) {
    file.write( "<?xml version='1.0' encoding='UTF-8' ?>\n<!DOCTYPE KJots>\n<KJots>\n" );
    file.write( m_domDoc.toByteArray() );
    file.write( "</KJots>\n" );
    kDebug() << file.fileName();
    QString newFileName = file.fileName();
    file.close();
    book->openBook( newFileName );
  }


  return book;
}
void Docbook2XhtmlGeneratorJob::run()
{
  UMLDoc* umlDoc = UMLApp::app()->document();
  xsltStylesheetPtr cur = NULL;
  xmlDocPtr doc, res;

  const char *params[16 + 1];
  int nbparams = 0;
  params[nbparams] = NULL;

  umlDoc->writeToStatusBar(i18n("Exporting to XHTML..."));

  QString xsltFileName(KGlobal::dirs()->findResource("appdata", QLatin1String("docbook2xhtml.xsl")));
  uDebug() << "XSLT file is'" << xsltFileName << "'";
  QFile xsltFile(xsltFileName);
  xsltFile.open(QIODevice::ReadOnly);
  QString xslt = QString::fromLatin1(xsltFile.readAll());
  uDebug() << "XSLT is'" << xslt << "'";
  xsltFile.close();

  QString localXsl = KGlobal::dirs()->findResource("data", QLatin1String("ksgmltools2/docbook/xsl/html/docbook.xsl"));
  uDebug() << "Local xsl is'" << localXsl << "'";
  if (!localXsl.isEmpty())
  {
    localXsl = QLatin1String("href=\"file://") + localXsl + QLatin1String("\"");
    xslt.replace(QRegExp(QLatin1String("href=\"http://[^\"]*\"")), localXsl);
  }
  KTemporaryFile tmpXsl;
  tmpXsl.setAutoRemove(false);
  tmpXsl.open();
  QTextStream str (&tmpXsl);
  str << xslt;
  str.flush();

  xmlSubstituteEntitiesDefault(1);
  xmlLoadExtDtdDefaultValue = 1;
  uDebug() << "Parsing stylesheet " << tmpXsl.fileName();
  cur = xsltParseStylesheetFile((const xmlChar *)tmpXsl.fileName().toLatin1().constData());
  uDebug() << "Parsing file " << m_docbookUrl.path();
  doc = xmlParseFile((const char*)(m_docbookUrl.path().toUtf8()));
  uDebug() << "Applying stylesheet ";
  res = xsltApplyStylesheet(cur, doc, params);

  KTemporaryFile tmpXhtml;
  tmpXhtml.setAutoRemove(false);
  tmpXhtml.open();

  uDebug() << "Writing HTML result to temp file: " << tmpXhtml.fileName();
  xsltSaveResultToFd(tmpXhtml.handle(), res, cur);

  xsltFreeStylesheet(cur);
  xmlFreeDoc(res);
  xmlFreeDoc(doc);

  xsltCleanupGlobals();
  xmlCleanupParser();

  emit xhtmlGenerated(tmpXhtml.fileName());
}
Example #5
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);
}
Example #6
0
    bool downloadRemoteUrls(const QString& collectionName, const KUrl::List& _list, RemoteUrlHash* hash)
    {
        Q_ASSERT(hash);
        KUrl::List list;
        Q_FOREACH(const KUrl& url, _list)
        {
            if (!url.isLocalFile())
            {
                list << url;
            }
        }

        if (list.count() == 0)
        {
            return true;
        }

        logInfo( i18n("Downloading remote files for \"%1\"", collectionName) );

        mProgressDialog->progressWidget()->setTotal(list.count());
        int count = 0;
        Q_FOREACH(const KUrl& url, list)
        {
            if (mProgressDialog->isHidden())
            {
                return false;
            }
            KTemporaryFile* tempFile = new KTemporaryFile;
            // Ensure the tempFile gets deleted when mProgressDialog is closed
            tempFile->setParent(mProgressDialog);
            tempFile->setPrefix("htmlexport-");

            if (!tempFile->open())
            {
                delete tempFile;
                logError(i18n("Could not open temporary file"));
                return false;
            }
            const QString tempPath = KStandardDirs::locate("tmp", tempFile->fileName());
            KIO::Job* job          = KIO::file_copy(url, KUrl::fromPath(tempPath), -1 /* permissions */, KIO::Overwrite);
            if (KIO::NetAccess::synchronousRun(job, mProgressDialog))
            {
                hash->insert(url, tempFile->fileName());
            }
            else
            {
                logWarning(i18n("Could not download %1", url.prettyUrl()));
                hash->insert(url, QString());
            }

            ++count;
            mProgressDialog->progressWidget()->setProgress(count);
        }

        return true;
    }
Example #7
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());
            }
        }
    }
}
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" ) );
            }
        }
    }
}
Example #9
0
void KSaveFileTest::test_simpleBackupFile()
{
    KTemporaryFile file;
    QVERIFY( file.open() );

    QVERIFY( KSaveFile::simpleBackupFile(file.fileName()));
    QVERIFY( QFile::exists(file.fileName() + '~'));
    QFile::remove(file.fileName() + '~');

    QVERIFY( KSaveFile::simpleBackupFile(file.fileName(), tmp) );
    QFileInfo fi ( file.fileName() );
    QVERIFY( QFile::exists(tmp + fi.fileName() + '~') );
    QFile::remove(tmp + fi.fileName() + '~');
}
Example #10
0
// All the simple tests for findByPath are in testFindByPathUsingFileName_data.
// In here we do the tests that need some content in a temporary file.
void KMimeTypeTest::testFindByPathWithContent()
{
    KMimeType::Ptr mime;

    // Test a real PDF file.
    // If we find x-matlab because it starts with '%' then we are not ordering by priority.
    KTemporaryFile tempFile;
    QVERIFY(tempFile.open());
    QString tempFileName = tempFile.fileName();
    tempFile.write("%PDF-");
    tempFile.close();
    mime = KMimeType::findByPath( tempFileName );
    QVERIFY( mime );
    QCOMPARE( mime->name(), QString::fromLatin1( "application/pdf" ) );
    // fast mode cannot find the mimetype
    mime = KMimeType::findByPath( tempFileName, 0, true );
    QVERIFY( mime );
    QCOMPARE(mime->name(), QString::fromLatin1("application/octet-stream"));

    // Test the case where the extension doesn't match the contents: extension wins
    {
        KTemporaryFile txtTempFile;
        txtTempFile.setSuffix(".txt");
        QVERIFY(txtTempFile.open());
        txtTempFile.write("%PDF-");
        QString txtTempFileName = txtTempFile.fileName();
        txtTempFile.close();
        mime = KMimeType::findByPath( txtTempFileName );
        QVERIFY( mime );
        QCOMPARE( mime->name(), QString::fromLatin1( "text/plain" ) );
        // fast mode finds the same
        mime = KMimeType::findByPath( txtTempFileName, 0, true );
        QVERIFY( mime );
        QCOMPARE( mime->name(), QString::fromLatin1( "text/plain" ) );
    }

    // Now the case where extension differs from contents, but contents has >80 magic rule
    // XDG spec says: contents wins. But we can't sniff all files...
    {
        KTemporaryFile txtTempFile;
        txtTempFile.setSuffix(".txt");
        QVERIFY(txtTempFile.open());
        txtTempFile.write("<smil");
        QString txtTempFileName = txtTempFile.fileName();
        txtTempFile.close();
        mime = KMimeType::findByPath( txtTempFileName );
        QVERIFY( mime );
        QCOMPARE( mime->name(), QString::fromLatin1( "text/plain" ) );
    }
}
Example #11
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();
}
Example #12
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"));
}
Example #13
0
void TestM3UPlaylist::testSave()
{
    KTemporaryFile temp;
    temp.setSuffix( ".m3u" );
    QVERIFY( temp.open() );
    QVERIFY( m_testPlaylist->save( temp.fileName(), false ) );
}
Example #14
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;
}
Example #16
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*/);
}
Example #17
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);
}
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 );
}
Example #19
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);
}
Example #20
0
bool DjVuGenerator::print( QPrinter& printer )
{
    bool result = false;

    // Create tempfile to write to
    KTemporaryFile tf;
    tf.setSuffix( ".ps" );
    if ( !tf.open() )
        return false;

    QMutexLocker locker( userMutex() );
    QList<int> pageList = Okular::FilePrinter::pageList( printer, m_djvu->pages().count(),
                                                         document()->currentPage() + 1,
                                                         document()->bookmarkedPageList() );

    if ( m_djvu->exportAsPostScript( &tf, pageList ) )
    {
        tf.setAutoRemove( false );
        const QString fileName = tf.fileName();
        tf.close();
        int ret = Okular::FilePrinter::printFile( printer, fileName, document()->orientation(),
                                                  Okular::FilePrinter::SystemDeletesFiles,
                                                  Okular::FilePrinter::ApplicationSelectsPages,
                                                  document()->bookmarkedPageRange() );
        result = ( ret >=0 );
    }

    return result;
}
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." ) );
  }
}
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();
}
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;
}
static void storeThumbnailToDiskCache(const QString& path, const QImage& image)
{
    LOG(path);
    KTemporaryFile tmp;
    tmp.setPrefix(path + ".gwenview.tmp");
    tmp.setSuffix(".png");
    if (!tmp.open()) {
        kWarning() << "Could not create a temporary file.";
        return;
    }

    if (!image.save(tmp.fileName(), "png")) {
        kWarning() << "Could not save thumbnail";
        return;
    }

    KDE_rename(QFile::encodeName(tmp.fileName()), QFile::encodeName(path));
}
Example #25
0
bool SSMLConvert::transform(const QString &text, const QString &xsltFilename) {
    m_xsltFilename = xsltFilename;
    /// Write @param text to a temporary file.
    KTemporaryFile inFile;
    inFile.setPrefix(QLatin1String( "kttsd-" ));
    inFile.setSuffix(QLatin1String( ".ssml" ));
    inFile.setAutoRemove(false);
    inFile.open();
    m_inFilename = inFile.fileName();
    QTextStream wstream (&inFile);
    // TODO: Is encoding an issue here?
    // TODO: It would be nice if we detected whether the XML is properly formed
    // with the required xml processing instruction and encoding attribute.  If
    // not wrap it in such.  But maybe this should be handled by SpeechData::setText()?
    wstream << text;
    inFile.flush();

    // Get a temporary output file name.
    KTemporaryFile outFile;
    outFile.setPrefix(QLatin1String( "kttsd-" ));
    outFile.setSuffix(QLatin1String( ".output" ));
    outFile.setAutoRemove(false);
    outFile.open();
    m_outFilename = outFile.fileName();

    /// Spawn an xsltproc process to apply our stylesheet to our SSML file.
	QStringList args;
    m_xsltProc = new QProcess;
    args << QLatin1String( "-o" ) << m_outFilename  << QLatin1String( "--novalid" )
        << m_xsltFilename << m_inFilename;
    // Warning: This won't compile under KDE 3.2.  See FreeTTS::argsToStringList().
    // kDebug() << "SSMLConvert::transform: executing command: " <<
    //     m_xsltProc->args() << endl;

    connect(m_xsltProc, SIGNAL(finished(int,QProcess::ExitStatus)),
        this, SLOT(slotProcessExited()));
    if (!m_xsltProc->execute(QLatin1String("xsltproc"), args))
    {
        kDebug() << "SSMLConvert::transform: Error starting xsltproc";
        return false;
    }
    m_state = tsTransforming;
    return true;
}
Example #26
0
void TutorialTester::sendTutorialToTargetApplication() {
    disconnect(TargetApplication::self(), SIGNAL(started()),
               this, SLOT(sendTutorialToTargetApplication()));

    //As this TutorialTester is set as parent of the KTemporaryFile object, the
    //file will be automatically removed when this TutorialTester is destroyed
    KTemporaryFile* temporaryFile = new KTemporaryFile();
    temporaryFile->setAutoRemove(true);
    temporaryFile->setParent(this);
    temporaryFile->setSuffix(".js");
    temporaryFile->open();

    const Tutorial* tutorial = mTutorialEditor->tutorial();
    try {
        Serialization(mTutorialEditor).
                    exportTutorial(tutorial, "*.js", temporaryFile->fileName());
    } catch (IOException e) {
        QString text = i18nc("@label", "There was a problem when trying to "
"save the tutorial to a temporary file (to be used by the target application "
"to test the tutorial):<nl/>%1", e.message());
        QString caption = i18nc("@title:window", "Tutorial could not be saved");
        KMessageBox::error(mTutorialEditor, text, caption);
        delete temporaryFile;
        return;
    }

    try {
        if (mStepId.isEmpty()) {
            TargetApplication::self()->remoteEditorSupport()->
                                testScriptedTutorial(temporaryFile->fileName());
        } else {
            TargetApplication::self()->remoteEditorSupport()->
                    testScriptedTutorial(temporaryFile->fileName(), mStepId);
        }
    } catch (DBusException e) {
        QString text = i18nc("@label", "There was a problem when trying to "
"tell the target application to start the tutorial:<nl/>%1", e.message());
        QString caption = i18nc("@title:window", "Tutorial could not be "
"started");
        KMessageBox::error(mTutorialEditor, text, caption);
    }
}
Example #27
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());
}
Example #28
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);

}
Example #29
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());
    }
}
Example #30
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;
}