diff --git a/autotests/data/file1-docdata.xml b/autotests/data/file1-docdata.xml
new file mode 100644
index 000000000..0904d748b
--- /dev/null
+++ b/autotests/data/file1-docdata.xml
@@ -0,0 +1,427 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/autotests/data/potato.jpg b/autotests/data/potato.jpg
new file mode 100644
index 000000000..b7dd4d188
Binary files /dev/null and b/autotests/data/potato.jpg differ
diff --git a/autotests/documenttest.cpp b/autotests/documenttest.cpp
index e96322834..2430be3b4 100644
--- a/autotests/documenttest.cpp
+++ b/autotests/documenttest.cpp
@@ -1,63 +1,133 @@
/***************************************************************************
* Copyright (C) 2013 by Fabio D'Urso *
+ * Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group *
+ * company, info@kdab.com. Work sponsored by the *
+ * LiMux project of the city of Munich *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include
#include
+#include "../core/annotations.h"
#include "../core/document.h"
+#include "../core/document_p.h"
#include "../core/generator.h"
#include "../core/observer.h"
+#include "../core/page.h"
#include "../core/rotationjob_p.h"
#include "../settings_core.h"
class DocumentTest
: public QObject
{
Q_OBJECT
private slots:
void testCloseDuringRotationJob();
+ void testDocdataMigration();
};
// Test that we don't crash if the document is closed while a RotationJob
// is enqueued/running
void DocumentTest::testCloseDuringRotationJob()
{
Okular::SettingsCore::instance( QStringLiteral("documenttest") );
Okular::Document *m_document = new Okular::Document( nullptr );
const QString testFile = QStringLiteral(KDESRCDIR "data/file1.pdf");
QMimeDatabase db;
const QMimeType mime = db.mimeTypeForFile( testFile );
Okular::DocumentObserver *dummyDocumentObserver = new Okular::DocumentObserver();
m_document->addObserver( dummyDocumentObserver );
m_document->openDocument( testFile, QUrl(), mime );
m_document->setRotation( 1 );
// Tell ThreadWeaver not to start any new job
ThreadWeaver::Queue::instance()->suspend();
// Request a pixmap. A RotationJob will be enqueued but not started
Okular::PixmapRequest *pixmapReq = new Okular::PixmapRequest(
dummyDocumentObserver, 0, 100, 100, 1, Okular::PixmapRequest::NoFeature );
m_document->requestPixmaps( QLinkedList() << pixmapReq );
// Delete the document
delete m_document;
// Resume job processing and wait for the RotationJob to finish
ThreadWeaver::Queue::instance()->resume();
ThreadWeaver::Queue::instance()->finish();
qApp->processEvents();
+
+ delete dummyDocumentObserver;
+}
+
+// Test that, if there's a XML file in docdata referring to a document, we
+// detect that it must be migrated, that it doesn't get wiped out if you close
+// the document without migrating and that it does get wiped out after migrating
+void DocumentTest::testDocdataMigration()
+{
+ Okular::SettingsCore::instance( "documenttest" );
+
+ const QUrl testFileUrl = QUrl::fromLocalFile(KDESRCDIR "data/file1.pdf");
+ const QString testFilePath = testFileUrl.toLocalFile();
+ const qint64 testFileSize = QFileInfo(testFilePath).size();
+
+ // Copy XML file to the docdata/ directory
+ const QString docDataPath = Okular::DocumentPrivate::docDataFileName(testFileUrl, testFileSize);
+ QFile::remove(docDataPath);
+ QVERIFY( QFile::copy(KDESRCDIR "data/file1-docdata.xml", docDataPath) );
+
+ // Open our document
+ Okular::Document *m_document = new Okular::Document( 0 );
+ QMimeDatabase db;
+ const QMimeType mime = db.mimeTypeForFile( testFilePath );
+ QCOMPARE( m_document->openDocument( testFilePath, testFileUrl, mime ), Okular::Document::OpenSuccess );
+
+ // Check that the annotation from file1-docdata.xml was loaded
+ QCOMPARE( m_document->page( 0 )->annotations().size(), 1 );
+ QCOMPARE( m_document->page( 0 )->annotations().first()->uniqueName(), QString("testannot") );
+
+ // Check that we detect that it must be migrated
+ QCOMPARE( m_document->isDocdataMigrationNeeded(), true );
+ m_document->closeDocument();
+
+ // Reopen the document and check that the annotation is still present
+ // (because we have not migrated)
+ QCOMPARE( m_document->openDocument( testFilePath, testFileUrl, mime ), Okular::Document::OpenSuccess );
+ QCOMPARE( m_document->page( 0 )->annotations().size(), 1 );
+ QCOMPARE( m_document->page( 0 )->annotations().first()->uniqueName(), QString("testannot") );
+ QCOMPARE( m_document->isDocdataMigrationNeeded(), true );
+
+ // Do the migration
+ QTemporaryFile migratedSaveFile( QString( "%1/okrXXXXXX.pdf" ).arg( QDir::tempPath() ) );
+ QVERIFY( migratedSaveFile.open() );
+ migratedSaveFile.close();
+ QVERIFY( m_document->saveChanges( migratedSaveFile.fileName() ) );
+ m_document->docdataMigrationDone();
+ QCOMPARE( m_document->isDocdataMigrationNeeded(), false );
+ m_document->closeDocument();
+
+ // Now the docdata file should have no annotations, let's check
+ QCOMPARE( m_document->openDocument( testFilePath, testFileUrl, mime ), Okular::Document::OpenSuccess );
+ QCOMPARE( m_document->page( 0 )->annotations().size(), 0 );
+ QCOMPARE( m_document->isDocdataMigrationNeeded(), false );
+ m_document->closeDocument();
+
+ // And the new file should have 1 annotation, let's check
+ QCOMPARE( m_document->openDocument( migratedSaveFile.fileName(), migratedSaveFile.fileName(), mime ), Okular::Document::OpenSuccess );
+ QCOMPARE( m_document->page( 0 )->annotations().size(), 1 );
+ QCOMPARE( m_document->isDocdataMigrationNeeded(), false );
+ m_document->closeDocument();
+
+ delete m_document;
}
QTEST_MAIN( DocumentTest )
#include "documenttest.moc"
diff --git a/autotests/parttest.cpp b/autotests/parttest.cpp
index 7d7d17594..0b25f4423 100644
--- a/autotests/parttest.cpp
+++ b/autotests/parttest.cpp
@@ -1,767 +1,1220 @@
/***************************************************************************
* Copyright (C) 2013 by Albert Astals Cid *
+ * Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group *
+ * company, info@kdab.com. Work sponsored by the *
+ * LiMux project of the city of Munich *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include
+#include "../core/annotations.h"
+#include "../core/form.h"
#include "../core/page.h"
#include "../part.h"
#include "../ui/toc.h"
#include "../ui/pageview.h"
#include
#include
+#include
+#include
#include
#include
#include
#include
#include
#include
+class CloseDialogHelper : public QObject
+{
+ Q_OBJECT
+
+public:
+ CloseDialogHelper(Okular::Part *p, QDialogButtonBox::StandardButton b) : m_part(p), m_button(b), m_clicked(false)
+ {
+ QTimer::singleShot(0, this, &CloseDialogHelper::closeDialog);
+ }
+
+ ~CloseDialogHelper()
+ {
+ QVERIFY(m_clicked);
+ }
+
+private slots:
+ void closeDialog()
+ {
+ QDialog *dialog = m_part->widget()->findChild();
+ if (!dialog) {
+ QTimer::singleShot(0, this, &CloseDialogHelper::closeDialog);
+ return;
+ }
+ QDialogButtonBox *buttonBox = dialog->findChild();
+ buttonBox->button(m_button)->click();
+ m_clicked = true;
+ }
+
+private:
+ Okular::Part *m_part;
+ QDialogButtonBox::StandardButton m_button;
+ bool m_clicked;
+};
+
namespace Okular
{
class PartTest
: public QObject
{
Q_OBJECT
static bool openDocument(Okular::Part *part, const QString &filePath);
signals:
void urlHandler(const QUrl &url);
private slots:
void testReload();
void testCanceledReload();
void testTOCReload();
void testForwardPDF();
void testForwardPDF_data();
void testGeneratorPreferences();
void testSelectText();
void testClickInternalLink();
+ void testSaveAs();
+ void testSaveAs_data();
+ void testSaveAsUndoStackAnnotations();
+ void testSaveAsUndoStackAnnotations_data();
+ void testSaveAsUndoStackForms();
+ void testSaveAsUndoStackForms_data();
void testMouseMoveOverLinkWhileInSelectionMode();
void testClickUrlLinkWhileInSelectionMode();
void testeTextSelectionOverAndAcrossLinks_data();
void testeTextSelectionOverAndAcrossLinks();
void testClickUrlLinkWhileLinkTextIsSelected();
void testRClickWhileLinkTextIsSelected();
void testRClickOverLinkWhileLinkTextIsSelected();
void testRClickOnSelectionModeShoulShowFollowTheLinkMenu();
void testClickAnywhereAfterSelectionShouldUnselect();
void testeRectSelectionStartingOnLinks();
private:
void simulateMouseSelection(double startX, double startY, double endX, double endY, QWidget *target);
};
class PartThatHijacksQueryClose : public Okular::Part
{
public:
PartThatHijacksQueryClose(QWidget* parentWidget, QObject* parent,
const QVariantList& args)
: Okular::Part(parentWidget, parent, args),
behavior(PassThru)
{}
enum Behavior { PassThru, ReturnTrue, ReturnFalse };
void setQueryCloseBehavior(Behavior new_behavior)
{
behavior = new_behavior;
}
bool queryClose() override
{
if (behavior == PassThru)
return Okular::Part::queryClose();
else // ReturnTrue or ReturnFalse
return (behavior == ReturnTrue);
}
private:
Behavior behavior;
};
bool PartTest::openDocument(Okular::Part *part, const QString &filePath)
{
part->openDocument( filePath );
return part->m_document->isOpened();
}
// Test that Okular doesn't crash after a successful reload
void PartTest::testReload()
{
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
QVERIFY( openDocument(&part, QStringLiteral(KDESRCDIR "data/file1.pdf")) );
part.reload();
qApp->processEvents();
}
// Test that Okular doesn't crash after a canceled reload
void PartTest::testCanceledReload()
{
QVariantList dummyArgs;
PartThatHijacksQueryClose part(nullptr, nullptr, dummyArgs);
QVERIFY( openDocument(&part, QStringLiteral(KDESRCDIR "data/file1.pdf")) );
// When queryClose() returns false, the reload operation is canceled (as if
// the user had chosen Cancel in the "Save changes?" message box)
part.setQueryCloseBehavior(PartThatHijacksQueryClose::ReturnFalse);
part.reload();
qApp->processEvents();
}
void PartTest::testTOCReload()
{
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
QVERIFY( openDocument(&part, QStringLiteral(KDESRCDIR "data/tocreload.pdf")) );
QCOMPARE(part.m_toc->expandedNodes().count(), 0);
part.m_toc->m_treeView->expandAll();
QCOMPARE(part.m_toc->expandedNodes().count(), 3);
part.reload();
qApp->processEvents();
QCOMPARE(part.m_toc->expandedNodes().count(), 3);
}
void PartTest::testForwardPDF()
{
QFETCH(QString, dir);
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
// Create temp dir named like this: ${system temp dir}/${random string}/${dir}
const QTemporaryDir tempDir;
const QDir workDir(QDir(tempDir.path()).filePath(dir));
workDir.mkpath(QStringLiteral("."));
QFile f(QStringLiteral(KDESRCDIR "data/synctextest.tex"));
const QString texDestination = workDir.path() + QStringLiteral("/synctextest.tex");
QVERIFY(f.copy(texDestination));
QProcess process;
process.setWorkingDirectory(workDir.path());
process.start(QStringLiteral("pdflatex"), QStringList() << QStringLiteral("-synctex=1") << QStringLiteral("-interaction=nonstopmode") << texDestination);
bool started = process.waitForStarted();
if (!started) {
qDebug() << "start error:" << process.error();
qDebug() << "start stdout:" << process.readAllStandardOutput();
qDebug() << "start stderr:" << process.readAllStandardError();
}
QVERIFY(started);
process.waitForFinished();
if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) {
qDebug() << "exit error:" << process.error() << "status" << process.exitStatus() << "code" << process.exitCode();
qDebug() << "exit stdout:" << process.readAllStandardOutput();
qDebug() << "exit stderr:" << process.readAllStandardError();
}
const QString pdfResult = workDir.path() + QStringLiteral("/synctextest.pdf");
QVERIFY(QFile::exists(pdfResult));
QVERIFY( openDocument(&part, pdfResult) );
part.m_document->setViewportPage(0);
QCOMPARE(part.m_document->currentPage(), 0u);
part.closeUrl();
QUrl u(QUrl::fromLocalFile(pdfResult));
u.setFragment(QStringLiteral("src:100") + texDestination);
part.openUrl(u);
QCOMPARE(part.m_document->currentPage(), 1u);
}
void PartTest::testForwardPDF_data()
{
QTest::addColumn("dir");
QTest::newRow("non-utf8") << QString::fromUtf8("synctextest");
QTest::newRow("utf8") << QString::fromUtf8("ßðđđŋßðđŋ");
}
void PartTest::testGeneratorPreferences()
{
KConfigDialog * dialog;
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
// Test that we don't crash while opening the dialog
dialog = part.slotGeneratorPreferences();
qApp->processEvents();
delete dialog; // closes the dialog and recursively destroys all widgets
// Test that we don't crash while opening a new instance of the dialog
// This catches attempts to reuse widgets that have been destroyed
dialog = part.slotGeneratorPreferences();
qApp->processEvents();
delete dialog;
}
void PartTest::testSelectText()
{
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
QVERIFY(openDocument(&part, QStringLiteral(KDESRCDIR "data/file2.pdf")));
part.widget()->show();
QTest::qWaitForWindowExposed(part.widget());
const int width = part.m_pageView->horizontalScrollBar()->maximum() +
part.m_pageView->viewport()->width();
const int height = part.m_pageView->verticalScrollBar()->maximum() +
part.m_pageView->viewport()->height();
part.m_document->setViewportPage(0);
// wait for pixmap
QTRY_VERIFY(part.m_document->page(0)->hasPixmap(part.m_pageView));
QVERIFY(QMetaObject::invokeMethod(part.m_pageView, "slotSetMouseTextSelect"));
const int mouseY = height * 0.052;
const int mouseStartX = width * 0.12;
const int mouseEndX = width * 0.7;
simulateMouseSelection(mouseStartX, mouseY, mouseEndX, mouseY, part.m_pageView->viewport());
QApplication::clipboard()->clear();
QVERIFY(QMetaObject::invokeMethod(part.m_pageView, "copyTextSelection"));
QCOMPARE(QApplication::clipboard()->text(), QStringLiteral("Hola que tal\n"));
}
void PartTest::testClickInternalLink()
{
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
QVERIFY(openDocument(&part, QStringLiteral(KDESRCDIR "data/file2.pdf")));
part.widget()->show();
QTest::qWaitForWindowExposed(part.widget());
const int width = part.m_pageView->horizontalScrollBar()->maximum() +
part.m_pageView->viewport()->width();
const int height = part.m_pageView->verticalScrollBar()->maximum() +
part.m_pageView->viewport()->height();
part.m_document->setViewportPage(0);
// wait for pixmap
QTRY_VERIFY(part.m_document->page(0)->hasPixmap(part.m_pageView));
QMetaObject::invokeMethod(part.m_pageView, "slotSetMouseNormal");
QCOMPARE(part.m_document->currentPage(), 0u);
QTest::mouseMove(part.m_pageView->viewport(), QPoint(width * 0.17, height * 0.05));
QTest::mouseClick(part.m_pageView->viewport(), Qt::LeftButton, Qt::NoModifier, QPoint(width * 0.17, height * 0.05));
QTRY_COMPARE(part.m_document->currentPage(), 1u);
}
// cursor switches to Hand when hovering over link in TextSelect mode.
void PartTest::testMouseMoveOverLinkWhileInSelectionMode()
{
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
QVERIFY(openDocument(&part, QStringLiteral(KDESRCDIR "data/pdf_with_links.pdf")));
// resize window to avoid problem with selection areas
part.widget()->resize(800, 600);
part.widget()->show();
QTest::qWaitForWindowExposed(part.widget());
const int width = part.m_pageView->horizontalScrollBar()->maximum() +
part.m_pageView->viewport()->width();
const int height = part.m_pageView->verticalScrollBar()->maximum() +
part.m_pageView->viewport()->height();
part.m_document->setViewportPage(0);
// wait for pixmap
QTRY_VERIFY(part.m_document->page(0)->hasPixmap(part.m_pageView));
// enter text-selection mode
QVERIFY(QMetaObject::invokeMethod(part.m_pageView, "slotSetMouseTextSelect"));
// move mouse over link
QTest::mouseMove(part.m_pageView->viewport(), QPoint(width * 0.250, height * 0.127));
// check if mouse icon changed to proper icon
QTRY_COMPARE(part.m_pageView->cursor().shape(), Qt::PointingHandCursor);
}
// clicking on hyperlink jumps to destination in TextSelect mode.
void PartTest::testClickUrlLinkWhileInSelectionMode()
{
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
QVERIFY(openDocument(&part, QStringLiteral(KDESRCDIR "data/pdf_with_links.pdf")));
// resize window to avoid problem with selection areas
part.widget()->resize(800, 600);
part.widget()->show();
QTest::qWaitForWindowExposed(part.widget());
const int width = part.m_pageView->horizontalScrollBar()->maximum() +
part.m_pageView->viewport()->width();
const int height = part.m_pageView->verticalScrollBar()->maximum() +
part.m_pageView->viewport()->height();
part.m_document->setViewportPage(0);
// wait for pixmap
QTRY_VERIFY(part.m_document->page(0)->hasPixmap(part.m_pageView));
// enter text-selection mode
QVERIFY(QMetaObject::invokeMethod(part.m_pageView, "slotSetMouseTextSelect"));
// overwrite urlHandler for 'mailto' urls
QDesktopServices::setUrlHandler("mailto", this, "urlHandler");
QSignalSpy openUrlSignalSpy(this, SIGNAL(urlHandler(QUrl)));
// click on url
QTest::mouseMove(part.m_pageView->viewport(), QPoint(width * 0.250, height * 0.127));
QTest::mouseClick(part.m_pageView->viewport(), Qt::LeftButton, Qt::NoModifier, QPoint(width * 0.250, height * 0.127));
// expect that the urlHandler signal was called
QTRY_COMPARE(openUrlSignalSpy.count(), 1);
QList arguments = openUrlSignalSpy.takeFirst();
QCOMPARE(arguments.at(0).value(), QUrl("mailto:foo@foo.bar"));
}
void PartTest::testeTextSelectionOverAndAcrossLinks_data()
{
QTest::addColumn("mouseStartX");
QTest::addColumn("mouseEndX");
QTest::addColumn("expectedResult");
// can text-select "over and across" hyperlink.
QTest::newRow("start selection before link") << 0.1564 << 0.2943 << QStringLiteral(" a link: foo@foo.b");
// can text-select starting at text and ending selection in middle of hyperlink.
QTest::newRow("start selection in the middle of the link") << 0.28 << 0.382 << QStringLiteral("o.bar\n");
// text selection works when selecting left to right or right to left
QTest::newRow("start selection after link") << 0.40 << 0.05 << QStringLiteral("This is a link: foo@foo.bar\n");
}
// can text-select "over and across" hyperlink.
void PartTest::testeTextSelectionOverAndAcrossLinks()
{
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
QVERIFY(openDocument(&part, QStringLiteral(KDESRCDIR "data/pdf_with_links.pdf")));
// resize window to avoid problem with selection areas
part.widget()->resize(800, 600);
part.widget()->show();
QTest::qWaitForWindowExposed(part.widget());
const int width = part.m_pageView->horizontalScrollBar()->maximum() +
part.m_pageView->viewport()->width();
const int height = part.m_pageView->verticalScrollBar()->maximum() +
part.m_pageView->viewport()->height();
part.m_document->setViewportPage(0);
// wait for pixmap
QTRY_VERIFY(part.m_document->page(0)->hasPixmap(part.m_pageView));
// enter text-selection mode
QVERIFY(QMetaObject::invokeMethod(part.m_pageView, "slotSetMouseTextSelect"));
const double mouseY = height * 0.127;
QFETCH(double, mouseStartX);
QFETCH(double, mouseEndX);
mouseStartX = width * mouseStartX;
mouseEndX = width * mouseEndX;
simulateMouseSelection(mouseStartX, mouseY, mouseEndX, mouseY, part.m_pageView->viewport());
QApplication::clipboard()->clear();
QVERIFY(QMetaObject::invokeMethod(part.m_pageView, "copyTextSelection"));
QFETCH(QString, expectedResult);
QCOMPARE(QApplication::clipboard()->text(), expectedResult);
}
// can jump to link while there's an active selection of text.
void PartTest::testClickUrlLinkWhileLinkTextIsSelected()
{
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
QVERIFY(openDocument(&part, QStringLiteral(KDESRCDIR "data/pdf_with_links.pdf")));
// resize window to avoid problem with selection areas
part.widget()->resize(800, 600);
part.widget()->show();
QTest::qWaitForWindowExposed(part.widget());
const int width = part.m_pageView->horizontalScrollBar()->maximum() +
part.m_pageView->viewport()->width();
const int height = part.m_pageView->verticalScrollBar()->maximum() +
part.m_pageView->viewport()->height();
part.m_document->setViewportPage(0);
// wait for pixmap
QTRY_VERIFY(part.m_document->page(0)->hasPixmap(part.m_pageView));
// enter text-selection mode
QVERIFY(QMetaObject::invokeMethod(part.m_pageView, "slotSetMouseTextSelect"));
const double mouseY = height * 0.127;
const double mouseStartX = width * 0.13;
const double mouseEndX = width * 0.40;
simulateMouseSelection(mouseStartX, mouseY, mouseEndX, mouseY, part.m_pageView->viewport());
// overwrite urlHandler for 'mailto' urls
QDesktopServices::setUrlHandler("mailto", this, "urlHandler");
QSignalSpy openUrlSignalSpy(this, SIGNAL(urlHandler(QUrl)));
// click on url
const double mouseClickX = width * 0.2997;
const double mouseClickY = height * 0.1293;
QTest::mouseMove(part.m_pageView->viewport(), QPoint(mouseClickX, mouseClickY));
QTest::mouseClick(part.m_pageView->viewport(), Qt::LeftButton, Qt::NoModifier, QPoint(mouseClickX, mouseClickY), 1000);
// expect that the urlHandler signal was called
QTRY_COMPARE(openUrlSignalSpy.count(), 1);
QList arguments = openUrlSignalSpy.takeFirst();
QCOMPARE(arguments.at(0).value(), QUrl("mailto:foo@foo.bar"));
}
// r-click on the selected text gives the "Go To:" content menu option
void PartTest::testRClickWhileLinkTextIsSelected()
{
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
QVERIFY(openDocument(&part, QStringLiteral(KDESRCDIR "data/pdf_with_links.pdf")));
// resize window to avoid problem with selection areas
part.widget()->resize(800, 600);
part.widget()->show();
QTest::qWaitForWindowExposed(part.widget());
const int width = part.m_pageView->horizontalScrollBar()->maximum() +
part.m_pageView->viewport()->width();
const int height = part.m_pageView->verticalScrollBar()->maximum() +
part.m_pageView->viewport()->height();
part.m_document->setViewportPage(0);
// wait for pixmap
QTRY_VERIFY(part.m_document->page(0)->hasPixmap(part.m_pageView));
// enter text-selection mode
QVERIFY(QMetaObject::invokeMethod(part.m_pageView, "slotSetMouseTextSelect"));
const double mouseY = height * 0.162;
const double mouseStartX = width * 0.42;
const double mouseEndX = width * 0.60;
simulateMouseSelection(mouseStartX, mouseY, mouseEndX, mouseY, part.m_pageView->viewport());
// Need to do this because the pop-menu will have his own mainloop and will block tests until
// the menu disappear
PageView *view = part.m_pageView;
QTimer::singleShot(2000, [view]() {
// check if popup menu is active and visible
QMenu *menu = qobject_cast(view->findChild("PopupMenu"));
QVERIFY(menu);
QVERIFY(menu->isVisible());
// check if the menu contains go-to link action
QAction *goToAction = qobject_cast(menu->findChild("GoToAction"));
QVERIFY(goToAction);
// check if the "follow this link" action is not visible
QAction *processLinkAction = qobject_cast(menu->findChild("ProcessLinkAction"));
QVERIFY(!processLinkAction);
// check if the "copy link address" action is not visible
QAction *copyLinkLocation = qobject_cast(menu->findChild("CopyLinkLocationAction"));
QVERIFY(!copyLinkLocation);
// close menu to continue test
menu->close();
});
// click on url
const double mouseClickX = width * 0.425;
const double mouseClickY = height * 0.162;
QTest::mouseMove(part.m_pageView->viewport(), QPoint(mouseClickX, mouseClickY));
QTest::mouseClick(part.m_pageView->viewport(), Qt::RightButton, Qt::NoModifier, QPoint(mouseClickX, mouseClickY), 1000);
// will continue after pop-menu get closed
}
// r-click on the link gives the "follow this link" content menu option
void PartTest::testRClickOverLinkWhileLinkTextIsSelected()
{
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
QVERIFY(openDocument(&part, QStringLiteral(KDESRCDIR "data/pdf_with_links.pdf")));
// resize window to avoid problem with selection areas
part.widget()->resize(800, 600);
part.widget()->show();
QTest::qWaitForWindowExposed(part.widget());
const int width = part.m_pageView->horizontalScrollBar()->maximum() +
part.m_pageView->viewport()->width();
const int height = part.m_pageView->verticalScrollBar()->maximum() +
part.m_pageView->viewport()->height();
part.m_document->setViewportPage(0);
// wait for pixmap
QTRY_VERIFY(part.m_document->page(0)->hasPixmap(part.m_pageView));
// enter text-selection mode
QVERIFY(QMetaObject::invokeMethod(part.m_pageView, "slotSetMouseTextSelect"));
const double mouseY = height * 0.162;
const double mouseStartX = width * 0.42;
const double mouseEndX = width * 0.60;
simulateMouseSelection(mouseStartX, mouseY, mouseEndX, mouseY, part.m_pageView->viewport());
// Need to do this because the pop-menu will have his own mainloop and will block tests until
// the menu disappear
PageView *view = part.m_pageView;
QTimer::singleShot(2000, [view]() {
// check if popup menu is active and visible
QMenu *menu = qobject_cast(view->findChild("PopupMenu"));
QVERIFY(menu);
QVERIFY(menu->isVisible());
// check if the menu contains "follow this link" action
QAction *processLinkAction = qobject_cast(menu->findChild("ProcessLinkAction"));
QVERIFY(processLinkAction);
// check if the menu contains "copy link address" action
QAction *copyLinkLocation = qobject_cast(menu->findChild("CopyLinkLocationAction"));
QVERIFY(copyLinkLocation);
// close menu to continue test
menu->close();
});
// click on url
const double mouseClickX = width * 0.593;
const double mouseClickY = height * 0.162;
QTest::mouseMove(part.m_pageView->viewport(), QPoint(mouseClickX, mouseClickY));
QTest::mouseClick(part.m_pageView->viewport(), Qt::RightButton, Qt::NoModifier, QPoint(mouseClickX, mouseClickY), 1000);
// will continue after pop-menu get closed
}
void PartTest::testRClickOnSelectionModeShoulShowFollowTheLinkMenu()
{
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
QVERIFY(openDocument(&part, QStringLiteral(KDESRCDIR "data/pdf_with_links.pdf")));
// resize window to avoid problem with selection areas
part.widget()->resize(800, 600);
part.widget()->show();
QTest::qWaitForWindowExposed(part.widget());
const int width = part.m_pageView->horizontalScrollBar()->maximum() +
part.m_pageView->viewport()->width();
const int height = part.m_pageView->verticalScrollBar()->maximum() +
part.m_pageView->viewport()->height();
part.m_document->setViewportPage(0);
// wait for pixmap
QTRY_VERIFY(part.m_document->page(0)->hasPixmap(part.m_pageView));
// enter text-selection mode
QVERIFY(QMetaObject::invokeMethod(part.m_pageView, "slotSetMouseTextSelect"));
// Need to do this because the pop-menu will have his own mainloop and will block tests until
// the menu disappear
PageView *view = part.m_pageView;
QTimer::singleShot(2000, [view]() {
// check if popup menu is active and visible
QMenu *menu = qobject_cast(view->findChild("PopupMenu"));
QVERIFY(menu);
QVERIFY(menu->isVisible());
// check if the menu contains "Follow this link" action
QAction *processLink = qobject_cast(menu->findChild("ProcessLinkAction"));
QVERIFY(processLink);
// chek if the menu contains "Copy Link Address" action
QAction *actCopyLinkLocation = qobject_cast(menu->findChild("CopyLinkLocationAction"));
QVERIFY(actCopyLinkLocation);
// close menu to continue test
menu->close();
});
// r-click on url
const double mouseClickX = width * 0.604;
const double mouseClickY = height * 0.162;
QTest::mouseMove(part.m_pageView->viewport(), QPoint(mouseClickX, mouseClickY));
QTest::mouseClick(part.m_pageView->viewport(), Qt::RightButton, Qt::NoModifier, QPoint(mouseClickX, mouseClickY), 1000);
QTest::qWait(3000);
// will continue after pop-menu get closed
}
void PartTest::testClickAnywhereAfterSelectionShouldUnselect()
{
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
QVERIFY(openDocument(&part, QStringLiteral(KDESRCDIR "data/pdf_with_links.pdf")));
// resize window to avoid problem with selection areas
part.widget()->resize(800, 600);
part.widget()->show();
QTest::qWaitForWindowExposed(part.widget());
const int width = part.m_pageView->horizontalScrollBar()->maximum() +
part.m_pageView->viewport()->width();
const int height = part.m_pageView->verticalScrollBar()->maximum() +
part.m_pageView->viewport()->height();
part.m_document->setViewportPage(0);
// wait for pixmap
QTRY_VERIFY(part.m_document->page(0)->hasPixmap(part.m_pageView));
// enter text-selection mode
QVERIFY(QMetaObject::invokeMethod(part.m_pageView, "slotSetMouseTextSelect"));
const double mouseY = height * 0.162;
const double mouseStartX = width * 0.42;
const double mouseEndX = width * 0.60;
simulateMouseSelection(mouseStartX, mouseY, mouseEndX, mouseY, part.m_pageView->viewport());
// click on url
const double mouseClickX = width * 0.10;
QTest::mouseMove(part.m_pageView->viewport(), QPoint(mouseClickX, mouseY));
QTest::mouseClick(part.m_pageView->viewport(), Qt::LeftButton, Qt::NoModifier, QPoint(mouseClickX, mouseY), 1000);
QApplication::clipboard()->clear();
QVERIFY(QMetaObject::invokeMethod(part.m_pageView, "copyTextSelection"));
// check if copied text is empty what means no text selected
QVERIFY(QApplication::clipboard()->text().isEmpty());
}
void PartTest::testeRectSelectionStartingOnLinks()
{
QVariantList dummyArgs;
Okular::Part part(nullptr, nullptr, dummyArgs);
QVERIFY(openDocument(&part, QStringLiteral(KDESRCDIR "data/pdf_with_links.pdf")));
// resize window to avoid problem with selection areas
part.widget()->resize(800, 600);
part.widget()->show();
QTest::qWaitForWindowExposed(part.widget());
const int width = part.m_pageView->horizontalScrollBar()->maximum() +
part.m_pageView->viewport()->width();
const int height = part.m_pageView->verticalScrollBar()->maximum() +
part.m_pageView->viewport()->height();
part.m_document->setViewportPage(0);
// wait for pixmap
QTRY_VERIFY(part.m_document->page(0)->hasPixmap(part.m_pageView));
// enter text-selection mode
QVERIFY(QMetaObject::invokeMethod(part.m_pageView, "slotSetMouseSelect"));
const double mouseStartY = height * 0.127;
const double mouseEndY = height * 0.127;
const double mouseStartX = width * 0.28;
const double mouseEndX = width * 0.382;
// Need to do this because the pop-menu will have his own mainloop and will block tests until
// the menu disappear
PageView *view = part.m_pageView;
QTimer::singleShot(2000, [view]() {
QApplication::clipboard()->clear();
// check if popup menu is active and visible
QMenu *menu = qobject_cast(view->findChild("PopupMenu"));
QVERIFY(menu);
QVERIFY(menu->isVisible());
// check if the copy selected text to clipboard is present
QAction *copyAct = qobject_cast(menu->findChild("CopyTextToClipboard"));
QVERIFY(copyAct);
menu->close();
});
simulateMouseSelection(mouseStartX, mouseStartY, mouseEndX, mouseEndY, part.m_pageView->viewport());
// wait menu get closed
}
void PartTest::simulateMouseSelection(double startX, double startY, double endX, double endY, QWidget *target)
{
QTestEventList events;
events.addMouseMove(QPoint(startX, startY));
events.addMousePress(Qt::LeftButton, Qt::NoModifier, QPoint(startX, startY));
events.addMouseMove(QPoint(endX, endY));
// without this wait the test fails. 100ms were enough on my local system, but when running under valgrind
// or on the CI server we need to wait longer.
events.addDelay(1000);
events.addMouseRelease(Qt::LeftButton, Qt::NoModifier, QPoint(endX, endY));
events.simulate(target);
}
+void PartTest::testSaveAs()
+{
+ QFETCH(QString, file);
+ QFETCH(QString, extension);
+ QFETCH(bool, nativelySupportsAnnotations);
+ QFETCH(bool, canSwapBackingFile);
+
+ QScopedPointer closeDialogHelper;
+
+ QString annotName;
+ QTemporaryFile archiveSave( QString( "%1/okrXXXXXX.okular" ).arg( QDir::tempPath() ) );
+ QTemporaryFile nativeDirectSave( QString( "%1/okrXXXXXX.%2" ).arg( QDir::tempPath() ).arg ( extension ) );
+ QTemporaryFile nativeFromArchiveFile( QString( "%1/okrXXXXXX.%2" ).arg( QDir::tempPath() ).arg ( extension ) );
+ QVERIFY( archiveSave.open() );
+ archiveSave.close();
+ QVERIFY( nativeDirectSave.open() );
+ nativeDirectSave.close();
+ QVERIFY( nativeFromArchiveFile.open() );
+ nativeFromArchiveFile.close();
+
+ qDebug() << "Open file, add annotation and save both natively and to .okular";
+ {
+ Okular::Part part(nullptr, nullptr, QVariantList());
+ part.openDocument( file );
+
+ QCOMPARE(part.m_document->canSwapBackingFile(), canSwapBackingFile);
+
+ Okular::Annotation *annot = new Okular::TextAnnotation();
+ annot->setBoundingRectangle( Okular::NormalizedRect( 0.1, 0.1, 0.15, 0.15 ) );
+ annot->setContents( "annot contents" );
+ part.m_document->addPageAnnotation( 0, annot );
+ annotName = annot->uniqueName();
+
+ if ( canSwapBackingFile )
+ {
+ if ( !nativelySupportsAnnotations )
+ {
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::No )); // this is the "you're going to lose the annotations" dialog
+ }
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( nativeDirectSave.fileName() ), Part::NoSaveAsFlags ) );
+ // For backends that don't support annotations natively we mark the part as still modified
+ // after a save because we keep the annotation around but it will get lost if the user closes the app
+ // so we want to give her a last chance to save on close with the "you have changes dialog"
+ QCOMPARE( part.isModified(), !nativelySupportsAnnotations );
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( archiveSave.fileName() ), Part::SaveAsOkularArchive ) );
+ }
+ else
+ {
+ // We need to save to archive first otherwise we lose the annotation
+
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::Yes )); // this is the "you're going to lose the undo/redo stack" dialog
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( archiveSave.fileName() ), Part::SaveAsOkularArchive ) );
+
+ if ( !nativelySupportsAnnotations )
+ {
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::No )); // this is the "you're going to lose the annotations" dialog
+ }
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( nativeDirectSave.fileName() ), Part::NoSaveAsFlags ) );
+ }
+
+ part.closeUrl();
+ }
+
+ qDebug() << "Open the .okular, check that the annotation is present and save to native";
+ {
+ Okular::Part part(nullptr, nullptr, QVariantList());
+ part.openDocument( archiveSave.fileName() );
+
+ QCOMPARE( part.m_document->page( 0 )->annotations().size(), 1 );
+ QCOMPARE( part.m_document->page( 0 )->annotations().first()->uniqueName(), annotName );
+
+ if ( !nativelySupportsAnnotations )
+ {
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::No )); // this is the "you're going to lose the annotations" dialog
+ }
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( nativeFromArchiveFile.fileName() ), Part::NoSaveAsFlags ) );
+
+ if ( canSwapBackingFile && !nativelySupportsAnnotations )
+ {
+ // For backends that don't support annotations natively we mark the part as still modified
+ // after a save because we keep the annotation around but it will get lost if the user closes the app
+ // so we want to give her a last chance to save on close with the "you have changes dialog"
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::No )); // this is the "do you want to save or discard" dialog
+ }
+
+ part.closeUrl();
+ }
+
+ qDebug() << "Open the native file saved directly, and check that the annot"
+ << "is there iff we expect it";
+ {
+ Okular::Part part(nullptr, nullptr, QVariantList());
+ part.openDocument( nativeDirectSave.fileName() );
+
+ QCOMPARE( part.m_document->page( 0 )->annotations().size(), nativelySupportsAnnotations ? 1 : 0 );
+ if ( nativelySupportsAnnotations )
+ QCOMPARE( part.m_document->page( 0 )->annotations().first()->uniqueName(), annotName );
+
+ part.closeUrl();
+ }
+
+ qDebug() << "Open the native file saved from the .okular, and check that the annot"
+ << "is there iff we expect it";
+ {
+ Okular::Part part(nullptr, nullptr, QVariantList());
+ part.openDocument( nativeFromArchiveFile.fileName() );
+
+ QCOMPARE( part.m_document->page( 0 )->annotations().size(), nativelySupportsAnnotations ? 1 : 0 );
+ if ( nativelySupportsAnnotations )
+ QCOMPARE( part.m_document->page( 0 )->annotations().first()->uniqueName(), annotName );
+
+ part.closeUrl();
+ }
+}
+
+void PartTest::testSaveAs_data()
+{
+ QTest::addColumn("file");
+ QTest::addColumn("extension");
+ QTest::addColumn("nativelySupportsAnnotations");
+ QTest::addColumn("canSwapBackingFile");
+
+ QTest::newRow("pdf") << KDESRCDIR "data/file1.pdf" << "pdf" << true << true;
+ QTest::newRow("epub") << KDESRCDIR "data/contents.epub" << "epub" << false << false;
+ QTest::newRow("jpg") << KDESRCDIR "data/potato.jpg" << "jpg" << false << true;
+}
+
+void PartTest::testSaveAsUndoStackAnnotations()
+{
+ QFETCH(QString, file);
+ QFETCH(QString, extension);
+ QFETCH(bool, nativelySupportsAnnotations);
+ QFETCH(bool, canSwapBackingFile);
+ QFETCH(bool, saveToArchive);
+
+ const Part::SaveAsFlag saveFlags = saveToArchive ? Part::SaveAsOkularArchive : Part::NoSaveAsFlags;
+
+ QScopedPointer closeDialogHelper;
+
+ QTemporaryFile saveFile( QString( "%1/okrXXXXXX.%2" ).arg( QDir::tempPath() ).arg ( extension ) );
+ QVERIFY( saveFile.open() );
+ saveFile.close();
+
+ Okular::Part part(nullptr, nullptr, QVariantList());
+ part.openDocument( file );
+
+ QCOMPARE(part.m_document->canSwapBackingFile(), canSwapBackingFile);
+
+ Okular::Annotation *annot = new Okular::TextAnnotation();
+ annot->setBoundingRectangle( Okular::NormalizedRect( 0.1, 0.1, 0.15, 0.15 ) );
+ annot->setContents( "annot contents" );
+ part.m_document->addPageAnnotation( 0, annot );
+ QString annotName = annot->uniqueName();
+
+ if ( !nativelySupportsAnnotations && !saveToArchive ) {
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::No )); // this is the "you're going to lose the annotations" dialog
+ }
+
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+
+ if (!canSwapBackingFile) {
+ // The undo/redo stack gets lost if you can not swap the backing file
+ QVERIFY( !part.m_document->canUndo() );
+ QVERIFY( !part.m_document->canRedo() );
+ return;
+ }
+
+ // Check we can still undo the annot add after save
+ QVERIFY( part.m_document->canUndo() );
+ part.m_document->undo();
+ QVERIFY( !part.m_document->canUndo() );
+
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+ QVERIFY( part.m_document->page( 0 )->annotations().isEmpty() );
+
+ // Check we can redo the annot add after save
+ QVERIFY( part.m_document->canRedo() );
+ part.m_document->redo();
+ QVERIFY( !part.m_document->canRedo() );
+
+ if ( nativelySupportsAnnotations ) {
+ // If the annots are provived by the backend we need to refetch the pointer after save
+ annot = part.m_document->page( 0 )->annotation( annotName );
+ QVERIFY( annot );
+ }
+
+
+
+ // Remove the annotation, creates another undo command
+ QVERIFY( part.m_document->canRemovePageAnnotation( annot ) );
+ part.m_document->removePageAnnotation( 0, annot );
+ QVERIFY( part.m_document->page( 0 )->annotations().isEmpty() );
+
+ // Check we can still undo the annot remove after save
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+ QVERIFY( part.m_document->canUndo() );
+ part.m_document->undo();
+ QVERIFY( part.m_document->canUndo() );
+ QCOMPARE( part.m_document->page( 0 )->annotations().count(), 1 );
+
+ // Check we can still undo the annot add after save
+ if ( !nativelySupportsAnnotations && !saveToArchive ) {
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::No )); // this is the "you're going to lose the annotations" dialog
+ }
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+ QVERIFY( part.m_document->canUndo() );
+ part.m_document->undo();
+ QVERIFY( !part.m_document->canUndo() );
+ QVERIFY( part.m_document->page( 0 )->annotations().isEmpty() );
+
+
+ // Redo the add annotation
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+ QVERIFY( part.m_document->canRedo() );
+ part.m_document->redo();
+ QVERIFY( part.m_document->canUndo() );
+ QVERIFY( part.m_document->canRedo() );
+
+ if ( nativelySupportsAnnotations ) {
+ // If the annots are provived by the backend we need to refetch the pointer after save
+ annot = part.m_document->page( 0 )->annotation( annotName );
+ QVERIFY( annot );
+ }
+
+
+ // Add translate, adjust and modify commands
+ part.m_document->translatePageAnnotation( 0, annot, Okular::NormalizedPoint( 0.1, 0.1 ) );
+ part.m_document->adjustPageAnnotation( 0, annot, Okular::NormalizedPoint( 0.1, 0.1 ), Okular::NormalizedPoint( 0.1, 0.1 ) );
+ part.m_document->prepareToModifyAnnotationProperties( annot );
+ part.m_document->modifyPageAnnotationProperties( 0, annot );
+
+ // Now check we can still undo/redo/save at all the intermediate states and things still work
+ if ( !nativelySupportsAnnotations && !saveToArchive ) {
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::No )); // this is the "you're going to lose the annotations" dialog
+ }
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+ QVERIFY( part.m_document->canUndo() );
+ part.m_document->undo();
+ QVERIFY( part.m_document->canUndo() );
+
+ if ( !nativelySupportsAnnotations && !saveToArchive ) {
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::No )); // this is the "you're going to lose the annotations" dialog
+ }
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+ QVERIFY( part.m_document->canUndo() );
+ part.m_document->undo();
+ QVERIFY( part.m_document->canUndo() );
+
+ if ( !nativelySupportsAnnotations && !saveToArchive ) {
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::No )); // this is the "you're going to lose the annotations" dialog
+ }
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+ QVERIFY( part.m_document->canUndo() );
+ part.m_document->undo();
+ QVERIFY( part.m_document->canUndo() );
+
+ if ( !nativelySupportsAnnotations && !saveToArchive ) {
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::No )); // this is the "you're going to lose the annotations" dialog
+ }
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+ QVERIFY( part.m_document->canUndo() );
+ part.m_document->undo();
+ QVERIFY( !part.m_document->canUndo() );
+ QVERIFY( part.m_document->canRedo() );
+ QVERIFY( part.m_document->page( 0 )->annotations().isEmpty() );
+
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+ QVERIFY( part.m_document->canRedo() );
+ part.m_document->redo();
+ QVERIFY( part.m_document->canRedo() );
+
+ if ( !nativelySupportsAnnotations && !saveToArchive ) {
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::No )); // this is the "you're going to lose the annotations" dialog
+ }
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+ QVERIFY( part.m_document->canRedo() );
+ part.m_document->redo();
+ QVERIFY( part.m_document->canRedo() );
+
+ if ( !nativelySupportsAnnotations && !saveToArchive ) {
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::No )); // this is the "you're going to lose the annotations" dialog
+ }
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+ QVERIFY( part.m_document->canRedo() );
+ part.m_document->redo();
+ QVERIFY( part.m_document->canRedo() );
+
+ if ( !nativelySupportsAnnotations && !saveToArchive ) {
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::No )); // this is the "you're going to lose the annotations" dialog
+ }
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+ QVERIFY( part.m_document->canRedo() );
+ part.m_document->redo();
+ QVERIFY( !part.m_document->canRedo() );
+
+ closeDialogHelper.reset(new CloseDialogHelper( &part, QDialogButtonBox::No )); // this is the "do you want to save or discard" dialog
+ part.closeUrl();
+}
+
+void PartTest::testSaveAsUndoStackAnnotations_data()
+{
+ QTest::addColumn("file");
+ QTest::addColumn("extension");
+ QTest::addColumn("nativelySupportsAnnotations");
+ QTest::addColumn("canSwapBackingFile");
+ QTest::addColumn("saveToArchive");
+
+ QTest::newRow("pdf") << KDESRCDIR "data/file1.pdf" << "pdf" << true << true << false;
+ QTest::newRow("epub") << KDESRCDIR "data/contents.epub" << "epub" << false << false << false;
+ QTest::newRow("jpg") << KDESRCDIR "data/potato.jpg" << "jpg" << false << true << false;
+ QTest::newRow("pdfarchive") << KDESRCDIR "data/file1.pdf" << "okular" << true << true << true;
+ QTest::newRow("jpgarchive") << KDESRCDIR "data/potato.jpg" << "okular" << false << true << true;
+}
+
+void PartTest::testSaveAsUndoStackForms()
+{
+ QFETCH(QString, file);
+ QFETCH(QString, extension);
+ QFETCH(bool, saveToArchive);
+
+ const Part::SaveAsFlag saveFlags = saveToArchive ? Part::SaveAsOkularArchive : Part::NoSaveAsFlags;
+
+ QTemporaryFile saveFile( QString( "%1/okrXXXXXX.%2" ).arg( QDir::tempPath(), extension ) );
+ QVERIFY( saveFile.open() );
+ saveFile.close();
+
+ Okular::Part part(nullptr, nullptr, QVariantList());
+ part.openDocument( file );
+
+ for ( FormField *ff : part.m_document->page( 0 )->formFields() )
+ {
+ if ( ff->id() == 65537 )
+ {
+ QCOMPARE( ff->type(), FormField::FormText );
+ FormFieldText *fft = static_cast( ff );
+ part.m_document->editFormText( 0, fft, "BlaBla", 6, 0, 0 );
+ }
+ else if ( ff->id() == 65538 )
+ {
+ QCOMPARE( ff->type(), FormField::FormButton );
+ FormFieldButton *ffb = static_cast( ff );
+ QCOMPARE( ffb->buttonType(), FormFieldButton::Radio );
+ part.m_document->editFormButtons( 0, QList< FormFieldButton* >() << ffb, QList< bool >() << true );
+ }
+ else if ( ff->id() == 65542 )
+ {
+ QCOMPARE( ff->type(), FormField::FormChoice );
+ FormFieldChoice *ffc = static_cast( ff );
+ QCOMPARE( ffc->choiceType(), FormFieldChoice::ListBox );
+ part.m_document->editFormList( 0, ffc, QList< int >() << 1 );
+ }
+ else if ( ff->id() == 65543 )
+ {
+ QCOMPARE( ff->type(), FormField::FormChoice );
+ FormFieldChoice *ffc = static_cast( ff );
+ QCOMPARE( ffc->choiceType(), FormFieldChoice::ComboBox );
+ part.m_document->editFormCombo( 0, ffc, "combo2", 3, 0, 0);
+ }
+ }
+
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+
+ QVERIFY( part.m_document->canUndo() );
+ part.m_document->undo();
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+
+ QVERIFY( part.m_document->canUndo() );
+ part.m_document->undo();
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+
+ QVERIFY( part.m_document->canUndo() );
+ part.m_document->undo();
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+
+ QVERIFY( part.m_document->canUndo() );
+ part.m_document->undo();
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+ QVERIFY( !part.m_document->canUndo() );
+
+ QVERIFY( part.m_document->canRedo() );
+ part.m_document->redo();
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+
+ QVERIFY( part.m_document->canRedo() );
+ part.m_document->redo();
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+
+ QVERIFY( part.m_document->canRedo() );
+ part.m_document->redo();
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+
+ QVERIFY( part.m_document->canRedo() );
+ part.m_document->redo();
+ QVERIFY( part.saveAs( QUrl::fromLocalFile( saveFile.fileName() ), saveFlags ) );
+}
+
+void PartTest::testSaveAsUndoStackForms_data()
+{
+ QTest::addColumn("file");
+ QTest::addColumn("extension");
+ QTest::addColumn("saveToArchive");
+
+ QTest::newRow("pdf") << KDESRCDIR "data/formSamples.pdf" << "pdf" << false;
+ QTest::newRow("pdfarchive") << KDESRCDIR "data/formSamples.pdf" << "okular" << true;
+}
+
}
int main(int argc, char *argv[])
{
// Force consistent locale
QLocale locale(QStringLiteral("en_US.UTF-8"));
if (locale == QLocale::c()) { // This is the way to check if the above worked
locale = QLocale(QLocale::English, QLocale::UnitedStates);
}
QLocale::setDefault(locale);
qputenv("LC_ALL", "en_US.UTF-8"); // For UNIX, third-party libraries
// Ensure consistent configs/caches
QTemporaryDir homeDir; // QTemporaryDir automatically cleans up when it goes out of scope
Q_ASSERT(homeDir.isValid());
QByteArray homePath = QFile::encodeName(homeDir.path());
qDebug() << homePath;
qputenv("USERPROFILE", homePath);
qputenv("HOME", homePath);
qputenv("XDG_DATA_HOME", homePath + "/.local");
qputenv("XDG_CONFIG_HOME", homePath + "/.kde-unit-test/xdg/config");
// Disable fancy debug output
qunsetenv("QT_MESSAGE_PATTERN");
QApplication app( argc, argv );
app.setApplicationName(QLatin1String("okularparttest"));
app.setOrganizationDomain(QLatin1String("kde.org"));
app.setQuitOnLastWindowClosed(false);
qRegisterMetaType(); /*as done by kapplication*/
qRegisterMetaType>();
Okular::PartTest test;
return QTest::qExec( &test, argc, argv );
}
#include "parttest.moc"
diff --git a/core/document.cpp b/core/document.cpp
index 3ac8de145..63e5ab8be 100644
--- a/core/document.cpp
+++ b/core/document.cpp
@@ -1,5202 +1,5390 @@
/***************************************************************************
* Copyright (C) 2004-2005 by Enrico Ros *
* Copyright (C) 2004-2008 by Albert Astals Cid *
* Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group *
* company, info@kdab.com. Work sponsored by the *
* LiMux project of the city of Munich *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "document.h"
#include "document_p.h"
#include "documentcommands_p.h"
#include
#ifdef Q_OS_WIN
#define _WIN32_WINNT 0x0500
#include
#elif defined(Q_OS_FREEBSD)
#include
#include
#include
#endif
// qt/kde/system includes
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
// local includes
#include "action.h"
#include "annotations.h"
#include "annotations_p.h"
#include "audioplayer.h"
#include "audioplayer_p.h"
#include "bookmarkmanager.h"
#include "chooseenginedialog_p.h"
#include "debug_p.h"
#include "generator_p.h"
#include "interfaces/configinterface.h"
#include "interfaces/guiinterface.h"
#include "interfaces/printinterface.h"
#include "interfaces/saveinterface.h"
#include "observer.h"
#include "misc.h"
#include "page.h"
#include "page_p.h"
#include "pagecontroller_p.h"
#include "scripter.h"
#include "settings_core.h"
#include "sourcereference.h"
#include "sourcereference_p.h"
#include "texteditors_p.h"
#include "tile.h"
#include "tilesmanager_p.h"
#include "utils_p.h"
#include "view.h"
#include "view_p.h"
#include "form.h"
#include "utils.h"
#include
#include
using namespace Okular;
struct AllocatedPixmap
{
// owner of the page
DocumentObserver *observer;
int page;
qulonglong memory;
// public constructor: initialize data
AllocatedPixmap( DocumentObserver *o, int p, qulonglong m ) : observer( o ), page( p ), memory( m ) {}
};
struct ArchiveData
{
ArchiveData()
{
}
+ QString originalFileName;
QTemporaryFile document;
QTemporaryFile metadataFile;
};
struct RunningSearch
{
// store search properties
int continueOnPage;
RegularAreaRect continueOnMatch;
QSet< int > highlightedPages;
// fields related to previous searches (used for 'continueSearch')
QString cachedString;
Document::SearchType cachedType;
Qt::CaseSensitivity cachedCaseSensitivity;
bool cachedViewportMove : 1;
bool isCurrentlySearching : 1;
QColor cachedColor;
int pagesDone;
};
#define foreachObserver( cmd ) {\
QSet< DocumentObserver * >::const_iterator it=d->m_observers.constBegin(), end=d->m_observers.constEnd();\
for ( ; it != end ; ++ it ) { (*it)-> cmd ; } }
#define foreachObserverD( cmd ) {\
QSet< DocumentObserver * >::const_iterator it = m_observers.constBegin(), end = m_observers.constEnd();\
for ( ; it != end ; ++ it ) { (*it)-> cmd ; } }
#define OKULAR_HISTORY_MAXSTEPS 100
#define OKULAR_HISTORY_SAVEDSTEPS 10
/***** Document ******/
QString DocumentPrivate::pagesSizeString() const
{
if (m_generator)
{
if (m_generator->pagesSizeMetric() != Generator::None)
{
QSizeF size = m_parent->allPagesSize();
if (size.isValid()) return localizedSize(size);
else return QString();
}
else return QString();
}
else return QString();
}
QString DocumentPrivate::namePaperSize(double inchesWidth, double inchesHeight) const
{
const QPrinter::Orientation orientation = inchesWidth > inchesHeight ? QPrinter::Landscape : QPrinter::Portrait;
const QSize pointsSize(inchesWidth *72.0, inchesHeight*72.0);
const QPageSize::PageSizeId paperSize = QPageSize::id(pointsSize, QPageSize::FuzzyOrientationMatch);
const QString paperName = QPageSize::name(paperSize);
if (orientation == QPrinter::Portrait) {
return i18nc("paper type and orientation (eg: Portrait A4)", "Portrait %0").arg(paperName);
} else {
return i18nc("paper type and orientation (eg: Portrait A4)", "Landscape %0").arg(paperName);
}
}
QString DocumentPrivate::localizedSize(const QSizeF &size) const
{
double inchesWidth = 0, inchesHeight = 0;
switch (m_generator->pagesSizeMetric())
{
case Generator::Points:
inchesWidth = size.width() / 72.0;
inchesHeight = size.height() / 72.0;
break;
case Generator::Pixels:
{
const QSizeF dpi = m_generator->dpi();
inchesWidth = size.width() / dpi.width();
inchesHeight = size.height() / dpi.height();
}
break;
case Generator::None:
break;
}
if (QLocale::system().measurementSystem() == QLocale::ImperialSystem)
{
return i18nc("%1 is width, %2 is height, %3 is paper size name", "%1 x %2 in (%3)", inchesWidth, inchesHeight, namePaperSize(inchesWidth, inchesHeight));
}
else
{
return i18nc("%1 is width, %2 is height, %3 is paper size name", "%1 x %2 mm (%3)", QString::number(inchesWidth * 25.4, 'd', 0), QString::number(inchesHeight * 25.4, 'd', 0), namePaperSize(inchesWidth, inchesHeight));
}
}
qulonglong DocumentPrivate::calculateMemoryToFree()
{
// [MEM] choose memory parameters based on configuration profile
qulonglong clipValue = 0;
qulonglong memoryToFree = 0;
switch ( SettingsCore::memoryLevel() )
{
case SettingsCore::EnumMemoryLevel::Low:
memoryToFree = m_allocatedPixmapsTotalMemory;
break;
case SettingsCore::EnumMemoryLevel::Normal:
{
qulonglong thirdTotalMemory = getTotalMemory() / 3;
qulonglong freeMemory = getFreeMemory();
if (m_allocatedPixmapsTotalMemory > thirdTotalMemory) memoryToFree = m_allocatedPixmapsTotalMemory - thirdTotalMemory;
if (m_allocatedPixmapsTotalMemory > freeMemory) clipValue = (m_allocatedPixmapsTotalMemory - freeMemory) / 2;
}
break;
case SettingsCore::EnumMemoryLevel::Aggressive:
{
qulonglong freeMemory = getFreeMemory();
if (m_allocatedPixmapsTotalMemory > freeMemory) clipValue = (m_allocatedPixmapsTotalMemory - freeMemory) / 2;
}
break;
case SettingsCore::EnumMemoryLevel::Greedy:
{
qulonglong freeSwap;
qulonglong freeMemory = getFreeMemory( &freeSwap );
const qulonglong memoryLimit = qMin( qMax( freeMemory, getTotalMemory()/2 ), freeMemory+freeSwap );
if (m_allocatedPixmapsTotalMemory > memoryLimit) clipValue = (m_allocatedPixmapsTotalMemory - memoryLimit) / 2;
}
break;
}
if ( clipValue > memoryToFree )
memoryToFree = clipValue;
return memoryToFree;
}
void DocumentPrivate::cleanupPixmapMemory()
{
cleanupPixmapMemory( calculateMemoryToFree() );
}
void DocumentPrivate::cleanupPixmapMemory( qulonglong memoryToFree )
{
if ( memoryToFree < 1 )
return;
const int currentViewportPage = (*m_viewportIterator).pageNumber;
// Create a QMap of visible rects, indexed by page number
QMap< int, VisiblePageRect * > visibleRects;
QVector< Okular::VisiblePageRect * >::const_iterator vIt = m_pageRects.constBegin(), vEnd = m_pageRects.constEnd();
for ( ; vIt != vEnd; ++vIt )
visibleRects.insert( (*vIt)->pageNumber, (*vIt) );
// Free memory starting from pages that are farthest from the current one
int pagesFreed = 0;
while ( memoryToFree > 0 )
{
AllocatedPixmap * p = searchLowestPriorityPixmap( true, true );
if ( !p ) // No pixmap to remove
break;
qCDebug(OkularCoreDebug).nospace() << "Evicting cache pixmap observer=" << p->observer << " page=" << p->page;
// m_allocatedPixmapsTotalMemory can't underflow because we always add or remove
// the memory used by the AllocatedPixmap so at most it can reach zero
m_allocatedPixmapsTotalMemory -= p->memory;
// Make sure memoryToFree does not underflow
if ( p->memory > memoryToFree )
memoryToFree = 0;
else
memoryToFree -= p->memory;
pagesFreed++;
// delete pixmap
m_pagesVector.at( p->page )->deletePixmap( p->observer );
// delete allocation descriptor
delete p;
}
// If we're still on low memory, try to free individual tiles
// Store pages that weren't completely removed
QLinkedList< AllocatedPixmap * > pixmapsToKeep;
while (memoryToFree > 0)
{
int clean_hits = 0;
foreach (DocumentObserver *observer, m_observers)
{
AllocatedPixmap * p = searchLowestPriorityPixmap( false, true, observer );
if ( !p ) // No pixmap to remove
continue;
clean_hits++;
TilesManager *tilesManager = m_pagesVector.at( p->page )->d->tilesManager( observer );
if ( tilesManager && tilesManager->totalMemory() > 0 )
{
qulonglong memoryDiff = p->memory;
NormalizedRect visibleRect;
if ( visibleRects.contains( p->page ) )
visibleRect = visibleRects[ p->page ]->rect;
// Free non visible tiles
tilesManager->cleanupPixmapMemory( memoryToFree, visibleRect, currentViewportPage );
p->memory = tilesManager->totalMemory();
memoryDiff -= p->memory;
memoryToFree = (memoryDiff < memoryToFree) ? (memoryToFree - memoryDiff) : 0;
m_allocatedPixmapsTotalMemory -= memoryDiff;
if ( p->memory > 0 )
pixmapsToKeep.append( p );
else
delete p;
}
else
pixmapsToKeep.append( p );
}
if (clean_hits == 0) break;
}
m_allocatedPixmaps += pixmapsToKeep;
//p--rintf("freeMemory A:[%d -%d = %d] \n", m_allocatedPixmaps.count() + pagesFreed, pagesFreed, m_allocatedPixmaps.count() );
}
/* Returns the next pixmap to evict from cache, or NULL if no suitable pixmap
* if found. If unloadableOnly is set, only unloadable pixmaps are returned. If
* thenRemoveIt is set, the pixmap is removed from m_allocatedPixmaps before
* returning it
*/
AllocatedPixmap * DocumentPrivate::searchLowestPriorityPixmap( bool unloadableOnly, bool thenRemoveIt, DocumentObserver *observer )
{
QLinkedList< AllocatedPixmap * >::iterator pIt = m_allocatedPixmaps.begin();
QLinkedList< AllocatedPixmap * >::iterator pEnd = m_allocatedPixmaps.end();
QLinkedList< AllocatedPixmap * >::iterator farthestPixmap = pEnd;
const int currentViewportPage = (*m_viewportIterator).pageNumber;
/* Find the pixmap that is farthest from the current viewport */
int maxDistance = -1;
while ( pIt != pEnd )
{
const AllocatedPixmap * p = *pIt;
// Filter by observer
if ( observer == nullptr || p->observer == observer )
{
const int distance = qAbs( p->page - currentViewportPage );
if ( maxDistance < distance && ( !unloadableOnly || p->observer->canUnloadPixmap( p->page ) ) )
{
maxDistance = distance;
farthestPixmap = pIt;
}
}
++pIt;
}
/* No pixmap to remove */
if ( farthestPixmap == pEnd )
return nullptr;
AllocatedPixmap * selectedPixmap = *farthestPixmap;
if ( thenRemoveIt )
m_allocatedPixmaps.erase( farthestPixmap );
return selectedPixmap;
}
qulonglong DocumentPrivate::getTotalMemory()
{
static qulonglong cachedValue = 0;
if ( cachedValue )
return cachedValue;
#if defined(Q_OS_LINUX)
// if /proc/meminfo doesn't exist, return 128MB
QFile memFile( QStringLiteral("/proc/meminfo") );
if ( !memFile.open( QIODevice::ReadOnly ) )
return (cachedValue = 134217728);
QTextStream readStream( &memFile );
while ( true )
{
QString entry = readStream.readLine();
if ( entry.isNull() ) break;
if ( entry.startsWith( QLatin1String("MemTotal:") ) )
return (cachedValue = (Q_UINT64_C(1024) * entry.section( QLatin1Char ( ' ' ), -2, -2 ).toULongLong()));
}
#elif defined(Q_OS_FREEBSD)
qulonglong physmem;
int mib[] = {CTL_HW, HW_PHYSMEM};
size_t len = sizeof( physmem );
if ( sysctl( mib, 2, &physmem, &len, NULL, 0 ) == 0 )
return (cachedValue = physmem);
#elif defined(Q_OS_WIN)
MEMORYSTATUSEX stat;
stat.dwLength = sizeof(stat);
GlobalMemoryStatusEx (&stat);
return ( cachedValue = stat.ullTotalPhys );
#endif
return (cachedValue = 134217728);
}
qulonglong DocumentPrivate::getFreeMemory( qulonglong *freeSwap )
{
static QTime lastUpdate = QTime::currentTime().addSecs(-3);
static qulonglong cachedValue = 0;
static qulonglong cachedFreeSwap = 0;
if ( qAbs( lastUpdate.secsTo( QTime::currentTime() ) ) <= 2 )
{
if (freeSwap)
*freeSwap = cachedFreeSwap;
return cachedValue;
}
/* Initialize the returned free swap value to 0. It is overwritten if the
* actual value is available */
if (freeSwap)
*freeSwap = 0;
#if defined(Q_OS_LINUX)
// if /proc/meminfo doesn't exist, return MEMORY FULL
QFile memFile( QStringLiteral("/proc/meminfo") );
if ( !memFile.open( QIODevice::ReadOnly ) )
return 0;
// read /proc/meminfo and sum up the contents of 'MemFree', 'Buffers'
// and 'Cached' fields. consider swapped memory as used memory.
qulonglong memoryFree = 0;
QString entry;
QTextStream readStream( &memFile );
static const int nElems = 5;
QString names[nElems] = { QStringLiteral("MemFree:"), QStringLiteral("Buffers:"), QStringLiteral("Cached:"), QStringLiteral("SwapFree:"), QStringLiteral("SwapTotal:") };
qulonglong values[nElems] = { 0, 0, 0, 0, 0 };
bool foundValues[nElems] = { false, false, false, false, false };
while ( true )
{
entry = readStream.readLine();
if ( entry.isNull() ) break;
for ( int i = 0; i < nElems; ++i )
{
if ( entry.startsWith( names[i] ) )
{
values[i] = entry.section( QLatin1Char ( ' ' ), -2, -2 ).toULongLong( &foundValues[i] );
}
}
}
memFile.close();
bool found = true;
for ( int i = 0; found && i < nElems; ++i )
found = found && foundValues[i];
if ( found )
{
/* MemFree + Buffers + Cached - SwapUsed =
* = MemFree + Buffers + Cached - (SwapTotal - SwapFree) =
* = MemFree + Buffers + Cached + SwapFree - SwapTotal */
memoryFree = values[0] + values[1] + values[2] + values[3];
if ( values[4] > memoryFree )
memoryFree = 0;
else
memoryFree -= values[4];
}
else
{
return 0;
}
lastUpdate = QTime::currentTime();
if (freeSwap)
*freeSwap = ( cachedFreeSwap = (Q_UINT64_C(1024) * values[3]) );
return ( cachedValue = (Q_UINT64_C(1024) * memoryFree) );
#elif defined(Q_OS_FREEBSD)
qulonglong cache, inact, free, psize;
size_t cachelen, inactlen, freelen, psizelen;
cachelen = sizeof( cache );
inactlen = sizeof( inact );
freelen = sizeof( free );
psizelen = sizeof( psize );
// sum up inactive, cached and free memory
if ( sysctlbyname( "vm.stats.vm.v_cache_count", &cache, &cachelen, NULL, 0 ) == 0 &&
sysctlbyname( "vm.stats.vm.v_inactive_count", &inact, &inactlen, NULL, 0 ) == 0 &&
sysctlbyname( "vm.stats.vm.v_free_count", &free, &freelen, NULL, 0 ) == 0 &&
sysctlbyname( "vm.stats.vm.v_page_size", &psize, &psizelen, NULL, 0 ) == 0 )
{
lastUpdate = QTime::currentTime();
return (cachedValue = (cache + inact + free) * psize);
}
else
{
return 0;
}
#elif defined(Q_OS_WIN)
MEMORYSTATUSEX stat;
stat.dwLength = sizeof(stat);
GlobalMemoryStatusEx (&stat);
lastUpdate = QTime::currentTime();
if (freeSwap)
*freeSwap = ( cachedFreeSwap = stat.ullAvailPageFile );
return ( cachedValue = stat.ullAvailPhys );
#else
// tell the memory is full.. will act as in LOW profile
return 0;
#endif
}
-void DocumentPrivate::loadDocumentInfo()
+bool DocumentPrivate::loadDocumentInfo( LoadDocumentInfoFlags loadWhat )
// note: load data and stores it internally (document or pages). observers
// are still uninitialized at this point so don't access them
{
//qCDebug(OkularCoreDebug).nospace() << "Using '" << d->m_xmlFileName << "' as document info file.";
if ( m_xmlFileName.isEmpty() )
- return;
+ return false;
QFile infoFile( m_xmlFileName );
- loadDocumentInfo( infoFile );
+ return loadDocumentInfo( infoFile, loadWhat );
}
-void DocumentPrivate::loadDocumentInfo( QFile &infoFile )
+bool DocumentPrivate::loadDocumentInfo( QFile &infoFile, LoadDocumentInfoFlags loadWhat )
{
if ( !infoFile.exists() || !infoFile.open( QIODevice::ReadOnly ) )
- return;
+ return false;
// Load DOM from XML file
QDomDocument doc( QStringLiteral("documentInfo") );
if ( !doc.setContent( &infoFile ) )
{
qCDebug(OkularCoreDebug) << "Can't load XML pair! Check for broken xml.";
infoFile.close();
- return;
+ return false;
}
infoFile.close();
QDomElement root = doc.documentElement();
+
if ( root.tagName() != QLatin1String("documentInfo") )
- return;
+ return false;
+
+ QUrl documentUrl( root.attribute( "url" ) );
+ bool loadedAnything = false; // set if something gets actually loaded
// Parse the DOM tree
QDomNode topLevelNode = root.firstChild();
while ( topLevelNode.isElement() )
{
QString catName = topLevelNode.toElement().tagName();
// Restore page attributes (bookmark, annotations, ...) from the DOM
- if ( catName == QLatin1String("pageList") )
+ if ( catName == QLatin1String("pageList") && ( loadWhat & LoadPageInfo ) )
{
QDomNode pageNode = topLevelNode.firstChild();
while ( pageNode.isElement() )
{
QDomElement pageElement = pageNode.toElement();
if ( pageElement.hasAttribute( QStringLiteral("number") ) )
{
// get page number (node's attribute)
bool ok;
int pageNumber = pageElement.attribute( QStringLiteral("number") ).toInt( &ok );
// pass the domElement to the right page, to read config data from
if ( ok && pageNumber >= 0 && pageNumber < (int)m_pagesVector.count() )
- m_pagesVector[ pageNumber ]->d->restoreLocalContents( pageElement );
+ {
+ if ( m_pagesVector[ pageNumber ]->d->restoreLocalContents( pageElement ) )
+ loadedAnything = true;
+ }
}
pageNode = pageNode.nextSibling();
}
}
// Restore 'general info' from the DOM
- else if ( catName == QLatin1String("generalInfo") )
+ else if ( catName == QLatin1String("generalInfo") && ( loadWhat & LoadGeneralInfo ) )
{
QDomNode infoNode = topLevelNode.firstChild();
while ( infoNode.isElement() )
{
QDomElement infoElement = infoNode.toElement();
// restore viewports history
if ( infoElement.tagName() == QLatin1String("history") )
{
// clear history
m_viewportHistory.clear();
// append old viewports
QDomNode historyNode = infoNode.firstChild();
while ( historyNode.isElement() )
{
QDomElement historyElement = historyNode.toElement();
if ( historyElement.hasAttribute( QStringLiteral("viewport") ) )
{
QString vpString = historyElement.attribute( QStringLiteral("viewport") );
m_viewportIterator = m_viewportHistory.insert( m_viewportHistory.end(),
DocumentViewport( vpString ) );
+ loadedAnything = true;
}
historyNode = historyNode.nextSibling();
}
// consistancy check
if ( m_viewportHistory.isEmpty() )
m_viewportIterator = m_viewportHistory.insert( m_viewportHistory.end(), DocumentViewport() );
}
else if ( infoElement.tagName() == QLatin1String("rotation") )
{
QString str = infoElement.text();
bool ok = true;
int newrotation = !str.isEmpty() ? ( str.toInt( &ok ) % 4 ) : 0;
if ( ok && newrotation != 0 )
{
setRotationInternal( newrotation, false );
+ loadedAnything = true;
}
}
else if ( infoElement.tagName() == QLatin1String("views") )
{
QDomNode viewNode = infoNode.firstChild();
while ( viewNode.isElement() )
{
QDomElement viewElement = viewNode.toElement();
if ( viewElement.tagName() == QLatin1String("view") )
{
const QString viewName = viewElement.attribute( QStringLiteral("name") );
Q_FOREACH ( View * view, m_views )
{
if ( view->name() == viewName )
{
loadViewsInfo( view, viewElement );
+ loadedAnything = true;
break;
}
}
}
viewNode = viewNode.nextSibling();
}
}
infoNode = infoNode.nextSibling();
}
}
topLevelNode = topLevelNode.nextSibling();
} //
+
+ return loadedAnything;
}
void DocumentPrivate::loadViewsInfo( View *view, const QDomElement &e )
{
QDomNode viewNode = e.firstChild();
while ( viewNode.isElement() )
{
QDomElement viewElement = viewNode.toElement();
if ( viewElement.tagName() == QLatin1String("zoom") )
{
const QString valueString = viewElement.attribute( QStringLiteral("value") );
bool newzoom_ok = true;
const double newzoom = !valueString.isEmpty() ? valueString.toDouble( &newzoom_ok ) : 1.0;
if ( newzoom_ok && newzoom != 0
&& view->supportsCapability( View::Zoom )
&& ( view->capabilityFlags( View::Zoom ) & ( View::CapabilityRead | View::CapabilitySerializable ) ) )
{
view->setCapability( View::Zoom, newzoom );
}
const QString modeString = viewElement.attribute( QStringLiteral("mode") );
bool newmode_ok = true;
const int newmode = !modeString.isEmpty() ? modeString.toInt( &newmode_ok ) : 2;
if ( newmode_ok
&& view->supportsCapability( View::ZoomModality )
&& ( view->capabilityFlags( View::ZoomModality ) & ( View::CapabilityRead | View::CapabilitySerializable ) ) )
{
view->setCapability( View::ZoomModality, newmode );
}
}
viewNode = viewNode.nextSibling();
}
}
void DocumentPrivate::saveViewsInfo( View *view, QDomElement &e ) const
{
if ( view->supportsCapability( View::Zoom )
&& ( view->capabilityFlags( View::Zoom ) & ( View::CapabilityRead | View::CapabilitySerializable ) )
&& view->supportsCapability( View::ZoomModality )
&& ( view->capabilityFlags( View::ZoomModality ) & ( View::CapabilityRead | View::CapabilitySerializable ) ) )
{
QDomElement zoomEl = e.ownerDocument().createElement( QStringLiteral("zoom") );
e.appendChild( zoomEl );
bool ok = true;
const double zoom = view->capability( View::Zoom ).toDouble( &ok );
if ( ok && zoom != 0 )
{
zoomEl.setAttribute( QStringLiteral("value"), QString::number(zoom) );
}
const int mode = view->capability( View::ZoomModality ).toInt( &ok );
if ( ok )
{
zoomEl.setAttribute( QStringLiteral("mode"), mode );
}
}
}
QUrl DocumentPrivate::giveAbsoluteUrl( const QString & fileName ) const
{
if ( !QDir::isRelativePath( fileName ) )
return QUrl::fromLocalFile(fileName);
if ( !m_url.isValid() )
return QUrl();
return QUrl(KIO::upUrl(m_url).toString() + fileName);
}
bool DocumentPrivate::openRelativeFile( const QString & fileName )
{
QUrl url = giveAbsoluteUrl( fileName );
if ( url.isEmpty() )
return false;
qCDebug(OkularCoreDebug).nospace() << "openRelativeFile: '" << url << "'";
emit m_parent->openUrl( url );
return true;
}
Generator * DocumentPrivate::loadGeneratorLibrary( const KPluginMetaData &service )
{
KPluginLoader loader( service.fileName() );
qCDebug(OkularCoreDebug) << service.fileName();
KPluginFactory *factory = loader.factory();
if ( !factory )
{
qCWarning(OkularCoreDebug).nospace() << "Invalid plugin factory for " << service.fileName() << ":" << loader.errorString();
return nullptr;
}
Generator * plugin = factory->create();
GeneratorInfo info( plugin, service );
m_loadedGenerators.insert( service.pluginId(), info );
return plugin;
}
void DocumentPrivate::loadAllGeneratorLibraries()
{
if ( m_generatorsLoaded )
return;
loadServiceList( availableGenerators() );
m_generatorsLoaded = true;
}
void DocumentPrivate::loadServiceList( const QVector& offers )
{
int count = offers.count();
if ( count <= 0 )
return;
for ( int i = 0; i < count; ++i )
{
QString id = offers.at(i).pluginId();
// don't load already loaded generators
QHash< QString, GeneratorInfo >::const_iterator genIt = m_loadedGenerators.constFind( id );
if ( !m_loadedGenerators.isEmpty() && genIt != m_loadedGenerators.constEnd() )
continue;
Generator * g = loadGeneratorLibrary( offers.at(i) );
(void)g;
}
}
void DocumentPrivate::unloadGenerator( const GeneratorInfo& info )
{
delete info.generator;
}
void DocumentPrivate::cacheExportFormats()
{
if ( m_exportCached )
return;
const ExportFormat::List formats = m_generator->exportFormats();
for ( int i = 0; i < formats.count(); ++i )
{
if ( formats.at( i ).mimeType().name() == QLatin1String( "text/plain" ) )
m_exportToText = formats.at( i );
else
m_exportFormats.append( formats.at( i ) );
}
m_exportCached = true;
}
ConfigInterface* DocumentPrivate::generatorConfig( GeneratorInfo& info )
{
if ( info.configChecked )
return info.config;
info.config = qobject_cast< Okular::ConfigInterface * >( info.generator );
info.configChecked = true;
return info.config;
}
SaveInterface* DocumentPrivate::generatorSave( GeneratorInfo& info )
{
if ( info.saveChecked )
return info.save;
info.save = qobject_cast< Okular::SaveInterface * >( info.generator );
info.saveChecked = true;
return info.save;
}
Document::OpenResult DocumentPrivate::openDocumentInternal( const KPluginMetaData& offer, bool isstdin, const QString& docFile, const QByteArray& filedata, const QString& password )
{
QString propName = offer.pluginId();
QHash< QString, GeneratorInfo >::const_iterator genIt = m_loadedGenerators.constFind( propName );
m_walletGenerator = nullptr;
if ( genIt != m_loadedGenerators.constEnd() )
{
m_generator = genIt.value().generator;
}
else
{
m_generator = loadGeneratorLibrary( offer );
if ( !m_generator )
return Document::OpenError;
genIt = m_loadedGenerators.constFind( propName );
Q_ASSERT( genIt != m_loadedGenerators.constEnd() );
}
Q_ASSERT_X( m_generator, "Document::load()", "null generator?!" );
m_generator->d_func()->m_document = this;
// connect error reporting signals
QObject::connect( m_generator, &Generator::error, m_parent, &Document::error );
QObject::connect( m_generator, &Generator::warning, m_parent, &Document::warning );
QObject::connect( m_generator, &Generator::notice, m_parent, &Document::notice );
QApplication::setOverrideCursor( Qt::WaitCursor );
const QSizeF dpi = Utils::realDpi(m_widget);
qCDebug(OkularCoreDebug) << "Output DPI:" << dpi;
m_generator->setDPI(dpi);
Document::OpenResult openResult = Document::OpenError;
if ( !isstdin )
{
openResult = m_generator->loadDocumentWithPassword( docFile, m_pagesVector, password );
}
else if ( !filedata.isEmpty() )
{
if ( m_generator->hasFeature( Generator::ReadRawData ) )
{
openResult = m_generator->loadDocumentFromDataWithPassword( filedata, m_pagesVector, password );
}
else
{
m_tempFile = new QTemporaryFile();
if ( !m_tempFile->open() )
{
delete m_tempFile;
m_tempFile = nullptr;
}
else
{
m_tempFile->write( filedata );
QString tmpFileName = m_tempFile->fileName();
m_tempFile->close();
openResult = m_generator->loadDocumentWithPassword( tmpFileName, m_pagesVector, password );
}
}
}
QApplication::restoreOverrideCursor();
if ( openResult != Document::OpenSuccess || m_pagesVector.size() <= 0 )
{
m_generator->d_func()->m_document = nullptr;
QObject::disconnect( m_generator, nullptr, m_parent, nullptr );
// TODO this is a bit of a hack, since basically means that
// you can only call walletDataForFile after calling openDocument
// but since in reality it's what happens I've decided not to refactor/break API
// One solution is just kill walletDataForFile and make OpenResult be an object
// where the wallet data is also returned when OpenNeedsPassword
m_walletGenerator = m_generator;
m_generator = nullptr;
qDeleteAll( m_pagesVector );
m_pagesVector.clear();
delete m_tempFile;
m_tempFile = nullptr;
// TODO: emit a message telling the document is empty
if ( openResult == Document::OpenSuccess )
openResult = Document::OpenError;
}
return openResult;
}
bool DocumentPrivate::savePageDocumentInfo( QTemporaryFile *infoFile, int what ) const
{
if ( infoFile->open() )
{
// 1. Create DOM
QDomDocument doc( QStringLiteral("documentInfo") );
QDomProcessingInstruction xmlPi = doc.createProcessingInstruction(
QStringLiteral( "xml" ), QStringLiteral( "version=\"1.0\" encoding=\"utf-8\"" ) );
doc.appendChild( xmlPi );
QDomElement root = doc.createElement( QStringLiteral("documentInfo") );
doc.appendChild( root );
// 2.1. Save page attributes (bookmark state, annotations, ... ) to DOM
QDomElement pageList = doc.createElement( QStringLiteral("pageList") );
root.appendChild( pageList );
// .... save pages that hold data
QVector< Page * >::const_iterator pIt = m_pagesVector.constBegin(), pEnd = m_pagesVector.constEnd();
for ( ; pIt != pEnd; ++pIt )
(*pIt)->d->saveLocalContents( pageList, doc, PageItems( what ) );
// 3. Save DOM to XML file
QString xml = doc.toString();
QTextStream os( infoFile );
os.setCodec( "UTF-8" );
os << xml;
return true;
}
return false;
}
DocumentViewport DocumentPrivate::nextDocumentViewport() const
{
DocumentViewport ret = m_nextDocumentViewport;
if ( !m_nextDocumentDestination.isEmpty() && m_generator )
{
DocumentViewport vp( m_parent->metaData( QStringLiteral("NamedViewport"), m_nextDocumentDestination ).toString() );
if ( vp.isValid() )
{
ret = vp;
}
}
return ret;
}
-void DocumentPrivate::warnLimitedAnnotSupport()
-{
- if ( !m_showWarningLimitedAnnotSupport )
- return;
- m_showWarningLimitedAnnotSupport = false; // Show the warning once
-
- if ( m_annotationsNeedSaveAs )
- {
- // Shown if the user is editing annotations in a file whose metadata is
- // not stored locally (.okular archives belong to this category)
- KMessageBox::information( m_widget, i18n("Your annotation changes will not be saved automatically. Use File -> Save As...\nor your changes will be lost once the document is closed"), QString(), QStringLiteral("annotNeedSaveAs") );
- }
- else if ( !canAddAnnotationsNatively() )
- {
- // If the generator doesn't support native annotations
- KMessageBox::information( m_widget, i18n("Your annotations are saved internally by Okular.\nYou can export the annotated document using File -> Export As -> Document Archive"), QString(), QStringLiteral("annotExportAsArchive") );
- }
-}
-
void DocumentPrivate::performAddPageAnnotation( int page, Annotation * annotation )
{
Okular::SaveInterface * iface = qobject_cast< Okular::SaveInterface * >( m_generator );
AnnotationProxy *proxy = iface ? iface->annotationProxy() : nullptr;
// find out the page to attach annotation
Page * kp = m_pagesVector[ page ];
if ( !m_generator || !kp )
return;
// the annotation belongs already to a page
if ( annotation->d_ptr->m_page )
return;
// add annotation to the page
kp->addAnnotation( annotation );
// tell the annotation proxy
if ( proxy && proxy->supports(AnnotationProxy::Addition) )
proxy->notifyAddition( annotation, page );
// notify observers about the change
notifyAnnotationChanges( page );
if ( annotation->flags() & Annotation::ExternallyDrawn )
{
// Redraw everything, including ExternallyDrawn annotations
refreshPixmaps( page );
}
-
- warnLimitedAnnotSupport();
}
void DocumentPrivate::performRemovePageAnnotation( int page, Annotation * annotation )
{
Okular::SaveInterface * iface = qobject_cast< Okular::SaveInterface * >( m_generator );
AnnotationProxy *proxy = iface ? iface->annotationProxy() : nullptr;
bool isExternallyDrawn;
// find out the page
Page * kp = m_pagesVector[ page ];
if ( !m_generator || !kp )
return;
if ( annotation->flags() & Annotation::ExternallyDrawn )
isExternallyDrawn = true;
else
isExternallyDrawn = false;
// try to remove the annotation
if ( m_parent->canRemovePageAnnotation( annotation ) )
{
// tell the annotation proxy
if ( proxy && proxy->supports(AnnotationProxy::Removal) )
proxy->notifyRemoval( annotation, page );
kp->removeAnnotation( annotation ); // Also destroys the object
// in case of success, notify observers about the change
notifyAnnotationChanges( page );
if ( isExternallyDrawn )
{
// Redraw everything, including ExternallyDrawn annotations
refreshPixmaps( page );
}
}
-
- warnLimitedAnnotSupport();
}
void DocumentPrivate::performModifyPageAnnotation( int page, Annotation * annotation, bool appearanceChanged )
{
Okular::SaveInterface * iface = qobject_cast< Okular::SaveInterface * >( m_generator );
AnnotationProxy *proxy = iface ? iface->annotationProxy() : nullptr;
// find out the page
Page * kp = m_pagesVector[ page ];
if ( !m_generator || !kp )
return;
// tell the annotation proxy
if ( proxy && proxy->supports(AnnotationProxy::Modification) )
{
proxy->notifyModification( annotation, page, appearanceChanged );
}
// notify observers about the change
notifyAnnotationChanges( page );
if ( appearanceChanged && (annotation->flags() & Annotation::ExternallyDrawn) )
{
/* When an annotation is being moved, the generator will not render it.
* Therefore there's no need to refresh pixmaps after the first time */
if ( annotation->flags() & (Annotation::BeingMoved | Annotation::BeingResized) )
{
if ( m_annotationBeingModified )
return;
else // First time: take note
m_annotationBeingModified = true;
}
else
{
m_annotationBeingModified = false;
}
// Redraw everything, including ExternallyDrawn annotations
qCDebug(OkularCoreDebug) << "Refreshing Pixmaps";
refreshPixmaps( page );
}
-
- // If the user is moving or resizing the annotation, don't steal the focus
- if ( (annotation->flags() & (Annotation::BeingMoved | Annotation::BeingResized) ) == 0 )
- warnLimitedAnnotSupport();
}
void DocumentPrivate::performSetAnnotationContents( const QString & newContents, Annotation *annot, int pageNumber )
{
bool appearanceChanged = false;
// Check if appearanceChanged should be true
switch ( annot->subType() )
{
// If it's an in-place TextAnnotation, set the inplace text
case Okular::Annotation::AText:
{
Okular::TextAnnotation * txtann = static_cast< Okular::TextAnnotation * >( annot );
if ( txtann->textType() == Okular::TextAnnotation::InPlace )
{
appearanceChanged = true;
}
break;
}
// If it's a LineAnnotation, check if caption text is visible
case Okular::Annotation::ALine:
{
Okular::LineAnnotation * lineann = static_cast< Okular::LineAnnotation * >( annot );
if ( lineann->showCaption() )
appearanceChanged = true;
break;
}
default:
break;
}
// Set contents
annot->setContents( newContents );
// Tell the document the annotation has been modified
performModifyPageAnnotation( pageNumber, annot, appearanceChanged );
}
void DocumentPrivate::recalculateForms()
{
const QVariant fco = m_parent->metaData(QLatin1String("FormCalculateOrder"));
const QVector formCalculateOrder = fco.value>();
foreach(int formId, formCalculateOrder) {
for ( uint pageIdx = 0; pageIdx < m_parent->pages(); pageIdx++ )
{
const Page *p = m_parent->page( pageIdx );
if (p)
{
foreach( FormField *form, p->formFields() )
{
if ( form->id() == formId ) {
Action *action = form->additionalAction( FormField::CalculateField );
if (action)
{
m_parent->processAction( action );
}
else
{
qWarning() << "Form that is part of calculate order doesn't have a calculate action";
}
}
}
}
}
}
}
void DocumentPrivate::saveDocumentInfo() const
{
if ( m_xmlFileName.isEmpty() )
return;
QFile infoFile( m_xmlFileName );
qCDebug(OkularCoreDebug) << "About to save document info to" << m_xmlFileName;
if (!infoFile.open( QIODevice::WriteOnly | QIODevice::Truncate))
{
qCWarning(OkularCoreDebug) << "Failed to open docdata file" << m_xmlFileName;
return;
-
}
// 1. Create DOM
QDomDocument doc( QStringLiteral("documentInfo") );
QDomProcessingInstruction xmlPi = doc.createProcessingInstruction(
QStringLiteral( "xml" ), QStringLiteral( "version=\"1.0\" encoding=\"utf-8\"" ) );
doc.appendChild( xmlPi );
QDomElement root = doc.createElement( QStringLiteral("documentInfo") );
root.setAttribute( QStringLiteral("url"), m_url.toDisplayString(QUrl::PreferLocalFile) );
doc.appendChild( root );
// 2.1. Save page attributes (bookmark state, annotations, ... ) to DOM
- QDomElement pageList = doc.createElement( QStringLiteral("pageList") );
- root.appendChild( pageList );
- PageItems saveWhat = AllPageItems;
- if ( m_annotationsNeedSaveAs )
- {
- /* In this case, if the user makes a modification, he's requested to
- * save to a new document. Therefore, if there are existing local
- * annotations, we save them back unmodified in the original
- * document's metadata, so that it appears that it was not changed */
- saveWhat |= OriginalAnnotationPageItems;
- }
- // .... save pages that hold data
- QVector< Page * >::const_iterator pIt = m_pagesVector.constBegin(), pEnd = m_pagesVector.constEnd();
- for ( ; pIt != pEnd; ++pIt )
- (*pIt)->d->saveLocalContents( pageList, doc, saveWhat );
+ // -> do this if there are not-yet-migrated annots or forms in docdata/
+ if ( m_docdataMigrationNeeded )
+ {
+ QDomElement pageList = doc.createElement( "pageList" );
+ root.appendChild( pageList );
+ // OriginalAnnotationPageItems and OriginalFormFieldPageItems tell to
+ // store the same unmodified annotation list and form contents that we
+ // read when we opened the file and ignore any change made by the user.
+ // Since we don't store annotations and forms in docdata/ any more, this is
+ // necessary to preserve annotations/forms that previous Okular version
+ // had stored there.
+ const PageItems saveWhat = AllPageItems | OriginalAnnotationPageItems | OriginalFormFieldPageItems;
+ // .... save pages that hold data
+ QVector< Page * >::const_iterator pIt = m_pagesVector.constBegin(), pEnd = m_pagesVector.constEnd();
+ for ( ; pIt != pEnd; ++pIt )
+ (*pIt)->d->saveLocalContents( pageList, doc, saveWhat );
+ }
// 2.2. Save document info (current viewport, history, ... ) to DOM
QDomElement generalInfo = doc.createElement( QStringLiteral("generalInfo") );
root.appendChild( generalInfo );
// create rotation node
if ( m_rotation != Rotation0 )
{
QDomElement rotationNode = doc.createElement( QStringLiteral("rotation") );
generalInfo.appendChild( rotationNode );
rotationNode.appendChild( doc.createTextNode( QString::number( (int)m_rotation ) ) );
}
// ... save history up to OKULAR_HISTORY_SAVEDSTEPS viewports
QLinkedList< DocumentViewport >::const_iterator backIterator = m_viewportIterator;
if ( backIterator != m_viewportHistory.constEnd() )
{
// go back up to OKULAR_HISTORY_SAVEDSTEPS steps from the current viewportIterator
int backSteps = OKULAR_HISTORY_SAVEDSTEPS;
while ( backSteps-- && backIterator != m_viewportHistory.constBegin() )
--backIterator;
// create history root node
QDomElement historyNode = doc.createElement( QStringLiteral("history") );
generalInfo.appendChild( historyNode );
// add old[backIterator] and present[viewportIterator] items
QLinkedList< DocumentViewport >::const_iterator endIt = m_viewportIterator;
++endIt;
while ( backIterator != endIt )
{
QString name = (backIterator == m_viewportIterator) ? QStringLiteral ("current") : QStringLiteral ("oldPage");
QDomElement historyEntry = doc.createElement( name );
historyEntry.setAttribute( QStringLiteral("viewport"), (*backIterator).toString() );
historyNode.appendChild( historyEntry );
++backIterator;
}
}
// create views root node
QDomElement viewsNode = doc.createElement( QStringLiteral("views") );
generalInfo.appendChild( viewsNode );
Q_FOREACH ( View * view, m_views )
{
QDomElement viewEntry = doc.createElement( QStringLiteral("view") );
viewEntry.setAttribute( QStringLiteral("name"), view->name() );
viewsNode.appendChild( viewEntry );
saveViewsInfo( view, viewEntry );
}
// 3. Save DOM to XML file
QString xml = doc.toString();
QTextStream os( &infoFile );
os.setCodec( "UTF-8" );
os << xml;
infoFile.close();
}
void DocumentPrivate::slotTimedMemoryCheck()
{
// [MEM] clean memory (for 'free mem dependant' profiles only)
if ( SettingsCore::memoryLevel() != SettingsCore::EnumMemoryLevel::Low &&
m_allocatedPixmapsTotalMemory > 1024*1024 )
cleanupPixmapMemory();
}
void DocumentPrivate::sendGeneratorPixmapRequest()
{
/* If the pixmap cache will have to be cleaned in order to make room for the
* next request, get the distance from the current viewport of the page
* whose pixmap will be removed. We will ignore preload requests for pages
* that are at the same distance or farther */
const qulonglong memoryToFree = calculateMemoryToFree();
const int currentViewportPage = (*m_viewportIterator).pageNumber;
int maxDistance = INT_MAX; // Default: No maximum
if ( memoryToFree )
{
AllocatedPixmap *pixmapToReplace = searchLowestPriorityPixmap( true );
if ( pixmapToReplace )
maxDistance = qAbs( pixmapToReplace->page - currentViewportPage );
}
// find a request
PixmapRequest * request = nullptr;
m_pixmapRequestsMutex.lock();
while ( !m_pixmapRequestsStack.isEmpty() && !request )
{
PixmapRequest * r = m_pixmapRequestsStack.last();
if (!r)
{
m_pixmapRequestsStack.pop_back();
continue;
}
QRect requestRect = r->isTile() ? r->normalizedRect().geometry( r->width(), r->height() ) : QRect( 0, 0, r->width(), r->height() );
TilesManager *tilesManager = r->d->tilesManager();
// If it's a preload but the generator is not threaded no point in trying to preload
if ( r->preload() && !m_generator->hasFeature( Generator::Threaded ) )
{
m_pixmapRequestsStack.pop_back();
delete r;
}
// request only if page isn't already present and request has valid id
// request only if page isn't already present and request has valid id
else if ( ( !r->d->mForce && r->page()->hasPixmap( r->observer(), r->width(), r->height(), r->normalizedRect() ) ) || !m_observers.contains(r->observer()) )
{
m_pixmapRequestsStack.pop_back();
delete r;
}
else if ( !r->d->mForce && r->preload() && qAbs( r->pageNumber() - currentViewportPage ) >= maxDistance )
{
m_pixmapRequestsStack.pop_back();
//qCDebug(OkularCoreDebug) << "Ignoring request that doesn't fit in cache";
delete r;
}
// Ignore requests for pixmaps that are already being generated
else if ( tilesManager && tilesManager->isRequesting( r->normalizedRect(), r->width(), r->height() ) )
{
m_pixmapRequestsStack.pop_back();
delete r;
}
// If the requested area is above 8000000 pixels, switch on the tile manager
else if ( !tilesManager && m_generator->hasFeature( Generator::TiledRendering ) && (long)r->width() * (long)r->height() > 8000000L )
{
// if the image is too big. start using tiles
qCDebug(OkularCoreDebug).nospace() << "Start using tiles on page " << r->pageNumber()
<< " (" << r->width() << "x" << r->height() << " px);";
// fill the tiles manager with the last rendered pixmap
const QPixmap *pixmap = r->page()->_o_nearestPixmap( r->observer(), r->width(), r->height() );
if ( pixmap )
{
tilesManager = new TilesManager( r->pageNumber(), pixmap->width(), pixmap->height(), r->page()->rotation() );
tilesManager->setPixmap( pixmap, NormalizedRect( 0, 0, 1, 1 ) );
tilesManager->setSize( r->width(), r->height() );
}
else
{
// create new tiles manager
tilesManager = new TilesManager( r->pageNumber(), r->width(), r->height(), r->page()->rotation() );
}
tilesManager->setRequest( r->normalizedRect(), r->width(), r->height() );
r->page()->deletePixmap( r->observer() );
r->page()->d->setTilesManager( r->observer(), tilesManager );
r->setTile( true );
// Change normalizedRect to the smallest rect that contains all
// visible tiles.
if ( !r->normalizedRect().isNull() )
{
NormalizedRect tilesRect;
const QList tiles = tilesManager->tilesAt( r->normalizedRect(), TilesManager::TerminalTile );
QList::const_iterator tIt = tiles.constBegin(), tEnd = tiles.constEnd();
while ( tIt != tEnd )
{
Tile tile = *tIt;
if ( tilesRect.isNull() )
tilesRect = tile.rect();
else
tilesRect |= tile.rect();
++tIt;
}
r->setNormalizedRect( tilesRect );
request = r;
}
else
{
// Discard request if normalizedRect is null. This happens in
// preload requests issued by PageView if the requested page is
// not visible and the user has just switched from a non-tiled
// zoom level to a tiled one
m_pixmapRequestsStack.pop_back();
delete r;
}
}
// If the requested area is below 6000000 pixels, switch off the tile manager
else if ( tilesManager && (long)r->width() * (long)r->height() < 6000000L )
{
qCDebug(OkularCoreDebug).nospace() << "Stop using tiles on page " << r->pageNumber()
<< " (" << r->width() << "x" << r->height() << " px);";
// page is too small. stop using tiles.
r->page()->deletePixmap( r->observer() );
r->setTile( false );
request = r;
}
else if ( (long)requestRect.width() * (long)requestRect.height() > 200000000L && (SettingsCore::memoryLevel() != SettingsCore::EnumMemoryLevel::Greedy ) )
{
m_pixmapRequestsStack.pop_back();
if ( !m_warnedOutOfMemory )
{
qCWarning(OkularCoreDebug).nospace() << "Running out of memory on page " << r->pageNumber()
<< " (" << r->width() << "x" << r->height() << " px);";
qCWarning(OkularCoreDebug) << "this message will be reported only once.";
m_warnedOutOfMemory = true;
}
delete r;
}
else
{
request = r;
}
}
// if no request found (or already generated), return
if ( !request )
{
m_pixmapRequestsMutex.unlock();
return;
}
// [MEM] preventive memory freeing
qulonglong pixmapBytes = 0;
TilesManager * tm = request->d->tilesManager();
if ( tm )
pixmapBytes = tm->totalMemory();
else
pixmapBytes = 4 * request->width() * request->height();
if ( pixmapBytes > (1024 * 1024) )
cleanupPixmapMemory( memoryToFree /* previously calculated value */ );
// submit the request to the generator
if ( m_generator->canGeneratePixmap() )
{
QRect requestRect = !request->isTile() ? QRect(0, 0, request->width(), request->height() ) : request->normalizedRect().geometry( request->width(), request->height() );
qCDebug(OkularCoreDebug).nospace() << "sending request observer=" << request->observer() << " " <pageNumber() << " async == " << request->asynchronous() << " isTile == " << request->isTile();
m_pixmapRequestsStack.removeAll ( request );
if ( tm )
tm->setRequest( request->normalizedRect(), request->width(), request->height() );
if ( (int)m_rotation % 2 )
request->d->swap();
if ( m_rotation != Rotation0 && !request->normalizedRect().isNull() )
request->setNormalizedRect( TilesManager::fromRotatedRect(
request->normalizedRect(), m_rotation ) );
request->setPartialUpdatesWanted( request->asynchronous() && !request->page()->hasPixmap( request->observer() ) );
// we always have to unlock _before_ the generatePixmap() because
// a sync generation would end with requestDone() -> deadlock, and
// we can not really know if the generator can do async requests
m_executingPixmapRequests.push_back( request );
m_pixmapRequestsMutex.unlock();
m_generator->generatePixmap( request );
}
else
{
m_pixmapRequestsMutex.unlock();
// pino (7/4/2006): set the polling interval from 10 to 30
QTimer::singleShot( 30, m_parent, SLOT(sendGeneratorPixmapRequest()) );
}
}
void DocumentPrivate::rotationFinished( int page, Okular::Page *okularPage )
{
Okular::Page *wantedPage = m_pagesVector.value( page, 0 );
if ( !wantedPage || wantedPage != okularPage )
return;
foreach(DocumentObserver *o, m_observers)
o->notifyPageChanged( page, DocumentObserver::Pixmap | DocumentObserver::Annotations );
}
void DocumentPrivate::slotFontReadingProgress( int page )
{
emit m_parent->fontReadingProgress( page );
if ( page >= (int)m_parent->pages() - 1 )
{
emit m_parent->fontReadingEnded();
m_fontThread = nullptr;
m_fontsCached = true;
}
}
void DocumentPrivate::fontReadingGotFont( const Okular::FontInfo& font )
{
// Try to avoid duplicate fonts
if (m_fontsCache.indexOf(font) == -1) {
m_fontsCache.append( font );
emit m_parent->gotFont( font );
}
}
void DocumentPrivate::slotGeneratorConfigChanged( const QString& )
{
if ( !m_generator )
return;
// reparse generator config and if something changed clear Pages
bool configchanged = false;
QHash< QString, GeneratorInfo >::iterator it = m_loadedGenerators.begin(), itEnd = m_loadedGenerators.end();
for ( ; it != itEnd; ++it )
{
Okular::ConfigInterface * iface = generatorConfig( it.value() );
if ( iface )
{
bool it_changed = iface->reparseConfig();
if ( it_changed && ( m_generator == it.value().generator ) )
configchanged = true;
}
}
if ( configchanged )
{
// invalidate pixmaps
QVector::const_iterator it = m_pagesVector.constBegin(), end = m_pagesVector.constEnd();
for ( ; it != end; ++it ) {
(*it)->deletePixmaps();
}
// [MEM] remove allocation descriptors
qDeleteAll( m_allocatedPixmaps );
m_allocatedPixmaps.clear();
m_allocatedPixmapsTotalMemory = 0;
// send reload signals to observers
foreachObserverD( notifyContentsCleared( DocumentObserver::Pixmap ) );
}
// free memory if in 'low' profile
if ( SettingsCore::memoryLevel() == SettingsCore::EnumMemoryLevel::Low &&
!m_allocatedPixmaps.isEmpty() && !m_pagesVector.isEmpty() )
cleanupPixmapMemory();
}
void DocumentPrivate::refreshPixmaps( int pageNumber )
{
Page* page = m_pagesVector.value( pageNumber, 0 );
if ( !page )
return;
QLinkedList< Okular::PixmapRequest * > requestedPixmaps;
QMap< DocumentObserver*, PagePrivate::PixmapObject >::ConstIterator it = page->d->m_pixmaps.constBegin(), itEnd = page->d->m_pixmaps.constEnd();
for ( ; it != itEnd; ++it )
{
QSize size = (*it).m_pixmap->size();
PixmapRequest * p = new PixmapRequest( it.key(), pageNumber, size.width() / qApp->devicePixelRatio(), size.height() / qApp->devicePixelRatio(), 1, PixmapRequest::Asynchronous );
p->d->mForce = true;
requestedPixmaps.push_back( p );
}
foreach (DocumentObserver *observer, m_observers)
{
TilesManager *tilesManager = page->d->tilesManager( observer );
if ( tilesManager )
{
tilesManager->markDirty();
PixmapRequest * p = new PixmapRequest( observer, pageNumber, tilesManager->width() / qApp->devicePixelRatio(), tilesManager->height() / qApp->devicePixelRatio(), 1, PixmapRequest::Asynchronous );
NormalizedRect tilesRect;
// Get the visible page rect
NormalizedRect visibleRect;
QVector< Okular::VisiblePageRect * >::const_iterator vIt = m_pageRects.constBegin(), vEnd = m_pageRects.constEnd();
for ( ; vIt != vEnd; ++vIt )
{
if ( (*vIt)->pageNumber == pageNumber )
{
visibleRect = (*vIt)->rect;
break;
}
}
if ( !visibleRect.isNull() )
{
p->setNormalizedRect( visibleRect );
p->setTile( true );
p->d->mForce = true;
requestedPixmaps.push_back( p );
}
else
{
delete p;
}
}
}
if ( !requestedPixmaps.isEmpty() )
m_parent->requestPixmaps( requestedPixmaps, Okular::Document::NoOption );
}
void DocumentPrivate::_o_configChanged()
{
// free text pages if needed
calculateMaxTextPages();
while (m_allocatedTextPagesFifo.count() > m_maxAllocatedTextPages)
{
int pageToKick = m_allocatedTextPagesFifo.takeFirst();
m_pagesVector.at(pageToKick)->setTextPage( nullptr ); // deletes the textpage
}
}
void DocumentPrivate::doContinueDirectionMatchSearch(void *doContinueDirectionMatchSearchStruct)
{
DoContinueDirectionMatchSearchStruct *searchStruct = static_cast(doContinueDirectionMatchSearchStruct);
RunningSearch *search = m_searches.value(searchStruct->searchID);
if ((m_searchCancelled && !searchStruct->match) || !search)
{
// if the user cancelled but he just got a match, give him the match!
QApplication::restoreOverrideCursor();
if (search) search->isCurrentlySearching = false;
emit m_parent->searchFinished( searchStruct->searchID, Document::SearchCancelled );
delete searchStruct->pagesToNotify;
delete searchStruct;
return;
}
const bool forward = search->cachedType == Document::NextMatch;
bool doContinue = false;
// if no match found, loop through the whole doc, starting from currentPage
if ( !searchStruct->match )
{
const int pageCount = m_pagesVector.count();
if (search->pagesDone < pageCount)
{
doContinue = true;
if ( searchStruct->currentPage >= pageCount )
{
searchStruct->currentPage = 0;
emit m_parent->notice(i18n("Continuing search from beginning"), 3000);
}
else if ( searchStruct->currentPage < 0 )
{
searchStruct->currentPage = pageCount - 1;
emit m_parent->notice(i18n("Continuing search from bottom"), 3000);
}
}
}
if (doContinue)
{
// get page
Page * page = m_pagesVector[ searchStruct->currentPage ];
// request search page if needed
if ( !page->hasTextPage() )
m_parent->requestTextPage( page->number() );
// if found a match on the current page, end the loop
searchStruct->match = page->findText( searchStruct->searchID, search->cachedString, forward ? FromTop : FromBottom, search->cachedCaseSensitivity );
if ( !searchStruct->match )
{
if (forward) searchStruct->currentPage++;
else searchStruct->currentPage--;
search->pagesDone++;
}
else
{
search->pagesDone = 1;
}
// Both of the previous if branches need to call doContinueDirectionMatchSearch
QMetaObject::invokeMethod(m_parent, "doContinueDirectionMatchSearch", Qt::QueuedConnection, Q_ARG(void *, searchStruct));
}
else
{
doProcessSearchMatch( searchStruct->match, search, searchStruct->pagesToNotify, searchStruct->currentPage, searchStruct->searchID, search->cachedViewportMove, search->cachedColor );
delete searchStruct;
}
}
void DocumentPrivate::doProcessSearchMatch( RegularAreaRect *match, RunningSearch *search, QSet< int > *pagesToNotify, int currentPage, int searchID, bool moveViewport, const QColor & color )
{
// reset cursor to previous shape
QApplication::restoreOverrideCursor();
bool foundAMatch = false;
search->isCurrentlySearching = false;
// if a match has been found..
if ( match )
{
// update the RunningSearch structure adding this match..
foundAMatch = true;
search->continueOnPage = currentPage;
search->continueOnMatch = *match;
search->highlightedPages.insert( currentPage );
// ..add highlight to the page..
m_pagesVector[ currentPage ]->d->setHighlight( searchID, match, color );
// ..queue page for notifying changes..
pagesToNotify->insert( currentPage );
// Create a normalized rectangle around the search match that includes a 5% buffer on all sides.
const Okular::NormalizedRect matchRectWithBuffer = Okular::NormalizedRect( match->first().left - 0.05,
match->first().top - 0.05,
match->first().right + 0.05,
match->first().bottom + 0.05 );
const bool matchRectFullyVisible = isNormalizedRectangleFullyVisible( matchRectWithBuffer, currentPage );
// ..move the viewport to show the first of the searched word sequence centered
if ( moveViewport && !matchRectFullyVisible )
{
DocumentViewport searchViewport( currentPage );
searchViewport.rePos.enabled = true;
searchViewport.rePos.normalizedX = (match->first().left + match->first().right) / 2.0;
searchViewport.rePos.normalizedY = (match->first().top + match->first().bottom) / 2.0;
m_parent->setViewport( searchViewport, nullptr, true );
}
delete match;
}
// notify observers about highlights changes
foreach(int pageNumber, *pagesToNotify)
foreach(DocumentObserver *observer, m_observers)
observer->notifyPageChanged( pageNumber, DocumentObserver::Highlights );
if (foundAMatch) emit m_parent->searchFinished( searchID, Document::MatchFound );
else emit m_parent->searchFinished( searchID, Document::NoMatchFound );
delete pagesToNotify;
}
void DocumentPrivate::doContinueAllDocumentSearch(void *pagesToNotifySet, void *pageMatchesMap, int currentPage, int searchID)
{
QMap< Page *, QVector > *pageMatches = static_cast< QMap< Page *, QVector > * >(pageMatchesMap);
QSet< int > *pagesToNotify = static_cast< QSet< int > * >( pagesToNotifySet );
RunningSearch *search = m_searches.value(searchID);
if (m_searchCancelled || !search)
{
typedef QVector MatchesVector;
QApplication::restoreOverrideCursor();
if (search) search->isCurrentlySearching = false;
emit m_parent->searchFinished( searchID, Document::SearchCancelled );
foreach(const MatchesVector &mv, *pageMatches) qDeleteAll(mv);
delete pageMatches;
delete pagesToNotify;
return;
}
if (currentPage < m_pagesVector.count())
{
// get page (from the first to the last)
Page *page = m_pagesVector.at(currentPage);
int pageNumber = page->number(); // redundant? is it == currentPage ?
// request search page if needed
if ( !page->hasTextPage() )
m_parent->requestTextPage( pageNumber );
// loop on a page adding highlights for all found items
RegularAreaRect * lastMatch = nullptr;
while ( 1 )
{
if ( lastMatch )
lastMatch = page->findText( searchID, search->cachedString, NextResult, search->cachedCaseSensitivity, lastMatch );
else
lastMatch = page->findText( searchID, search->cachedString, FromTop, search->cachedCaseSensitivity );
if ( !lastMatch )
break;
// add highligh rect to the matches map
(*pageMatches)[page].append(lastMatch);
}
delete lastMatch;
QMetaObject::invokeMethod(m_parent, "doContinueAllDocumentSearch", Qt::QueuedConnection, Q_ARG(void *, pagesToNotifySet), Q_ARG(void *, pageMatches), Q_ARG(int, currentPage + 1), Q_ARG(int, searchID));
}
else
{
// reset cursor to previous shape
QApplication::restoreOverrideCursor();
search->isCurrentlySearching = false;
bool foundAMatch = pageMatches->count() != 0;
QMap< Page *, QVector >::const_iterator it, itEnd;
it = pageMatches->constBegin();
itEnd = pageMatches->constEnd();
for ( ; it != itEnd; ++it)
{
foreach(RegularAreaRect *match, it.value())
{
it.key()->d->setHighlight( searchID, match, search->cachedColor );
delete match;
}
search->highlightedPages.insert( it.key()->number() );
pagesToNotify->insert( it.key()->number() );
}
foreach(DocumentObserver *observer, m_observers)
observer->notifySetup( m_pagesVector, 0 );
// notify observers about highlights changes
foreach(int pageNumber, *pagesToNotify)
foreach(DocumentObserver *observer, m_observers)
observer->notifyPageChanged( pageNumber, DocumentObserver::Highlights );
if (foundAMatch) emit m_parent->searchFinished(searchID, Document::MatchFound );
else emit m_parent->searchFinished( searchID, Document::NoMatchFound );
delete pageMatches;
delete pagesToNotify;
}
}
void DocumentPrivate::doContinueGooglesDocumentSearch(void *pagesToNotifySet, void *pageMatchesMap, int currentPage, int searchID, const QStringList & words)
{
typedef QPair MatchColor;
QMap< Page *, QVector > *pageMatches = static_cast< QMap< Page *, QVector > * >(pageMatchesMap);
QSet< int > *pagesToNotify = static_cast< QSet< int > * >( pagesToNotifySet );
RunningSearch *search = m_searches.value(searchID);
if (m_searchCancelled || !search)
{
typedef QVector MatchesVector;
QApplication::restoreOverrideCursor();
if (search) search->isCurrentlySearching = false;
emit m_parent->searchFinished( searchID, Document::SearchCancelled );
foreach(const MatchesVector &mv, *pageMatches)
{
foreach(const MatchColor &mc, mv) delete mc.first;
}
delete pageMatches;
delete pagesToNotify;
return;
}
const int wordCount = words.count();
const int hueStep = (wordCount > 1) ? (60 / (wordCount - 1)) : 60;
int baseHue, baseSat, baseVal;
search->cachedColor.getHsv( &baseHue, &baseSat, &baseVal );
if (currentPage < m_pagesVector.count())
{
// get page (from the first to the last)
Page *page = m_pagesVector.at(currentPage);
int pageNumber = page->number(); // redundant? is it == currentPage ?
// request search page if needed
if ( !page->hasTextPage() )
m_parent->requestTextPage( pageNumber );
// loop on a page adding highlights for all found items
bool allMatched = wordCount > 0,
anyMatched = false;
for ( int w = 0; w < wordCount; w++ )
{
const QString &word = words[ w ];
int newHue = baseHue - w * hueStep;
if ( newHue < 0 )
newHue += 360;
QColor wordColor = QColor::fromHsv( newHue, baseSat, baseVal );
RegularAreaRect * lastMatch = nullptr;
// add all highlights for current word
bool wordMatched = false;
while ( 1 )
{
if ( lastMatch )
lastMatch = page->findText( searchID, word, NextResult, search->cachedCaseSensitivity, lastMatch );
else
lastMatch = page->findText( searchID, word, FromTop, search->cachedCaseSensitivity);
if ( !lastMatch )
break;
// add highligh rect to the matches map
(*pageMatches)[page].append(MatchColor(lastMatch, wordColor));
wordMatched = true;
}
allMatched = allMatched && wordMatched;
anyMatched = anyMatched || wordMatched;
}
// if not all words are present in page, remove partial highlights
const bool matchAll = search->cachedType == Document::GoogleAll;
if ( !allMatched && matchAll )
{
QVector &matches = (*pageMatches)[page];
foreach(const MatchColor &mc, matches) delete mc.first;
pageMatches->remove(page);
}
QMetaObject::invokeMethod(m_parent, "doContinueGooglesDocumentSearch", Qt::QueuedConnection, Q_ARG(void *, pagesToNotifySet), Q_ARG(void *, pageMatches), Q_ARG(int, currentPage + 1), Q_ARG(int, searchID), Q_ARG(QStringList, words));
}
else
{
// reset cursor to previous shape
QApplication::restoreOverrideCursor();
search->isCurrentlySearching = false;
bool foundAMatch = pageMatches->count() != 0;
QMap< Page *, QVector >::const_iterator it, itEnd;
it = pageMatches->constBegin();
itEnd = pageMatches->constEnd();
for ( ; it != itEnd; ++it)
{
foreach(const MatchColor &mc, it.value())
{
it.key()->d->setHighlight( searchID, mc.first, mc.second );
delete mc.first;
}
search->highlightedPages.insert( it.key()->number() );
pagesToNotify->insert( it.key()->number() );
}
// send page lists to update observers (since some filter on bookmarks)
foreach(DocumentObserver *observer, m_observers)
observer->notifySetup( m_pagesVector, 0 );
// notify observers about highlights changes
foreach(int pageNumber, *pagesToNotify)
foreach(DocumentObserver *observer, m_observers)
observer->notifyPageChanged( pageNumber, DocumentObserver::Highlights );
if (foundAMatch) emit m_parent->searchFinished( searchID, Document::MatchFound );
else emit m_parent->searchFinished( searchID, Document::NoMatchFound );
delete pageMatches;
delete pagesToNotify;
}
}
QVariant DocumentPrivate::documentMetaData( const Generator::DocumentMetaDataKey key, const QVariant &option ) const
{
switch ( key )
{
case Generator::PaperColorMetaData:
{
bool giveDefault = option.toBool();
QColor color;
if ( ( SettingsCore::renderMode() == SettingsCore::EnumRenderMode::Paper )
&& SettingsCore::changeColors() )
{
color = SettingsCore::paperColor();
}
else if ( giveDefault )
{
color = Qt::white;
}
return color;
}
break;
case Generator::TextAntialiasMetaData:
switch ( SettingsCore::textAntialias() )
{
case SettingsCore::EnumTextAntialias::Enabled:
return true;
break;
#if 0
case Settings::EnumTextAntialias::UseKDESettings:
// TODO: read the KDE configuration
return true;
break;
#endif
case SettingsCore::EnumTextAntialias::Disabled:
return false;
break;
}
break;
case Generator::GraphicsAntialiasMetaData:
switch ( SettingsCore::graphicsAntialias() )
{
case SettingsCore::EnumGraphicsAntialias::Enabled:
return true;
break;
case SettingsCore::EnumGraphicsAntialias::Disabled:
return false;
break;
}
break;
case Generator::TextHintingMetaData:
switch ( SettingsCore::textHinting() )
{
case SettingsCore::EnumTextHinting::Enabled:
return true;
break;
case SettingsCore::EnumTextHinting::Disabled:
return false;
break;
}
break;
}
return QVariant();
}
bool DocumentPrivate::isNormalizedRectangleFullyVisible( const Okular::NormalizedRect & rectOfInterest, int rectPage )
{
bool rectFullyVisible = false;
const QVector & visibleRects = m_parent->visiblePageRects();
QVector::const_iterator vEnd = visibleRects.end();
QVector::const_iterator vIt = visibleRects.begin();
for ( ; ( vIt != vEnd ) && !rectFullyVisible; ++vIt )
{
if ( (*vIt)->pageNumber == rectPage &&
(*vIt)->rect.contains( rectOfInterest.left, rectOfInterest.top ) &&
(*vIt)->rect.contains( rectOfInterest.right, rectOfInterest.bottom ) )
{
rectFullyVisible = true;
}
}
return rectFullyVisible;
}
struct pdfsyncpoint
{
QString file;
qlonglong x;
qlonglong y;
int row;
int column;
int page;
};
void DocumentPrivate::loadSyncFile( const QString & filePath )
{
QFile f( filePath + QLatin1String( "sync" ) );
if ( !f.open( QIODevice::ReadOnly ) )
return;
QTextStream ts( &f );
// first row: core name of the pdf output
const QString coreName = ts.readLine();
// second row: version string, in the form 'Version %u'
QString versionstr = ts.readLine();
QRegExp versionre( QStringLiteral("Version (\\d+)") );
versionre.setCaseSensitivity( Qt::CaseInsensitive );
if ( !versionre.exactMatch( versionstr ) )
return;
QHash points;
QStack fileStack;
int currentpage = -1;
const QLatin1String texStr( ".tex" );
const QChar spaceChar = QChar::fromLatin1( ' ' );
fileStack.push( coreName + texStr );
const QSizeF dpi = m_generator->dpi();
QString line;
while ( !ts.atEnd() )
{
line = ts.readLine();
const QStringList tokens = line.split( spaceChar, QString::SkipEmptyParts );
const int tokenSize = tokens.count();
if ( tokenSize < 1 )
continue;
if ( tokens.first() == QLatin1String( "l" ) && tokenSize >= 3 )
{
int id = tokens.at( 1 ).toInt();
QHash::const_iterator it = points.constFind( id );
if ( it == points.constEnd() )
{
pdfsyncpoint pt;
pt.x = 0;
pt.y = 0;
pt.row = tokens.at( 2 ).toInt();
pt.column = 0; // TODO
pt.page = -1;
pt.file = fileStack.top();
points[ id ] = pt;
}
}
else if ( tokens.first() == QLatin1String( "s" ) && tokenSize >= 2 )
{
currentpage = tokens.at( 1 ).toInt() - 1;
}
else if ( tokens.first() == QLatin1String( "p*" ) && tokenSize >= 4 )
{
// TODO
qCDebug(OkularCoreDebug) << "PdfSync: 'p*' line ignored";
}
else if ( tokens.first() == QLatin1String( "p" ) && tokenSize >= 4 )
{
int id = tokens.at( 1 ).toInt();
QHash::iterator it = points.find( id );
if ( it != points.end() )
{
it->x = tokens.at( 2 ).toInt();
it->y = tokens.at( 3 ).toInt();
it->page = currentpage;
}
}
else if ( line.startsWith( QLatin1Char( '(' ) ) && tokenSize == 1 )
{
QString newfile = line;
// chop the leading '('
newfile.remove( 0, 1 );
if ( !newfile.endsWith( texStr ) )
{
newfile += texStr;
}
fileStack.push( newfile );
}
else if ( line == QLatin1String( ")" ) )
{
if ( !fileStack.isEmpty() )
{
fileStack.pop();
}
else
qCDebug(OkularCoreDebug) << "PdfSync: going one level down too much";
}
else
qCDebug(OkularCoreDebug).nospace() << "PdfSync: unknown line format: '" << line << "'";
}
QVector< QLinkedList< Okular::SourceRefObjectRect * > > refRects( m_pagesVector.size() );
foreach ( const pdfsyncpoint& pt, points )
{
// drop pdfsync points not completely valid
if ( pt.page < 0 || pt.page >= m_pagesVector.size() )
continue;
// magic numbers for TeX's RSU's (Ridiculously Small Units) conversion to pixels
Okular::NormalizedPoint p(
( pt.x * dpi.width() ) / ( 72.27 * 65536.0 * m_pagesVector[pt.page]->width() ),
( pt.y * dpi.height() ) / ( 72.27 * 65536.0 * m_pagesVector[pt.page]->height() )
);
QString file = pt.file;
Okular::SourceReference * sourceRef = new Okular::SourceReference( file, pt.row, pt.column );
refRects[ pt.page ].append( new Okular::SourceRefObjectRect( p, sourceRef ) );
}
for ( int i = 0; i < refRects.size(); ++i )
if ( !refRects.at(i).isEmpty() )
m_pagesVector[i]->setSourceReferences( refRects.at(i) );
}
Document::Document( QWidget *widget )
: QObject( nullptr ), d( new DocumentPrivate( this ) )
{
d->m_widget = widget;
d->m_bookmarkManager = new BookmarkManager( d );
d->m_viewportIterator = d->m_viewportHistory.insert( d->m_viewportHistory.end(), DocumentViewport() );
d->m_undoStack = new QUndoStack(this);
connect( SettingsCore::self(), SIGNAL(configChanged()), this, SLOT(_o_configChanged()) );
connect(d->m_undoStack, &QUndoStack::canUndoChanged, this, &Document::canUndoChanged);
connect(d->m_undoStack, &QUndoStack::canRedoChanged, this, &Document::canRedoChanged);
+ connect(d->m_undoStack, &QUndoStack::cleanChanged, this, &Document::undoHistoryCleanChanged);
qRegisterMetaType();
}
Document::~Document()
{
// delete generator, pages, and related stuff
closeDocument();
QSet< View * >::const_iterator viewIt = d->m_views.constBegin(), viewEnd = d->m_views.constEnd();
for ( ; viewIt != viewEnd; ++viewIt )
{
View *v = *viewIt;
v->d_func()->document = nullptr;
}
// delete the bookmark manager
delete d->m_bookmarkManager;
// delete the loaded generators
QHash< QString, GeneratorInfo >::const_iterator it = d->m_loadedGenerators.constBegin(), itEnd = d->m_loadedGenerators.constEnd();
for ( ; it != itEnd; ++it )
d->unloadGenerator( it.value() );
d->m_loadedGenerators.clear();
// delete the private structure
delete d;
}
QString DocumentPrivate::docDataFileName(const QUrl &url, qint64 document_size)
{
QString fn = url.fileName();
fn = QString::number( document_size ) + QLatin1Char('.') + fn + QStringLiteral(".xml");
QString docdataDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation)
+ QStringLiteral("/okular/docdata");
// make sure that the okular/docdata/ directory exists (probably this used to be handled by KStandardDirs)
if (!QFileInfo::exists(docdataDir))
{
qCDebug(OkularCoreDebug) << "creating docdata folder" << docdataDir;
QDir().mkpath(docdataDir);
}
QString newokularfile = docdataDir + QLatin1Char('/') + fn;
// we don't want to accidentally migrate old files when running unit tests
if (!QFile::exists( newokularfile ) && !QStandardPaths::isTestModeEnabled())
{
// see if an KDE4 file still exists
static Kdelibs4Migration k4migration;
QString oldfile = k4migration.locateLocal("data", QStringLiteral("okular/docdata/") + fn);
if (oldfile.isEmpty())
{
oldfile = k4migration.locateLocal("data", QStringLiteral("kpdf/") + fn);
}
if ( !oldfile.isEmpty() && QFile::exists( oldfile ) )
{
// ### copy or move?
if ( !QFile::copy( oldfile, newokularfile ) )
return QString();
}
}
return newokularfile;
}
QVector DocumentPrivate::availableGenerators()
{
static QVector result;
if (result.isEmpty())
{
result = KPluginLoader::findPlugins( QLatin1String ( "okular/generators" ) );
}
return result;
}
KPluginMetaData DocumentPrivate::generatorForMimeType(const QMimeType& type, QWidget* widget, const QVector &triedOffers)
{
// First try to find an exact match, and then look for more general ones (e. g. the plain text one)
// Ideally we would rank these by "closeness", but that might be overdoing it
const QVector available = availableGenerators();
QVector offers;
QVector exactMatches;
QMimeDatabase mimeDatabase;
for (const KPluginMetaData& md : available)
{
if (triedOffers.contains(md))
continue;
foreach (const QString& supported, md.mimeTypes())
{
QMimeType mimeType = mimeDatabase.mimeTypeForName(supported);
if (mimeType == type && !exactMatches.contains(md)) {
exactMatches << md;
}
if (type.inherits(supported) && !offers.contains(md))
{
offers << md;
}
}
}
if (!exactMatches.isEmpty()) {
offers = exactMatches;
}
if (offers.isEmpty())
{
return KPluginMetaData();
}
int hRank=0;
// best ranked offer search
int offercount = offers.size();
if (offercount > 1)
{
// sort the offers: the offers with an higher priority come before
auto cmp = [](const KPluginMetaData& s1, const KPluginMetaData& s2)
{
const QString property = QStringLiteral("X-KDE-Priority");
return s1.rawData()[property].toInt() > s2.rawData()[property].toInt();
};
std::stable_sort(offers.begin(), offers.end(), cmp);
if (SettingsCore::chooseGenerators())
{
QStringList list;
for (int i = 0; i < offercount; ++i)
{
list << offers.at(i).pluginId();
}
ChooseEngineDialog choose(list, type, widget);
if (choose.exec() == QDialog::Rejected)
return KPluginMetaData();
hRank = choose.selectedGenerator();
}
}
Q_ASSERT(hRank < offers.size());
return offers.at(hRank);
}
Document::OpenResult Document::openDocument(const QString & docFile, const QUrl &url, const QMimeType &_mime, const QString & password )
{
QMimeDatabase db;
QMimeType mime = _mime;
QByteArray filedata;
- qint64 document_size = -1;
bool isstdin = url.fileName() == QLatin1String( "-" );
bool triedMimeFromFileContent = false;
if ( !isstdin )
{
if ( !mime.isValid() )
return OpenError;
- // docFile is always local so we can use QFileInfo on it
- QFileInfo fileReadTest( docFile );
- if ( fileReadTest.isFile() && !fileReadTest.isReadable() )
- {
- d->m_docFileName.clear();
- return OpenError;
- }
- // determine the related "xml document-info" filename
d->m_url = url;
d->m_docFileName = docFile;
- if ( url.isLocalFile() && !d->m_archiveData )
- {
- document_size = fileReadTest.size();
- d->m_xmlFileName = DocumentPrivate::docDataFileName(url, document_size);
- }
+
+ if ( !d->updateMetadataXmlNameAndDocSize() )
+ return OpenError;
}
else
{
QFile qstdin;
qstdin.open( stdin, QIODevice::ReadOnly );
filedata = qstdin.readAll();
mime = db.mimeTypeForData( filedata );
if ( !mime.isValid() || mime.isDefault() )
return OpenError;
- document_size = filedata.size();
+ d->m_docSize = filedata.size();
triedMimeFromFileContent = true;
}
// 0. load Generator
// request only valid non-disabled plugins suitable for the mimetype
KPluginMetaData offer = DocumentPrivate::generatorForMimeType(mime, d->m_widget);
if ( !offer.isValid() && !triedMimeFromFileContent )
{
QMimeType newmime = db.mimeTypeForFile(docFile, QMimeDatabase::MatchExtension);
triedMimeFromFileContent = true;
if ( newmime != mime )
{
mime = newmime;
offer = DocumentPrivate::generatorForMimeType(mime, d->m_widget);
}
if ( !offer.isValid() )
{
// There's still no offers, do a final mime search based on the filename
// We need this because sometimes (e.g. when downloading from a webserver) the mimetype we
// use is the one fed by the server, that may be wrong
newmime = db.mimeTypeForUrl( url );
if ( !newmime.isDefault() && newmime != mime )
{
mime = newmime;
offer = DocumentPrivate::generatorForMimeType(mime, d->m_widget);
}
}
}
if (!offer.isValid())
{
emit error( i18n( "Can not find a plugin which is able to handle the document being passed." ), -1 );
qCWarning(OkularCoreDebug).nospace() << "No plugin for mimetype '" << mime.name() << "'.";
return OpenError;
}
// 1. load Document
OpenResult openResult = d->openDocumentInternal( offer, isstdin, docFile, filedata, password );
if ( openResult == OpenError )
{
QVector triedOffers;
triedOffers << offer;
offer = DocumentPrivate::generatorForMimeType(mime, d->m_widget, triedOffers);
while ( offer.isValid() )
{
openResult = d->openDocumentInternal( offer, isstdin, docFile, filedata, password );
if ( openResult == OpenError )
{
triedOffers << offer;
offer = DocumentPrivate::generatorForMimeType(mime, d->m_widget, triedOffers);
}
else break;
}
if (openResult == OpenError && !triedMimeFromFileContent )
{
QMimeType newmime = db.mimeTypeForFile(docFile, QMimeDatabase::MatchExtension);
triedMimeFromFileContent = true;
if ( newmime != mime )
{
mime = newmime;
offer = DocumentPrivate::generatorForMimeType(mime, d->m_widget, triedOffers);
while ( offer.isValid() )
{
openResult = d->openDocumentInternal( offer, isstdin, docFile, filedata, password );
if ( openResult == OpenError )
{
triedOffers << offer;
offer = DocumentPrivate::generatorForMimeType(mime, d->m_widget, triedOffers);
}
else break;
}
}
}
if ( openResult == OpenSuccess )
{
// Clear errors, since we're trying various generators, maybe one of them errored out
// but we finally succeeded
// TODO one can still see the error message animating out but since this is a very rare
// condition we can leave this for future work
emit error( QString(), -1 );
}
}
if ( openResult != OpenSuccess )
{
return openResult;
}
// no need to check for the existence of a synctex file, no parser will be
// created if none exists
d->m_synctex_scanner = synctex_scanner_new_with_output_file( QFile::encodeName( docFile ).constData(), nullptr, 1);
if ( !d->m_synctex_scanner && QFile::exists(docFile + QLatin1String( "sync" ) ) )
{
d->loadSyncFile(docFile);
}
d->m_generatorName = offer.pluginId();
d->m_pageController = new PageController();
connect( d->m_pageController, SIGNAL(rotationFinished(int,Okular::Page*)),
this, SLOT(rotationFinished(int,Okular::Page*)) );
- bool containsExternalAnnotations = false;
foreach ( Page * p, d->m_pagesVector )
- {
p->d->m_doc = d;
- if ( !p->annotations().empty() )
- containsExternalAnnotations = true;
- }
- // Be quiet while restoring local annotations
- d->m_showWarningLimitedAnnotSupport = false;
- d->m_annotationsNeedSaveAs = false;
+ d->m_metadataLoadingCompleted = false;
+ d->m_docdataMigrationNeeded = false;
// 2. load Additional Data (bookmarks, local annotations and metadata) about the document
if ( d->m_archiveData )
{
- d->loadDocumentInfo( d->m_archiveData->metadataFile );
- d->m_annotationsNeedSaveAs = true;
+ d->loadDocumentInfo( d->m_archiveData->metadataFile, LoadPageInfo );
+ d->loadDocumentInfo( LoadGeneralInfo );
}
else
{
- d->loadDocumentInfo();
- d->m_annotationsNeedSaveAs = ( d->canAddAnnotationsNatively() && containsExternalAnnotations );
+ if ( d->loadDocumentInfo( LoadPageInfo ) )
+ d->m_docdataMigrationNeeded = true;
+ d->loadDocumentInfo( LoadGeneralInfo );
}
- d->m_showWarningLimitedAnnotSupport = true;
+ d->m_metadataLoadingCompleted = true;
d->m_bookmarkManager->setUrl( d->m_url );
// 3. setup observers inernal lists and data
- foreachObserver( notifySetup( d->m_pagesVector, DocumentObserver::DocumentChanged ) );
+ foreachObserver( notifySetup( d->m_pagesVector, DocumentObserver::DocumentChanged | DocumentObserver::UrlChanged ) );
// 4. set initial page (restoring the page saved in xml if loaded)
DocumentViewport loadedViewport = (*d->m_viewportIterator);
if ( loadedViewport.isValid() )
{
(*d->m_viewportIterator) = DocumentViewport();
if ( loadedViewport.pageNumber >= (int)d->m_pagesVector.size() )
loadedViewport.pageNumber = d->m_pagesVector.size() - 1;
}
else
loadedViewport.pageNumber = 0;
setViewport( loadedViewport );
// start bookmark saver timer
if ( !d->m_saveBookmarksTimer )
{
d->m_saveBookmarksTimer = new QTimer( this );
connect( d->m_saveBookmarksTimer, SIGNAL(timeout()), this, SLOT(saveDocumentInfo()) );
}
d->m_saveBookmarksTimer->start( 5 * 60 * 1000 );
// start memory check timer
if ( !d->m_memCheckTimer )
{
d->m_memCheckTimer = new QTimer( this );
connect( d->m_memCheckTimer, SIGNAL(timeout()), this, SLOT(slotTimedMemoryCheck()) );
}
d->m_memCheckTimer->start( 2000 );
const DocumentViewport nextViewport = d->nextDocumentViewport();
if ( nextViewport.isValid() )
{
setViewport( nextViewport );
d->m_nextDocumentViewport = DocumentViewport();
d->m_nextDocumentDestination = QString();
}
AudioPlayer::instance()->d->m_currentDocument = isstdin ? QUrl() : d->m_url;
- d->m_docSize = document_size;
const QStringList docScripts = d->m_generator->metaData( QStringLiteral("DocumentScripts"), QStringLiteral ( "JavaScript" ) ).toStringList();
if ( !docScripts.isEmpty() )
{
d->m_scripter = new Scripter( d );
Q_FOREACH ( const QString &docscript, docScripts )
{
d->m_scripter->execute( JavaScript, docscript );
}
}
return OpenSuccess;
}
+bool DocumentPrivate::updateMetadataXmlNameAndDocSize()
+{
+ // m_docFileName is always local so we can use QFileInfo on it
+ QFileInfo fileReadTest( m_docFileName );
+ if ( !fileReadTest.isFile() && !fileReadTest.isReadable() )
+ return false;
+
+ m_docSize = fileReadTest.size();
+
+ // determine the related "xml document-info" filename
+ if ( m_url.isLocalFile() )
+ {
+ const QString filePath = docDataFileName( m_url, m_docSize );
+ qCDebug(OkularCoreDebug) << "Metadata file is now:" << filePath;
+ m_xmlFileName = filePath;
+ }
+ else
+ {
+ qCDebug(OkularCoreDebug) << "Metadata file: disabled";
+ m_xmlFileName = QString();
+ }
+
+ return true;
+}
+
KXMLGUIClient* Document::guiClient()
{
if ( d->m_generator )
{
Okular::GuiInterface * iface = qobject_cast< Okular::GuiInterface * >( d->m_generator );
if ( iface )
return iface->guiClient();
}
return nullptr;
}
void Document::closeDocument()
{
// check if there's anything to close...
if ( !d->m_generator )
return;
delete d->m_pageController;
d->m_pageController = nullptr;
delete d->m_scripter;
d->m_scripter = nullptr;
// remove requests left in queue
d->m_pixmapRequestsMutex.lock();
QLinkedList< PixmapRequest * >::const_iterator sIt = d->m_pixmapRequestsStack.constBegin();
QLinkedList< PixmapRequest * >::const_iterator sEnd = d->m_pixmapRequestsStack.constEnd();
for ( ; sIt != sEnd; ++sIt )
delete *sIt;
d->m_pixmapRequestsStack.clear();
d->m_pixmapRequestsMutex.unlock();
QEventLoop loop;
bool startEventLoop = false;
do
{
d->m_pixmapRequestsMutex.lock();
startEventLoop = !d->m_executingPixmapRequests.isEmpty();
d->m_pixmapRequestsMutex.unlock();
if ( startEventLoop )
{
d->m_closingLoop = &loop;
loop.exec();
d->m_closingLoop = nullptr;
}
}
while ( startEventLoop );
if ( d->m_fontThread )
{
disconnect( d->m_fontThread, nullptr, this, nullptr );
d->m_fontThread->stopExtraction();
d->m_fontThread->wait();
d->m_fontThread = nullptr;
}
// stop any audio playback
AudioPlayer::instance()->stopPlaybacks();
// close the current document and save document info if a document is still opened
if ( d->m_generator && d->m_pagesVector.size() > 0 )
{
d->saveDocumentInfo();
d->m_generator->closeDocument();
}
if ( d->m_synctex_scanner )
{
synctex_scanner_free( d->m_synctex_scanner );
d->m_synctex_scanner = nullptr;
}
// stop timers
if ( d->m_memCheckTimer )
d->m_memCheckTimer->stop();
if ( d->m_saveBookmarksTimer )
d->m_saveBookmarksTimer->stop();
if ( d->m_generator )
{
// disconnect the generator from this document ...
d->m_generator->d_func()->m_document = nullptr;
// .. and this document from the generator signals
disconnect( d->m_generator, nullptr, this, nullptr );
QHash< QString, GeneratorInfo >::const_iterator genIt = d->m_loadedGenerators.constFind( d->m_generatorName );
Q_ASSERT( genIt != d->m_loadedGenerators.constEnd() );
}
d->m_generator = nullptr;
d->m_generatorName = QString();
d->m_url = QUrl();
d->m_walletGenerator = nullptr;
d->m_docFileName = QString();
d->m_xmlFileName = QString();
delete d->m_tempFile;
d->m_tempFile = nullptr;
delete d->m_archiveData;
d->m_archiveData = nullptr;
d->m_docSize = -1;
d->m_exportCached = false;
d->m_exportFormats.clear();
d->m_exportToText = ExportFormat();
d->m_fontsCached = false;
d->m_fontsCache.clear();
d->m_rotation = Rotation0;
// send an empty list to observers (to free their data)
- foreachObserver( notifySetup( QVector< Page * >(), DocumentObserver::DocumentChanged ) );
+ foreachObserver( notifySetup( QVector< Page * >(), DocumentObserver::DocumentChanged | DocumentObserver::UrlChanged ) );
// delete pages and clear 'd->m_pagesVector' container
QVector< Page * >::const_iterator pIt = d->m_pagesVector.constBegin();
QVector< Page * >::const_iterator pEnd = d->m_pagesVector.constEnd();
for ( ; pIt != pEnd; ++pIt )
delete *pIt;
d->m_pagesVector.clear();
// clear 'memory allocation' descriptors
qDeleteAll( d->m_allocatedPixmaps );
d->m_allocatedPixmaps.clear();
// clear 'running searches' descriptors
QMap< int, RunningSearch * >::const_iterator rIt = d->m_searches.constBegin();
QMap< int, RunningSearch * >::const_iterator rEnd = d->m_searches.constEnd();
for ( ; rIt != rEnd; ++rIt )
delete *rIt;
d->m_searches.clear();
// clear the visible areas and notify the observers
QVector< VisiblePageRect * >::const_iterator vIt = d->m_pageRects.constBegin();
QVector< VisiblePageRect * >::const_iterator vEnd = d->m_pageRects.constEnd();
for ( ; vIt != vEnd; ++vIt )
delete *vIt;
d->m_pageRects.clear();
foreachObserver( notifyVisibleRectsChanged() );
// reset internal variables
d->m_viewportHistory.clear();
d->m_viewportHistory.append( DocumentViewport() );
d->m_viewportIterator = d->m_viewportHistory.begin();
d->m_allocatedPixmapsTotalMemory = 0;
d->m_allocatedTextPagesFifo.clear();
d->m_pageSize = PageSize();
d->m_pageSizes.clear();
d->m_documentInfo = DocumentInfo();
d->m_documentInfoAskedKeys.clear();
AudioPlayer::instance()->d->m_currentDocument = QUrl();
d->m_undoStack->clear();
+ d->m_docdataMigrationNeeded = false;
}
void Document::addObserver( DocumentObserver * pObserver )
{
Q_ASSERT( !d->m_observers.contains( pObserver ) );
d->m_observers << pObserver;
// if the observer is added while a document is already opened, tell it
if ( !d->m_pagesVector.isEmpty() )
{
- pObserver->notifySetup( d->m_pagesVector, DocumentObserver::DocumentChanged );
+ pObserver->notifySetup( d->m_pagesVector, DocumentObserver::DocumentChanged | DocumentObserver::UrlChanged );
pObserver->notifyViewportChanged( false /*disables smoothMove*/ );
}
}
void Document::removeObserver( DocumentObserver * pObserver )
{
// remove observer from the map. it won't receive notifications anymore
if ( d->m_observers.contains( pObserver ) )
{
// free observer's pixmap data
QVector::const_iterator it = d->m_pagesVector.constBegin(), end = d->m_pagesVector.constEnd();
for ( ; it != end; ++it )
(*it)->deletePixmap( pObserver );
// [MEM] free observer's allocation descriptors
QLinkedList< AllocatedPixmap * >::iterator aIt = d->m_allocatedPixmaps.begin();
QLinkedList< AllocatedPixmap * >::iterator aEnd = d->m_allocatedPixmaps.end();
while ( aIt != aEnd )
{
AllocatedPixmap * p = *aIt;
if ( p->observer == pObserver )
{
aIt = d->m_allocatedPixmaps.erase( aIt );
delete p;
}
else
++aIt;
}
// delete observer entry from the map
d->m_observers.remove( pObserver );
}
}
void Document::reparseConfig()
{
// reparse generator config and if something changed clear Pages
bool configchanged = false;
if ( d->m_generator )
{
Okular::ConfigInterface * iface = qobject_cast< Okular::ConfigInterface * >( d->m_generator );
if ( iface )
configchanged = iface->reparseConfig();
}
if ( configchanged )
{
// invalidate pixmaps
QVector::const_iterator it = d->m_pagesVector.constBegin(), end = d->m_pagesVector.constEnd();
for ( ; it != end; ++it ) {
(*it)->deletePixmaps();
}
// [MEM] remove allocation descriptors
qDeleteAll( d->m_allocatedPixmaps );
d->m_allocatedPixmaps.clear();
d->m_allocatedPixmapsTotalMemory = 0;
// send reload signals to observers
foreachObserver( notifyContentsCleared( DocumentObserver::Pixmap ) );
}
// free memory if in 'low' profile
if ( SettingsCore::memoryLevel() == SettingsCore::EnumMemoryLevel::Low &&
!d->m_allocatedPixmaps.isEmpty() && !d->m_pagesVector.isEmpty() )
d->cleanupPixmapMemory();
}
bool Document::isOpened() const
{
return d->m_generator;
}
bool Document::canConfigurePrinter( ) const
{
if ( d->m_generator )
{
Okular::PrintInterface * iface = qobject_cast< Okular::PrintInterface * >( d->m_generator );
return iface ? true : false;
}
else
return 0;
}
DocumentInfo Document::documentInfo() const
{
QSet keys;
for (Okular::DocumentInfo::Key ks = Okular::DocumentInfo::Title;
ks < Okular::DocumentInfo::Invalid;
ks = Okular::DocumentInfo::Key( ks+1 ) )
{
keys << ks;
}
return documentInfo( keys );
}
DocumentInfo Document::documentInfo( const QSet &keys ) const
{
DocumentInfo result = d->m_documentInfo;
const QSet missingKeys = keys - d->m_documentInfoAskedKeys;
if ( d->m_generator && !missingKeys.isEmpty() )
{
DocumentInfo info = d->m_generator->generateDocumentInfo( missingKeys );
if ( missingKeys.contains( DocumentInfo::FilePath ) )
{
info.set( DocumentInfo::FilePath, currentDocument().toDisplayString() );
}
if ( d->m_docSize != -1 && missingKeys.contains( DocumentInfo::DocumentSize ) )
{
const QString sizeString = KFormat().formatByteSize( d->m_docSize );
info.set( DocumentInfo::DocumentSize, sizeString );
}
if ( missingKeys.contains( DocumentInfo::PagesSize ) )
{
const QString pagesSize = d->pagesSizeString();
if ( !pagesSize.isEmpty() )
{
info.set( DocumentInfo::PagesSize, pagesSize );
}
}
if ( missingKeys.contains( DocumentInfo::Pages ) && info.get( DocumentInfo::Pages ).isEmpty() ) {
info.set( DocumentInfo::Pages, QString::number( this->pages() ) );
}
d->m_documentInfo.d->values.unite(info.d->values);
d->m_documentInfo.d->titles.unite(info.d->titles);
result.d->values.unite(info.d->values);
result.d->titles.unite(info.d->titles);
}
d->m_documentInfoAskedKeys += keys;
return result;
}
const DocumentSynopsis * Document::documentSynopsis() const
{
return d->m_generator ? d->m_generator->generateDocumentSynopsis() : nullptr;
}
void Document::startFontReading()
{
if ( !d->m_generator || !d->m_generator->hasFeature( Generator::FontInfo ) || d->m_fontThread )
return;
if ( d->m_fontsCached )
{
// in case we have cached fonts, simulate a reading
// this way the API is the same, and users no need to care about the
// internal caching
for ( int i = 0; i < d->m_fontsCache.count(); ++i )
{
emit gotFont( d->m_fontsCache.at( i ) );
emit fontReadingProgress( i / pages() );
}
emit fontReadingEnded();
return;
}
d->m_fontThread = new FontExtractionThread( d->m_generator, pages() );
connect( d->m_fontThread, SIGNAL(gotFont(Okular::FontInfo)), this, SLOT(fontReadingGotFont(Okular::FontInfo)) );
connect( d->m_fontThread.data(), SIGNAL(progress(int)), this, SLOT(slotFontReadingProgress(int)) );
d->m_fontThread->startExtraction( /*d->m_generator->hasFeature( Generator::Threaded )*/true );
}
void Document::stopFontReading()
{
if ( !d->m_fontThread )
return;
disconnect( d->m_fontThread, nullptr, this, nullptr );
d->m_fontThread->stopExtraction();
d->m_fontThread = nullptr;
d->m_fontsCache.clear();
}
bool Document::canProvideFontInformation() const
{
return d->m_generator ? d->m_generator->hasFeature( Generator::FontInfo ) : false;
}
const QList *Document::embeddedFiles() const
{
return d->m_generator ? d->m_generator->embeddedFiles() : nullptr;
}
const Page * Document::page( int n ) const
{
return ( n < d->m_pagesVector.count() ) ? d->m_pagesVector.at(n) : 0;
}
const DocumentViewport & Document::viewport() const
{
return (*d->m_viewportIterator);
}
const QVector< VisiblePageRect * > & Document::visiblePageRects() const
{
return d->m_pageRects;
}
void Document::setVisiblePageRects( const QVector< VisiblePageRect * > & visiblePageRects, DocumentObserver *excludeObserver )
{
QVector< VisiblePageRect * >::const_iterator vIt = d->m_pageRects.constBegin();
QVector< VisiblePageRect * >::const_iterator vEnd = d->m_pageRects.constEnd();
for ( ; vIt != vEnd; ++vIt )
delete *vIt;
d->m_pageRects = visiblePageRects;
// notify change to all other (different from id) observers
foreach(DocumentObserver *o, d->m_observers)
if ( o != excludeObserver )
o->notifyVisibleRectsChanged();
}
uint Document::currentPage() const
{
return (*d->m_viewportIterator).pageNumber;
}
uint Document::pages() const
{
return d->m_pagesVector.size();
}
QUrl Document::currentDocument() const
{
return d->m_url;
}
bool Document::isAllowed( Permission action ) const
{
- if ( action == Okular::AllowNotes && !d->m_annotationEditingEnabled )
+ if ( action == Okular::AllowNotes && ( d->m_docdataMigrationNeeded || !d->m_annotationEditingEnabled ) )
+ return false;
+ if ( action == Okular::AllowFillForms && d->m_docdataMigrationNeeded )
return false;
#if !OKULAR_FORCE_DRM
if ( KAuthorized::authorize( QStringLiteral("skip_drm") ) && !SettingsCore::obeyDRM() )
return true;
#endif
return d->m_generator ? d->m_generator->isAllowed( action ) : false;
}
bool Document::supportsSearching() const
{
return d->m_generator ? d->m_generator->hasFeature( Generator::TextExtraction ) : false;
}
bool Document::supportsPageSizes() const
{
return d->m_generator ? d->m_generator->hasFeature( Generator::PageSizes ) : false;
}
bool Document::supportsTiles() const
{
return d->m_generator ? d->m_generator->hasFeature( Generator::TiledRendering ) : false;
}
PageSize::List Document::pageSizes() const
{
if ( d->m_generator )
{
if ( d->m_pageSizes.isEmpty() )
d->m_pageSizes = d->m_generator->pageSizes();
return d->m_pageSizes;
}
return PageSize::List();
}
bool Document::canExportToText() const
{
if ( !d->m_generator )
return false;
d->cacheExportFormats();
return !d->m_exportToText.isNull();
}
bool Document::exportToText( const QString& fileName ) const
{
if ( !d->m_generator )
return false;
d->cacheExportFormats();
if ( d->m_exportToText.isNull() )
return false;
return d->m_generator->exportTo( fileName, d->m_exportToText );
}
ExportFormat::List Document::exportFormats() const
{
if ( !d->m_generator )
return ExportFormat::List();
d->cacheExportFormats();
return d->m_exportFormats;
}
bool Document::exportTo( const QString& fileName, const ExportFormat& format ) const
{
return d->m_generator ? d->m_generator->exportTo( fileName, format ) : false;
}
bool Document::historyAtBegin() const
{
return d->m_viewportIterator == d->m_viewportHistory.begin();
}
bool Document::historyAtEnd() const
{
return d->m_viewportIterator == --(d->m_viewportHistory.end());
}
QVariant Document::metaData( const QString & key, const QVariant & option ) const
{
// if option starts with "src:" assume that we are handling a
// source reference
if ( key == QLatin1String("NamedViewport")
&& option.toString().startsWith( QLatin1String("src:"), Qt::CaseInsensitive )
&& d->m_synctex_scanner)
{
const QString reference = option.toString();
// The reference is of form "src:1111Filename", where "1111"
// points to line number 1111 in the file "Filename".
// Extract the file name and the numeral part from the reference string.
// This will fail if Filename starts with a digit.
QString name, lineString;
// Remove "src:". Presence of substring has been checked before this
// function is called.
name = reference.mid( 4 );
// split
int nameLength = name.length();
int i = 0;
for( i = 0; i < nameLength; ++i )
{
if ( !name[i].isDigit() ) break;
}
lineString = name.left( i );
name = name.mid( i );
// Remove spaces.
name = name.trimmed();
lineString = lineString.trimmed();
// Convert line to integer.
bool ok;
int line = lineString.toInt( &ok );
if (!ok) line = -1;
// Use column == -1 for now.
if( synctex_display_query( d->m_synctex_scanner, QFile::encodeName(name).constData(), line, -1, 0 ) > 0 )
{
synctex_node_p node;
// For now use the first hit. Could possibly be made smarter
// in case there are multiple hits.
while( ( node = synctex_scanner_next_result( d->m_synctex_scanner ) ) )
{
Okular::DocumentViewport viewport;
// TeX pages start at 1.
viewport.pageNumber = synctex_node_page( node ) - 1;
if ( viewport.pageNumber >= 0 )
{
const QSizeF dpi = d->m_generator->dpi();
// TeX small points ...
double px = (synctex_node_visible_h( node ) * dpi.width()) / 72.27;
double py = (synctex_node_visible_v( node ) * dpi.height()) / 72.27;
viewport.rePos.normalizedX = px / page(viewport.pageNumber)->width();
viewport.rePos.normalizedY = ( py + 0.5 ) / page(viewport.pageNumber)->height();
viewport.rePos.enabled = true;
viewport.rePos.pos = Okular::DocumentViewport::Center;
return viewport.toString();
}
}
}
}
return d->m_generator ? d->m_generator->metaData( key, option ) : QVariant();
}
Rotation Document::rotation() const
{
return d->m_rotation;
}
QSizeF Document::allPagesSize() const
{
bool allPagesSameSize = true;
QSizeF size;
for (int i = 0; allPagesSameSize && i < d->m_pagesVector.count(); ++i)
{
const Page *p = d->m_pagesVector.at(i);
if (i == 0) size = QSizeF(p->width(), p->height());
else
{
allPagesSameSize = (size == QSizeF(p->width(), p->height()));
}
}
if (allPagesSameSize) return size;
else return QSizeF();
}
QString Document::pageSizeString(int page) const
{
if (d->m_generator)
{
if (d->m_generator->pagesSizeMetric() != Generator::None)
{
const Page *p = d->m_pagesVector.at( page );
return d->localizedSize(QSizeF(p->width(), p->height()));
}
}
return QString();
}
void Document::requestPixmaps( const QLinkedList< PixmapRequest * > & requests )
{
requestPixmaps( requests, RemoveAllPrevious );
}
void Document::requestPixmaps( const QLinkedList< PixmapRequest * > & requests, PixmapRequestFlags reqOptions )
{
if ( requests.isEmpty() )
return;
if ( !d->m_pageController )
{
// delete requests..
QLinkedList< PixmapRequest * >::const_iterator rIt = requests.constBegin(), rEnd = requests.constEnd();
for ( ; rIt != rEnd; ++rIt )
delete *rIt;
// ..and return
return;
}
// 1. [CLEAN STACK] remove previous requests of requesterID
// FIXME This assumes all requests come from the same observer, that is true atm but not enforced anywhere
DocumentObserver *requesterObserver = requests.first()->observer();
QSet< int > requestedPages;
{
QLinkedList< PixmapRequest * >::const_iterator rIt = requests.constBegin(), rEnd = requests.constEnd();
for ( ; rIt != rEnd; ++rIt )
requestedPages.insert( (*rIt)->pageNumber() );
}
const bool removeAllPrevious = reqOptions & RemoveAllPrevious;
d->m_pixmapRequestsMutex.lock();
QLinkedList< PixmapRequest * >::iterator sIt = d->m_pixmapRequestsStack.begin(), sEnd = d->m_pixmapRequestsStack.end();
while ( sIt != sEnd )
{
if ( (*sIt)->observer() == requesterObserver
&& ( removeAllPrevious || requestedPages.contains( (*sIt)->pageNumber() ) ) )
{
// delete request and remove it from stack
delete *sIt;
sIt = d->m_pixmapRequestsStack.erase( sIt );
}
else
++sIt;
}
// 2. [ADD TO STACK] add requests to stack
QLinkedList< PixmapRequest * >::const_iterator rIt = requests.constBegin(), rEnd = requests.constEnd();
for ( ; rIt != rEnd; ++rIt )
{
// set the 'page field' (see PixmapRequest) and check if it is valid
PixmapRequest * request = *rIt;
qCDebug(OkularCoreDebug).nospace() << "request observer=" << request->observer() << " " <width() << "x" << request->height() << "@" << request->pageNumber();
if ( d->m_pagesVector.value( request->pageNumber() ) == 0 )
{
// skip requests referencing an invalid page (must not happen)
delete request;
continue;
}
request->d->mPage = d->m_pagesVector.value( request->pageNumber() );
if ( request->isTile() )
{
// Change the current request rect so that only invalid tiles are
// requested. Also make sure the rect is tile-aligned.
NormalizedRect tilesRect;
const QList tiles = request->d->tilesManager()->tilesAt( request->normalizedRect(), TilesManager::TerminalTile );
QList::const_iterator tIt = tiles.constBegin(), tEnd = tiles.constEnd();
while ( tIt != tEnd )
{
const Tile &tile = *tIt;
if ( !tile.isValid() )
{
if ( tilesRect.isNull() )
tilesRect = tile.rect();
else
tilesRect |= tile.rect();
}
tIt++;
}
request->setNormalizedRect( tilesRect );
}
if ( !request->asynchronous() )
request->d->mPriority = 0;
// add request to the 'stack' at the right place
if ( !request->priority() )
// add priority zero requests to the top of the stack
d->m_pixmapRequestsStack.append( request );
else
{
// insert in stack sorted by priority
sIt = d->m_pixmapRequestsStack.begin();
sEnd = d->m_pixmapRequestsStack.end();
while ( sIt != sEnd && (*sIt)->priority() > request->priority() )
++sIt;
d->m_pixmapRequestsStack.insert( sIt, request );
}
}
d->m_pixmapRequestsMutex.unlock();
// 3. [START FIRST GENERATION] if generator is ready, start a new generation,
// or else (if gen is running) it will be started when the new contents will
//come from generator (in requestDone())
// all handling of requests put into sendGeneratorPixmapRequest
// if ( generator->canRequestPixmap() )
d->sendGeneratorPixmapRequest();
}
void Document::requestTextPage( uint page )
{
Page * kp = d->m_pagesVector[ page ];
if ( !d->m_generator || !kp )
return;
// Memory management for TextPages
d->m_generator->generateTextPage( kp );
}
void DocumentPrivate::notifyAnnotationChanges( int page )
{
- int flags = DocumentObserver::Annotations;
-
- if ( m_annotationsNeedSaveAs )
- flags |= DocumentObserver::NeedSaveAs;
+ foreachObserverD( notifyPageChanged( page, DocumentObserver::Annotations ) );
+}
- foreachObserverD( notifyPageChanged( page, flags ) );
+void DocumentPrivate::notifyFormChanges( int /*page*/ )
+{
}
void Document::addPageAnnotation( int page, Annotation * annotation )
{
// Transform annotation's base boundary rectangle into unrotated coordinates
Page *p = d->m_pagesVector[page];
QTransform t = p->d->rotationMatrix();
annotation->d_ptr->baseTransform(t.inverted());
QUndoCommand *uc = new AddAnnotationCommand(this->d, annotation, page);
d->m_undoStack->push(uc);
}
bool Document::canModifyPageAnnotation( const Annotation * annotation ) const
{
if ( !annotation || ( annotation->flags() & Annotation::DenyWrite ) )
return false;
if ( !isAllowed(Okular::AllowNotes) )
return false;
if ( ( annotation->flags() & Annotation::External ) && !d->canModifyExternalAnnotations() )
return false;
switch ( annotation->subType() )
{
case Annotation::AText:
case Annotation::ALine:
case Annotation::AGeom:
case Annotation::AHighlight:
case Annotation::AStamp:
case Annotation::AInk:
return true;
default:
return false;
}
}
void Document::prepareToModifyAnnotationProperties( Annotation * annotation )
{
Q_ASSERT(d->m_prevPropsOfAnnotBeingModified.isNull());
if (!d->m_prevPropsOfAnnotBeingModified.isNull())
{
qCCritical(OkularCoreDebug) << "Error: Document::prepareToModifyAnnotationProperties has already been called since last call to Document::modifyPageAnnotationProperties";
return;
}
d->m_prevPropsOfAnnotBeingModified = annotation->getAnnotationPropertiesDomNode();
}
void Document::modifyPageAnnotationProperties( int page, Annotation * annotation )
{
Q_ASSERT(!d->m_prevPropsOfAnnotBeingModified.isNull());
if (d->m_prevPropsOfAnnotBeingModified.isNull())
{
qCCritical(OkularCoreDebug) << "Error: Document::prepareToModifyAnnotationProperties must be called before Annotation is modified";
return;
}
QDomNode prevProps = d->m_prevPropsOfAnnotBeingModified;
QUndoCommand *uc = new Okular::ModifyAnnotationPropertiesCommand( d,
annotation,
page,
prevProps,
annotation->getAnnotationPropertiesDomNode() );
d->m_undoStack->push( uc );
d->m_prevPropsOfAnnotBeingModified.clear();
}
void Document::translatePageAnnotation(int page, Annotation* annotation, const NormalizedPoint & delta )
{
int complete = (annotation->flags() & Okular::Annotation::BeingMoved) == 0;
QUndoCommand *uc = new Okular::TranslateAnnotationCommand( d, annotation, page, delta, complete );
d->m_undoStack->push(uc);
}
void Document::adjustPageAnnotation( int page, Annotation *annotation, const Okular::NormalizedPoint & delta1, const Okular::NormalizedPoint & delta2 )
{
const bool complete = (annotation->flags() & Okular::Annotation::BeingResized) == 0;
QUndoCommand *uc = new Okular::AdjustAnnotationCommand( d, annotation, page, delta1, delta2, complete );
d->m_undoStack->push(uc);
}
void Document::editPageAnnotationContents( int page, Annotation* annotation,
const QString & newContents,
int newCursorPos,
int prevCursorPos,
int prevAnchorPos
)
{
QString prevContents = annotation->contents();
QUndoCommand *uc = new EditAnnotationContentsCommand( d, annotation, page, newContents, newCursorPos,
prevContents, prevCursorPos, prevAnchorPos );
d->m_undoStack->push( uc );
}
bool Document::canRemovePageAnnotation( const Annotation * annotation ) const
{
if ( !annotation || ( annotation->flags() & Annotation::DenyDelete ) )
return false;
if ( ( annotation->flags() & Annotation::External ) && !d->canRemoveExternalAnnotations() )
return false;
switch ( annotation->subType() )
{
case Annotation::AText:
case Annotation::ALine:
case Annotation::AGeom:
case Annotation::AHighlight:
case Annotation::AStamp:
case Annotation::AInk:
case Annotation::ACaret:
return true;
default:
return false;
}
}
void Document::removePageAnnotation( int page, Annotation * annotation )
{
QUndoCommand *uc = new RemoveAnnotationCommand(this->d, annotation, page);
d->m_undoStack->push(uc);
}
void Document::removePageAnnotations( int page, const QList &annotations )
{
d->m_undoStack->beginMacro(i18nc("remove a collection of annotations from the page", "remove annotations"));
foreach(Annotation* annotation, annotations)
{
QUndoCommand *uc = new RemoveAnnotationCommand(this->d, annotation, page);
d->m_undoStack->push(uc);
}
d->m_undoStack->endMacro();
}
bool DocumentPrivate::canAddAnnotationsNatively() const
{
Okular::SaveInterface * iface = qobject_cast< Okular::SaveInterface * >( m_generator );
if ( iface && iface->supportsOption(Okular::SaveInterface::SaveChanges) &&
iface->annotationProxy() && iface->annotationProxy()->supports(AnnotationProxy::Addition) )
return true;
return false;
}
bool DocumentPrivate::canModifyExternalAnnotations() const
{
Okular::SaveInterface * iface = qobject_cast< Okular::SaveInterface * >( m_generator );
if ( iface && iface->supportsOption(Okular::SaveInterface::SaveChanges) &&
iface->annotationProxy() && iface->annotationProxy()->supports(AnnotationProxy::Modification) )
return true;
return false;
}
bool DocumentPrivate::canRemoveExternalAnnotations() const
{
Okular::SaveInterface * iface = qobject_cast< Okular::SaveInterface * >( m_generator );
if ( iface && iface->supportsOption(Okular::SaveInterface::SaveChanges) &&
iface->annotationProxy() && iface->annotationProxy()->supports(AnnotationProxy::Removal) )
return true;
return false;
}
void Document::setPageTextSelection( int page, RegularAreaRect * rect, const QColor & color )
{
Page * kp = d->m_pagesVector[ page ];
if ( !d->m_generator || !kp )
return;
// add or remove the selection basing whether rect is null or not
if ( rect )
kp->d->setTextSelections( rect, color );
else
kp->d->deleteTextSelections();
// notify observers about the change
foreachObserver( notifyPageChanged( page, DocumentObserver::TextSelection ) );
}
bool Document::canUndo() const
{
return d->m_undoStack->canUndo();
}
bool Document::canRedo() const
{
return d->m_undoStack->canRedo();
}
/* REFERENCE IMPLEMENTATION: better calling setViewport from other code
void Document::setNextPage()
{
// advance page and set viewport on observers
if ( (*d->m_viewportIterator).pageNumber < (int)d->m_pagesVector.count() - 1 )
setViewport( DocumentViewport( (*d->m_viewportIterator).pageNumber + 1 ) );
}
void Document::setPrevPage()
{
// go to previous page and set viewport on observers
if ( (*d->m_viewportIterator).pageNumber > 0 )
setViewport( DocumentViewport( (*d->m_viewportIterator).pageNumber - 1 ) );
}
*/
void Document::setViewportPage( int page, DocumentObserver *excludeObserver, bool smoothMove )
{
// clamp page in range [0 ... numPages-1]
if ( page < 0 )
page = 0;
else if ( page > (int)d->m_pagesVector.count() )
page = d->m_pagesVector.count() - 1;
// make a viewport from the page and broadcast it
setViewport( DocumentViewport( page ), excludeObserver, smoothMove );
}
void Document::setViewport( const DocumentViewport & viewport, DocumentObserver *excludeObserver, bool smoothMove )
{
if ( !viewport.isValid() )
{
qCDebug(OkularCoreDebug) << "invalid viewport:" << viewport.toString();
return;
}
if ( viewport.pageNumber >= int(d->m_pagesVector.count()) )
{
//qCDebug(OkularCoreDebug) << "viewport out of document:" << viewport.toString();
return;
}
// if already broadcasted, don't redo it
DocumentViewport & oldViewport = *d->m_viewportIterator;
// disabled by enrico on 2005-03-18 (less debug output)
//if ( viewport == oldViewport )
// qCDebug(OkularCoreDebug) << "setViewport with the same viewport.";
const int oldPageNumber = oldViewport.pageNumber;
// set internal viewport taking care of history
if ( oldViewport.pageNumber == viewport.pageNumber || !oldViewport.isValid() )
{
// if page is unchanged save the viewport at current position in queue
oldViewport = viewport;
}
else
{
// remove elements after viewportIterator in queue
d->m_viewportHistory.erase( ++d->m_viewportIterator, d->m_viewportHistory.end() );
// keep the list to a reasonable size by removing head when needed
if ( d->m_viewportHistory.count() >= OKULAR_HISTORY_MAXSTEPS )
d->m_viewportHistory.pop_front();
// add the item at the end of the queue
d->m_viewportIterator = d->m_viewportHistory.insert( d->m_viewportHistory.end(), viewport );
}
const int currentViewportPage = (*d->m_viewportIterator).pageNumber;
const bool currentPageChanged = (oldPageNumber != currentViewportPage);
// notify change to all other (different from id) observers
foreach(DocumentObserver *o, d->m_observers)
{
if ( o != excludeObserver )
o->notifyViewportChanged( smoothMove );
if ( currentPageChanged )
o->notifyCurrentPageChanged( oldPageNumber, currentViewportPage );
}
}
void Document::setZoom(int factor, DocumentObserver *excludeObserver)
{
// notify change to all other (different from id) observers
foreach(DocumentObserver *o, d->m_observers)
if (o != excludeObserver)
o->notifyZoom( factor );
}
void Document::setPrevViewport()
// restore viewport from the history
{
if ( d->m_viewportIterator != d->m_viewportHistory.begin() )
{
const int oldViewportPage = (*d->m_viewportIterator).pageNumber;
// restore previous viewport and notify it to observers
--d->m_viewportIterator;
foreachObserver( notifyViewportChanged( true ) );
const int currentViewportPage = (*d->m_viewportIterator).pageNumber;
if (oldViewportPage != currentViewportPage)
foreachObserver( notifyCurrentPageChanged( oldViewportPage, currentViewportPage ) );
}
}
void Document::setNextViewport()
// restore next viewport from the history
{
QLinkedList< DocumentViewport >::const_iterator nextIterator = d->m_viewportIterator;
++nextIterator;
if ( nextIterator != d->m_viewportHistory.end() )
{
const int oldViewportPage = (*d->m_viewportIterator).pageNumber;
// restore next viewport and notify it to observers
++d->m_viewportIterator;
foreachObserver( notifyViewportChanged( true ) );
const int currentViewportPage = (*d->m_viewportIterator).pageNumber;
if (oldViewportPage != currentViewportPage)
foreachObserver( notifyCurrentPageChanged( oldViewportPage, currentViewportPage ) );
}
}
void Document::setNextDocumentViewport( const DocumentViewport & viewport )
{
d->m_nextDocumentViewport = viewport;
}
void Document::setNextDocumentDestination( const QString &namedDestination )
{
d->m_nextDocumentDestination = namedDestination;
}
void Document::searchText( int searchID, const QString & text, bool fromStart, Qt::CaseSensitivity caseSensitivity,
SearchType type, bool moveViewport, const QColor & color )
{
d->m_searchCancelled = false;
// safety checks: don't perform searches on empty or unsearchable docs
if ( !d->m_generator || !d->m_generator->hasFeature( Generator::TextExtraction ) || d->m_pagesVector.isEmpty() )
{
emit searchFinished( searchID, NoMatchFound );
return;
}
// if searchID search not recorded, create new descriptor and init params
QMap< int, RunningSearch * >::iterator searchIt = d->m_searches.find( searchID );
if ( searchIt == d->m_searches.end() )
{
RunningSearch * search = new RunningSearch();
search->continueOnPage = -1;
searchIt = d->m_searches.insert( searchID, search );
}
RunningSearch * s = *searchIt;
// update search structure
bool newText = text != s->cachedString;
s->cachedString = text;
s->cachedType = type;
s->cachedCaseSensitivity = caseSensitivity;
s->cachedViewportMove = moveViewport;
s->cachedColor = color;
s->isCurrentlySearching = true;
// global data for search
QSet< int > *pagesToNotify = new QSet< int >;
// remove highlights from pages and queue them for notifying changes
*pagesToNotify += s->highlightedPages;
foreach(int pageNumber, s->highlightedPages)
d->m_pagesVector.at(pageNumber)->d->deleteHighlights( searchID );
s->highlightedPages.clear();
// set hourglass cursor
QApplication::setOverrideCursor( Qt::WaitCursor );
// 1. ALLDOC - proces all document marking pages
if ( type == AllDocument )
{
QMap< Page *, QVector > *pageMatches = new QMap< Page *, QVector >;
// search and highlight 'text' (as a solid phrase) on all pages
QMetaObject::invokeMethod(this, "doContinueAllDocumentSearch", Qt::QueuedConnection, Q_ARG(void *, pagesToNotify), Q_ARG(void *, pageMatches), Q_ARG(int, 0), Q_ARG(int, searchID));
}
// 2. NEXTMATCH - find next matching item (or start from top)
// 3. PREVMATCH - find previous matching item (or start from bottom)
else if ( type == NextMatch || type == PreviousMatch )
{
// find out from where to start/resume search from
const bool forward = type == NextMatch;
const int viewportPage = (*d->m_viewportIterator).pageNumber;
const int fromStartSearchPage = forward ? 0 : d->m_pagesVector.count() - 1;
int currentPage = fromStart ? fromStartSearchPage : ((s->continueOnPage != -1) ? s->continueOnPage : viewportPage);
Page * lastPage = fromStart ? 0 : d->m_pagesVector[ currentPage ];
int pagesDone = 0;
// continue checking last TextPage first (if it is the current page)
RegularAreaRect * match = nullptr;
if ( lastPage && lastPage->number() == s->continueOnPage )
{
if ( newText )
match = lastPage->findText( searchID, text, forward ? FromTop : FromBottom, caseSensitivity );
else
match = lastPage->findText( searchID, text, forward ? NextResult : PreviousResult, caseSensitivity, &s->continueOnMatch );
if ( !match )
{
if (forward) currentPage++;
else currentPage--;
pagesDone++;
}
}
s->pagesDone = pagesDone;
DoContinueDirectionMatchSearchStruct *searchStruct = new DoContinueDirectionMatchSearchStruct();
searchStruct->pagesToNotify = pagesToNotify;
searchStruct->match = match;
searchStruct->currentPage = currentPage;
searchStruct->searchID = searchID;
QMetaObject::invokeMethod(this, "doContinueDirectionMatchSearch", Qt::QueuedConnection, Q_ARG(void *, searchStruct));
}
// 4. GOOGLE* - process all document marking pages
else if ( type == GoogleAll || type == GoogleAny )
{
QMap< Page *, QVector< QPair > > *pageMatches = new QMap< Page *, QVector > >;
const QStringList words = text.split( QLatin1Char ( ' ' ), QString::SkipEmptyParts );
// search and highlight every word in 'text' on all pages
QMetaObject::invokeMethod(this, "doContinueGooglesDocumentSearch", Qt::QueuedConnection, Q_ARG(void *, pagesToNotify), Q_ARG(void *, pageMatches), Q_ARG(int, 0), Q_ARG(int, searchID), Q_ARG(QStringList, words));
}
}
void Document::continueSearch( int searchID )
{
// check if searchID is present in runningSearches
QMap< int, RunningSearch * >::const_iterator it = d->m_searches.constFind( searchID );
if ( it == d->m_searches.constEnd() )
{
emit searchFinished( searchID, NoMatchFound );
return;
}
// start search with cached parameters from last search by searchID
RunningSearch * p = *it;
if ( !p->isCurrentlySearching )
searchText( searchID, p->cachedString, false, p->cachedCaseSensitivity,
p->cachedType, p->cachedViewportMove, p->cachedColor );
}
void Document::continueSearch( int searchID, SearchType type )
{
// check if searchID is present in runningSearches
QMap< int, RunningSearch * >::const_iterator it = d->m_searches.constFind( searchID );
if ( it == d->m_searches.constEnd() )
{
emit searchFinished( searchID, NoMatchFound );
return;
}
// start search with cached parameters from last search by searchID
RunningSearch * p = *it;
if ( !p->isCurrentlySearching )
searchText( searchID, p->cachedString, false, p->cachedCaseSensitivity,
type, p->cachedViewportMove, p->cachedColor );
}
void Document::resetSearch( int searchID )
{
// if we are closing down, don't bother doing anything
if ( !d->m_generator )
return;
// check if searchID is present in runningSearches
QMap< int, RunningSearch * >::iterator searchIt = d->m_searches.find( searchID );
if ( searchIt == d->m_searches.end() )
return;
// get previous parameters for search
RunningSearch * s = *searchIt;
// unhighlight pages and inform observers about that
foreach(int pageNumber, s->highlightedPages)
{
d->m_pagesVector.at(pageNumber)->d->deleteHighlights( searchID );
foreachObserver( notifyPageChanged( pageNumber, DocumentObserver::Highlights ) );
}
// send the setup signal too (to update views that filter on matches)
foreachObserver( notifySetup( d->m_pagesVector, 0 ) );
// remove serch from the runningSearches list and delete it
d->m_searches.erase( searchIt );
delete s;
}
void Document::cancelSearch()
{
d->m_searchCancelled = true;
}
void Document::undo()
{
d->m_undoStack->undo();
}
void Document::redo()
{
d->m_undoStack->redo();
}
void Document::editFormText( int pageNumber,
Okular::FormFieldText* form,
const QString & newContents,
int newCursorPos,
int prevCursorPos,
int prevAnchorPos )
{
QUndoCommand *uc = new EditFormTextCommand( this->d, form, pageNumber, newContents, newCursorPos, form->text(), prevCursorPos, prevAnchorPos );
d->m_undoStack->push( uc );
d->recalculateForms();
}
void Document::editFormList( int pageNumber,
FormFieldChoice* form,
const QList< int > & newChoices )
{
const QList< int > prevChoices = form->currentChoices();
QUndoCommand *uc = new EditFormListCommand( this->d, form, pageNumber, newChoices, prevChoices );
d->m_undoStack->push( uc );
d->recalculateForms();
}
void Document::editFormCombo( int pageNumber,
FormFieldChoice* form,
const QString & newText,
int newCursorPos,
int prevCursorPos,
int prevAnchorPos )
{
QString prevText;
if ( form->currentChoices().isEmpty() )
{
prevText = form->editChoice();
}
else
{
prevText = form->choices()[form->currentChoices().constFirst()];
}
QUndoCommand *uc = new EditFormComboCommand( this->d, form, pageNumber, newText, newCursorPos, prevText, prevCursorPos, prevAnchorPos );
d->m_undoStack->push( uc );
d->recalculateForms();
}
void Document::editFormButtons( int pageNumber, const QList< FormFieldButton* >& formButtons, const QList< bool >& newButtonStates )
{
QUndoCommand *uc = new EditFormButtonsCommand( this->d, pageNumber, formButtons, newButtonStates );
d->m_undoStack->push( uc );
}
void Document::reloadDocument() const
{
const int numOfPages = pages();
for( int i = currentPage(); i >= 0; i -- )
d->refreshPixmaps( i );
for( int i = currentPage() + 1; i < numOfPages; i ++ )
d->refreshPixmaps( i );
}
BookmarkManager * Document::bookmarkManager() const
{
return d->m_bookmarkManager;
}
QList Document::bookmarkedPageList() const
{
QList list;
uint docPages = pages();
//pages are 0-indexed internally, but 1-indexed externally
for ( uint i = 0; i < docPages; i++ )
{
if ( bookmarkManager()->isBookmarked( i ) )
{
list << i + 1;
}
}
return list;
}
QString Document::bookmarkedPageRange() const
{
// Code formerly in Part::slotPrint()
// range detecting
QString range;
uint docPages = pages();
int startId = -1;
int endId = -1;
for ( uint i = 0; i < docPages; ++i )
{
if ( bookmarkManager()->isBookmarked( i ) )
{
if ( startId < 0 )
startId = i;
if ( endId < 0 )
endId = startId;
else
++endId;
}
else if ( startId >= 0 && endId >= 0 )
{
if ( !range.isEmpty() )
range += QLatin1Char ( ',' );
if ( endId - startId > 0 )
range += QStringLiteral( "%1-%2" ).arg( startId + 1 ).arg( endId + 1 );
else
range += QString::number( startId + 1 );
startId = -1;
endId = -1;
}
}
if ( startId >= 0 && endId >= 0 )
{
if ( !range.isEmpty() )
range += QLatin1Char ( ',' );
if ( endId - startId > 0 )
range += QStringLiteral( "%1-%2" ).arg( startId + 1 ).arg( endId + 1 );
else
range += QString::number( startId + 1 );
}
return range;
}
void Document::processAction( const Action * action )
{
if ( !action )
return;
switch( action->actionType() )
{
case Action::Goto: {
const GotoAction * go = static_cast< const GotoAction * >( action );
d->m_nextDocumentViewport = go->destViewport();
d->m_nextDocumentDestination = go->destinationName();
// Explanation of why d->m_nextDocumentViewport is needed:
// all openRelativeFile does is launch a signal telling we
// want to open another URL, the problem is that when the file is
// non local, the loading is done assynchronously so you can't
// do a setViewport after the if as it was because you are doing the setViewport
// on the old file and when the new arrives there is no setViewport for it and
// it does not show anything
// first open filename if link is pointing outside this document
if ( go->isExternal() && !d->openRelativeFile( go->fileName() ) )
{
qCWarning(OkularCoreDebug).nospace() << "Action: Error opening '" << go->fileName() << "'.";
return;
}
else
{
const DocumentViewport nextViewport = d->nextDocumentViewport();
// skip local links that point to nowhere (broken ones)
if ( !nextViewport.isValid() )
return;
setViewport( nextViewport, nullptr, true );
d->m_nextDocumentViewport = DocumentViewport();
d->m_nextDocumentDestination = QString();
}
} break;
case Action::Execute: {
const ExecuteAction * exe = static_cast< const ExecuteAction * >( action );
const QString fileName = exe->fileName();
if ( fileName.endsWith( QLatin1String(".pdf"), Qt::CaseInsensitive ) )
{
d->openRelativeFile( fileName );
return;
}
// Albert: the only pdf i have that has that kind of link don't define
// an application and use the fileName as the file to open
QUrl url = d->giveAbsoluteUrl( fileName );
QMimeDatabase db;
QMimeType mime = db.mimeTypeForUrl( url );
// Check executables
if ( KRun::isExecutableFile( url, mime.name() ) )
{
// Don't have any pdf that uses this code path, just a guess on how it should work
if ( !exe->parameters().isEmpty() )
{
url = d->giveAbsoluteUrl( exe->parameters() );
mime = db.mimeTypeForUrl( url );
if ( KRun::isExecutableFile( url, mime.name() ) )
{
// this case is a link pointing to an executable with a parameter
// that also is an executable, possibly a hand-crafted pdf
KMessageBox::information( d->m_widget, i18n("The document is trying to execute an external application and, for your safety, Okular does not allow that.") );
return;
}
}
else
{
// this case is a link pointing to an executable with no parameters
// core developers find unacceptable executing it even after asking the user
KMessageBox::information( d->m_widget, i18n("The document is trying to execute an external application and, for your safety, Okular does not allow that.") );
return;
}
}
KService::Ptr ptr = KMimeTypeTrader::self()->preferredService( mime.name(), QStringLiteral("Application") );
if ( ptr )
{
QList lst;
lst.append( url );
KRun::runService( *ptr, lst, nullptr );
}
else
KMessageBox::information( d->m_widget, i18n( "No application found for opening file of mimetype %1.", mime.name() ) );
} break;
case Action::DocAction: {
const DocumentAction * docaction = static_cast< const DocumentAction * >( action );
switch( docaction->documentActionType() )
{
case DocumentAction::PageFirst:
setViewportPage( 0 );
break;
case DocumentAction::PagePrev:
if ( (*d->m_viewportIterator).pageNumber > 0 )
setViewportPage( (*d->m_viewportIterator).pageNumber - 1 );
break;
case DocumentAction::PageNext:
if ( (*d->m_viewportIterator).pageNumber < (int)d->m_pagesVector.count() - 1 )
setViewportPage( (*d->m_viewportIterator).pageNumber + 1 );
break;
case DocumentAction::PageLast:
setViewportPage( d->m_pagesVector.count() - 1 );
break;
case DocumentAction::HistoryBack:
setPrevViewport();
break;
case DocumentAction::HistoryForward:
setNextViewport();
break;
case DocumentAction::Quit:
emit quit();
break;
case DocumentAction::Presentation:
emit linkPresentation();
break;
case DocumentAction::EndPresentation:
emit linkEndPresentation();
break;
case DocumentAction::Find:
emit linkFind();
break;
case DocumentAction::GoToPage:
emit linkGoToPage();
break;
case DocumentAction::Close:
emit close();
break;
}
} break;
case Action::Browse: {
const BrowseAction * browse = static_cast< const BrowseAction * >( action );
QString lilySource;
int lilyRow = 0, lilyCol = 0;
// if the url is a mailto one, invoke mailer
if ( browse->url().scheme() == QLatin1String("mailto") )
{
QDesktopServices::openUrl( browse->url() );
}
else if ( extractLilyPondSourceReference( browse->url(), &lilySource, &lilyRow, &lilyCol ) )
{
const SourceReference ref( lilySource, lilyRow, lilyCol );
processSourceReference( &ref );
}
else
{
const QUrl url = browse->url();
// fix for #100366, documents with relative links that are the form of http:foo.pdf
if ((url.scheme() == "http") && url.host().isEmpty() && url.fileName().endsWith("pdf"))
{
d->openRelativeFile(url.fileName());
return;
}
// handle documents with relative path
if ( d->m_url.isValid() )
{
const QUrl realUrl = KIO::upUrl(d->m_url).resolved(url);
// KRun autodeletes
new KRun( realUrl, d->m_widget );
}
}
} break;
case Action::Sound: {
const SoundAction * linksound = static_cast< const SoundAction * >( action );
AudioPlayer::instance()->playSound( linksound->sound(), linksound );
} break;
case Action::Script: {
const ScriptAction * linkscript = static_cast< const ScriptAction * >( action );
if ( !d->m_scripter )
d->m_scripter = new Scripter( d );
d->m_scripter->execute( linkscript->scriptType(), linkscript->script() );
} break;
case Action::Movie:
emit processMovieAction( static_cast< const MovieAction * >( action ) );
break;
case Action::Rendition: {
const RenditionAction * linkrendition = static_cast< const RenditionAction * >( action );
if ( !linkrendition->script().isEmpty() )
{
if ( !d->m_scripter )
d->m_scripter = new Scripter( d );
d->m_scripter->execute( linkrendition->scriptType(), linkrendition->script() );
}
emit processRenditionAction( static_cast< const RenditionAction * >( action ) );
} break;
case Action::BackendOpaque: {
d->m_generator->opaqueAction( static_cast< const BackendOpaqueAction * >( action ) );
} break;
}
}
void Document::processSourceReference( const SourceReference * ref )
{
if ( !ref )
return;
const QUrl url = d->giveAbsoluteUrl( ref->fileName() );
if ( !url.isLocalFile() )
{
qCDebug(OkularCoreDebug) << url.url() << "is not a local file.";
return;
}
const QString absFileName = url.toLocalFile();
if ( !QFile::exists( absFileName ) )
{
qCDebug(OkularCoreDebug) << "No such file:" << absFileName;
return;
}
bool handled = false;
emit sourceReferenceActivated(absFileName, ref->row(), ref->column(), &handled);
if(handled) {
return;
}
static QHash< int, QString > editors;
// init the editors table if empty (on first run, usually)
if ( editors.isEmpty() )
{
editors = buildEditorsMap();
}
QHash< int, QString >::const_iterator it = editors.constFind( SettingsCore::externalEditor() );
QString p;
if ( it != editors.constEnd() )
p = *it;
else
p = SettingsCore::externalEditorCommand();
// custom editor not yet configured
if ( p.isEmpty() )
return;
// manually append the %f placeholder if not specified
if ( p.indexOf( QLatin1String( "%f" ) ) == -1 )
p.append( QLatin1String( " %f" ) );
// replacing the placeholders
QHash< QChar, QString > map;
map.insert( QLatin1Char ( 'f' ), absFileName );
map.insert( QLatin1Char ( 'c' ), QString::number( ref->column() ) );
map.insert( QLatin1Char ( 'l' ), QString::number( ref->row() ) );
const QString cmd = KMacroExpander::expandMacrosShellQuote( p, map );
if ( cmd.isEmpty() )
return;
const QStringList args = KShell::splitArgs( cmd );
if ( args.isEmpty() )
return;
KProcess::startDetached( args );
}
const SourceReference * Document::dynamicSourceReference( int pageNr, double absX, double absY )
{
if ( !d->m_synctex_scanner )
return nullptr;
const QSizeF dpi = d->m_generator->dpi();
if (synctex_edit_query(d->m_synctex_scanner, pageNr + 1, absX * 72. / dpi.width(), absY * 72. / dpi.height()) > 0)
{
synctex_node_p node;
// TODO what should we do if there is really more than one node?
while (( node = synctex_scanner_next_result( d->m_synctex_scanner ) ))
{
int line = synctex_node_line(node);
int col = synctex_node_column(node);
// column extraction does not seem to be implemented in synctex so far. set the SourceReference default value.
if ( col == -1 )
{
col = 0;
}
const char *name = synctex_scanner_get_name( d->m_synctex_scanner, synctex_node_tag( node ) );
return new Okular::SourceReference( QFile::decodeName( name ), line, col );
}
}
return nullptr;
}
Document::PrintingType Document::printingSupport() const
{
if ( d->m_generator )
{
if ( d->m_generator->hasFeature( Generator::PrintNative ) )
{
return NativePrinting;
}
#ifndef Q_OS_WIN
if ( d->m_generator->hasFeature( Generator::PrintPostscript ) )
{
return PostscriptPrinting;
}
#endif
}
return NoPrinting;
}
bool Document::supportsPrintToFile() const
{
return d->m_generator ? d->m_generator->hasFeature( Generator::PrintToFile ) : false;
}
bool Document::print( QPrinter &printer )
{
return d->m_generator ? d->m_generator->print( printer ) : false;
}
QString Document::printError() const
{
Okular::Generator::PrintError err = Generator::UnknownPrintError;
if ( d->m_generator )
{
QMetaObject::invokeMethod( d->m_generator, "printError", Qt::DirectConnection, Q_RETURN_ARG(Okular::Generator::PrintError, err) );
}
Q_ASSERT( err != Generator::NoPrintError );
switch ( err )
{
case Generator::TemporaryFileOpenPrintError:
return i18n( "Could not open a temporary file" );
case Generator::FileConversionPrintError:
return i18n( "Print conversion failed" );
case Generator::PrintingProcessCrashPrintError:
return i18n( "Printing process crashed" );
case Generator::PrintingProcessStartPrintError:
return i18n( "Printing process could not start" );
case Generator::PrintToFilePrintError:
return i18n( "Printing to file failed" );
case Generator::InvalidPrinterStatePrintError:
return i18n( "Printer was in invalid state" );
case Generator::UnableToFindFilePrintError:
return i18n( "Unable to find file to print" );
case Generator::NoFileToPrintError:
return i18n( "There was no file to print" );
case Generator::NoBinaryToPrintError:
return i18n( "Could not find a suitable binary for printing. Make sure CUPS lpr binary is available" );
case Generator::InvalidPageSizePrintError:
return i18n( "The page print size is invalid" );
case Generator::NoPrintError:
return QString();
case Generator::UnknownPrintError:
return QString();
}
return QString();
}
QWidget* Document::printConfigurationWidget() const
{
if ( d->m_generator )
{
PrintInterface * iface = qobject_cast< Okular::PrintInterface * >( d->m_generator );
return iface ? iface->printConfigurationWidget() : nullptr;
}
else
return nullptr;
}
void Document::fillConfigDialog( KConfigDialog * dialog )
{
if ( !dialog )
return;
// ensure that we have all the generators with settings loaded
QVector offers = DocumentPrivate::configurableGenerators();
d->loadServiceList( offers );
bool pagesAdded = false;
QHash< QString, GeneratorInfo >::iterator it = d->m_loadedGenerators.begin();
QHash< QString, GeneratorInfo >::iterator itEnd = d->m_loadedGenerators.end();
for ( ; it != itEnd; ++it )
{
Okular::ConfigInterface * iface = d->generatorConfig( it.value() );
if ( iface )
{
iface->addPages( dialog );
pagesAdded = true;
}
}
if ( pagesAdded )
{
connect( dialog, SIGNAL(settingsChanged(QString)),
this, SLOT(slotGeneratorConfigChanged(QString)) );
}
}
QVector DocumentPrivate::configurableGenerators()
{
const QVector available = availableGenerators();
QVector result;
for (const KPluginMetaData& md : available)
{
if (md.rawData()[QStringLiteral("X-KDE-okularHasInternalSettings")].toBool())
{
result << md;
}
}
return result;
}
KPluginMetaData Document::generatorInfo() const
{
if (!d->m_generator)
return KPluginMetaData();
auto genIt = d->m_loadedGenerators.constFind(d->m_generatorName);
Q_ASSERT(genIt != d->m_loadedGenerators.constEnd());
return genIt.value().metadata;
}
int Document::configurableGenerators() const
{
return DocumentPrivate::configurableGenerators().size();
}
QStringList Document::supportedMimeTypes() const
{
// TODO: make it a static member of DocumentPrivate?
QStringList result = d->m_supportedMimeTypes;
if (result.isEmpty())
{
const QVector available = DocumentPrivate::availableGenerators();
for (const KPluginMetaData& md : available)
{
result << md.mimeTypes();
}
// Remove duplicate mimetypes represented by different names
QMimeDatabase mimeDatabase;
QSet uniqueMimetypes;
for (const QString &mimeName : result) {
uniqueMimetypes.insert(mimeDatabase.mimeTypeForName(mimeName));
}
result.clear();
for (const QMimeType &mimeType : uniqueMimetypes) {
result.append(mimeType.name());
}
+ // Add the Okular archive mimetype
+ result << QStringLiteral("application/vnd.kde.okular-archive");
+
// Sorting by mimetype name doesn't make a ton of sense,
// but ensures that the list is ordered the same way every time
qSort(result);
d->m_supportedMimeTypes = result;
}
return result;
}
+bool Document::canSwapBackingFile() const
+{
+ if ( !d->m_generator )
+ return false;
+ Q_ASSERT( !d->m_generatorName.isEmpty() );
+
+ QHash< QString, GeneratorInfo >::iterator genIt = d->m_loadedGenerators.find( d->m_generatorName );
+ Q_ASSERT( genIt != d->m_loadedGenerators.end() );
+
+ return genIt->generator->hasFeature( Generator::SwapBackingFile );
+}
+
+bool Document::swapBackingFile( const QString &newFileName, const QUrl &url )
+{
+ if ( !d->m_generator )
+ return false;
+ Q_ASSERT( !d->m_generatorName.isEmpty() );
+
+ QHash< QString, GeneratorInfo >::iterator genIt = d->m_loadedGenerators.find( d->m_generatorName );
+ Q_ASSERT( genIt != d->m_loadedGenerators.end() );
+
+ if ( !genIt->generator->hasFeature( Generator::SwapBackingFile ) )
+ return false;
+
+ // Save metadata about the file we're about to close
+ d->saveDocumentInfo();
+
+ qCDebug(OkularCoreDebug) << "Swapping backing file to" << newFileName;
+ QVector< Page * > newPagesVector;
+ Generator::SwapBackingFileResult result = genIt->generator->swapBackingFile( newFileName, newPagesVector );
+ if (result != Generator::SwapBackingFileError)
+ {
+ QLinkedList< ObjectRect* > rectsToDelete;
+ QLinkedList< Annotation* > annotationsToDelete;
+ QSet< PagePrivate* > pagePrivatesToDelete;
+
+ if (result == Generator::SwapBackingFileReloadInternalData)
+ {
+ // Here we need to replace everything that the old generator
+ // had created with what the new one has without making it look like
+ // we have actually closed and opened the file again
+
+ // Simple sanity check
+ if (newPagesVector.count() != d->m_pagesVector.count())
+ return false;
+
+ // Update the undo stack contents
+ for (int i = 0; i < d->m_undoStack->count(); ++i)
+ {
+ // Trust me on the const_cast ^_^
+ QUndoCommand *uc = const_cast( d->m_undoStack->command( i ) );
+ if (OkularUndoCommand *ouc = dynamic_cast( uc ))
+ {
+ const bool success = ouc->refreshInternalPageReferences( newPagesVector );
+ if ( !success )
+ {
+ qWarning() << "Document::swapBackingFile: refreshInternalPageReferences failed" << ouc;
+ return false;
+ }
+ }
+ else
+ {
+ qWarning() << "Document::swapBackingFile: Unhandled undo command" << uc;
+ return false;
+ }
+ }
+
+ for (int i = 0; i < d->m_pagesVector.count(); ++i)
+ {
+ // switch the PagePrivate* from newPage to oldPage
+ // this way everyone still holding Page* doesn't get
+ // disturbed by it
+ Page *oldPage = d->m_pagesVector[i];
+ Page *newPage = newPagesVector[i];
+ newPage->d->adoptGeneratedContents(oldPage->d);
+
+ pagePrivatesToDelete << oldPage->d;
+ oldPage->d = newPage->d;
+ oldPage->d->m_page = oldPage;
+ oldPage->d->m_doc = d;
+ newPage->d = nullptr;
+
+ annotationsToDelete << oldPage->m_annotations;
+ rectsToDelete << oldPage->m_rects;
+ oldPage->m_annotations = newPage->m_annotations;
+ oldPage->m_rects = newPage->m_rects;
+ }
+ qDeleteAll( newPagesVector );
+ }
+
+ d->m_url = url;
+ d->m_docFileName = newFileName;
+ d->updateMetadataXmlNameAndDocSize();
+ d->m_bookmarkManager->setUrl( d->m_url );
+
+ if ( d->m_synctex_scanner )
+ {
+ synctex_scanner_free( d->m_synctex_scanner );
+ d->m_synctex_scanner = synctex_scanner_new_with_output_file( QFile::encodeName( newFileName ).constData(), nullptr, 1);
+ if ( !d->m_synctex_scanner && QFile::exists(newFileName + QLatin1String( "sync" ) ) )
+ {
+ d->loadSyncFile(newFileName);
+ }
+ }
+
+ foreachObserver( notifySetup( d->m_pagesVector, DocumentObserver::UrlChanged ) );
+
+ qDeleteAll( annotationsToDelete );
+ qDeleteAll( rectsToDelete );
+ qDeleteAll( pagePrivatesToDelete );
+
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+}
+
+bool Document::swapBackingFileArchive( const QString &newFileName, const QUrl &url )
+{
+ qCDebug(OkularCoreDebug) << "Swapping backing archive to" << newFileName;
+
+ ArchiveData *newArchive = DocumentPrivate::unpackDocumentArchive( newFileName );
+ if ( !newArchive )
+ return false;
+
+ const QString tempFileName = newArchive->document.fileName();
+
+ const bool success = swapBackingFile( tempFileName, url );
+
+ if ( success )
+ {
+ delete d->m_archiveData;
+ d->m_archiveData = newArchive;
+ }
+
+ return success;
+}
+
+void Document::setHistoryClean( bool clean )
+{
+ if ( clean )
+ d->m_undoStack->setClean();
+ else
+ d->m_undoStack->resetClean();
+}
+
bool Document::canSaveChanges() const
{
if ( !d->m_generator )
return false;
Q_ASSERT( !d->m_generatorName.isEmpty() );
QHash< QString, GeneratorInfo >::iterator genIt = d->m_loadedGenerators.find( d->m_generatorName );
Q_ASSERT( genIt != d->m_loadedGenerators.end() );
SaveInterface* saveIface = d->generatorSave( genIt.value() );
if ( !saveIface )
return false;
return saveIface->supportsOption( SaveInterface::SaveChanges );
}
bool Document::canSaveChanges( SaveCapability cap ) const
{
switch ( cap )
{
case SaveFormsCapability:
/* Assume that if the generator supports saving, forms can be saved.
* We have no means to actually query the generator at the moment
* TODO: Add some method to query the generator in SaveInterface */
return canSaveChanges();
case SaveAnnotationsCapability:
return d->canAddAnnotationsNatively();
}
return false;
}
bool Document::saveChanges( const QString &fileName )
{
QString errorText;
return saveChanges( fileName, &errorText );
}
bool Document::saveChanges( const QString &fileName, QString *errorText )
{
if ( !d->m_generator || fileName.isEmpty() )
return false;
Q_ASSERT( !d->m_generatorName.isEmpty() );
QHash< QString, GeneratorInfo >::iterator genIt = d->m_loadedGenerators.find( d->m_generatorName );
Q_ASSERT( genIt != d->m_loadedGenerators.end() );
SaveInterface* saveIface = d->generatorSave( genIt.value() );
if ( !saveIface || !saveIface->supportsOption( SaveInterface::SaveChanges ) )
return false;
return saveIface->save( fileName, SaveInterface::SaveChanges, errorText );
}
void Document::registerView( View *view )
{
if ( !view )
return;
Document *viewDoc = view->viewDocument();
if ( viewDoc )
{
// check if already registered for this document
if ( viewDoc == this )
return;
viewDoc->unregisterView( view );
}
d->m_views.insert( view );
view->d_func()->document = d;
}
void Document::unregisterView( View *view )
{
if ( !view )
return;
Document *viewDoc = view->viewDocument();
if ( !viewDoc || viewDoc != this )
return;
view->d_func()->document = nullptr;
d->m_views.remove( view );
}
QByteArray Document::fontData(const FontInfo &font) const
{
QByteArray result;
if (d->m_generator)
{
QMetaObject::invokeMethod(d->m_generator, "requestFontData", Qt::DirectConnection, Q_ARG(Okular::FontInfo, font), Q_ARG(QByteArray *, &result));
}
return result;
}
-Document::OpenResult Document::openDocumentArchive( const QString & docFile, const QUrl & url, const QString & password )
+ArchiveData *DocumentPrivate::unpackDocumentArchive( const QString &archivePath )
{
QMimeDatabase db;
- const QMimeType mime = db.mimeTypeForFile( docFile, QMimeDatabase::MatchExtension );
+ const QMimeType mime = db.mimeTypeForFile( archivePath, QMimeDatabase::MatchExtension );
if ( !mime.inherits( QStringLiteral("application/vnd.kde.okular-archive") ) )
- return OpenError;
+ return nullptr;
- KZip okularArchive( docFile );
+ KZip okularArchive( archivePath );
if ( !okularArchive.open( QIODevice::ReadOnly ) )
- return OpenError;
+ return nullptr;
const KArchiveDirectory * mainDir = okularArchive.directory();
const KArchiveEntry * mainEntry = mainDir->entry( QStringLiteral("content.xml") );
if ( !mainEntry || !mainEntry->isFile() )
- return OpenError;
+ return nullptr;
std::unique_ptr< QIODevice > mainEntryDevice( static_cast< const KZipFileEntry * >( mainEntry )->createDevice() );
QDomDocument doc;
if ( !doc.setContent( mainEntryDevice.get() ) )
- return OpenError;
+ return nullptr;
mainEntryDevice.reset();
QDomElement root = doc.documentElement();
- if ( root.tagName() != QLatin1String("OkularArchive") )
- return OpenError;
+ if ( root.tagName() != QLatin1String("OkularArchive") )
+ return nullptr;
QString documentFileName;
QString metadataFileName;
QDomElement el = root.firstChild().toElement();
for ( ; !el.isNull(); el = el.nextSibling().toElement() )
{
if ( el.tagName() == QLatin1String("Files") )
{
QDomElement fileEl = el.firstChild().toElement();
for ( ; !fileEl.isNull(); fileEl = fileEl.nextSibling().toElement() )
{
if ( fileEl.tagName() == QLatin1String("DocumentFileName") )
documentFileName = fileEl.text();
else if ( fileEl.tagName() == QLatin1String("MetadataFileName") )
metadataFileName = fileEl.text();
}
}
}
if ( documentFileName.isEmpty() )
- return OpenError;
+ return nullptr;
const KArchiveEntry * docEntry = mainDir->entry( documentFileName );
if ( !docEntry || !docEntry->isFile() )
- return OpenError;
+ return nullptr;
std::unique_ptr< ArchiveData > archiveData( new ArchiveData() );
const int dotPos = documentFileName.indexOf( QLatin1Char('.') );
if ( dotPos != -1 )
archiveData->document.setFileTemplate(QDir::tempPath() + QLatin1String("/okular_XXXXXX") + documentFileName.mid(dotPos));
if ( !archiveData->document.open() )
- return OpenError;
+ return nullptr;
+
+ archiveData->originalFileName = documentFileName;
- QString tempFileName = archiveData->document.fileName();
{
std::unique_ptr< QIODevice > docEntryDevice( static_cast< const KZipFileEntry * >( docEntry )->createDevice() );
copyQIODevice( docEntryDevice.get(), &archiveData->document );
archiveData->document.close();
}
const KArchiveEntry * metadataEntry = mainDir->entry( metadataFileName );
if ( metadataEntry && metadataEntry->isFile() )
{
std::unique_ptr< QIODevice > metadataEntryDevice( static_cast< const KZipFileEntry * >( metadataEntry )->createDevice() );
archiveData->metadataFile.setFileTemplate(QDir::tempPath() + QLatin1String("/okular_XXXXXX.xml"));
if ( archiveData->metadataFile.open() )
{
copyQIODevice( metadataEntryDevice.get(), &archiveData->metadataFile );
archiveData->metadataFile.close();
}
}
+ return archiveData.release();
+}
+
+Document::OpenResult Document::openDocumentArchive( const QString & docFile, const QUrl & url, const QString & password )
+{
+ d->m_archiveData = DocumentPrivate::unpackDocumentArchive( docFile );
+ if ( !d->m_archiveData )
+ return OpenError;
+
+ const QString tempFileName = d->m_archiveData->document.fileName();
+ QMimeDatabase db;
const QMimeType docMime = db.mimeTypeForFile( tempFileName, QMimeDatabase::MatchContent );
- d->m_archiveData = archiveData.get();
- d->m_archivedFileName = documentFileName;
const OpenResult ret = openDocument( tempFileName, url, docMime, password );
- if ( ret == OpenSuccess )
- {
- archiveData.release();
- }
- else
+ if ( ret != OpenSuccess )
{
+ delete d->m_archiveData;
d->m_archiveData = nullptr;
}
return ret;
}
bool Document::saveDocumentArchive( const QString &fileName )
{
if ( !d->m_generator )
return false;
/* If we opened an archive, use the name of original file (eg foo.pdf)
* instead of the archive's one (eg foo.okular) */
- QString docFileName = d->m_archiveData ? d->m_archivedFileName : d->m_url.fileName();
+ QString docFileName = d->m_archiveData ? d->m_archiveData->originalFileName : d->m_url.fileName();
if ( docFileName == QLatin1String( "-" ) )
return false;
QString docPath = d->m_docFileName;
const QFileInfo fi( docPath );
if ( fi.isSymLink() )
docPath = fi.symLinkTarget();
KZip okularArchive( fileName );
if ( !okularArchive.open( QIODevice::WriteOnly ) )
return false;
const KUser user;
#ifndef Q_OS_WIN
const KUserGroup userGroup( user.groupId() );
#else
const KUserGroup userGroup( QString( "" ) );
#endif
QDomDocument contentDoc( QStringLiteral("OkularArchive") );
QDomProcessingInstruction xmlPi = contentDoc.createProcessingInstruction(
QStringLiteral( "xml" ), QStringLiteral( "version=\"1.0\" encoding=\"utf-8\"" ) );
contentDoc.appendChild( xmlPi );
QDomElement root = contentDoc.createElement( QStringLiteral("OkularArchive") );
contentDoc.appendChild( root );
QDomElement filesNode = contentDoc.createElement( QStringLiteral("Files") );
root.appendChild( filesNode );
QDomElement fileNameNode = contentDoc.createElement( QStringLiteral("DocumentFileName") );
filesNode.appendChild( fileNameNode );
fileNameNode.appendChild( contentDoc.createTextNode( docFileName ) );
QDomElement metadataFileNameNode = contentDoc.createElement( QStringLiteral("MetadataFileName") );
filesNode.appendChild( metadataFileNameNode );
metadataFileNameNode.appendChild( contentDoc.createTextNode( QStringLiteral("metadata.xml") ) );
// If the generator can save annotations natively, do it
QTemporaryFile modifiedFile;
bool annotationsSavedNatively = false;
- if ( d->canAddAnnotationsNatively() )
+ bool formsSavedNatively = false;
+ if ( d->canAddAnnotationsNatively() || canSaveChanges( SaveFormsCapability ) )
{
if ( !modifiedFile.open() )
return false;
modifiedFile.close(); // We're only interested in the file name
QString errorText;
if ( saveChanges( modifiedFile.fileName(), &errorText ) )
{
docPath = modifiedFile.fileName(); // Save this instead of the original file
- annotationsSavedNatively = true;
+ annotationsSavedNatively = d->canAddAnnotationsNatively();
+ formsSavedNatively = canSaveChanges( SaveFormsCapability );
}
else
{
qCWarning(OkularCoreDebug) << "saveChanges failed: " << errorText;
qCDebug(OkularCoreDebug) << "Falling back to saving a copy of the original file";
}
}
+ PageItems saveWhat = None;
+ if ( !annotationsSavedNatively )
+ saveWhat |= AnnotationPageItems;
+ if ( !formsSavedNatively )
+ saveWhat |= FormFieldPageItems;
+
QTemporaryFile metadataFile;
- PageItems saveWhat = annotationsSavedNatively ? None : AnnotationPageItems;
if ( !d->savePageDocumentInfo( &metadataFile, saveWhat ) )
return false;
const QByteArray contentDocXml = contentDoc.toByteArray();
const mode_t perm = 0100644;
okularArchive.writeFile( QStringLiteral("content.xml"), contentDocXml, perm,
user.loginName(), userGroup.name() );
okularArchive.addLocalFile( docPath, docFileName );
okularArchive.addLocalFile( metadataFile.fileName(), QStringLiteral("metadata.xml") );
if ( !okularArchive.close() )
return false;
return true;
}
+bool Document::extractArchivedFile( const QString &destFileName )
+{
+ if ( !d->m_archiveData )
+ return false;
+
+ // Remove existing file, if present (QFile::copy doesn't overwrite by itself)
+ QFile::remove( destFileName );
+
+ return d->m_archiveData->document.copy( destFileName );
+}
+
QPrinter::Orientation Document::orientation() const
{
double width, height;
int landscape, portrait;
const Okular::Page *currentPage;
// if some pages are landscape and others are not, the most common wins, as
// QPrinter does not accept a per-page setting
landscape = 0;
portrait = 0;
for (uint i = 0; i < pages(); i++)
{
currentPage = page(i);
width = currentPage->width();
height = currentPage->height();
if (currentPage->orientation() == Okular::Rotation90 || currentPage->orientation() == Okular::Rotation270) qSwap(width, height);
if (width > height) landscape++;
else portrait++;
}
return (landscape > portrait) ? QPrinter::Landscape : QPrinter::Portrait;
}
void Document::setAnnotationEditingEnabled( bool enable )
{
d->m_annotationEditingEnabled = enable;
foreachObserver( notifySetup( d->m_pagesVector, 0 ) );
}
void Document::walletDataForFile( const QString &fileName, QString *walletName, QString *walletFolder, QString *walletKey ) const
{
if (d->m_generator) {
d->m_generator->walletDataForFile( fileName, walletName, walletFolder, walletKey );
} else if (d->m_walletGenerator) {
d->m_walletGenerator->walletDataForFile( fileName, walletName, walletFolder, walletKey );
}
}
+bool Document::isDocdataMigrationNeeded() const
+{
+ return d->m_docdataMigrationNeeded;
+}
+
+void Document::docdataMigrationDone()
+{
+ if (d->m_docdataMigrationNeeded)
+ {
+ d->m_docdataMigrationNeeded = false;
+ foreachObserver( notifySetup( d->m_pagesVector, 0 ) );
+ }
+}
+
QAbstractItemModel * Document::layersModel() const
{
return d->m_generator ? d->m_generator->layersModel() : nullptr;
}
void DocumentPrivate::requestDone( PixmapRequest * req )
{
if ( !req )
return;
if ( !m_generator || m_closingLoop )
{
m_pixmapRequestsMutex.lock();
m_executingPixmapRequests.removeAll( req );
m_pixmapRequestsMutex.unlock();
delete req;
if ( m_closingLoop )
m_closingLoop->exit();
return;
}
#ifndef NDEBUG
if ( !m_generator->canGeneratePixmap() )
qCDebug(OkularCoreDebug) << "requestDone with generator not in READY state.";
#endif
// [MEM] 1.1 find and remove a previous entry for the same page and id
QLinkedList< AllocatedPixmap * >::iterator aIt = m_allocatedPixmaps.begin();
QLinkedList< AllocatedPixmap * >::iterator aEnd = m_allocatedPixmaps.end();
for ( ; aIt != aEnd; ++aIt )
if ( (*aIt)->page == req->pageNumber() && (*aIt)->observer == req->observer() )
{
AllocatedPixmap * p = *aIt;
m_allocatedPixmaps.erase( aIt );
m_allocatedPixmapsTotalMemory -= p->memory;
delete p;
break;
}
DocumentObserver *observer = req->observer();
if ( m_observers.contains(observer) )
{
// [MEM] 1.2 append memory allocation descriptor to the FIFO
qulonglong memoryBytes = 0;
const TilesManager *tm = req->d->tilesManager();
if ( tm )
memoryBytes = tm->totalMemory();
else
memoryBytes = 4 * req->width() * req->height();
AllocatedPixmap * memoryPage = new AllocatedPixmap( req->observer(), req->pageNumber(), memoryBytes );
m_allocatedPixmaps.append( memoryPage );
m_allocatedPixmapsTotalMemory += memoryBytes;
// 2. notify an observer that its pixmap changed
observer->notifyPageChanged( req->pageNumber(), DocumentObserver::Pixmap );
}
#ifndef NDEBUG
else
qCWarning(OkularCoreDebug) << "Receiving a done request for the defunct observer" << observer;
#endif
// 3. delete request
m_pixmapRequestsMutex.lock();
m_executingPixmapRequests.removeAll( req );
m_pixmapRequestsMutex.unlock();
delete req;
// 4. start a new generation if some is pending
m_pixmapRequestsMutex.lock();
bool hasPixmaps = !m_pixmapRequestsStack.isEmpty();
m_pixmapRequestsMutex.unlock();
if ( hasPixmaps )
sendGeneratorPixmapRequest();
}
void DocumentPrivate::setPageBoundingBox( int page, const NormalizedRect& boundingBox )
{
Page * kp = m_pagesVector[ page ];
if ( !m_generator || !kp )
return;
if ( kp->boundingBox() == boundingBox )
return;
kp->setBoundingBox( boundingBox );
// notify observers about the change
foreachObserverD( notifyPageChanged( page, DocumentObserver::BoundingBox ) );
// TODO: For generators that generate the bbox by pixmap scanning, if the first generated pixmap is very small, the bounding box will forever be inaccurate.
// TODO: Crop computation should also consider annotations, actions, etc. to make sure they're not cropped away.
// TODO: Help compute bounding box for generators that create a QPixmap without a QImage, like text and plucker.
// TODO: Don't compute the bounding box if no one needs it (e.g., Trim Borders is off).
}
void DocumentPrivate::calculateMaxTextPages()
{
int multipliers = qMax(1, qRound(getTotalMemory() / 536870912.0)); // 512 MB
switch (SettingsCore::memoryLevel())
{
case SettingsCore::EnumMemoryLevel::Low:
m_maxAllocatedTextPages = multipliers * 2;
break;
case SettingsCore::EnumMemoryLevel::Normal:
m_maxAllocatedTextPages = multipliers * 50;
break;
case SettingsCore::EnumMemoryLevel::Aggressive:
m_maxAllocatedTextPages = multipliers * 250;
break;
case SettingsCore::EnumMemoryLevel::Greedy:
m_maxAllocatedTextPages = multipliers * 1250;
break;
}
}
void DocumentPrivate::textGenerationDone( Page *page )
{
if ( !m_pageController ) return;
// 1. If we reached the cache limit, delete the first text page from the fifo
if (m_allocatedTextPagesFifo.size() == m_maxAllocatedTextPages)
{
int pageToKick = m_allocatedTextPagesFifo.takeFirst();
if (pageToKick != page->number()) // this should never happen but better be safe than sorry
{
m_pagesVector.at(pageToKick)->setTextPage( nullptr ); // deletes the textpage
}
}
// 2. Add the page to the fifo of generated text pages
m_allocatedTextPagesFifo.append( page->number() );
}
void Document::setRotation( int r )
{
d->setRotationInternal( r, true );
}
void DocumentPrivate::setRotationInternal( int r, bool notify )
{
Rotation rotation = (Rotation)r;
if ( !m_generator || ( m_rotation == rotation ) )
return;
// tell the pages to rotate
QVector< Okular::Page * >::const_iterator pIt = m_pagesVector.constBegin();
QVector< Okular::Page * >::const_iterator pEnd = m_pagesVector.constEnd();
for ( ; pIt != pEnd; ++pIt )
(*pIt)->d->rotateAt( rotation );
if ( notify )
{
// notify the generator that the current rotation has changed
m_generator->rotationChanged( rotation, m_rotation );
}
// set the new rotation
m_rotation = rotation;
if ( notify )
{
foreachObserverD( notifySetup( m_pagesVector, DocumentObserver::NewLayoutForPages ) );
foreachObserverD( notifyContentsCleared( DocumentObserver::Pixmap | DocumentObserver::Highlights | DocumentObserver::Annotations ) );
}
qCDebug(OkularCoreDebug) << "Rotated:" << r;
}
void Document::setPageSize( const PageSize &size )
{
if ( !d->m_generator || !d->m_generator->hasFeature( Generator::PageSizes ) )
return;
if ( d->m_pageSizes.isEmpty() )
d->m_pageSizes = d->m_generator->pageSizes();
int sizeid = d->m_pageSizes.indexOf( size );
if ( sizeid == -1 )
return;
// tell the pages to change size
QVector< Okular::Page * >::const_iterator pIt = d->m_pagesVector.constBegin();
QVector< Okular::Page * >::const_iterator pEnd = d->m_pagesVector.constEnd();
for ( ; pIt != pEnd; ++pIt )
(*pIt)->d->changeSize( size );
// clear 'memory allocation' descriptors
qDeleteAll( d->m_allocatedPixmaps );
d->m_allocatedPixmaps.clear();
d->m_allocatedPixmapsTotalMemory = 0;
// notify the generator that the current page size has changed
d->m_generator->pageSizeChanged( size, d->m_pageSize );
// set the new page size
d->m_pageSize = size;
foreachObserver( notifySetup( d->m_pagesVector, DocumentObserver::NewLayoutForPages ) );
foreachObserver( notifyContentsCleared( DocumentObserver::Pixmap | DocumentObserver::Highlights ) );
qCDebug(OkularCoreDebug) << "New PageSize id:" << sizeid;
}
/** DocumentViewport **/
DocumentViewport::DocumentViewport( int n )
: pageNumber( n )
{
// default settings
rePos.enabled = false;
rePos.normalizedX = 0.5;
rePos.normalizedY = 0.0;
rePos.pos = Center;
autoFit.enabled = false;
autoFit.width = false;
autoFit.height = false;
}
DocumentViewport::DocumentViewport( const QString & xmlDesc )
: pageNumber( -1 )
{
// default settings (maybe overridden below)
rePos.enabled = false;
rePos.normalizedX = 0.5;
rePos.normalizedY = 0.0;
rePos.pos = Center;
autoFit.enabled = false;
autoFit.width = false;
autoFit.height = false;
// check for string presence
if ( xmlDesc.isEmpty() )
return;
// decode the string
bool ok;
int field = 0;
QString token = xmlDesc.section( QLatin1Char(';'), field, field );
while ( !token.isEmpty() )
{
// decode the current token
if ( field == 0 )
{
pageNumber = token.toInt( &ok );
if ( !ok )
return;
}
else if ( token.startsWith( QLatin1String("C1") ) )
{
rePos.enabled = true;
rePos.normalizedX = token.section( QLatin1Char(':'), 1, 1 ).toDouble();
rePos.normalizedY = token.section( QLatin1Char(':'), 2, 2 ).toDouble();
rePos.pos = Center;
}
else if ( token.startsWith( QLatin1String("C2") ) )
{
rePos.enabled = true;
rePos.normalizedX = token.section( QLatin1Char(':'), 1, 1 ).toDouble();
rePos.normalizedY = token.section( QLatin1Char(':'), 2, 2 ).toDouble();
if (token.section( QLatin1Char(':'), 3, 3 ).toInt() == 1) rePos.pos = Center;
else rePos.pos = TopLeft;
}
else if ( token.startsWith( QLatin1String("AF1") ) )
{
autoFit.enabled = true;
autoFit.width = token.section( QLatin1Char(':'), 1, 1 ) == QLatin1String("T");
autoFit.height = token.section( QLatin1Char(':'), 2, 2 ) == QLatin1String("T");
}
// proceed tokenizing string
field++;
token = xmlDesc.section( QLatin1Char(';'), field, field );
}
}
QString DocumentViewport::toString() const
{
// start string with page number
QString s = QString::number( pageNumber );
// if has center coordinates, save them on string
if ( rePos.enabled )
s += QStringLiteral( ";C2:" ) + QString::number( rePos.normalizedX ) +
QLatin1Char(':') + QString::number( rePos.normalizedY ) +
QLatin1Char(':') + QString::number( rePos.pos );
// if has autofit enabled, save its state on string
if ( autoFit.enabled )
s += QStringLiteral( ";AF1:" ) + (autoFit.width ? QLatin1Char('T') : QLatin1Char('F')) +
QLatin1Char(':') + (autoFit.height ? QLatin1Char('T') : QLatin1Char('F'));
return s;
}
bool DocumentViewport::isValid() const
{
return pageNumber >= 0;
}
bool DocumentViewport::operator==( const DocumentViewport & vp ) const
{
bool equal = ( pageNumber == vp.pageNumber ) &&
( rePos.enabled == vp.rePos.enabled ) &&
( autoFit.enabled == vp.autoFit.enabled );
if ( !equal )
return false;
if ( rePos.enabled &&
(( rePos.normalizedX != vp.rePos.normalizedX) ||
( rePos.normalizedY != vp.rePos.normalizedY ) || rePos.pos != vp.rePos.pos) )
return false;
if ( autoFit.enabled &&
(( autoFit.width != vp.autoFit.width ) ||
( autoFit.height != vp.autoFit.height )) )
return false;
return true;
}
bool DocumentViewport::operator<( const DocumentViewport & vp ) const
{
// TODO: Check autoFit and Position
if ( pageNumber != vp.pageNumber )
return pageNumber < vp.pageNumber;
if ( !rePos.enabled && vp.rePos.enabled )
return true;
if ( !vp.rePos.enabled )
return false;
if ( rePos.normalizedY != vp.rePos.normalizedY )
return rePos.normalizedY < vp.rePos.normalizedY;
return rePos.normalizedX < vp.rePos.normalizedX;
}
/** DocumentInfo **/
DocumentInfo::DocumentInfo() : d(new DocumentInfoPrivate())
{
}
DocumentInfo::DocumentInfo(const DocumentInfo &info) : d(new DocumentInfoPrivate())
{
*this = info;
}
DocumentInfo& DocumentInfo::operator=(const DocumentInfo &info)
{
d->values = info.d->values;
d->titles = info.d->titles;
return *this;
}
DocumentInfo::~DocumentInfo()
{
delete d;
}
void DocumentInfo::set( const QString &key, const QString &value, const QString &title )
{
d->values[ key ] = value;
d->titles[ key ] = title;
}
void DocumentInfo::set( Key key, const QString &value )
{
d->values[ getKeyString( key ) ] = value;
}
QStringList DocumentInfo::keys() const
{
return d->values.keys();
}
QString DocumentInfo::get( Key key ) const
{
return get( getKeyString( key ) );
}
QString DocumentInfo::get( const QString &key ) const
{
return d->values[ key ];
}
QString DocumentInfo::getKeyString( Key key ) //const
{
switch ( key ) {
case Title:
return QStringLiteral("title");
break;
case Subject:
return QStringLiteral("subject");
break;
case Description:
return QStringLiteral("description");
break;
case Author:
return QStringLiteral("author");
break;
case Creator:
return QStringLiteral("creator");
break;
case Producer:
return QStringLiteral("producer");
break;
case Copyright:
return QStringLiteral("copyright");
break;
case Pages:
return QStringLiteral("pages");
break;
case CreationDate:
return QStringLiteral("creationDate");
break;
case ModificationDate:
return QStringLiteral("modificationDate");
break;
case MimeType:
return QStringLiteral("mimeType");
break;
case Category:
return QStringLiteral("category");
break;
case Keywords:
return QStringLiteral("keywords");
break;
case FilePath:
return QStringLiteral("filePath");
break;
case DocumentSize:
return QStringLiteral("documentSize");
break;
case PagesSize:
return QStringLiteral("pageSize");
break;
default:
qCWarning(OkularCoreDebug) << "Unknown" << key;
return QString();
break;
}
}
DocumentInfo::Key DocumentInfo::getKeyFromString( const QString &key ) //const
{
if (key == QLatin1String("title")) return Title;
else if (key == QLatin1String("subject")) return Subject;
else if (key == QLatin1String("description")) return Description;
else if (key == QLatin1String("author")) return Author;
else if (key == QLatin1String("creator")) return Creator;
else if (key == QLatin1String("producer")) return Producer;
else if (key == QLatin1String("copyright")) return Copyright;
else if (key == QLatin1String("pages")) return Pages;
else if (key == QLatin1String("creationDate")) return CreationDate;
else if (key == QLatin1String("modificationDate")) return ModificationDate;
else if (key == QLatin1String("mimeType")) return MimeType;
else if (key == QLatin1String("category")) return Category;
else if (key == QLatin1String("keywords")) return Keywords;
else if (key == QLatin1String("filePath")) return FilePath;
else if (key == QLatin1String("documentSize")) return DocumentSize;
else if (key == QLatin1String("pageSize")) return PagesSize;
else return Invalid;
}
QString DocumentInfo::getKeyTitle( Key key ) //const
{
switch ( key ) {
case Title:
return i18n( "Title" );
break;
case Subject:
return i18n( "Subject" );
break;
case Description:
return i18n( "Description" );
break;
case Author:
return i18n( "Author" );
break;
case Creator:
return i18n( "Creator" );
break;
case Producer:
return i18n( "Producer" );
break;
case Copyright:
return i18n( "Copyright" );
break;
case Pages:
return i18n( "Pages" );
break;
case CreationDate:
return i18n( "Created" );
break;
case ModificationDate:
return i18n( "Modified" );
break;
case MimeType:
return i18n( "Mime Type" );
break;
case Category:
return i18n( "Category" );
break;
case Keywords:
return i18n( "Keywords" );
break;
case FilePath:
return i18n( "File Path" );
break;
case DocumentSize:
return i18n( "File Size" );
break;
case PagesSize:
return i18n("Page Size");
break;
default:
return QString();
break;
}
}
QString DocumentInfo::getKeyTitle( const QString &key ) const
{
QString title = getKeyTitle ( getKeyFromString( key ) );
if ( title.isEmpty() )
title = d->titles[ key ];
return title;
}
/** DocumentSynopsis **/
DocumentSynopsis::DocumentSynopsis()
: QDomDocument( QStringLiteral("DocumentSynopsis") )
{
// void implementation, only subclassed for naming
}
DocumentSynopsis::DocumentSynopsis( const QDomDocument &document )
: QDomDocument( document )
{
}
/** EmbeddedFile **/
EmbeddedFile::EmbeddedFile()
{
}
EmbeddedFile::~EmbeddedFile()
{
}
VisiblePageRect::VisiblePageRect( int page, const NormalizedRect &rectangle )
: pageNumber( page ), rect( rectangle )
{
}
#undef foreachObserver
#undef foreachObserverD
#include "moc_document.cpp"
/* kate: replace-tabs on; indent-width 4; */
diff --git a/core/document.h b/core/document.h
index a52dedd20..f996f41f6 100644
--- a/core/document.h
+++ b/core/document.h
@@ -1,1343 +1,1422 @@
/***************************************************************************
* Copyright (C) 2004-2005 by Enrico Ros *
* Copyright (C) 2004-2008 by Albert Astals Cid *
+ * Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group *
+ * company, info@kdab.com. Work sponsored by the *
+ * LiMux project of the city of Munich *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#ifndef _OKULAR_DOCUMENT_H_
#define _OKULAR_DOCUMENT_H_
#include "okularcore_export.h"
#include "area.h"
#include "global.h"
#include "pagesize.h"
#include
#include
#include
#include
#include
#include
#include
class QPrintDialog;
class KBookmark;
class KConfigDialog;
class KPluginMetaData;
class KXMLGUIClient;
class DocumentItem;
class QAbstractItemModel;
namespace Okular {
class Annotation;
class BookmarkManager;
class DocumentInfoPrivate;
class DocumentObserver;
class DocumentPrivate;
class DocumentSynopsis;
class DocumentViewport;
class EmbeddedFile;
class ExportFormat;
class FontInfo;
class FormFieldText;
class FormFieldButton;
class FormFieldChoice;
class Generator;
class Action;
class MovieAction;
class Page;
class PixmapRequest;
class RenditionAction;
class SourceReference;
class View;
class VisiblePageRect;
/** IDs for seaches. Globally defined here. **/
#define PART_SEARCH_ID 1
#define PAGEVIEW_SEARCH_ID 2
#define SW_SEARCH_ID 3
#define PRESENTATION_SEARCH_ID 4
/**
* The DocumentInfo structure can be filled in by generators to display
* metadata about the currently opened file.
*/
class OKULARCORE_EXPORT DocumentInfo
{
friend class Document;
public:
/**
* The list of predefined keys.
*/
enum Key {
Title, ///< The title of the document
Subject, ///< The subject of the document
Description, ///< The description of the document
Author, ///< The author of the document
Creator, ///< The creator of the document (this can be different from the author)
Producer, ///< The producer of the document (e.g. some software)
Copyright, ///< The copyright of the document
Pages, ///< The number of pages of the document
CreationDate, ///< The date of creation of the document
ModificationDate, ///< The date of last modification of the document
MimeType, ///< The mime type of the document
Category, ///< The category of the document
Keywords, ///< The keywords which describe the content of the document
FilePath, ///< The path of the file @since 0.10 (KDE 4.4)
DocumentSize, ///< The size of the document @since 0.10 (KDE 4.4)
PagesSize, ///< The size of the pages (if all pages have the same size) @since 0.10 (KDE 4.4)
CustomKeys, ///< All the custom keys the generator supports @since 0.21
Invalid ///< An invalid key @since 0.21. It will always be the last element in the enum
};
/**
* Creates a new document info.
*/
DocumentInfo();
DocumentInfo(const DocumentInfo &info);
DocumentInfo& operator=( const DocumentInfo& );
~DocumentInfo();
/**
* Returns all the keys present in this DocumentInfo
*
* @since 0.21
*/
QStringList keys() const;
/**
* Returns the value for a given key or an null string when the
* key doesn't exist.
*/
QString get( Key key ) const;
/**
* Returns the value for a given key or an null string when the
* key doesn't exist.
*/
QString get( const QString &key ) const;
/**
* Sets a value for a custom key. The title should be an i18n'ed
* string, since it's used in the document information dialog.
*/
void set( const QString &key, const QString &value,
const QString &title = QString() );
/**
* Sets a value for a special key. The title should be an i18n'ed
* string, since it's used in the document information dialog.
*/
void set( Key key, const QString &value );
/**
* Returns the user visible string for the given key
* Takes into account keys added by the set() that takes a QString
*
* @since 0.21
*/
QString getKeyTitle( const QString &key ) const;
/**
* Returns the internal string for the given key
* @since 0.10 (KDE 4.4)
*/
static QString getKeyString( Key key );
/**
* Returns the user visible string for the given key
* @since 0.10 (KDE 4.4)
*/
static QString getKeyTitle( Key key );
/**
* Returns the Key from a string key
* @since 0.21
*/
static Key getKeyFromString( const QString &key );
private:
DocumentInfoPrivate *d;
};
/**
* @short The Document. Heart of everything. Actions take place here.
*
* The Document is the main object in Okular. All views query the Document to
* get data/properties or even for accessing pages (in a 'const' way).
*
* It is designed to keep it detached from the document type (pdf, ps, you
* name it..) so whenever you want to get some data, it asks its internal
* generators to do the job and return results in a format-indepedent way.
*
* Apart from the generator (the currently running one) the document stores
* all the Pages ('Page' class) of the current document in a vector and
* notifies all the registered DocumentObservers when some content changes.
*
* For a better understanding of hierarchies @see README.internals.png
* @see DocumentObserver, Page
*/
class OKULARCORE_EXPORT Document : public QObject
{
Q_OBJECT
public:
/**
* Creates a new document with the given @p widget as widget to relay GUI things (messageboxes, ...).
*/
explicit Document( QWidget *widget );
/**
* Destroys the document.
*/
~Document();
/**
* Describes the result of an open document operation.
* @since 0.20 (KDE 4.14)
*/
enum OpenResult
{
OpenSuccess, //< The document was opened successfully
OpenError, //< The document failed to open
OpenNeedsPassword //< The document needs a password to be opened or the one provided is not the correct
};
/**
* Opens the document.
* @since 0.20 (KDE 4.14)
*/
OpenResult openDocument( const QString & docFile, const QUrl & url, const QMimeType &mime, const QString &password = QString() );
/**
* Closes the document.
*/
void closeDocument();
/**
* Registers a new @p observer for the document.
*/
void addObserver( DocumentObserver *observer );
/**
* Unregisters the given @p observer for the document.
*/
void removeObserver( DocumentObserver *observer );
/**
* Reparses and applies the configuration.
*/
void reparseConfig();
/**
* Returns whether the document is currently opened.
*/
bool isOpened() const;
/**
* Returns the meta data of the document.
*/
DocumentInfo documentInfo() const;
/**
* Returns the asked set of meta data of the document. The result may contain more
* metadata than the one asked for.
*/
DocumentInfo documentInfo( const QSet &keys ) const;
/**
* Returns the table of content of the document or 0 if no
* table of content is available.
*/
const DocumentSynopsis * documentSynopsis() const;
/**
* Starts the reading of the information about the fonts in the
* document, if available.
*
* The results as well the end of the reading is notified using the
* signals gotFont(), fontReadingProgress() and fontReadingEnded()
*/
void startFontReading();
/**
* Force the termination of the reading of the information about the
* fonts in the document, if running.
*/
void stopFontReading();
/**
* Whether the current document can provide information about the
* fonts used in it.
*/
bool canProvideFontInformation() const;
/**
* Returns the list of embedded files or 0 if no embedded files
* are available.
*/
const QList *embeddedFiles() const;
/**
* Returns the page object for the given page @p number or 0
* if the number is out of range.
*/
const Page * page( int number ) const;
/**
* Returns the current viewport of the document.
*/
const DocumentViewport & viewport() const;
/**
* Sets the list of visible page rectangles.
* @see VisiblePageRect
*/
void setVisiblePageRects( const QVector< VisiblePageRect * > & visiblePageRects, DocumentObserver *excludeObserver = nullptr );
/**
* Returns the list of visible page rectangles.
*/
const QVector< VisiblePageRect * > & visiblePageRects() const;
/**
* Returns the number of the current page.
*/
uint currentPage() const;
/**
* Returns the number of pages of the document.
*/
uint pages() const;
/**
* Returns the url of the currently opened document.
*/
QUrl currentDocument() const;
/**
* Returns whether the given @p action is allowed in the document.
* @see @ref Permission
*/
bool isAllowed( Permission action ) const;
/**
* Returns whether the document supports searching.
*/
bool supportsSearching() const;
/**
* Returns whether the document supports the listing of page sizes.
*/
bool supportsPageSizes() const;
/**
* Returns whether the current document supports tiles
*
* @since 0.16 (KDE 4.10)
*/
bool supportsTiles() const;
/**
* Returns the list of supported page sizes or an empty list if this
* feature is not available.
* @see supportsPageSizes()
*/
PageSize::List pageSizes() const;
/**
* Returns whether the document supports the export to ASCII text.
*/
bool canExportToText() const;
/**
* Exports the document as ASCII text and saves it under @p fileName.
*/
bool exportToText( const QString& fileName ) const;
/**
* Returns the list of supported export formats.
* @see ExportFormat
*/
QList exportFormats() const;
/**
* Exports the document in the given @p format and saves it under @p fileName.
*/
bool exportTo( const QString& fileName, const ExportFormat& format ) const;
/**
* Returns whether the document history is at the begin.
*/
bool historyAtBegin() const;
/**
* Returns whether the document history is at the end.
*/
bool historyAtEnd() const;
/**
* Returns the meta data for the given @p key and @p option or an empty variant
* if the key doesn't exists.
*/
QVariant metaData( const QString & key, const QVariant & option = QVariant() ) const;
/**
* Returns the current rotation of the document.
*/
Rotation rotation() const;
/**
* If all pages have the same size this method returns it, if the page sizes
* differ an empty size object is returned.
*/
QSizeF allPagesSize() const;
/**
* Returns the size string for the given @p page or an empty string
* if the page is out of range.
*/
QString pageSizeString( int page ) const;
/**
* Returns the gui client of the generator, if it provides one.
*/
KXMLGUIClient* guiClient();
/**
* Sets the current document viewport to the given @p page.
*
* @param excludeObserver The observer ids which shouldn't be effected by this change.
* @param smoothMove Whether the move shall be animated smoothly.
*/
void setViewportPage( int page, DocumentObserver *excludeObserver = nullptr, bool smoothMove = false );
/**
* Sets the current document viewport to the given @p viewport.
*
* @param excludeObserver The observer which shouldn't be effected by this change.
* @param smoothMove Whether the move shall be animated smoothly.
*/
void setViewport( const DocumentViewport &viewport, DocumentObserver *excludeObserver = nullptr, bool smoothMove = false );
/**
* Sets the current document viewport to the next viewport in the
* viewport history.
*/
void setPrevViewport();
/**
* Sets the current document viewport to the previous viewport in the
* viewport history.
*/
void setNextViewport();
/**
* Sets the next @p viewport in the viewport history.
*/
void setNextDocumentViewport( const DocumentViewport &viewport );
/**
* Sets the next @p namedDestination in the viewport history.
*
* @since 0.9 (KDE 4.3)
*/
void setNextDocumentDestination( const QString &namedDestination );
/**
* Sets the zoom for the current document.
*/
void setZoom( int factor, DocumentObserver *excludeObserver = nullptr );
/**
* Describes the possible options for the pixmap requests.
*/
enum PixmapRequestFlag
{
NoOption = 0, ///< No options
RemoveAllPrevious = 1 ///< Remove all the previous requests, even for non requested page pixmaps
};
Q_DECLARE_FLAGS( PixmapRequestFlags, PixmapRequestFlag )
/**
* Sends @p requests for pixmap generation.
*
* The same as requestPixmaps( requests, RemoveAllPrevious );
*/
void requestPixmaps( const QLinkedList &requests );
/**
* Sends @p requests for pixmap generation.
*
* @param reqOptions the options for the request
*
* @since 0.7 (KDE 4.1)
*/
void requestPixmaps( const QLinkedList &requests, PixmapRequestFlags reqOptions );
/**
* Sends a request for text page generation for the given page @p number.
*/
void requestTextPage( uint number );
/**
* Adds a new @p annotation to the given @p page.
*/
void addPageAnnotation( int page, Annotation *annotation );
/**
* Tests if the @p annotation can be modified
*
* @since 0.15 (KDE 4.9)
*/
bool canModifyPageAnnotation( const Annotation * annotation ) const;
/**
* Prepares to modify the properties of the given @p annotation.
* Must be called before the annotation's properties are modified
*
* @since 0.17 (KDE 4.11)
*/
void prepareToModifyAnnotationProperties( Annotation * annotation );
/**
* Modifies the given @p annotation on the given @p page.
* Must be preceded by a call to prepareToModifyAnnotationProperties before
* the annotation's properties are modified
*
* @since 0.17 (KDE 4.11)
*/
void modifyPageAnnotationProperties( int page, Annotation * annotation );
/**
* Translates the position of the given @p annotation on the given @p page by a distance @p delta in normalized coordinates.
*
* Consecutive translations applied to the same @p annotation are merged together on the undo stack if the
* BeingMoved flag is set on the @P annotation.
*
* @since 0.17 (KDE 4.11)
*/
void translatePageAnnotation( int page, Annotation *annotation, const Okular::NormalizedPoint & delta );
/**
* Adjusts the position of the top-left and bottom-right corners of given @p annotation on the given @p page.
*
* Can be used to implement resize functionality.
* @p delta1 in normalized coordinates is added to top-left.
* @p delta2 in normalized coordinates is added to bottom-right.
*
* Consecutive adjustments applied to the same @p annotation are merged together on the undo stack if the
* BeingResized flag is set on the @P annotation.
*
* @since 1.1.0
*/
void adjustPageAnnotation( int page, Annotation * annotation, const Okular::NormalizedPoint & delta1, const Okular::NormalizedPoint & delta2 );
/**
* Edits the plain text contents of the given @p annotation on the given @p page.
*
* The contents are set to @p newContents with cursor position @p newCursorPos.
* The previous cursor position @p prevCursorPos and previous anchor position @p prevAnchorPos
* must also be supplied so that they can be restored if the edit action is undone.
*
* The Annotation's internal contents should not be modified prior to calling this method.
*
* @since 0.17 (KDE 4.11)
*/
void editPageAnnotationContents( int page, Annotation* annotation, const QString & newContents,
int newCursorPos, int prevCursorPos, int prevAnchorPos );
/**
* Tests if the @p annotation can be removed
*
* @since 0.15 (KDE 4.9)
*/
bool canRemovePageAnnotation( const Annotation * annotation ) const;
/**
* Removes the given @p annotation from the given @p page.
*/
void removePageAnnotation( int page, Annotation *annotation );
/**
* Removes the given @p annotations from the given @p page.
*/
void removePageAnnotations( int page, const QList &annotations );
/**
* Sets the text selection for the given @p page.
*
* @param rect The rectangle of the selection.
* @param color The color of the selection.
*/
void setPageTextSelection( int page, RegularAreaRect * rect, const QColor & color );
/**
* Returns true if there is an undo command available; otherwise returns false.
* @since 0.17 (KDE 4.11)
*/
bool canUndo() const;
/**
* Returns true if there is a redo command available; otherwise returns false.
* @since 0.17 (KDE 4.11)
*/
bool canRedo() const;
/**
* Describes the possible search types.
*/
enum SearchType
{
NextMatch, ///< Search next match
PreviousMatch, ///< Search previous match
AllDocument, ///< Search complete document
GoogleAll, ///< Search complete document (all words in google style)
GoogleAny ///< Search complete document (any words in google style)
};
/**
* Describes how search ended
*/
// TODO remove EndOfDocumentReached when we break API
enum SearchStatus
{
MatchFound, ///< Any match was found
NoMatchFound, ///< No match was found
SearchCancelled, ///< The search was cancelled
EndOfDocumentReached ///< This is not ever emitted since 1.3. The end of document was reached without any match @since 0.20 (KDE 4.14)
};
/**
* Searches the given @p text in the document.
*
* @param searchID The unique id for this search request.
* @param fromStart Whether the search should be started at begin of the document.
* @param caseSensitivity Whether the search is case sensitive.
* @param type The type of the search. @ref SearchType
* @param moveViewport Whether the viewport shall be moved to the position of the matches.
* @param color The highlighting color of the matches.
*/
void searchText( int searchID, const QString & text, bool fromStart, Qt::CaseSensitivity caseSensitivity,
SearchType type, bool moveViewport, const QColor & color );
/**
* Continues the search for the given @p searchID.
*/
void continueSearch( int searchID );
/**
* Continues the search for the given @p searchID, optionally specifying
* a new type for the search.
*
* @since 0.7 (KDE 4.1)
*/
void continueSearch( int searchID, SearchType type );
/**
* Resets the search for the given @p searchID.
*/
void resetSearch( int searchID );
/**
* Returns the bookmark manager of the document.
*/
BookmarkManager * bookmarkManager() const;
/**
* Processes the given @p action.
*/
void processAction( const Action *action );
/**
* Returns a list of the bookmarked.pages
*/
QList bookmarkedPageList() const;
/**
* Returns the range of the bookmarked.pages
*/
QString bookmarkedPageRange() const;
/**
* Processes/Executes the given source @p reference.
*/
void processSourceReference( const SourceReference *reference );
/**
* Returns whether the document can configure the printer itself.
*/
bool canConfigurePrinter() const;
/**
* What type of printing a document supports
*/
enum PrintingType
{
NoPrinting, ///< Printing Not Supported
NativePrinting, ///< Native Cross-Platform Printing
PostscriptPrinting ///< Postscript file printing
};
/**
* Returns what sort of printing the document supports:
* Native, Postscript, None
*/
PrintingType printingSupport() const;
/**
* Returns whether the document supports printing to both PDF and PS files.
*/
bool supportsPrintToFile() const;
/**
* Prints the document to the given @p printer.
*/
bool print( QPrinter &printer );
/**
* Returns the last print error in case print() failed
* @since 0.11 (KDE 4.5)
*/
QString printError() const;
/**
* Returns a custom printer configuration page or 0 if no
* custom printer configuration page is available.
*/
QWidget* printConfigurationWidget() const;
/**
* Fill the KConfigDialog @p dialog with the setting pages of the
* generators.
*/
void fillConfigDialog( KConfigDialog * dialog );
/**
* Returns the number of generators that have a configuration widget.
*/
int configurableGenerators() const;
/**
* Returns the list with the supported MIME types.
*/
QStringList supportedMimeTypes() const;
/**
* Returns the metadata associated with the generator. May be invalid.
*/
KPluginMetaData generatorInfo() const;
+ /**
+ * Returns whether the generator supports hot-swapping the current file
+ * with another identical file
+ *
+ * @since 1.3
+ */
+ bool canSwapBackingFile() const;
+
+ /**
+ * Reload the document from a new location, without any visible effect
+ * to the user.
+ *
+ * The new file must be identical to the current one or, if the document
+ * has been modified (eg the user edited forms and annotations), the new
+ * document must have these changes too. For example, you can call
+ * saveChanges first to write changes to a file and then swapBackingFile
+ * to switch to the new location.
+ *
+ * @since 1.3
+ */
+ bool swapBackingFile( const QString &newFileName, const QUrl &url );
+
+ /**
+ * Same as swapBackingFile, but newFileName must be a .okular file.
+ *
+ * The new file must be identical to the current one or, if the document
+ * has been modified (eg the user edited forms and annotations), the new
+ * document must have these changes too. For example, you can call
+ * saveDocumentArchive first to write changes to a file and then
+ * swapBackingFileArchive to switch to the new location.
+ *
+ * @since 1.3
+ */
+ bool swapBackingFileArchive( const QString &newFileName, const QUrl &url );
+
+ /**
+ * Sets the history to be clean
+ *
+ * @since 1.3
+ */
+ void setHistoryClean( bool clean );
+
/**
* Saving capabilities. Their availability varies according to the
* underlying generator and/or the document type.
*
* @see canSaveChanges (SaveCapability)
* @since 0.15 (KDE 4.9)
*/
enum SaveCapability
{
SaveFormsCapability = 1, ///< Can save form changes
SaveAnnotationsCapability = 2 ///< Can save annotation changes
};
/**
* Returns whether it's possible to save a given category of changes to
* another document.
*
* @since 0.15 (KDE 4.9)
*/
bool canSaveChanges( SaveCapability cap ) const;
/**
* Returns whether the changes to the document (modified annotations,
* values in form fields, etc) can be saved to another document.
*
* Equivalent to the logical OR of canSaveChanges(SaveCapability) for
* each capability.
*
* @since 0.7 (KDE 4.1)
*/
bool canSaveChanges() const;
/**
* Save the document and the optional changes to it to the specified
* @p fileName.
*
* @since 0.7 (KDE 4.1)
*/
bool saveChanges( const QString &fileName );
/**
* Save the document and the optional changes to it to the specified
* @p fileName and returns a @p errorText if fails.
*
* @since 0.10 (KDE 4.4)
*/
bool saveChanges( const QString &fileName, QString *errorText );
/**
* Register the specified @p view for the current document.
*
* It is unregistered from the previous document, if any.
*
* @since 0.7 (KDE 4.1)
*/
void registerView( View *view );
/**
* Unregister the specified @p view from the current document.
*
* @since 0.7 (KDE 4.1)
*/
void unregisterView( View *view );
/**
* Gets the font data for the given font
*
* @since 0.8 (KDE 4.2)
*/
QByteArray fontData(const FontInfo &font) const;
/**
* Opens a document archive.
*
* @since 0.20 (KDE 4.14)
*/
OpenResult openDocumentArchive( const QString & docFile, const QUrl & url, const QString &password = QString() );
/**
* Saves a document archive.
*
* @since 0.8 (KDE 4.2)
*/
bool saveDocumentArchive( const QString &fileName );
+ /**
+ * Extract the document file from the current archive.
+ *
+ * @warning This function only works if the current file is a document archive
+ *
+ * @since 1.3
+ */
+ bool extractArchivedFile( const QString &destFileName );
+
/**
* Asks the generator to dynamically generate a SourceReference for a given
* page number and absolute X and Y position on this page.
*
* @attention Ownership of the returned SourceReference is transferred to the caller.
* @note This method does not call processSourceReference( const SourceReference * )
*
* @since 0.10 (KDE 4.4)
*/
const SourceReference * dynamicSourceReference( int pageNr, double absX, double absY );
/**
* Returns the orientation of the document (for printing purposes). This
* is used in the KPart to initialize the print dialog and in the
* generators to check whether the document needs to be rotated or not.
*
* @since 0.14 (KDE 4.8)
*/
QPrinter::Orientation orientation() const;
/**
* Control annotation editing (creation, modification and removal),
* which is enabled by default.
*
* @since 0.15 (KDE 4.9)
*/
void setAnnotationEditingEnabled( bool enable );
/**
* Returns which wallet data to use to read/write the password for the given fileName
*
* @since 0.20 (KDE 4.14)
*/
void walletDataForFile( const QString &fileName, QString *walletName, QString *walletFolder, QString *walletKey ) const;
+ /**
+ * Since version 0.21, okular does not allow editing annotations and
+ * form data if they are stored in the docdata directory (like older
+ * okular versions did by default).
+ * If this flag is set, then annotations and forms cannot be edited.
+ *
+ * @since 1.3
+ */
+ bool isDocdataMigrationNeeded() const;
+
+ /**
+ * Delete annotations and form data from the docdata folder. Call it if
+ * isDocdataMigrationNeeded() was true and you've just saved them to an
+ * external file.
+ *
+ * @since 1.3
+ */
+ void docdataMigrationDone();
+
/**
* Returns the model for rendering layers (NULL if the document has no layers)
*
* @since 0.24
*/
QAbstractItemModel * layersModel() const;
public Q_SLOTS:
/**
* This slot is called whenever the user changes the @p rotation of
* the document.
*/
void setRotation( int rotation );
/**
* This slot is called whenever the user changes the page @p size
* of the document.
*/
void setPageSize( const PageSize &size );
/**
* Cancels the current search
*/
void cancelSearch();
/**
* Undo last edit command
* @since 0.17 (KDE 4.11)
*/
void undo();
/**
* Redo last undone edit command
* @since 0.17 (KDE 4.11)
*/
void redo();
/**
* Edit the text contents of the specified @p form on page @p page to be @p newContents.
* The new text cursor position (@p newCursorPos), previous text cursor position (@p prevCursorPos),
* and previous cursor anchor position will be restored by the undo / redo commands.
* @since 0.17 (KDE 4.11)
*/
void editFormText( int pageNumber,
Okular::FormFieldText* form,
const QString & newContents,
int newCursorPos,
int prevCursorPos,
int prevAnchorPos );
/**
* Edit the selected list entries in @p form on page @p page to be @p newChoices.
* @since 0.17 (KDE 4.11)
*/
void editFormList( int pageNumber,
Okular::FormFieldChoice* form,
const QList & newChoices );
/**
* Set the active choice in the combo box @p form on page @p page to @p newText
* The new cursor position (@p newCursorPos), previous cursor position
* (@p prevCursorPos), and previous anchor position (@p prevAnchorPos)
* will be restored by the undo / redo commands.
*
* @since 0.17 (KDE 4.11)
*/
void editFormCombo( int pageNumber,
Okular::FormFieldChoice *form,
const QString & newText,
int newCursorPos,
int prevCursorPos,
int prevAnchorPos );
/**
* Set the states of the group of form buttons @p formButtons on page @p page to @p newButtonStates.
* The lists @p formButtons and @p newButtonStates should be the same length and true values
* in @p newButtonStates indicate that the corresponding entry in @p formButtons should be enabled.
*/
void editFormButtons( int pageNumber,
const QList< Okular::FormFieldButton* > & formButtons,
const QList< bool > & newButtonStates );
/**
* Reloads the pixmaps for whole document
*
* @since 0.24
*/
void reloadDocument() const;
Q_SIGNALS:
/**
* This signal is emitted whenever an action requests a
* document close operation.
*/
void close();
/**
* This signal is emitted whenever an action requests an
* application quit operation.
*/
void quit();
/**
* This signal is emitted whenever an action requests a
* find operation.
*/
void linkFind();
/**
* This signal is emitted whenever an action requests a
* goto operation.
*/
void linkGoToPage();
/**
* This signal is emitted whenever an action requests a
* start presentation operation.
*/
void linkPresentation();
/**
* This signal is emitted whenever an action requests an
* end presentation operation.
*/
void linkEndPresentation();
/**
* This signal is emitted whenever an action requests an
* open url operation for the given document @p url.
*/
void openUrl( const QUrl &url );
/**
* This signal is emitted whenever an error occurred.
*
* @param text The description of the error.
* @param duration The time in milliseconds the message should be shown to the user.
*/
void error( const QString &text, int duration );
/**
* This signal is emitted to signal a warning.
*
* @param text The description of the warning.
* @param duration The time in milliseconds the message should be shown to the user.
*/
void warning( const QString &text, int duration );
/**
* This signal is emitted to signal a notice.
*
* @param text The description of the notice.
* @param duration The time in milliseconds the message should be shown to the user.
*/
void notice( const QString &text, int duration );
/**
* Emitted when a new font is found during the reading of the fonts of
* the document.
*/
void gotFont( const Okular::FontInfo& font );
/**
* Reports the progress when reading the fonts in the document.
*
* \param page is the page that was just finished to scan for fonts
*/
void fontReadingProgress( int page );
/**
* Reports that the reading of the fonts in the document is finished.
*/
void fontReadingEnded();
/**
* Reports that the current search finished
*/
void searchFinished( int searchID, Okular::Document::SearchStatus endStatus );
/**
* This signal is emitted whenever a source reference with the given parameters has been
* activated.
*
* \param handled should be set to 'true' if a slot handles this source reference; the
* default action to launch the configured editor will then not be performed
* by the document
*
* @since 0.14 (KDE 4.8)
*/
void sourceReferenceActivated(const QString& absFileName, int line, int col, bool *handled);
/**
* This signal is emitted whenever an movie action is triggered and the UI should process it.
*/
void processMovieAction( const Okular::MovieAction *action );
/**
* This signal is emmitted whenever the availability of the undo function changes
* @since 0.17 (KDE 4.11)
*/
void canUndoChanged( bool undoAvailable );
/**
* This signal is emmitted whenever the availability of the redo function changes
* @since 0.17 (KDE 4.11)
*/
void canRedoChanged( bool redoAvailable );
+ /**
+ * This signal is emmitted whenever the undo history is clean (i.e. the same status the last time it was saved)
+ * @since 1.3
+ */
+ void undoHistoryCleanChanged( bool clean );
+
/**
* This signal is emitted whenever an rendition action is triggered and the UI should process it.
*
* @since 0.16 (KDE 4.10)
*/
void processRenditionAction( const Okular::RenditionAction *action );
/**
* This signal is emmitted whenever the contents of the given @p annotation are changed by an undo
* or redo action.
*
* The new contents (@p contents), cursor position (@p cursorPos), and anchor position (@p anchorPos) are
* included
* @since 0.17 (KDE 4.11)
*/
void annotationContentsChangedByUndoRedo( Okular::Annotation* annotation, const QString & contents, int cursorPos, int anchorPos );
/**
* This signal is emmitted whenever the text contents of the given text @p form on the given @p page
* are changed by an undo or redo action.
*
* The new text contents (@p contents), cursor position (@p cursorPos), and anchor position (@p anchorPos) are
* included
* @since 0.17 (KDE 4.11)
*/
void formTextChangedByUndoRedo( int page, Okular::FormFieldText* form, const QString & contents, int cursorPos, int anchorPos );
/**
* This signal is emmitted whenever the selected @p choices for the given list @p form on the
* given @p page are changed by an undo or redo action.
* @since 0.17 (KDE 4.11)
*/
void formListChangedByUndoRedo( int page, Okular::FormFieldChoice* form, const QList< int > & choices );
/**
* This signal is emmitted whenever the active @p text for the given combo @p form on the
* given @p page is changed by an undo or redo action.
* @since 0.17 (KDE 4.11)
*/
void formComboChangedByUndoRedo( int page, Okular::FormFieldChoice* form, const QString & text, int cursorPos, int anchorPos );
/**
* This signal is emmitted whenever the state of the specified group of form buttons (@p formButtons) on the
* given @p page is changed by an undo or redo action.
* @since 0.17 (KDE 4.11)
*/
void formButtonsChangedByUndoRedo( int page, const QList< Okular::FormFieldButton* > & formButtons );
private:
/// @cond PRIVATE
friend class DocumentPrivate;
friend class ::DocumentItem;
friend class EditAnnotationContentsCommand;
friend class EditFormTextCommand;
friend class EditFormListCommand;
friend class EditFormComboCommand;
friend class EditFormButtonsCommand;
/// @endcond
DocumentPrivate *const d;
Q_DISABLE_COPY( Document )
Q_PRIVATE_SLOT( d, void saveDocumentInfo() const )
Q_PRIVATE_SLOT( d, void slotTimedMemoryCheck() )
Q_PRIVATE_SLOT( d, void sendGeneratorPixmapRequest() )
Q_PRIVATE_SLOT( d, void rotationFinished( int page, Okular::Page *okularPage ) )
Q_PRIVATE_SLOT( d, void slotFontReadingProgress( int page ) )
Q_PRIVATE_SLOT( d, void fontReadingGotFont( const Okular::FontInfo& font ) )
Q_PRIVATE_SLOT( d, void slotGeneratorConfigChanged( const QString& ) )
Q_PRIVATE_SLOT( d, void refreshPixmaps( int ) )
Q_PRIVATE_SLOT( d, void _o_configChanged() )
// search thread simulators
Q_PRIVATE_SLOT( d, void doContinueDirectionMatchSearch(void *doContinueDirectionMatchSearchStruct) )
Q_PRIVATE_SLOT( d, void doContinueAllDocumentSearch(void *pagesToNotifySet, void *pageMatchesMap, int currentPage, int searchID) )
Q_PRIVATE_SLOT( d, void doContinueGooglesDocumentSearch(void *pagesToNotifySet, void *pageMatchesMap, int currentPage, int searchID, const QStringList & words) )
};
/**
* @short A view on the document.
*
* The Viewport structure is the 'current view' over the document. Contained
* data is broadcasted between observers to synchronize their viewports to get
* the 'I scroll one view and others scroll too' views.
*/
class OKULARCORE_EXPORT DocumentViewport
{
public:
/**
* Creates a new viewport for the given page @p number.
*/
DocumentViewport( int number = -1 );
/**
* Creates a new viewport from the given xml @p description.
*/
DocumentViewport( const QString &description );
/**
* Returns the viewport as xml description.
*/
QString toString() const;
/**
* Returns whether the viewport is valid.
*/
bool isValid() const;
/**
* @internal
*/
bool operator==( const DocumentViewport &other ) const;
bool operator<( const DocumentViewport &other ) const;
/**
* The number of the page nearest the center of the viewport.
*/
int pageNumber;
/**
* Describes the relative position of the viewport.
*/
enum Position
{
Center = 1, ///< Relative to the center of the page.
TopLeft = 2 ///< Relative to the top left corner of the page.
};
/**
* If 'rePos.enabled == true' then this structure contains the
* viewport center or top left depending on the value of pos.
*/
struct {
bool enabled;
double normalizedX;
double normalizedY;
Position pos;
} rePos;
/**
* If 'autoFit.enabled == true' then the page must be autofitted in the viewport.
*/
struct {
bool enabled;
bool width;
bool height;
} autoFit;
};
/**
* @short A DOM tree that describes the Table of Contents.
*
* The Synopsis (TOC or Table Of Contents for friends) is represented via
* a dom tree where each node has an internal name (displayed in the TOC)
* and one or more attributes.
*
* In the tree the tag name is the 'screen' name of the entry. A tag can have
* attributes. Here follows the list of tag attributes with meaning:
* - Destination: A string description of the referred viewport
* - DestinationName: A 'named reference' to the viewport that must be converted
* using metaData( "NamedViewport", viewport_name )
* - ExternalFileName: A document to be opened, whose destination is specified
* with Destination or DestinationName
* - Open: a boolean saying whether its TOC branch is open or not (default: false)
* - URL: a URL to be open as destination; if set, no other Destination* or
* ExternalFileName entry is used
*/
class OKULARCORE_EXPORT DocumentSynopsis : public QDomDocument
{
public:
/**
* Creates a new document synopsis object.
*/
DocumentSynopsis();
/**
* Creates a new document synopsis object with the given
* @p document as parent node.
*/
DocumentSynopsis( const QDomDocument &document );
};
/**
* @short An embedded file into the document.
*
* This class represents a sort of interface of an embedded file in a document.
*
* Generators \b must re-implement its members to give the all the information
* about an embedded file, like its name, its description, the date of creation
* and modification, and the real data of the file.
*/
class OKULARCORE_EXPORT EmbeddedFile
{
public:
/**
* Creates a new embedded file.
*/
EmbeddedFile();
/**
* Destroys the embedded file.
*/
virtual ~EmbeddedFile();
/**
* Returns the name of the file
*/
virtual QString name() const = 0;
/**
* Returns the description of the file, or an empty string if not
* available
*/
virtual QString description() const = 0;
/**
* Returns the real data representing the file contents
*/
virtual QByteArray data() const = 0;
/**
* Returns the size (in bytes) of the file, if available, or -1 otherwise.
*
* @note this method should be a fast way to know the size of the file
* with no need to extract all the data from it
*/
virtual int size() const = 0;
/**
* Returns the modification date of the file, or an invalid date
* if not available
*/
virtual QDateTime modificationDate() const = 0;
/**
* Returns the creation date of the file, or an invalid date
* if not available
*/
virtual QDateTime creationDate() const = 0;
};
/**
* @short An area of a specified page
*/
class OKULARCORE_EXPORT VisiblePageRect
{
public:
/**
* Creates a new visible page rectangle.
*
* @param pageNumber The page number where the rectangle is located.
* @param rectangle The rectangle in normalized coordinates.
*/
explicit VisiblePageRect( int pageNumber = -1, const NormalizedRect &rectangle = NormalizedRect() );
/**
* The page number where the rectangle is located.
*/
int pageNumber;
/**
* The rectangle in normalized coordinates.
*/
NormalizedRect rect;
};
}
Q_DECLARE_METATYPE( Okular::DocumentInfo::Key )
Q_DECLARE_OPERATORS_FOR_FLAGS( Okular::Document::PixmapRequestFlags )
#endif
/* kate: replace-tabs on; indent-width 4; */
diff --git a/core/document_p.h b/core/document_p.h
index b6cf425bc..644a3c77b 100644
--- a/core/document_p.h
+++ b/core/document_p.h
@@ -1,302 +1,320 @@
/***************************************************************************
* Copyright (C) 2004-2005 by Enrico Ros *
* Copyright (C) 2004-2007 by Albert Astals Cid *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#ifndef _OKULAR_DOCUMENT_P_H_
#define _OKULAR_DOCUMENT_P_H_
#include "document.h"
#include "synctex/synctex_parser.h"
// qt/kde/system includes
#include
#include
#include
#include
#include
#include
#include
// local includes
#include "fontinfo.h"
#include "generator.h"
class QUndoStack;
class QEventLoop;
class QFile;
class QTimer;
class QTemporaryFile;
class KPluginMetaData;
struct AllocatedPixmap;
struct ArchiveData;
struct RunningSearch;
namespace Okular {
class ConfigInterface;
class PageController;
class SaveInterface;
class Scripter;
class View;
}
struct GeneratorInfo
{
explicit GeneratorInfo( Okular::Generator *g, const KPluginMetaData &data)
: generator( g ), metadata( data ), config( nullptr ), save( nullptr ),
configChecked( false ), saveChecked( false )
{}
Okular::Generator * generator;
KPluginMetaData metadata;
Okular::ConfigInterface * config;
Okular::SaveInterface * save;
bool configChecked : 1;
bool saveChecked : 1;
};
namespace Okular {
class FontExtractionThread;
struct DoContinueDirectionMatchSearchStruct
{
QSet< int > *pagesToNotify;
RegularAreaRect *match;
int currentPage;
int searchID;
};
+enum LoadDocumentInfoFlag
+{
+ LoadNone = 0,
+ LoadPageInfo = 1, // Load annotations and forms
+ LoadGeneralInfo = 2, // History, rotation, ...
+ LoadAllInfo = 0xff
+};
+Q_DECLARE_FLAGS(LoadDocumentInfoFlags, LoadDocumentInfoFlag)
+
class DocumentPrivate
{
public:
DocumentPrivate( Document *parent )
: m_parent( parent ),
m_tempFile( nullptr ),
m_docSize( -1 ),
m_allocatedPixmapsTotalMemory( 0 ),
m_maxAllocatedTextPages( 0 ),
m_warnedOutOfMemory( false ),
m_rotation( Rotation0 ),
m_exportCached( false ),
m_bookmarkManager( nullptr ),
m_memCheckTimer( nullptr ),
m_saveBookmarksTimer( nullptr ),
m_generator( nullptr ),
m_walletGenerator( nullptr ),
m_generatorsLoaded( false ),
m_pageController( nullptr ),
m_closingLoop( nullptr ),
m_scripter( nullptr ),
m_archiveData( nullptr ),
m_fontsCached( false ),
m_annotationEditingEnabled ( true ),
m_annotationBeingModified( false ),
+ m_docdataMigrationNeeded( false ),
m_synctex_scanner( nullptr )
{
calculateMaxTextPages();
}
// private methods
+ bool updateMetadataXmlNameAndDocSize();
QString pagesSizeString() const;
QString namePaperSize(double inchesWidth, double inchesHeight) const;
QString localizedSize(const QSizeF &size) const;
qulonglong calculateMemoryToFree();
void cleanupPixmapMemory();
void cleanupPixmapMemory( qulonglong memoryToFree );
AllocatedPixmap * searchLowestPriorityPixmap( bool unloadableOnly = false, bool thenRemoveIt = false, DocumentObserver *observer = nullptr /* any */ );
void calculateMaxTextPages();
qulonglong getTotalMemory();
qulonglong getFreeMemory( qulonglong *freeSwap = nullptr );
- void loadDocumentInfo();
- void loadDocumentInfo( QFile &infoFile );
+ bool loadDocumentInfo( LoadDocumentInfoFlags loadWhat );
+ bool loadDocumentInfo( QFile &infoFile, LoadDocumentInfoFlags loadWhat );
void loadViewsInfo( View *view, const QDomElement &e );
void saveViewsInfo( View *view, QDomElement &e ) const;
QUrl giveAbsoluteUrl( const QString & fileName ) const;
bool openRelativeFile( const QString & fileName );
Generator * loadGeneratorLibrary( const KPluginMetaData& service );
void loadAllGeneratorLibraries();
void loadServiceList( const QVector& offers );
void unloadGenerator( const GeneratorInfo& info );
void cacheExportFormats();
void setRotationInternal( int r, bool notify );
ConfigInterface* generatorConfig( GeneratorInfo& info );
SaveInterface* generatorSave( GeneratorInfo& info );
Document::OpenResult openDocumentInternal( const KPluginMetaData& offer, bool isstdin, const QString& docFile, const QByteArray& filedata, const QString& password );
+ static ArchiveData *unpackDocumentArchive( const QString &archivePath );
bool savePageDocumentInfo( QTemporaryFile *infoFile, int what ) const;
DocumentViewport nextDocumentViewport() const;
void notifyAnnotationChanges( int page );
+ void notifyFormChanges( int page );
bool canAddAnnotationsNatively() const;
bool canModifyExternalAnnotations() const;
bool canRemoveExternalAnnotations() const;
- void warnLimitedAnnotSupport();
OKULARCORE_EXPORT static QString docDataFileName(const QUrl &url, qint64 document_size);
// Methods that implement functionality needed by undo commands
void performAddPageAnnotation( int page, Annotation *annotation );
void performRemovePageAnnotation( int page, Annotation * annotation );
void performModifyPageAnnotation( int page, Annotation * annotation, bool appearanceChanged );
void performSetAnnotationContents( const QString & newContents, Annotation *annot, int pageNumber );
void recalculateForms();
// private slots
void saveDocumentInfo() const;
void slotTimedMemoryCheck();
void sendGeneratorPixmapRequest();
void rotationFinished( int page, Okular::Page *okularPage );
void slotFontReadingProgress( int page );
void fontReadingGotFont( const Okular::FontInfo& font );
void slotGeneratorConfigChanged( const QString& );
void refreshPixmaps( int );
void _o_configChanged();
void doContinueDirectionMatchSearch(void *doContinueDirectionMatchSearchStruct);
void doContinueAllDocumentSearch(void *pagesToNotifySet, void *pageMatchesMap, int currentPage, int searchID);
void doContinueGooglesDocumentSearch(void *pagesToNotifySet, void *pageMatchesMap, int currentPage, int searchID, const QStringList & words);
void doProcessSearchMatch( RegularAreaRect *match, RunningSearch *search, QSet< int > *pagesToNotify, int currentPage, int searchID, bool moveViewport, const QColor & color );
// generators stuff
/**
* This method is used by the generators to signal the finish of
* the pixmap generation @p request.
*/
void requestDone( PixmapRequest * request );
void textGenerationDone( Page *page );
/**
* Sets the bounding box of the given @p page (in terms of upright orientation, i.e., Rotation0).
*/
void setPageBoundingBox( int page, const NormalizedRect& boundingBox );
/**
* Request a particular metadata of the Document itself (ie, not something
* depending on the document type/backend).
*/
QVariant documentMetaData( const Generator::DocumentMetaDataKey key, const QVariant &option ) const;
/**
* Return whether the normalized rectangle @p rectOfInterest on page number @p rectPage
* is fully visible.
*/
bool isNormalizedRectangleFullyVisible( const Okular::NormalizedRect & rectOfInterest, int rectPage );
// For sync files
void loadSyncFile( const QString & filePath );
// member variables
Document *m_parent;
QPointer m_widget;
// find descriptors, mapped by ID (we handle multiple searches)
QMap< int, RunningSearch * > m_searches;
bool m_searchCancelled;
// needed because for remote documents docFileName is a local file and
// we want the remote url when the document refers to relativeNames
QUrl m_url;
// cached stuff
QString m_docFileName;
QString m_xmlFileName;
QTemporaryFile *m_tempFile;
qint64 m_docSize;
// viewport stuff
QLinkedList< DocumentViewport > m_viewportHistory;
QLinkedList< DocumentViewport >::iterator m_viewportIterator;
DocumentViewport m_nextDocumentViewport; // see Link::Goto for an explanation
QString m_nextDocumentDestination;
// observers / requests / allocator stuff
QSet< DocumentObserver * > m_observers;
QLinkedList< PixmapRequest * > m_pixmapRequestsStack;
QLinkedList< PixmapRequest * > m_executingPixmapRequests;
QMutex m_pixmapRequestsMutex;
QLinkedList< AllocatedPixmap * > m_allocatedPixmaps;
qulonglong m_allocatedPixmapsTotalMemory;
QList< int > m_allocatedTextPagesFifo;
int m_maxAllocatedTextPages;
bool m_warnedOutOfMemory;
// the rotation applied to the document
Rotation m_rotation;
// the current size of the pages (if available), and the cache of the
// available page sizes
PageSize m_pageSize;
PageSize::List m_pageSizes;
// cache of the export formats
bool m_exportCached;
ExportFormat::List m_exportFormats;
ExportFormat m_exportToText;
// our bookmark manager
BookmarkManager *m_bookmarkManager;
// timers (memory checking / info saver)
QTimer *m_memCheckTimer;
QTimer *m_saveBookmarksTimer;
QHash m_loadedGenerators;
Generator * m_generator;
QString m_generatorName;
Generator * m_walletGenerator;
bool m_generatorsLoaded;
QVector< Page * > m_pagesVector;
QVector< VisiblePageRect * > m_pageRects;
// cache of the mimetype we support
QStringList m_supportedMimeTypes;
PageController *m_pageController;
QEventLoop *m_closingLoop;
Scripter *m_scripter;
ArchiveData *m_archiveData;
QString m_archivedFileName;
QPointer< FontExtractionThread > m_fontThread;
bool m_fontsCached;
QSet m_documentInfoAskedKeys;
DocumentInfo m_documentInfo;
FontInfo::List m_fontsCache;
QSet< View * > m_views;
bool m_annotationEditingEnabled;
- bool m_annotationsNeedSaveAs;
bool m_annotationBeingModified; // is an annotation currently being moved or resized?
- bool m_showWarningLimitedAnnotSupport;
+ bool m_metadataLoadingCompleted;
QUndoStack *m_undoStack;
QDomNode m_prevPropsOfAnnotBeingModified;
+ // Since 0.21, we no longer support saving annotations and form data in
+ // the docdata/ directory and we ask the user to migrate them to an
+ // external file as soon as possible, otherwise the document will be
+ // shown in read-only mode. This flag is set if the docdata/ XML file
+ // for the current document contains any annotation or form.
+ bool m_docdataMigrationNeeded;
+
synctex_scanner_p m_synctex_scanner;
// generator selection
static QVector availableGenerators();
static QVector configurableGenerators();
static KPluginMetaData generatorForMimeType(const QMimeType& type, QWidget* widget, const QVector &triedOffers = QVector());
};
class DocumentInfoPrivate
{
public:
QMap values; // key -> value
QMap titles; // key -> title For the custom keys
};
}
#endif
/* kate: replace-tabs on; indent-width 4; */
diff --git a/core/documentcommands.cpp b/core/documentcommands.cpp
index 3239ab058..3b9348bd4 100644
--- a/core/documentcommands.cpp
+++ b/core/documentcommands.cpp
@@ -1,632 +1,753 @@
/***************************************************************************
* Copyright (C) 2013 Jon Mease *
+ * Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group *
+ * company, info@kdab.com. Work sponsored by the *
+ * LiMux project of the city of Munich *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "documentcommands_p.h"
#include "annotations.h"
#include "debug_p.h"
#include "document_p.h"
#include "form.h"
#include "utils_p.h"
#include "page.h"
+#include "page_p.h"
#include
namespace Okular {
void moveViewportIfBoundingRectNotFullyVisible( Okular::NormalizedRect boundingRect,
DocumentPrivate *docPriv,
int pageNumber )
{
const Rotation pageRotation = docPriv->m_parent->page( pageNumber )->rotation();
const QTransform rotationMatrix = Okular::buildRotationMatrix( pageRotation );
boundingRect.transform( rotationMatrix );
if ( !docPriv->isNormalizedRectangleFullyVisible( boundingRect, pageNumber ) )
{
DocumentViewport searchViewport( pageNumber );
searchViewport.rePos.enabled = true;
searchViewport.rePos.normalizedX = ( boundingRect.left + boundingRect.right ) / 2.0;
searchViewport.rePos.normalizedY = ( boundingRect.top + boundingRect.bottom ) / 2.0;
docPriv->m_parent->setViewport( searchViewport, nullptr, true );
}
}
Okular::NormalizedRect buildBoundingRectangleForButtons( const QList & formButtons )
{
// Initialize coordinates of the bounding rect
double left = 1.0;
double top = 1.0;
double right = 0.0;
double bottom = 0.0;
foreach( FormFieldButton* formButton, formButtons )
{
left = qMin( left, formButton->rect().left );
top = qMin( top, formButton->rect().top );
right = qMax( right, formButton->rect().right );
bottom = qMax( bottom, formButton->rect().bottom );
}
Okular::NormalizedRect boundingRect( left, top, right, bottom );
return boundingRect;
}
AddAnnotationCommand::AddAnnotationCommand( Okular::DocumentPrivate * docPriv, Okular::Annotation* annotation, int pageNumber )
: m_docPriv( docPriv ),
m_annotation( annotation ),
m_pageNumber( pageNumber ),
m_done( false )
{
setText( i18nc ("Add an annotation to the page", "add annotation" ) );
}
AddAnnotationCommand::~AddAnnotationCommand()
{
if ( !m_done )
{
delete m_annotation;
}
}
void AddAnnotationCommand::undo()
{
moveViewportIfBoundingRectNotFullyVisible( m_annotation->boundingRectangle(), m_docPriv, m_pageNumber );
m_docPriv->performRemovePageAnnotation( m_pageNumber, m_annotation );
m_done = false;
}
void AddAnnotationCommand::redo()
{
moveViewportIfBoundingRectNotFullyVisible( m_annotation->boundingRectangle(), m_docPriv, m_pageNumber );
m_docPriv->performAddPageAnnotation( m_pageNumber, m_annotation );
m_done = true;
}
+bool AddAnnotationCommand::refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector )
+{
+ if ( m_done )
+ {
+ // We don't always update m_annotation because even if the annotation has been added to the document
+ // it can have been removed later so the annotation pointer is stored inside a following RemoveAnnotationCommand
+ // and thus doesn't need updating because it didn't change
+ // because of the document reload
+ auto a = newPagesVector[m_pageNumber]->annotation( m_annotation->uniqueName() );
+ if (a) m_annotation = a;
+ }
+
+ return true;
+}
+
RemoveAnnotationCommand::RemoveAnnotationCommand(Okular::DocumentPrivate * doc, Okular::Annotation* annotation, int pageNumber)
: m_docPriv( doc ),
m_annotation( annotation ),
m_pageNumber( pageNumber ),
m_done( false )
{
setText( i18nc( "Remove an annotation from the page", "remove annotation" ) );
}
RemoveAnnotationCommand::~RemoveAnnotationCommand()
{
if ( m_done )
{
delete m_annotation;
}
}
void RemoveAnnotationCommand::undo()
{
moveViewportIfBoundingRectNotFullyVisible( m_annotation->boundingRectangle(), m_docPriv, m_pageNumber );
m_docPriv->performAddPageAnnotation( m_pageNumber, m_annotation );
m_done = false;
}
-void RemoveAnnotationCommand::redo(){
+void RemoveAnnotationCommand::redo()
+{
moveViewportIfBoundingRectNotFullyVisible( m_annotation->boundingRectangle(), m_docPriv, m_pageNumber );
m_docPriv->performRemovePageAnnotation( m_pageNumber, m_annotation );
m_done = true;
}
+bool RemoveAnnotationCommand::refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector )
+{
+ if ( !m_done )
+ {
+ // We don't always update m_annotation because it can happen that the annotation remove has been undo
+ // and that annotation addition has also been undone so the the annotation pointer is stored inside
+ // a previous AddAnnotationCommand and thus doesn't need updating because it didn't change
+ // because of the document reload
+ auto a = newPagesVector[m_pageNumber]->annotation( m_annotation->uniqueName() );
+ if (a) m_annotation = a;
+ }
+
+ return true;
+}
ModifyAnnotationPropertiesCommand::ModifyAnnotationPropertiesCommand( DocumentPrivate* docPriv,
Annotation* annotation,
int pageNumber,
QDomNode oldProperties,
QDomNode newProperties )
: m_docPriv( docPriv ),
m_annotation( annotation ),
m_pageNumber( pageNumber ),
m_prevProperties( oldProperties ),
m_newProperties( newProperties )
{
setText(i18nc("Modify an annotation's internal properties (Color, line-width, etc.)", "modify annotation properties"));
}
void ModifyAnnotationPropertiesCommand::undo()
{
moveViewportIfBoundingRectNotFullyVisible( m_annotation->boundingRectangle(), m_docPriv, m_pageNumber );
m_annotation->setAnnotationProperties( m_prevProperties );
m_docPriv->performModifyPageAnnotation( m_pageNumber, m_annotation, true );
}
void ModifyAnnotationPropertiesCommand::redo()
{
moveViewportIfBoundingRectNotFullyVisible( m_annotation->boundingRectangle(), m_docPriv, m_pageNumber );
m_annotation->setAnnotationProperties( m_newProperties );
m_docPriv->performModifyPageAnnotation( m_pageNumber, m_annotation, true );
}
+bool ModifyAnnotationPropertiesCommand::refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector )
+{
+ // Same reason for not unconditionally updating m_annotation, the annotation pointer can be stored in an add/Remove command
+ auto a = newPagesVector[m_pageNumber]->annotation( m_annotation->uniqueName() );
+ if (a) m_annotation = a;
+
+ return true;
+}
+
+
TranslateAnnotationCommand::TranslateAnnotationCommand( DocumentPrivate* docPriv,
Annotation* annotation,
int pageNumber,
const Okular::NormalizedPoint & delta,
bool completeDrag )
: m_docPriv( docPriv ),
m_annotation( annotation ),
m_pageNumber( pageNumber ),
m_delta( delta ),
m_completeDrag( completeDrag )
{
setText( i18nc( "Translate an annotation's position on the page", "translate annotation" ) );
}
void TranslateAnnotationCommand::undo()
{
moveViewportIfBoundingRectNotFullyVisible(translateBoundingRectangle( minusDelta() ), m_docPriv, m_pageNumber );
m_annotation->translate( minusDelta() );
m_docPriv->performModifyPageAnnotation( m_pageNumber, m_annotation, true );
}
void TranslateAnnotationCommand::redo()
{
moveViewportIfBoundingRectNotFullyVisible(translateBoundingRectangle( m_delta ), m_docPriv, m_pageNumber );
m_annotation->translate( m_delta );
m_docPriv->performModifyPageAnnotation( m_pageNumber, m_annotation, true );
}
int TranslateAnnotationCommand::id() const
{
return 1;
}
bool TranslateAnnotationCommand::mergeWith( const QUndoCommand* uc )
{
TranslateAnnotationCommand *tuc = (TranslateAnnotationCommand*)uc;
if ( tuc->m_annotation != m_annotation )
return false;
if ( m_completeDrag )
{
return false;
}
m_delta = Okular::NormalizedPoint( tuc->m_delta.x + m_delta.x, tuc->m_delta.y + m_delta.y );
m_completeDrag = tuc->m_completeDrag;
return true;
}
Okular::NormalizedPoint TranslateAnnotationCommand::minusDelta()
{
return Okular::NormalizedPoint( -m_delta.x, -m_delta.y );
}
Okular::NormalizedRect TranslateAnnotationCommand::translateBoundingRectangle( const Okular::NormalizedPoint & delta )
{
Okular::NormalizedRect annotBoundingRect = m_annotation->boundingRectangle();
double left = qMin( annotBoundingRect.left, annotBoundingRect.left + delta.x );
double right = qMax( annotBoundingRect.right, annotBoundingRect.right + delta.x );
double top = qMin( annotBoundingRect.top, annotBoundingRect.top + delta.y );
double bottom = qMax( annotBoundingRect.bottom, annotBoundingRect.bottom + delta.y );
Okular::NormalizedRect boundingRect( left, top, right, bottom );
return boundingRect;
}
+bool TranslateAnnotationCommand::refreshInternalPageReferences( const QVector< Page * > &newPagesVector )
+{
+ // Same reason for not unconditionally updating m_annotation, the annotation pointer can be stored in an add/Remove command
+ auto a = newPagesVector[m_pageNumber]->annotation( m_annotation->uniqueName() );
+ if (a) m_annotation = a;
+
+ return true;
+}
+
+
AdjustAnnotationCommand::AdjustAnnotationCommand(Okular::DocumentPrivate * docPriv,
Okular::Annotation * annotation,
int pageNumber,
const Okular::NormalizedPoint & delta1,
const Okular::NormalizedPoint & delta2,
bool completeDrag )
: m_docPriv( docPriv ),
m_annotation( annotation ),
m_pageNumber( pageNumber ),
m_delta1( delta1 ),
m_delta2( delta2 ),
m_completeDrag( completeDrag )
{
setText( i18nc( "Change an annotation's size", "adjust annotation" ) );
}
void AdjustAnnotationCommand::undo()
{
const NormalizedPoint minusDelta1 = Okular::NormalizedPoint( -m_delta1.x, -m_delta1.y );
const NormalizedPoint minusDelta2 = Okular::NormalizedPoint( -m_delta2.x, -m_delta2.y );
moveViewportIfBoundingRectNotFullyVisible( adjustBoundingRectangle( minusDelta1, minusDelta2 ), m_docPriv, m_pageNumber );
m_annotation->adjust( minusDelta1, minusDelta2 );
m_docPriv->performModifyPageAnnotation( m_pageNumber, m_annotation, true );
}
void AdjustAnnotationCommand::redo()
{
moveViewportIfBoundingRectNotFullyVisible( adjustBoundingRectangle( m_delta1, m_delta2 ), m_docPriv, m_pageNumber );
m_annotation->adjust( m_delta1, m_delta2 );
m_docPriv->performModifyPageAnnotation( m_pageNumber, m_annotation, true );
}
int AdjustAnnotationCommand::id() const
{
return 5;
}
bool AdjustAnnotationCommand::mergeWith( const QUndoCommand * uc )
{
AdjustAnnotationCommand *tuc = (AdjustAnnotationCommand *)uc;
if ( tuc->m_annotation != m_annotation )
return false;
if ( m_completeDrag )
{
return false;
}
m_delta1 = Okular::NormalizedPoint( tuc->m_delta1.x + m_delta1.x, tuc->m_delta1.y + m_delta1.y );
m_delta2 = Okular::NormalizedPoint( tuc->m_delta2.x + m_delta2.x, tuc->m_delta2.y + m_delta2.y );
m_completeDrag = tuc->m_completeDrag;
return true;
}
Okular::NormalizedRect AdjustAnnotationCommand::adjustBoundingRectangle(
const Okular::NormalizedPoint & delta1, const Okular::NormalizedPoint & delta2 )
{
const Okular::NormalizedRect annotBoundingRect = m_annotation->boundingRectangle();
const double left = qMin( annotBoundingRect.left, annotBoundingRect.left + delta1.x );
const double right = qMax( annotBoundingRect.right, annotBoundingRect.right + delta2.x );
const double top = qMin( annotBoundingRect.top, annotBoundingRect.top + delta1.y );
const double bottom = qMax( annotBoundingRect.bottom, annotBoundingRect.bottom + delta2.y );
return Okular::NormalizedRect( left, top, right, bottom );
}
+bool AdjustAnnotationCommand::refreshInternalPageReferences( const QVector< Page * > &newPagesVector )
+{
+ // Same reason for not unconditionally updating m_annotation, the annotation pointer can be stored in an add/Remove command
+ auto a = newPagesVector[m_pageNumber]->annotation( m_annotation->uniqueName() );
+ if (a) m_annotation = a;
+
+ return true;
+}
+
+
EditTextCommand::EditTextCommand( const QString & newContents,
int newCursorPos,
const QString & prevContents,
int prevCursorPos,
int prevAnchorPos )
: m_newContents( newContents ),
m_newCursorPos( newCursorPos ),
m_prevContents( prevContents ),
m_prevCursorPos( prevCursorPos ),
m_prevAnchorPos( prevAnchorPos )
{
setText( i18nc( "Generic text edit command", "edit text" ) );
//// Determine edit type
// If There was a selection then edit was not a simple single character backspace, delete, or insert
if (m_prevCursorPos != m_prevAnchorPos)
{
qCDebug(OkularCoreDebug) << "OtherEdit, selection";
m_editType = OtherEdit;
}
else if ( newContentsRightOfCursor() == oldContentsRightOfCursor() &&
newContentsLeftOfCursor() == oldContentsLeftOfCursor().left(oldContentsLeftOfCursor().length() - 1) &&
oldContentsLeftOfCursor().right(1) != QLatin1String("\n") )
{
qCDebug(OkularCoreDebug) << "CharBackspace";
m_editType = CharBackspace;
}
else if ( newContentsLeftOfCursor() == oldContentsLeftOfCursor() &&
newContentsRightOfCursor() == oldContentsRightOfCursor().right(oldContentsRightOfCursor().length() - 1) &&
oldContentsRightOfCursor().left(1) != QLatin1String("\n") )
{
qCDebug(OkularCoreDebug) << "CharDelete";
m_editType = CharDelete;
}
else if ( newContentsRightOfCursor() == oldContentsRightOfCursor() &&
newContentsLeftOfCursor().left( newContentsLeftOfCursor().length() - 1) == oldContentsLeftOfCursor() &&
newContentsLeftOfCursor().right(1) != QLatin1String("\n") )
{
qCDebug(OkularCoreDebug) << "CharInsert";
m_editType = CharInsert;
}
else
{
qCDebug(OkularCoreDebug) << "OtherEdit";
m_editType = OtherEdit;
}
}
bool EditTextCommand::mergeWith(const QUndoCommand* uc)
{
EditTextCommand *euc = (EditTextCommand*)uc;
// Only attempt merge of euc into this if our new state matches euc's old state and
// the editTypes match and are not type OtherEdit
if ( m_newContents == euc->m_prevContents
&& m_newCursorPos == euc->m_prevCursorPos
&& m_editType == euc->m_editType
&& m_editType != OtherEdit )
{
m_newContents = euc->m_newContents;
m_newCursorPos = euc->m_newCursorPos;
return true;
}
return false;
}
QString EditTextCommand::oldContentsLeftOfCursor()
{
return m_prevContents.left(m_prevCursorPos);
}
QString EditTextCommand::oldContentsRightOfCursor()
{
return m_prevContents.right(m_prevContents.length() - m_prevCursorPos);
}
QString EditTextCommand::newContentsLeftOfCursor()
{
return m_newContents.left(m_newCursorPos);
}
QString EditTextCommand::newContentsRightOfCursor()
{
return m_newContents.right(m_newContents.length() - m_newCursorPos);
}
+
EditAnnotationContentsCommand::EditAnnotationContentsCommand( DocumentPrivate* docPriv,
Annotation* annotation,
int pageNumber,
const QString & newContents,
int newCursorPos,
const QString & prevContents,
int prevCursorPos,
int prevAnchorPos )
: EditTextCommand( newContents, newCursorPos, prevContents, prevCursorPos, prevAnchorPos ),
m_docPriv( docPriv ),
m_annotation( annotation ),
m_pageNumber( pageNumber )
{
setText( i18nc( "Edit an annotation's text contents", "edit annotation contents" ) );
}
void EditAnnotationContentsCommand::undo()
{
moveViewportIfBoundingRectNotFullyVisible( m_annotation->boundingRectangle(), m_docPriv, m_pageNumber );
m_docPriv->performSetAnnotationContents( m_prevContents, m_annotation, m_pageNumber );
emit m_docPriv->m_parent->annotationContentsChangedByUndoRedo( m_annotation, m_prevContents, m_prevCursorPos, m_prevAnchorPos );
}
void EditAnnotationContentsCommand::redo()
{
moveViewportIfBoundingRectNotFullyVisible( m_annotation->boundingRectangle(), m_docPriv, m_pageNumber );
m_docPriv->performSetAnnotationContents( m_newContents, m_annotation, m_pageNumber );
emit m_docPriv->m_parent->annotationContentsChangedByUndoRedo( m_annotation, m_newContents, m_newCursorPos, m_newCursorPos );
}
int EditAnnotationContentsCommand::id() const
{
return 2;
}
bool EditAnnotationContentsCommand::mergeWith(const QUndoCommand* uc)
{
EditAnnotationContentsCommand *euc = (EditAnnotationContentsCommand*)uc;
// Only attempt merge of euc into this if they modify the same annotation
if ( m_annotation == euc->m_annotation )
{
return EditTextCommand::mergeWith( uc );
}
else
{
return false;
}
}
+bool EditAnnotationContentsCommand::refreshInternalPageReferences( const QVector< Page * > &newPagesVector )
+{
+ auto a = newPagesVector[m_pageNumber]->annotation( m_annotation->uniqueName() );
+ if (a) m_annotation = a;
+
+ return true;
+}
+
+
EditFormTextCommand::EditFormTextCommand( Okular::DocumentPrivate* docPriv,
Okular::FormFieldText* form,
int pageNumber,
const QString & newContents,
int newCursorPos,
const QString & prevContents,
int prevCursorPos,
int prevAnchorPos )
: EditTextCommand( newContents, newCursorPos, prevContents, prevCursorPos, prevAnchorPos ),
m_docPriv ( docPriv ),
m_form( form ),
m_pageNumber( pageNumber )
{
setText( i18nc( "Edit an form's text contents", "edit form contents" ) );
}
void EditFormTextCommand::undo()
{
moveViewportIfBoundingRectNotFullyVisible( m_form->rect(), m_docPriv, m_pageNumber );
m_form->setText( m_prevContents );
emit m_docPriv->m_parent->formTextChangedByUndoRedo( m_pageNumber, m_form, m_prevContents, m_prevCursorPos, m_prevAnchorPos );
+ m_docPriv->notifyFormChanges( m_pageNumber );
}
void EditFormTextCommand::redo()
{
moveViewportIfBoundingRectNotFullyVisible( m_form->rect(), m_docPriv, m_pageNumber );
m_form->setText( m_newContents );
emit m_docPriv->m_parent->formTextChangedByUndoRedo( m_pageNumber, m_form, m_newContents, m_newCursorPos, m_newCursorPos );
+ m_docPriv->notifyFormChanges( m_pageNumber );
}
int EditFormTextCommand::id() const
{
return 3;
}
bool EditFormTextCommand::mergeWith(const QUndoCommand* uc)
{
EditFormTextCommand *euc = (EditFormTextCommand*)uc;
// Only attempt merge of euc into this if they modify the same form
if ( m_form == euc->m_form )
{
return EditTextCommand::mergeWith( uc );
}
else
{
return false;
}
}
+bool EditFormTextCommand::refreshInternalPageReferences( const QVector< Page * > &newPagesVector )
+{
+ m_form = dynamic_cast(Okular::PagePrivate::findEquivalentForm( newPagesVector[m_pageNumber], m_form ));
+
+ return m_form;
+}
+
+
EditFormListCommand::EditFormListCommand( Okular::DocumentPrivate* docPriv,
FormFieldChoice* form,
int pageNumber,
const QList< int > & newChoices,
const QList< int > & prevChoices )
: m_docPriv( docPriv ),
m_form( form ),
m_pageNumber( pageNumber ),
m_newChoices( newChoices ),
m_prevChoices( prevChoices )
{
setText( i18nc( "Edit a list form's choices", "edit list form choices" ) );
}
void EditFormListCommand::undo()
{
moveViewportIfBoundingRectNotFullyVisible( m_form->rect(), m_docPriv, m_pageNumber );
m_form->setCurrentChoices( m_prevChoices );
emit m_docPriv->m_parent->formListChangedByUndoRedo( m_pageNumber, m_form, m_prevChoices );
+ m_docPriv->notifyFormChanges( m_pageNumber );
}
void EditFormListCommand::redo()
{
moveViewportIfBoundingRectNotFullyVisible( m_form->rect(), m_docPriv, m_pageNumber );
m_form->setCurrentChoices( m_newChoices );
emit m_docPriv->m_parent->formListChangedByUndoRedo( m_pageNumber, m_form, m_newChoices );
+ m_docPriv->notifyFormChanges( m_pageNumber );
}
+bool EditFormListCommand::refreshInternalPageReferences( const QVector< Page * > &newPagesVector )
+{
+ m_form = dynamic_cast(Okular::PagePrivate::findEquivalentForm( newPagesVector[m_pageNumber], m_form ));
+
+ return m_form;
+}
+
+
EditFormComboCommand::EditFormComboCommand( Okular::DocumentPrivate* docPriv,
FormFieldChoice* form,
int pageNumber,
const QString & newContents,
int newCursorPos,
const QString & prevContents,
int prevCursorPos,
int prevAnchorPos )
: EditTextCommand( newContents, newCursorPos, prevContents, prevCursorPos, prevAnchorPos ),
m_docPriv( docPriv ),
m_form( form ),
m_pageNumber( pageNumber ),
m_newIndex( -1 ),
m_prevIndex( -1 )
{
setText( i18nc( "Edit a combo form's selection", "edit combo form selection" ) );
// Determine new and previous choice indices (if any)
for ( int i = 0; i < m_form->choices().size(); i++ )
{
if ( m_form->choices()[i] == m_prevContents )
{
m_prevIndex = i;
}
if ( m_form->choices()[i] == m_newContents )
{
m_newIndex = i;
}
}
}
void EditFormComboCommand::undo()
{
if ( m_prevIndex != -1 )
{
m_form->setCurrentChoices( QList() << m_prevIndex );
}
else
{
m_form->setEditChoice( m_prevContents );
}
moveViewportIfBoundingRectNotFullyVisible( m_form->rect(), m_docPriv, m_pageNumber );
emit m_docPriv->m_parent->formComboChangedByUndoRedo( m_pageNumber, m_form, m_prevContents, m_prevCursorPos, m_prevAnchorPos );
+ m_docPriv->notifyFormChanges( m_pageNumber );
}
void EditFormComboCommand::redo()
{
if ( m_newIndex != -1 )
{
m_form->setCurrentChoices( QList() << m_newIndex );
}
else
{
m_form->setEditChoice( m_newContents );
}
moveViewportIfBoundingRectNotFullyVisible( m_form->rect(), m_docPriv, m_pageNumber );
emit m_docPriv->m_parent->formComboChangedByUndoRedo( m_pageNumber, m_form, m_newContents, m_newCursorPos, m_newCursorPos );
+ m_docPriv->notifyFormChanges( m_pageNumber );
}
int EditFormComboCommand::id() const
{
return 4;
}
bool EditFormComboCommand::mergeWith( const QUndoCommand *uc )
{
EditFormComboCommand *euc = (EditFormComboCommand*)uc;
// Only attempt merge of euc into this if they modify the same form
if ( m_form == euc->m_form )
{
bool shouldMerge = EditTextCommand::mergeWith( uc );
if( shouldMerge )
{
m_newIndex = euc->m_newIndex;
}
return shouldMerge;
}
else
{
return false;
}
}
+bool EditFormComboCommand::refreshInternalPageReferences( const QVector< Page * > &newPagesVector )
+{
+ m_form = dynamic_cast(Okular::PagePrivate::findEquivalentForm( newPagesVector[m_pageNumber], m_form ));
+
+ return m_form;
+}
+
+
EditFormButtonsCommand::EditFormButtonsCommand( Okular::DocumentPrivate* docPriv,
int pageNumber,
const QList< FormFieldButton* > & formButtons,
const QList< bool > & newButtonStates )
: m_docPriv( docPriv ),
m_pageNumber( pageNumber ),
m_formButtons( formButtons ),
m_newButtonStates( newButtonStates ),
m_prevButtonStates( QList< bool >() )
{
setText( i18nc( "Edit the state of a group of form buttons", "edit form button states" ) );
foreach( FormFieldButton* formButton, m_formButtons )
{
m_prevButtonStates.append( formButton->state() );
}
}
void EditFormButtonsCommand::undo()
{
clearFormButtonStates();
for( int i = 0; i < m_formButtons.size(); i++ )
{
bool checked = m_prevButtonStates.at( i );
if ( checked )
m_formButtons.at( i )->setState( checked );
}
Okular::NormalizedRect boundingRect = buildBoundingRectangleForButtons( m_formButtons );
moveViewportIfBoundingRectNotFullyVisible( boundingRect, m_docPriv, m_pageNumber );
emit m_docPriv->m_parent->formButtonsChangedByUndoRedo( m_pageNumber, m_formButtons );
+ m_docPriv->notifyFormChanges( m_pageNumber );
}
void EditFormButtonsCommand::redo()
{
clearFormButtonStates();
for( int i = 0; i < m_formButtons.size(); i++ )
{
bool checked = m_newButtonStates.at( i );
if ( checked )
m_formButtons.at( i )->setState( checked );
}
Okular::NormalizedRect boundingRect = buildBoundingRectangleForButtons( m_formButtons );
moveViewportIfBoundingRectNotFullyVisible( boundingRect, m_docPriv, m_pageNumber );
emit m_docPriv->m_parent->formButtonsChangedByUndoRedo( m_pageNumber, m_formButtons );
+ m_docPriv->notifyFormChanges( m_pageNumber );
+}
+
+bool EditFormButtonsCommand::refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector )
+{
+ const QList< FormFieldButton* > oldFormButtons = m_formButtons;
+ m_formButtons.clear();
+ foreach( FormFieldButton* oldFormButton, oldFormButtons )
+ {
+ FormFieldButton *button = dynamic_cast(Okular::PagePrivate::findEquivalentForm( newPagesVector[m_pageNumber], oldFormButton ));
+ if ( !button )
+ return false;
+ m_formButtons << button;
+ }
+
+ return true;
}
void EditFormButtonsCommand::clearFormButtonStates()
{
foreach( FormFieldButton* formButton, m_formButtons )
{
formButton->setState( false );
}
}
}
diff --git a/core/documentcommands_p.h b/core/documentcommands_p.h
index 757397337..2f4cc2d7a 100644
--- a/core/documentcommands_p.h
+++ b/core/documentcommands_p.h
@@ -1,285 +1,316 @@
/***************************************************************************
* Copyright (C) 2013 Jon Mease *
+ * Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group *
+ * company, info@kdab.com. Work sponsored by the *
+ * LiMux project of the city of Munich *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#ifndef _OKULAR_DOCUMENT_COMMANDS_P_H_
#define _OKULAR_DOCUMENT_COMMANDS_P_H_
#include
#include
#include "area.h"
namespace Okular {
class Document;
class Annotation;
class DocumentPrivate;
class FormFieldText;
class FormFieldButton;
class FormFieldChoice;
+class Page;
-class AddAnnotationCommand : public QUndoCommand
+class OkularUndoCommand : public QUndoCommand
+{
+ public:
+ virtual bool refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector ) = 0;
+};
+
+class AddAnnotationCommand : public OkularUndoCommand
{
public:
AddAnnotationCommand(Okular::DocumentPrivate * docPriv, Okular::Annotation* annotation, int pageNumber);
virtual ~AddAnnotationCommand();
void undo() override;
void redo() override;
+ bool refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector ) override;
+
private:
Okular::DocumentPrivate * m_docPriv;
Okular::Annotation* m_annotation;
int m_pageNumber;
bool m_done;
};
-class RemoveAnnotationCommand : public QUndoCommand
+class RemoveAnnotationCommand : public OkularUndoCommand
{
public:
RemoveAnnotationCommand(Okular::DocumentPrivate * doc, Okular::Annotation* annotation, int pageNumber);
virtual ~RemoveAnnotationCommand();
void undo() override;
void redo() override;
+ bool refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector ) override;
+
private:
Okular::DocumentPrivate * m_docPriv;
Okular::Annotation* m_annotation;
int m_pageNumber;
bool m_done;
};
-class ModifyAnnotationPropertiesCommand : public QUndoCommand
+class ModifyAnnotationPropertiesCommand : public OkularUndoCommand
{
public:
ModifyAnnotationPropertiesCommand( Okular::DocumentPrivate* docPriv, Okular::Annotation* annotation,
int pageNumber,
QDomNode oldProperties,
QDomNode newProperties );
void undo() override;
void redo() override;
+ bool refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector ) override;
+
private:
Okular::DocumentPrivate * m_docPriv;
Okular::Annotation* m_annotation;
int m_pageNumber;
QDomNode m_prevProperties;
QDomNode m_newProperties;
};
-class TranslateAnnotationCommand : public QUndoCommand
+class TranslateAnnotationCommand : public OkularUndoCommand
{
public:
TranslateAnnotationCommand(Okular::DocumentPrivate* docPriv,
Okular::Annotation* annotation,
int pageNumber,
const Okular::NormalizedPoint & delta,
bool completeDrag
);
void undo() override;
void redo() override;
int id() const override;
bool mergeWith(const QUndoCommand *uc) override;
Okular::NormalizedPoint minusDelta();
Okular::NormalizedRect translateBoundingRectangle( const Okular::NormalizedPoint & delta );
+ bool refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector ) override;
+
private:
Okular::DocumentPrivate * m_docPriv;
Okular::Annotation* m_annotation;
int m_pageNumber;
Okular::NormalizedPoint m_delta;
bool m_completeDrag;
};
-class AdjustAnnotationCommand : public QUndoCommand
+class AdjustAnnotationCommand : public OkularUndoCommand
{
public:
AdjustAnnotationCommand(Okular::DocumentPrivate * docPriv,
Okular::Annotation * annotation,
int pageNumber,
const Okular::NormalizedPoint & delta1,
const Okular::NormalizedPoint & delta2,
bool completeDrag
);
void undo() override;
void redo() override;
int id() const override;
bool mergeWith(const QUndoCommand * uc) override;
Okular::NormalizedRect adjustBoundingRectangle(
const Okular::NormalizedPoint & delta1, const Okular::NormalizedPoint & delta2 );
+ bool refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector ) override;
+
private:
Okular::DocumentPrivate * m_docPriv;
Okular::Annotation* m_annotation;
int m_pageNumber;
Okular::NormalizedPoint m_delta1;
Okular::NormalizedPoint m_delta2;
bool m_completeDrag;
};
-class EditTextCommand : public QUndoCommand
+class EditTextCommand : public OkularUndoCommand
{
public:
EditTextCommand( const QString & newContents,
int newCursorPos,
const QString & prevContents,
int prevCursorPos,
int prevAnchorPos
);
void undo() override = 0;
void redo() override = 0;
int id() const override = 0;
bool mergeWith(const QUndoCommand *uc) override;
private:
enum EditType {
CharBackspace, ///< Edit made up of one or more single character backspace operations
CharDelete, ///< Edit made up of one or more single character delete operations
CharInsert, ///< Edit made up of one or more single character insertion operations
OtherEdit ///< All other edit operations (these will not be merged together)
};
QString oldContentsLeftOfCursor();
QString newContentsLeftOfCursor();
QString oldContentsRightOfCursor();
QString newContentsRightOfCursor();
protected:
QString m_newContents;
int m_newCursorPos;
QString m_prevContents;
int m_prevCursorPos;
int m_prevAnchorPos;
EditType m_editType;
};
class EditAnnotationContentsCommand : public EditTextCommand
{
public:
EditAnnotationContentsCommand(Okular::DocumentPrivate* docPriv,
Okular::Annotation* annotation,
int pageNumber,
const QString & newContents,
int newCursorPos,
const QString & prevContents,
int prevCursorPos,
int prevAnchorPos
);
void undo() override;
void redo() override;
int id() const override;
bool mergeWith(const QUndoCommand *uc) override;
+ bool refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector ) override;
+
private:
Okular::DocumentPrivate * m_docPriv;
Okular::Annotation* m_annotation;
int m_pageNumber;
};
class EditFormTextCommand : public EditTextCommand
{
public:
EditFormTextCommand( Okular::DocumentPrivate* docPriv,
Okular::FormFieldText* form,
int pageNumber,
const QString & newContents,
int newCursorPos,
const QString & prevContents,
int prevCursorPos,
int prevAnchorPos );
void undo() override;
void redo() override;
int id() const override;
bool mergeWith( const QUndoCommand *uc ) override;
+
+ bool refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector ) override;
+
private:
Okular::DocumentPrivate* m_docPriv;
Okular::FormFieldText* m_form;
int m_pageNumber;
};
-class EditFormListCommand : public QUndoCommand
+class EditFormListCommand : public OkularUndoCommand
{
public:
EditFormListCommand( Okular::DocumentPrivate* docPriv,
FormFieldChoice* form,
int pageNumber,
const QList< int > & newChoices,
const QList< int > & prevChoices
);
void undo() override;
void redo() override;
+ bool refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector ) override;
+
private:
Okular::DocumentPrivate* m_docPriv;
FormFieldChoice* m_form;
int m_pageNumber;
QList< int > m_newChoices;
QList< int > m_prevChoices;
};
class EditFormComboCommand : public EditTextCommand
{
public:
EditFormComboCommand( Okular::DocumentPrivate* docPriv,
FormFieldChoice* form,
int pageNumber,
const QString & newText,
int newCursorPos,
const QString & prevText,
int prevCursorPos,
int prevAnchorPos
);
void undo() override;
void redo() override;
int id() const override;
bool mergeWith( const QUndoCommand *uc ) override;
+ bool refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector ) override;
+
private:
Okular::DocumentPrivate* m_docPriv;
FormFieldChoice* m_form;
int m_pageNumber;
int m_newIndex;
int m_prevIndex;
};
-class EditFormButtonsCommand : public QUndoCommand
+class EditFormButtonsCommand : public OkularUndoCommand
{
public:
EditFormButtonsCommand( Okular::DocumentPrivate* docPriv,
int pageNumber,
const QList< FormFieldButton* > & formButtons,
const QList< bool > & newButtonStates
);
void undo() override;
void redo() override;
+ bool refreshInternalPageReferences( const QVector< Okular::Page * > &newPagesVector ) override;
+
private:
void clearFormButtonStates();
private:
Okular::DocumentPrivate* m_docPriv;
int m_pageNumber;
QList< FormFieldButton* > m_formButtons;
QList< bool > m_newButtonStates;
QList< bool > m_prevButtonStates;
};
}
#endif
/* kate: replace-tabs on; indent-width 4; */
diff --git a/core/generator.cpp b/core/generator.cpp
index 8e888557d..ba6013bec 100644
--- a/core/generator.cpp
+++ b/core/generator.cpp
@@ -1,724 +1,729 @@
/***************************************************************************
* Copyright (C) 2005 by Piotr Szymanski *
* Copyright (C) 2008 by Albert Astals Cid *
* Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group *
* company, info@kdab.com. Work sponsored by the *
* LiMux project of the city of Munich *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "generator.h"
#include "generator_p.h"
#include "observer.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include "document.h"
#include "document_p.h"
#include "page.h"
#include "page_p.h"
#include "textpage.h"
#include "utils.h"
using namespace Okular;
GeneratorPrivate::GeneratorPrivate()
: m_document( nullptr ),
mPixmapGenerationThread( nullptr ), mTextPageGenerationThread( nullptr ),
m_mutex( nullptr ), m_threadsMutex( nullptr ), mPixmapReady( true ), mTextPageReady( true ),
m_closing( false ), m_closingLoop( nullptr ),
m_dpi(72.0, 72.0)
{
qRegisterMetaType();
}
GeneratorPrivate::~GeneratorPrivate()
{
if ( mPixmapGenerationThread )
mPixmapGenerationThread->wait();
delete mPixmapGenerationThread;
if ( mTextPageGenerationThread )
mTextPageGenerationThread->wait();
delete mTextPageGenerationThread;
delete m_mutex;
delete m_threadsMutex;
}
PixmapGenerationThread* GeneratorPrivate::pixmapGenerationThread()
{
if ( mPixmapGenerationThread )
return mPixmapGenerationThread;
Q_Q( Generator );
mPixmapGenerationThread = new PixmapGenerationThread( q );
QObject::connect( mPixmapGenerationThread, SIGNAL(finished()), q, SLOT(pixmapGenerationFinished()),
Qt::QueuedConnection );
return mPixmapGenerationThread;
}
TextPageGenerationThread* GeneratorPrivate::textPageGenerationThread()
{
if ( mTextPageGenerationThread )
return mTextPageGenerationThread;
Q_Q( Generator );
mTextPageGenerationThread = new TextPageGenerationThread( q );
QObject::connect( mTextPageGenerationThread, SIGNAL(finished()), q, SLOT(textpageGenerationFinished()),
Qt::QueuedConnection );
return mTextPageGenerationThread;
}
void GeneratorPrivate::pixmapGenerationFinished()
{
Q_Q( Generator );
PixmapRequest *request = mPixmapGenerationThread->request();
mPixmapGenerationThread->endGeneration();
QMutexLocker locker( threadsLock() );
mPixmapReady = true;
if ( m_closing )
{
delete request;
if ( mTextPageReady )
{
locker.unlock();
m_closingLoop->quit();
}
return;
}
const QImage& img = mPixmapGenerationThread->image();
request->page()->setPixmap( request->observer(), new QPixmap( QPixmap::fromImage( img ) ), request->normalizedRect() );
const int pageNumber = request->page()->number();
if ( mPixmapGenerationThread->calcBoundingBox() )
q->updatePageBoundingBox( pageNumber, mPixmapGenerationThread->boundingBox() );
q->signalPixmapRequestDone( request );
}
void GeneratorPrivate::textpageGenerationFinished()
{
Q_Q( Generator );
Page *page = mTextPageGenerationThread->page();
mTextPageGenerationThread->endGeneration();
QMutexLocker locker( threadsLock() );
mTextPageReady = true;
if ( m_closing )
{
delete mTextPageGenerationThread->textPage();
if ( mPixmapReady )
{
locker.unlock();
m_closingLoop->quit();
}
return;
}
if ( mTextPageGenerationThread->textPage() )
{
TextPage *tp = mTextPageGenerationThread->textPage();
page->setTextPage( tp );
q->signalTextGenerationDone( page, tp );
}
}
QMutex* GeneratorPrivate::threadsLock()
{
if ( !m_threadsMutex )
m_threadsMutex = new QMutex();
return m_threadsMutex;
}
QVariant GeneratorPrivate::metaData( const QString &, const QVariant & ) const
{
return QVariant();
}
QImage GeneratorPrivate::image( PixmapRequest * )
{
return QImage();
}
Generator::Generator(QObject* parent, const QVariantList&)
: QObject(parent)
, d_ptr( new GeneratorPrivate() )
{
d_ptr->q_ptr = this;
}
Generator::Generator(GeneratorPrivate &dd, QObject *parent, const QVariantList &args)
: QObject(parent), d_ptr(&dd)
{
d_ptr->q_ptr = this;
Q_UNUSED(args)
}
Generator::~Generator()
{
delete d_ptr;
}
bool Generator::loadDocument( const QString & fileName, QVector< Page * > & pagesVector )
{
Q_UNUSED(fileName);
Q_UNUSED(pagesVector);
return false;
}
bool Generator::loadDocumentFromData( const QByteArray &, QVector< Page * > & )
{
return false;
}
Document::OpenResult Generator::loadDocumentWithPassword( const QString & fileName, QVector< Page * > & pagesVector, const QString & )
{
return loadDocument( fileName, pagesVector ) ? Document::OpenSuccess : Document::OpenError;
}
Document::OpenResult Generator::loadDocumentFromDataWithPassword( const QByteArray & fileData, QVector< Page * > & pagesVector, const QString & )
{
return loadDocumentFromData( fileData, pagesVector ) ? Document::OpenSuccess : Document::OpenError;
}
+Generator::SwapBackingFileResult Generator::swapBackingFile( QString const &/*newFileName */, QVector & /*newPagesVector*/ )
+{
+ return SwapBackingFileError;
+}
+
bool Generator::closeDocument()
{
Q_D( Generator );
d->m_closing = true;
d->threadsLock()->lock();
if ( !( d->mPixmapReady && d->mTextPageReady ) )
{
QEventLoop loop;
d->m_closingLoop = &loop;
d->threadsLock()->unlock();
loop.exec();
d->m_closingLoop = nullptr;
}
else
{
d->threadsLock()->unlock();
}
bool ret = doCloseDocument();
d->m_closing = false;
return ret;
}
bool Generator::canGeneratePixmap() const
{
Q_D( const Generator );
return d->mPixmapReady;
}
void Generator::generatePixmap( PixmapRequest *request )
{
Q_D( Generator );
d->mPixmapReady = false;
const bool calcBoundingBox = !request->isTile() && !request->page()->isBoundingBoxKnown();
if ( request->asynchronous() && hasFeature( Threaded ) )
{
d->pixmapGenerationThread()->startGeneration( request, calcBoundingBox );
/**
* We create the text page for every page that is visible to the
* user, so he can use the text extraction tools without a delay.
*/
if ( hasFeature( TextExtraction ) && !request->page()->hasTextPage() && canGenerateTextPage() && !d->m_closing ) {
d->mTextPageReady = false;
// Queue the text generation request so that pixmap generation gets a chance to start before the text generation
QMetaObject::invokeMethod(d->textPageGenerationThread(), "startGeneration", Qt::QueuedConnection, Q_ARG(Okular::Page*, request->page()));
}
return;
}
const QImage& img = image( request );
request->page()->setPixmap( request->observer(), new QPixmap( QPixmap::fromImage( img ) ), request->normalizedRect() );
const int pageNumber = request->page()->number();
d->mPixmapReady = true;
signalPixmapRequestDone( request );
if ( calcBoundingBox )
updatePageBoundingBox( pageNumber, Utils::imageBoundingBox( &img ) );
}
bool Generator::canGenerateTextPage() const
{
Q_D( const Generator );
return d->mTextPageReady;
}
void Generator::generateTextPage( Page *page )
{
TextPage *tp = textPage( page );
page->setTextPage( tp );
signalTextGenerationDone( page, tp );
}
QImage Generator::image( PixmapRequest *request )
{
Q_D( Generator );
return d->image( request );
}
TextPage* Generator::textPage( Page* )
{
return nullptr;
}
DocumentInfo Generator::generateDocumentInfo(const QSet &keys) const
{
Q_UNUSED(keys);
return DocumentInfo();
}
const DocumentSynopsis * Generator::generateDocumentSynopsis()
{
return nullptr;
}
FontInfo::List Generator::fontsForPage( int )
{
return FontInfo::List();
}
const QList * Generator::embeddedFiles() const
{
return nullptr;
}
Generator::PageSizeMetric Generator::pagesSizeMetric() const
{
return None;
}
bool Generator::isAllowed( Permission ) const
{
return true;
}
void Generator::rotationChanged( Rotation, Rotation )
{
}
PageSize::List Generator::pageSizes() const
{
return PageSize::List();
}
void Generator::pageSizeChanged( const PageSize &, const PageSize & )
{
}
bool Generator::print( QPrinter& )
{
return false;
}
Generator::PrintError Generator::printError() const
{
return UnknownPrintError;
}
void Generator::opaqueAction( const BackendOpaqueAction * /*action*/ )
{
}
QVariant Generator::metaData( const QString &key, const QVariant &option ) const
{
Q_D( const Generator );
return d->metaData( key, option );
}
ExportFormat::List Generator::exportFormats() const
{
return ExportFormat::List();
}
bool Generator::exportTo( const QString&, const ExportFormat& )
{
return false;
}
void Generator::walletDataForFile( const QString &fileName, QString *walletName, QString *walletFolder, QString *walletKey ) const
{
*walletKey = fileName.section( QLatin1Char('/'), -1, -1);
*walletName = KWallet::Wallet::NetworkWallet();
*walletFolder = QStringLiteral("KPdf");
}
bool Generator::hasFeature( GeneratorFeature feature ) const
{
Q_D( const Generator );
return d->m_features.contains( feature );
}
void Generator::signalPixmapRequestDone( PixmapRequest * request )
{
Q_D( Generator );
if ( d->m_document )
d->m_document->requestDone( request );
else
{
delete request;
}
}
void Generator::signalTextGenerationDone( Page *page, TextPage *textPage )
{
Q_D( Generator );
if ( d->m_document )
d->m_document->textGenerationDone( page );
else
delete textPage;
}
void Generator::signalPartialPixmapRequest( PixmapRequest *request, const QImage &image )
{
request->page()->setPixmap( request->observer(), new QPixmap( QPixmap::fromImage( image ) ), request->normalizedRect() );
const int pageNumber = request->page()->number();
request->observer()->notifyPageChanged( pageNumber, Okular::DocumentObserver::Pixmap );
}
const Document * Generator::document() const
{
Q_D( const Generator );
if ( d->m_document )
{
return d->m_document->m_parent;
}
return nullptr;
}
void Generator::setFeature( GeneratorFeature feature, bool on )
{
Q_D( Generator );
if ( on )
d->m_features.insert( feature );
else
d->m_features.remove( feature );
}
QVariant Generator::documentMetaData( const QString &key, const QVariant &option ) const
{
Q_D( const Generator );
if ( !d->m_document )
return QVariant();
if (key == QLatin1String("PaperColor"))
return documentMetaData(PaperColorMetaData, option);
if (key == QLatin1String("GraphicsAntialias"))
return documentMetaData(GraphicsAntialiasMetaData, option);
if (key == QLatin1String("TextAntialias"))
return documentMetaData(TextAntialiasMetaData, option);
if (key == QLatin1String("TextHinting"))
return documentMetaData(TextHintingMetaData, option);
return QVariant();
}
QVariant Generator::documentMetaData( const DocumentMetaDataKey key, const QVariant &option ) const
{
Q_D( const Generator );
if ( !d->m_document )
return QVariant();
return d->m_document->documentMetaData( key, option );
}
QMutex* Generator::userMutex() const
{
Q_D( const Generator );
if ( !d->m_mutex )
{
d->m_mutex = new QMutex();
}
return d->m_mutex;
}
void Generator::updatePageBoundingBox( int page, const NormalizedRect & boundingBox )
{
Q_D( Generator );
if ( d->m_document ) // still connected to document?
d->m_document->setPageBoundingBox( page, boundingBox );
}
void Generator::requestFontData(const Okular::FontInfo & /*font*/, QByteArray * /*data*/)
{
}
void Generator::setDPI(const QSizeF & dpi)
{
Q_D( Generator );
d->m_dpi = dpi;
}
QSizeF Generator::dpi() const
{
Q_D( const Generator );
return d->m_dpi;
}
QAbstractItemModel * Generator::layersModel() const
{
return nullptr;
}
PixmapRequest::PixmapRequest( DocumentObserver *observer, int pageNumber, int width, int height, int priority, PixmapRequestFeatures features )
: d( new PixmapRequestPrivate )
{
d->mObserver = observer;
d->mPageNumber = pageNumber;
d->mWidth = ceil(width * qApp->devicePixelRatio());
d->mHeight = ceil(height * qApp->devicePixelRatio());
d->mPriority = priority;
d->mFeatures = features;
d->mForce = false;
d->mTile = false;
d->mNormalizedRect = NormalizedRect();
d->mPartialUpdatesWanted = false;
}
PixmapRequest::~PixmapRequest()
{
delete d;
}
DocumentObserver *PixmapRequest::observer() const
{
return d->mObserver;
}
int PixmapRequest::pageNumber() const
{
return d->mPageNumber;
}
int PixmapRequest::width() const
{
return d->mWidth;
}
int PixmapRequest::height() const
{
return d->mHeight;
}
int PixmapRequest::priority() const
{
return d->mPriority;
}
bool PixmapRequest::asynchronous() const
{
return d->mFeatures & Asynchronous;
}
bool PixmapRequest::preload() const
{
return d->mFeatures & Preload;
}
Page* PixmapRequest::page() const
{
return d->mPage;
}
void PixmapRequest::setTile( bool tile )
{
d->mTile = tile;
}
bool PixmapRequest::isTile() const
{
return d->mTile;
}
void PixmapRequest::setNormalizedRect( const NormalizedRect &rect )
{
if ( d->mNormalizedRect == rect )
return;
d->mNormalizedRect = rect;
}
const NormalizedRect& PixmapRequest::normalizedRect() const
{
return d->mNormalizedRect;
}
void PixmapRequest::setPartialUpdatesWanted(bool partialUpdatesWanted)
{
d->mPartialUpdatesWanted = partialUpdatesWanted;
}
bool PixmapRequest::partialUpdatesWanted() const
{
return d->mPartialUpdatesWanted;
}
Okular::TilesManager* PixmapRequestPrivate::tilesManager() const
{
return mPage->d->tilesManager(mObserver);
}
void PixmapRequestPrivate::swap()
{
qSwap( mWidth, mHeight );
}
class Okular::ExportFormatPrivate : public QSharedData
{
public:
ExportFormatPrivate( const QString &description, const QMimeType &mimeType, const QIcon &icon = QIcon() )
: QSharedData(), mDescription( description ), mMimeType( mimeType ), mIcon( icon )
{
}
~ExportFormatPrivate()
{
}
QString mDescription;
QMimeType mMimeType;
QIcon mIcon;
};
ExportFormat::ExportFormat()
: d( new ExportFormatPrivate( QString(), QMimeType() ) )
{
}
ExportFormat::ExportFormat( const QString &description, const QMimeType &mimeType )
: d( new ExportFormatPrivate( description, mimeType ) )
{
}
ExportFormat::ExportFormat( const QIcon &icon, const QString &description, const QMimeType &mimeType )
: d( new ExportFormatPrivate( description, mimeType, icon ) )
{
}
ExportFormat::~ExportFormat()
{
}
ExportFormat::ExportFormat( const ExportFormat &other )
: d( other.d )
{
}
ExportFormat& ExportFormat::operator=( const ExportFormat &other )
{
if ( this == &other )
return *this;
d = other.d;
return *this;
}
QString ExportFormat::description() const
{
return d->mDescription;
}
QMimeType ExportFormat::mimeType() const
{
return d->mMimeType;
}
QIcon ExportFormat::icon() const
{
return d->mIcon;
}
bool ExportFormat::isNull() const
{
return !d->mMimeType.isValid() || d->mDescription.isNull();
}
ExportFormat ExportFormat::standardFormat( StandardExportFormat type )
{
QMimeDatabase db;
switch ( type )
{
case PlainText:
return ExportFormat( QIcon::fromTheme( QStringLiteral("text-x-generic") ), i18n( "Plain &Text..." ), db.mimeTypeForName( QStringLiteral("text/plain") ) );
break;
case PDF:
return ExportFormat( QIcon::fromTheme( QStringLiteral("application-pdf") ), i18n( "PDF" ), db.mimeTypeForName( QStringLiteral("application/pdf") ) );
break;
case OpenDocumentText:
return ExportFormat(
QIcon::fromTheme( QStringLiteral("application-vnd.oasis.opendocument.text") ),
i18nc( "This is the document format", "OpenDocument Text" ),
db.mimeTypeForName( QStringLiteral("application/vnd.oasis.opendocument.text") ) );
break;
case HTML:
return ExportFormat( QIcon::fromTheme( QStringLiteral("text-html") ), i18nc( "This is the document format", "HTML" ), db.mimeTypeForName( QStringLiteral("text/html") ) );
break;
}
return ExportFormat();
}
bool ExportFormat::operator==( const ExportFormat &other ) const
{
return d == other.d;
}
bool ExportFormat::operator!=( const ExportFormat &other ) const
{
return d != other.d;
}
QDebug operator<<( QDebug str, const Okular::PixmapRequest &req )
{
QString s = QStringLiteral( "PixmapRequest(#%2, %1, %3x%4, page %6, prio %5)" )
.arg( QString( req.asynchronous() ? QStringLiteral ( "async" ) : QStringLiteral ( "sync" ) ) )
.arg( (qulonglong)req.observer() )
.arg( req.width() )
.arg( req.height() )
.arg( req.priority() )
.arg( req.pageNumber() );
str << qPrintable( s );
return str;
}
#include "moc_generator.cpp"
/* kate: replace-tabs on; indent-width 4; */
diff --git a/core/generator.h b/core/generator.h
index 5209093a1..24438548e 100644
--- a/core/generator.h
+++ b/core/generator.h
@@ -1,751 +1,773 @@
/***************************************************************************
* Copyright (C) 2004-5 by Enrico Ros *
* Copyright (C) 2005 by Piotr Szymanski *
* Copyright (C) 2008 by Albert Astals Cid *
* Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group *
* company, info@kdab.com. Work sponsored by the *
* LiMux project of the city of Munich *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#ifndef _OKULAR_GENERATOR_H_
#define _OKULAR_GENERATOR_H_
#include "okularcore_export.h"
#include "document.h"
#include "fontinfo.h"
#include "global.h"
#include "pagesize.h"
#include
#include
#include
#include