Exemplo n.º 1
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" ) );
    }
}
Exemplo n.º 2
0
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;
}
Exemplo n.º 3
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"));
}
Exemplo n.º 4
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 );
}
Exemplo n.º 6
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;
}
Exemplo n.º 7
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);
}
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." ) );
  }
}
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;
}
Exemplo n.º 10
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);

}
Exemplo n.º 11
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());
    }
}
Exemplo n.º 12
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);
}
Exemplo n.º 13
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);
}
Exemplo n.º 14
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);
}
    KUrl tempFileForAttachment( KCal::Attachment *attachment )
    {
      if ( mTempFiles.contains( attachment ) ) {
        return mTempFiles.value( attachment );
      }
      KTemporaryFile *file = new KTemporaryFile();
      file->setParent( this );

      QStringList patterns = KMimeType::mimeType( attachment->mimeType() )->patterns();

      if ( !patterns.empty() ) {
        file->setSuffix( QString( patterns.first() ).remove( '*' ) );
      }
      file->setAutoRemove( true );
      file->open();
      // read-only not to give the idea that it could be written to
      file->setPermissions( QFile::ReadUser );
      file->write( QByteArray::fromBase64( attachment->data() ) );
      mTempFiles.insert( attachment, file->fileName() );
      file->close();
      return mTempFiles.value( attachment );
    }
