// 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" ) ); } }
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." ) ); } }
void TestM3UPlaylist::testSave() { KTemporaryFile temp; temp.setSuffix( ".m3u" ); QVERIFY( temp.open() ); QVERIFY( m_testPlaylist->save( temp.fileName(), false ) ); }
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; }
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 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 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 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() ); } }
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 ); }
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; }
//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 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); }
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; }
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)); }
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); }
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); }
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); } }
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 ); }
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); }
bool KWebPage::handleReply(QNetworkReply* reply, QString* contentType, KIO::MetaData* metaData) { // Reply url... const KUrl replyUrl (reply->url()); // Get suggested file name... const KIO::MetaData& data = reply->attribute(static_cast<QNetworkRequest::Attribute>(KIO::AccessManager::MetaData)).toMap(); const QString suggestedFileName = data.value(QL1S("content-disposition-filename")); if (metaData) { *metaData = data; } // Get the mime-type... QString mimeType; extractMimeType(reply, mimeType); if (contentType) { *contentType = mimeType; } // Let the calling function deal with handling empty or inode/* mimetypes... if (mimeType.isEmpty() || mimeType.startsWith(QL1S("inode/"), Qt::CaseInsensitive)) { return false; } // Convert executable text files to plain text... if (KParts::BrowserRun::isTextExecutable(mimeType)) mimeType = QL1S("text/plain"); //kDebug(800) << "Content-disposition:" << suggestedFileName; //kDebug(800) << "Got unsupported content of type:" << mimeType << "URL:" << replyUrl; //kDebug(800) << "Error code:" << reply->error() << reply->errorString(); if (isReplyStatusOk(reply)) { while (true) { KParts::BrowserOpenOrSaveQuestion::Result result; KParts::BrowserOpenOrSaveQuestion dlg(d->windowWidget(), replyUrl, mimeType); dlg.setSuggestedFileName(suggestedFileName); dlg.setFeatures(KParts::BrowserOpenOrSaveQuestion::ServiceSelection); result = dlg.askOpenOrSave(); switch (result) { case KParts::BrowserOpenOrSaveQuestion::Open: // Handle Post operations that return content... if (reply->operation() == QNetworkAccessManager::PostOperation) { d->mimeType = mimeType; QFileInfo finfo (suggestedFileName.isEmpty() ? replyUrl.fileName() : suggestedFileName); KTemporaryFile tempFile; tempFile.setSuffix(QL1C('.') + finfo.suffix()); tempFile.setAutoRemove(false); tempFile.open(); KUrl destUrl; destUrl.setPath(tempFile.fileName()); KIO::Job *job = KIO::file_copy(replyUrl, destUrl, 0600, KIO::Overwrite); job->ui()->setWindow(d->windowWidget()); job->ui()->setAutoErrorHandlingEnabled(true); connect(job, SIGNAL(result(KJob*)), this, SLOT(_k_copyResultToTempFile(KJob*))); return true; } // Ask before running any executables... if (KParts::BrowserRun::allowExecution(mimeType, replyUrl)) { KService::Ptr offer = dlg.selectedService(); // HACK: The check below is necessary to break an infinite // recursion that occurs whenever this function is called as a result // of receiving content that can be rendered by the app using this engine. // For example a text/html header that containing a content-disposition // header is received by the app using this class. if (isMimeTypeAssociatedWithSelf(offer)) { reloadRequestWithoutDisposition(reply); } else { KUrl::List list; list.append(replyUrl); bool success = false; // kDebug(800) << "Suggested file name:" << suggestedFileName; if (offer) { success = KRun::run(*offer, list, d->windowWidget() , false, suggestedFileName); } else { success = KRun::displayOpenWithDialog(list, d->windowWidget(), false, suggestedFileName); if (!success) break; } // For non KIO apps and cancelled Open With dialog, remove slave on hold. if (!success || (offer && !offer->categories().contains(QL1S("KDE")))) { KIO::SimpleJob::removeOnHold(); // Remove any slave-on-hold... } } return true; } // TODO: Instead of silently failing when allowExecution fails, notify // the user why the requested action cannot be fulfilled... return false; case KParts::BrowserOpenOrSaveQuestion::Save: // Do not download local files... if (!replyUrl.isLocalFile()) { QString downloadCmd (reply->property("DownloadManagerExe").toString()); if (!downloadCmd.isEmpty()) { downloadCmd += QLatin1Char(' '); downloadCmd += KShell::quoteArg(replyUrl.url()); if (!suggestedFileName.isEmpty()) { downloadCmd += QLatin1Char(' '); downloadCmd += KShell::quoteArg(suggestedFileName); } // kDebug(800) << "download command:" << downloadCmd; if (KRun::runCommand(downloadCmd, view())) return true; } if (!downloadResource(replyUrl, suggestedFileName, d->windowWidget())) break; } return true; case KParts::BrowserOpenOrSaveQuestion::Cancel: default: KIO::SimpleJob::removeOnHold(); // Remove any slave-on-hold... return true; } } } else {
void WebPage::handleUnsupportedContent(QNetworkReply *reply) { Q_ASSERT(reply); // Put the job on hold... #if KDE_IS_VERSION( 4, 5, 96) kDebug() << "PUT REPLY ON HOLD..."; KIO::Integration::AccessManager::putReplyOnHold(reply); #else reply->abort(); #endif // This is probably needed just in ONE stupid case.. if (_protHandler.postHandling(reply->request(), mainFrame())) { kDebug() << "POST HANDLING the unsupported..."; return; } if (reply->error() != QNetworkReply::NoError) return; // get reply url... KUrl replyUrl = reply->url(); bool isLocal = replyUrl.isLocalFile(); if(isLocal && KProtocolInfo::isKnownProtocol(replyUrl)) { kDebug() << "WARNING: launching a new app..."; new KRun(replyUrl, rApp->mainWindow()); // No need to delete KRun, it autodeletes itself return; } // Get suggested file name... extractSuggestedFileName(reply, _suggestedFileName); // Get mimeType... extractMimeType(reply, _mimeType); // Convert executable text files to plain text... if (KParts::BrowserRun::isTextExecutable(_mimeType)) _mimeType = QL1S("text/plain"); kDebug() << "Detected MimeType = " << _mimeType; kDebug() << "Suggested File Name = " << _suggestedFileName; // ------------------------------------------------ KService::Ptr appService = KMimeTypeTrader::self()->preferredService(_mimeType); if (appService.isNull()) // no service can handle this. We can just download it.. { kDebug() << "no service can handle this. We can just download it.."; isLocal ? KMessageBox::sorry(view(), i18n("No service can handle this file.")) : downloadReply(reply, _suggestedFileName); return; } if (!isLocal) { KParts::BrowserOpenOrSaveQuestion dlg(rApp->mainWindow(), replyUrl, _mimeType); if (!_suggestedFileName.isEmpty()) dlg.setSuggestedFileName(_suggestedFileName); switch (dlg.askEmbedOrSave()) { case KParts::BrowserOpenOrSaveQuestion::Save: kDebug() << "user choice: no services, just download!"; downloadReply(reply, _suggestedFileName); return; case KParts::BrowserOpenOrSaveQuestion::Cancel: return; default: // non extant case break; } } // Handle Post operations that return content... if (reply->operation() == QNetworkAccessManager::PostOperation) { kDebug() << "POST OPERATION: downloading file..."; QFileInfo finfo(_suggestedFileName.isEmpty() ? _loadingUrl.fileName() : _suggestedFileName); KTemporaryFile tempFile; tempFile.setSuffix(QL1C('.') + finfo.suffix()); tempFile.setAutoRemove(false); tempFile.open(); KUrl destUrl; destUrl.setPath(tempFile.fileName()); kDebug() << "First save content to" << destUrl; KIO::Job *job = KIO::file_copy(_loadingUrl, destUrl, 0600, KIO::Overwrite); job->ui()->setWindow(rApp->mainWindow()); connect(job, SIGNAL(result(KJob *)), this, SLOT(copyToTempFileResult(KJob*))); return; }
//bool xBaseConnectionInternal::db_connect(QCString host, QCString user, // QCString password, unsigned short int port, QString socket) bool xBaseConnectionInternal::db_connect(const Predicate::ConnectionData& data) { // we have to migrate the xbase source database into a .kexi file // xbase source database directory will be in connectiondata // we can choose a KTemporaryFile for the destination .kexi file KexiMigration::MigrateManager xBase2KexiMigrateManager; // create a temporary .kexi file KTemporaryFile temporaryKexiFile; temporaryKexiFile.setSuffix( ".kexi" ); temporaryKexiFile.setAutoRemove( false ); if ( !temporaryKexiFile.open() ) { PreDrvDbg<<"Couldn't create .kexi file for exporting from xBase to .kexi"; return false; } tempDatabase = temporaryKexiFile.fileName(); Predicate::ConnectionData* kexiConnectionData = 0; kexiConnectionData = new Predicate::ConnectionData(); // set destination file name here. kexiConnectionData->driverName = Predicate::defaultFileBasedDriverName(); kexiConnectionData->setFileName( tempDatabase ); PreDrvDbg << "Current file name: " << tempDatabase; QString sourceDriverName = "xbase"; // get the source migration driver KexiMigration::KexiMigrate* sourceDriver = 0; sourceDriver = xBase2KexiMigrateManager.driver( sourceDriverName ); if(!sourceDriver || xBase2KexiMigrateManager.error()) { PreDrvDbg << "Import migrate driver error..."; return false; } KexiMigration::Data* md = new KexiMigration::Data(); md->keepData = true; md->destination = new KexiProjectData(*kexiConnectionData, tempDatabase); // Setup XBase connection data from input connection data passed //! TODO Check sanity of this md->source = new Predicate::ConnectionData(data); md->sourceName = ""; sourceDriver->setData(md); if ( !sourceDriver->performImport() ) { PreDrvDbg<<"Import failed"; return false; } // finished transferring xBase database into .kexi file // Get a driver to the destination database if ( internalDriver ) internalConn = internalDriver->createConnection(*kexiConnectionData); else return false; if (!internalConn || internalDriver->error()) { internalDriver->debugError(); return false; } if (!internalConn->connect()) { internalConn->debugError(); storeResult(); return false; } if (!internalConn->useDatabase(tempDatabase)) { internalConn->debugError(); storeResult(); return false; } // store mapping from xbase directory to .kexi file name for future use // Note: When a directory is specified ( as has to be done for xBase ), fileName() // will give directory name with an additional forward slash. dbPath() won't do so. // Need some more maintainable solution. dbMap[data.fileName()] = tempDatabase; return true; }
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; }
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; }