bool KoReportHTMLTableRenderer::render(const KoReportRendererContext& context, ORODocument *document, int page)
{
    Q_UNUSED(page);
    KTemporaryFile tempHtmlFile; // auto removed by default on destruction
    if (!tempHtmlFile.open()) {
        kDebug() << "Couldn't create temporary file to write into";
        return false;
    }

    QTextStream out(&tempHtmlFile);

    QString dirSuffix = ".files";
    QDir tempDir;
    QFileInfo fi(tempHtmlFile);

    QString tempFileName = fi.absoluteFilePath();
    m_tempDirName = tempFileName + dirSuffix;
    m_actualDirName = context.destinationUrl.fileName() + dirSuffix;

    if (!tempDir.mkpath(m_tempDirName))
        return false;

    out << renderTable(document);

    out.flush();
    tempHtmlFile.close();

    bool status = false;
    if (KIO::NetAccess::upload(tempFileName, context.destinationUrl, 0) && KIO::NetAccess::dircopy(KUrl(m_tempDirName),  KUrl(context.destinationUrl.url() + dirSuffix), 0)) {
        status = true;
    }

    // cleanup the temporary directory
    tempDir.setPath(m_tempDirName);
    QStringList fileList = tempDir.entryList();
    foreach(const QString& fileName, fileList) {
        tempDir.remove(fileName);
    }
Exemplo 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 TodoPlugin::processDropEvent( QDropEvent *event )
{
  const QMimeData *md = event->mimeData();

  if ( KABC::VCardDrag::canDecode( md ) ) {
    KABC::Addressee::List contacts;

    KABC::VCardDrag::fromMimeData( md, contacts );

    KABC::Addressee::List::Iterator it;

    QStringList attendees;
    for ( it = contacts.begin(); it != contacts.end(); ++it ) {
      QString email = (*it).fullEmail();
      if ( email.isEmpty() ) {
        attendees.append( (*it).realName() + "<>" );
      } else {
        attendees.append( email );
      }
    }

    interface()->openTodoEditor( i18nc( "@item", "Meeting" ),
                                 QString(), QStringList(), attendees );
    return;
  }

  if ( KCalUtils::ICalDrag::canDecode( event->mimeData() ) ) {
    KCalCore::MemoryCalendar::Ptr cal( new KCalCore::MemoryCalendar( KSystemTimeZones::local() ) );
    if ( KCalUtils::ICalDrag::fromMimeData( event->mimeData(), cal ) ) {
      KCalCore::Incidence::List incidences = cal->incidences();
      Q_ASSERT( incidences.count() );
      if ( !incidences.isEmpty() ) {
        event->accept();
        KCalCore::Incidence::Ptr i = incidences.first();
        QString summary;
        if ( i->type() == KCalCore::Incidence::TypeJournal ) {
          summary = i18nc( "@item", "Note: %1", i->summary() );
        } else {
          summary = i->summary();
        }
        interface()->openTodoEditor( summary, i->description(), QStringList() );
        return;
      }
      // else fall through to text decoding
    }
  }

  if ( md->hasText() ) {
    QString text = md->text();
    interface()->openTodoEditor( text );
    return;
  }

  if ( KPIM::MailList::canDecode( md ) ) {
    KPIM::MailList mails = KPIM::MailList::fromMimeData( md );
    event->accept();
    if ( mails.count() != 1 ) {
      KMessageBox::sorry(
        core(),
        i18nc( "@info", "Dropping multiple mails is not supported." ) );
    } else {
      KPIM::MailSummary mail = mails.first();
      QString txt = i18nc( "@item", "From: %1\nTo: %2\nSubject: %3",
                           mail.from(), mail.to(), mail.subject() );
      QString uri = QLatin1String( "kmail:" ) +
                    QString::number( mail.serialNumber() ) + '/' +
                    mail.messageId();
      KTemporaryFile tf;
      tf.setAutoRemove( true );
      tf.write( event->encodedData( "message/rfc822" ) );
      interface()->openTodoEditor(
        i18nc( "@item", "Mail: %1", mail.subject() ),
        txt, uri, tf.fileName(), QStringList(), "message/rfc822" );
      tf.close();
    }
    return;
  }

  kWarning() << QString( "Cannot handle drop events of type '%1'." ).arg( event->format() );
}
Exemplo n.º 19
0
QString PostscriptDialog::buildTempfile()
{
	// build command
	m_program = "pstops";          // default
	m_param = "";

	switch (m_PostscriptDialog.m_cbTask->currentIndex()) {
		case PS_A5_EMPTY:      m_param = "1:0L(29.7cm,0cm)";
		                       break;
		case PS_A5_DUPLICATE:  m_param = "1:0L(29.7cm,0cm)+0L(29.7cm,14.85cm)";
		                       break;
		case PS_2xA5:          m_param = "2:0L(29.7cm,0cm)+1L(29.7cm,14.85cm)";
		                       break;
		case PS_2xA5L:         break;
		case PS_4xA5:          m_param = "4:[email protected](0cm,8.7cm)"
		                                 "[email protected](10.5cm,8.7cm)"
		                                 "[email protected](0cm,-6.15cm)"
		                                 "[email protected](10.5cm,-6.15cm)";
		                       break;
		case PS_A4_EMPTY:      m_param = "1:[email protected](21cm,0cm)";
		                       break;
		case PS_A4_DUPLICATE:  m_param = "1:[email protected](21cm,0cm)[email protected](21cm,14.85cm)";
		                       break;
		case PS_2xA4:          m_param = "2:[email protected](21cm,0cm)[email protected](21cm,14.85cm)";
		                       break;
		case PS_2xA4L:         m_param = "2:[email protected](0cm,29.7cm)[email protected](0cm,14.85cm)";
		                       break;
		case PS_EVEN:          m_program = "psselect";
		                       m_param = "-e";
		                       break;
		case PS_ODD:           m_program = "psselect";
		                       m_param = "-o";
		                       break;
		case PS_EVEN_REV:      m_program = "psselect";
		                       m_param = "-e -r";
		                       break;
		case PS_ODD_REV:       m_program = "psselect";
		                       m_param = "-o -r";
		                       break;
		case PS_REVERSE:       m_program = "psselect";
		                       m_param = "-r";
		                       break;
		case PS_COPY_SORTED:   m_program = "psselect";
		                       m_param = "-p" + duplicateParameter("1-");
		                       break;
		case PS_COPY_UNSORTED: m_param = "1:" + duplicateParameter("0");
		                       break;
		case PS_PSTOPS_FREE:   m_param = m_PostscriptDialog.m_edParameter->text();
		                       break;
		case PS_PSSELECT_FREE: m_program = "psselect";
		                       m_param = m_PostscriptDialog.m_edParameter->text();
		                       break;
	}

	// create a temporary file
	KTemporaryFile temp;
	temp.setSuffix(".sh");
	temp.setAutoRemove(false);
	if(!temp.open()) {
		KILE_DEBUG() << "Could not create tempfile in QString PostscriptDialog::buildTempfile()" ;
		return QString();
	}
	QString tempname = temp.fileName();
	
	QTextStream stream(&temp);
	stream << "#! /bin/sh" << endl;

	// accept only ".ps" or ".ps.gz" as an input file
	QFileInfo fi(m_PostscriptDialog.m_edInfile->lineEdit()->text());
	bool zipped_psfile = (fi.completeSuffix() == "ps.gz") ? true : false;

	// there are four possible cases
	//         outfile view
	//     1)    +      +        pstops/psselect + okular
	//     2)    +      -        pstops/psselect
	//     3)    -      +        pstops/psselect | okular (nur Shell)
	//     4)    -      -        error (already detected by checkParameter())

	// some files, which are used
	QString command    = m_program + " \"" + m_param + "\"";
	QString inputfile  = "\"" + m_PostscriptDialog.m_edInfile->lineEdit()->text() + "\"";
	QString outputfile = "\"" + m_PostscriptDialog.m_edOutfile->lineEdit()->text() + "\"";
	bool viewer = m_PostscriptDialog.m_cbView->isChecked();
	
	bool equalfiles = false;
	if (inputfile == outputfile) {
		outputfile = tempname + ".tmp";
		equalfiles = true;
	}
	
	if (!zipped_psfile) {                                       // unzipped ps files
		if (m_PostscriptDialog.m_edOutfile->lineEdit()->text().isEmpty()) { // pstops/psselect | okular
			stream << command << " " << inputfile << " | okular -" << endl;
			viewer = false;
		} else {                                                    // pstops/psselect
			stream << command << " " << inputfile << " " << outputfile << endl;
		}
	} else {                                                      // zipped ps files
		if (m_PostscriptDialog.m_edOutfile->lineEdit()->text().isEmpty()) { // pstops/psselect | okular
			stream << "gunzip -c " << inputfile
			       << " | " << command
			       << " | okular -"
			       << endl;
			viewer = false;
		} else {
			stream << "gunzip -c " << inputfile                    // pstops/psselect
			       << " | " << command
			       << " > " << outputfile
			       << endl;
		}
	}

	// check, if we should stop
	if ( equalfiles || viewer ) {
		stream << "if [ $? != 0 ]; then" << endl;
		stream << "   exit 1" << endl;
		stream << "fi" << endl;
	}

	// replace the original file
	if ( equalfiles ) {
		stream << "rm " << inputfile << endl;
		stream << "mv " << outputfile << " " << inputfile << endl;
	}

	// viewer
	if ( viewer ) {                                                // viewer: okular
		stream << "okular" << " " 
		       << ((equalfiles) ? inputfile : outputfile) << endl;
	}

	// everything is prepared to do the job
	temp.close();

	return(tempname);
}
Exemplo n.º 20
0
void ghostscript_interface::gs_generate_graphics_file(const PageNumber& page, const QString& filename, long magnification) {
#ifdef DEBUG_PSGS
  kDebug(kvs::dvi) << "ghostscript_interface::gs_generate_graphics_file( " << page << ", " << filename << " )";
#endif

  if (knownDevices.isEmpty()) {
    kError(kvs::dvi) << "No known devices found" << endl;
    return;
  }

  pageInfo *info = pageList.value(page);

  // Generate a PNG-file
  // Step 1: Write the PostScriptString to a File
  KTemporaryFile PSfile;
  PSfile.setAutoRemove(false);
  PSfile.setSuffix(".ps");
  PSfile.open();
  const QString PSfileName = PSfile.fileName();

  QTextStream os(&PSfile);
  os << "%!PS-Adobe-2.0\n"
     << "%%Creator: kdvi\n"
     << "%%Title: KDVI temporary PostScript\n"
     << "%%Pages: 1\n"
     << "%%PageOrder: Ascend\n"
        // HSize and VSize in 1/72 inch
     << "%%BoundingBox: 0 0 "
     << (qint32)(72*(pixel_page_w/resolution)) << ' '
     << (qint32)(72*(pixel_page_h/resolution)) << '\n'
     << "%%EndComments\n"
     << "%!\n"
     << psheader
     << "TeXDict begin "
        // HSize in (1/(65781.76*72))inch
     << (qint32)(72*65781*(pixel_page_w/resolution)) << ' '
        // VSize in (1/(65781.76*72))inch
     << (qint32)(72*65781*(pixel_page_h/resolution)) << ' '
        // Magnification
     << (qint32)(magnification)
        // dpi and vdpi
     << " 300 300"
        // Name
     << " (test.dvi)"
     << " @start end\n"
     << "TeXDict begin\n"
        // Start page
     << "1 0 bop 0 0 a \n";

  if (!PostScriptHeaderString->toLatin1().isNull())
    os << PostScriptHeaderString->toLatin1();

  if (info->background != Qt::white) {
    QString colorCommand = QString("gsave %1 %2 %3 setrgbcolor clippath fill grestore\n").
      arg(info->background.red()/255.0).
      arg(info->background.green()/255.0).
      arg(info->background.blue()/255.0);
    os << colorCommand.toLatin1();
  }

  if (!info->PostScriptString->isNull())
    os << *(info->PostScriptString);

  os << "end\n"
     << "showpage \n";

  PSfile.close();

  // Step 2: Call GS with the File
  QFile::remove(filename.toAscii());
  KProcess proc;
  proc.setOutputChannelMode(KProcess::SeparateChannels);
  QStringList argus;
  argus << "gs";
  argus << "-dSAFER" << "-dPARANOIDSAFER" << "-dDELAYSAFER" << "-dNOPAUSE" << "-dBATCH";
  argus << QString("-sDEVICE=%1").arg(*gsDevice);
  argus << QString("-sOutputFile=%1").arg(filename);
  argus << QString("-sExtraIncludePath=%1").arg(includePath);
  argus << QString("-g%1x%2").arg(pixel_page_w).arg(pixel_page_h); // page size in pixels
  argus << QString("-r%1").arg(resolution);                       // resolution in dpi
  argus << "-dTextAlphaBits=4 -dGraphicsAlphaBits=2"; // Antialiasing
  argus << "-c" << "<< /PermitFileReading [ ExtraIncludePath ] /PermitFileWriting [] /PermitFileControl [] >> setuserparams .locksafe";
  argus << "-f" << PSfileName;

#ifdef DEBUG_PSGS
  kDebug(kvs::dvi) << argus.join(" ");
#endif
 
  proc << argus;
  int res = proc.execute();
  
  if ( res ) {
    // Starting ghostscript did not work. 
    // TODO: Issue error message, switch PS support off.
    kError(kvs::dvi) << "ghostview could not be started" << endl;
  } 

  PSfile.remove();

 // Check if gs has indeed produced a file.
  if (QFile::exists(filename) == false) {
    kError(kvs::dvi) << "GS did not produce output." << endl;

    // No. Check is the reason is that the device is not compiled into
    // ghostscript. If so, try again with another device.
    QString GSoutput;
    proc.setReadChannel(QProcess::StandardOutput);
    while(proc.canReadLine()) {
      GSoutput = QString::fromLocal8Bit(proc.readLine());
      if (GSoutput.contains("Unknown device")) {
	kDebug(kvs::dvi) << QString("The version of ghostview installed on this computer does not support "
                                     "the '%1' ghostview device driver.").arg(*gsDevice) << endl;
	knownDevices.erase(gsDevice);
	gsDevice = knownDevices.begin();
	if (knownDevices.isEmpty())
	  // TODO: show a requestor of some sort.
#if 0
	  KMessageBox::detailedError(0, 
				     i18n("<qt>The version of Ghostview that is installed on this computer does not contain "
					  "any of the Ghostview device drivers that are known to Okular. PostScript "
					  "support has therefore been turned off in Okular.</qt>"), 
				     i18n("<qt><p>The Ghostview program, which Okular uses internally to display the "
					  "PostScript graphics that is included in this DVI file, is generally able to "
					  "write its output in a variety of formats. The sub-programs that Ghostview uses "
					  "for these tasks are called 'device drivers'; there is one device driver for "
					  "each format that Ghostview is able to write. Different versions of Ghostview "
					  "often have different sets of device drivers available. It seems that the "
					  "version of Ghostview that is installed on this computer does not contain "
					  "<strong>any</strong> of the device drivers that are known to Okular.</p>"
					  "<p>It seems unlikely that a regular installation of Ghostview would not contain "
					  "these drivers. This error may therefore point to a serious misconfiguration of "
					  "the Ghostview installation on your computer.</p>"
					  "<p>If you want to fix the problems with Ghostview, you can use the command "
					  "<strong>gs --help</strong> to display the list of device drivers contained in "
					  "Ghostview. Among others, Okular can use the 'png256', 'jpeg' and 'pnm' "
					  "drivers. Note that Okular needs to be restarted to re-enable PostScript support."
					  "</p></qt>"));
#else
	{}
#endif
	else {
	  kDebug(kvs::dvi) << QString("Okular will now try to use the '%1' device driver.").arg(*gsDevice);
	  gs_generate_graphics_file(page, filename, magnification);
	}
	return;
      }