Enable readability-braces-around-statements

This commit is contained in:
Volker Krause 2022-03-08 11:10:43 +01:00 committed by Albert Astals Cid
parent f28764e59c
commit 50d0703ae0
160 changed files with 5791 additions and 3007 deletions

View File

@ -1,5 +1,5 @@
---
Checks: 'clang-diagnostic-*,clang-analyzer-*,-*,performance-*,bugprone-*,readability-inconsistent-declaration-parameter-name,readability-string-compare,modernize-redundant-void-arg,modernize-use-bool-literals,modernize-make-unique,modernize-make-shared,modernize-use-override,modernize-use-equals-delete,modernize-use-emplace,modernize-loop-convert,modernize-use-nullptr,google-explicit-constructor,-bugprone-macro-parentheses,-bugprone-narrowing-conversions,-bugprone-branch-clone,-bugprone-incorrect-roundings,-bugprone-suspicious-include,-bugprone-reserved-identifier,-performance-no-automatic-move,-bugprone-suspicious-enum-usage,-bugprone-easily-swappable-parameters,-performance-no-int-to-ptr,-bugprone-implicit-widening-of-multiplication-result'
Checks: 'clang-diagnostic-*,clang-analyzer-*,-*,performance-*,bugprone-*,readability-inconsistent-declaration-parameter-name,readability-string-compare,readability-braces-around-statements,modernize-redundant-void-arg,modernize-use-bool-literals,modernize-make-unique,modernize-make-shared,modernize-use-override,modernize-use-equals-delete,modernize-use-emplace,modernize-loop-convert,modernize-use-nullptr,google-explicit-constructor,-bugprone-macro-parentheses,-bugprone-narrowing-conversions,-bugprone-branch-clone,-bugprone-incorrect-roundings,-bugprone-suspicious-include,-bugprone-reserved-identifier,-performance-no-automatic-move,-bugprone-suspicious-enum-usage,-bugprone-easily-swappable-parameters,-performance-no-int-to-ptr,-bugprone-implicit-widening-of-multiplication-result'
WarningsAsErrors: '*'
HeaderFilterRegex: '.*/okular/.*'
AnalyzeTemporaryDtors: false

View File

@ -90,8 +90,9 @@ void AnnotationTest::testDistance_data()
Okular::GeomAnnotation *square = new Okular::GeomAnnotation;
square->setGeometricalType(Okular::GeomAnnotation::InscribedSquare);
square->setBoundingRectangle(Okular::NormalizedRect(0.1, 0.1, 0.9, 0.9));
if (i != 0)
if (i != 0) {
square->setGeometricalInnerColor(QColor(0, 0, 0));
}
m_document->addPageAnnotation(0, square);
QTest::newRow("Square: Base point 1") << (Okular::Annotation *)square << 0.1 << 0.1 << 0;
QTest::newRow("Square: On edge 1") << (Okular::Annotation *)square << 0.1 << 0.2 << 0;
@ -105,8 +106,9 @@ void AnnotationTest::testDistance_data()
Okular::GeomAnnotation *ellipse = new Okular::GeomAnnotation;
ellipse->setGeometricalType(Okular::GeomAnnotation::InscribedCircle);
ellipse->setBoundingRectangle(Okular::NormalizedRect(0.1, 0.1, 0.9, 0.5));
if (i != 0)
if (i != 0) {
ellipse->setGeometricalInnerColor(QColor(0, 0, 0));
}
m_document->addPageAnnotation(0, ellipse);
QTest::newRow("Ellipse: Base point 1") << (Okular::Annotation *)ellipse << 0.1 << 0.3 << 0;
QTest::newRow("Ellipse: Inside") << (Okular::Annotation *)ellipse << 0.2 << 0.3 << qRound((i == 0) ? pow(documentX * 0.1, 2) - 1 /* pen */ : 0);

View File

@ -75,8 +75,9 @@ Shell *findShell(Shell *ignore = nullptr)
const QWidgetList wList = QApplication::topLevelWidgets();
for (QWidget *widget : wList) {
Shell *s = qobject_cast<Shell *>(widget);
if (s && s != ignore)
if (s && s != ignore) {
return s;
}
}
return nullptr;
}

View File

@ -55,8 +55,9 @@ void FormatTest::initTestCase()
connect(m_document, &Okular::Document::refreshFormWidget, this, [this](Okular::FormField *form) {
Okular::FormFieldText *fft = reinterpret_cast<Okular::FormFieldText *>(form);
if (fft)
if (fft) {
m_formattedText = fft->text();
}
});
const Okular::Page *page = m_document->page(0);

View File

@ -170,8 +170,9 @@ void KJSFunctionsTest::testDisplay()
void delay()
{
QTime dieTime = QTime::currentTime().addSecs(2);
while (QTime::currentTime() < dieTime)
while (QTime::currentTime() < dieTime) {
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
}
void KJSFunctionsTest::testSetClearInterval()

View File

@ -123,8 +123,9 @@ Shell *findShell(Shell *ignore = nullptr)
const QWidgetList wList = QApplication::topLevelWidgets();
for (QWidget *widget : wList) {
Shell *s = qobject_cast<Shell *>(widget);
if (s && s != ignore)
if (s && s != ignore) {
return s;
}
}
return nullptr;
}
@ -311,14 +312,18 @@ void MainShellTest::testShell()
QProcess p;
QStringList args;
args << externalProcessPath;
if (unique)
if (unique) {
args << QStringLiteral("-unique");
if (externalProcessExpectedPage != 0)
}
if (externalProcessExpectedPage != 0) {
args << QStringLiteral("-page") << QString::number(externalProcessExpectedPage + 1);
if (externalProcessExpectPresentation)
}
if (externalProcessExpectPresentation) {
args << QStringLiteral("-presentation");
if (externalProcessExpectPrintDialog)
}
if (externalProcessExpectPrintDialog) {
args << QStringLiteral("-print");
}
p.start(QStringLiteral(OKULAR_BINARY), args);
p.waitForStarted();
QCOMPARE(p.state(), QProcess::Running);
@ -409,10 +414,11 @@ void MainShellTest::testFileRemembersPagePosition()
const QStringList paths = QStringList(QStringLiteral(KDESRCDIR "data/contents.epub"));
QString serializedOptions;
if (mode == 1 || mode == 3)
if (mode == 1 || mode == 3) {
serializedOptions = ShellUtils::serializeOptions(false, false, false, false, false, QString(), QString(), QString());
else
} else {
serializedOptions = ShellUtils::serializeOptions(false, false, false, true, false, QString(), QString(), QString());
}
Okular::Settings::self()->setShellOpenFileInTabs(mode == 3);
@ -437,8 +443,9 @@ void MainShellTest::testFileRemembersPagePosition()
QProcess p;
QStringList args;
args << paths[0];
if (mode == 2)
if (mode == 2) {
args << QStringLiteral("-unique");
}
p.start(QStringLiteral(OKULAR_BINARY), args);
p.waitForStarted();
QCOMPARE(p.state(), QProcess::Running);

View File

@ -129,10 +129,11 @@ public:
bool queryClose() override
{
if (behavior == PassThru)
if (behavior == PassThru) {
return Okular::Part::queryClose();
else // ReturnTrue or ReturnFalse
} else { // ReturnTrue or ReturnFalse
return (behavior == ReturnTrue);
}
}
private:
@ -1020,8 +1021,9 @@ void PartTest::testSaveAs()
part.openDocument(nativeDirectSave.fileName());
QCOMPARE(part.m_document->page(0)->annotations().size(), nativelySupportsAnnotations ? 1 : 0);
if (nativelySupportsAnnotations)
if (nativelySupportsAnnotations) {
QCOMPARE(part.m_document->page(0)->annotations().first()->uniqueName(), annotName);
}
part.closeUrl();
}
@ -1033,8 +1035,9 @@ void PartTest::testSaveAs()
part.openDocument(nativeFromArchiveFile.fileName());
QCOMPARE(part.m_document->page(0)->annotations().size(), nativelySupportsAnnotations ? 1 : 0);
if (nativelySupportsAnnotations)
if (nativelySupportsAnnotations) {
QCOMPARE(part.m_document->page(0)->annotations().first()->uniqueName(), annotName);
}
part.closeUrl();
}

View File

@ -14,8 +14,9 @@
static const QUrl makeUrlFromCwd(const QString &u, const QString &ref = QString())
{
QUrl url = QUrl::fromLocalFile(QDir::currentPath() + QLatin1Char('/') + u);
if (!ref.isEmpty())
if (!ref.isEmpty()) {
url.setFragment(ref);
}
url.setPath(QDir::cleanPath(url.path()));
return url;
}

View File

@ -53,8 +53,9 @@ static double distanceSqr(double x, double y, double xScale, double yScale, cons
for (++i; i != path.constEnd(); ++i) {
thisDistance = NormalizedPoint::distanceSqr(x, y, xScale, yScale, lastPoint, (*i));
if (thisDistance < distance)
if (thisDistance < distance) {
distance = thisDistance;
}
lastPoint = *i;
}
@ -91,8 +92,9 @@ static double strokeDistance(double distance, double penWidth)
Annotation *AnnotationUtils::createAnnotation(const QDomElement &annElement)
{
// safety check on annotation element
if (!annElement.hasAttribute(QStringLiteral("type")))
if (!annElement.hasAttribute(QStringLiteral("type"))) {
return nullptr;
}
// build annotation of given type
Annotation *annotation = nullptr;
@ -140,8 +142,9 @@ QDomElement AnnotationUtils::findChildElement(const QDomNode &parentNode, const
QDomNode subNode = parentNode.firstChild();
while (subNode.isElement()) {
QDomElement element = subNode.toElement();
if (element.tagName() == name)
if (element.tagName() == name) {
return element;
}
subNode = subNode.nextSibling();
}
// if the name can't be found, return a dummy null element
@ -257,8 +260,9 @@ Annotation::Style::Style(const Style &other)
Annotation::Style &Annotation::Style::operator=(const Style &other)
{
if (this != &other)
if (this != &other) {
*d = *other.d;
}
return *this;
}
@ -399,8 +403,9 @@ Annotation::Window::Window(const Window &other)
Annotation::Window &Annotation::Window::operator=(const Window &other)
{
if (this != &other)
if (this != &other) {
*d = *other.d;
}
return *this;
}
@ -498,8 +503,9 @@ Annotation::Revision::Revision(const Revision &other)
Annotation::Revision &Annotation::Revision::operator=(const Revision &other)
{
if (this != &other)
if (this != &other) {
*d = *other.d;
}
return *this;
}
@ -544,12 +550,14 @@ AnnotationPrivate::AnnotationPrivate()
AnnotationPrivate::~AnnotationPrivate()
{
// delete all children revisions
if (m_revisions.isEmpty())
if (m_revisions.isEmpty()) {
return;
}
QLinkedList<Annotation::Revision>::iterator it = m_revisions.begin(), end = m_revisions.end();
for (; it != end; ++it)
for (; it != end; ++it) {
delete (*it).annotation();
}
}
AnnotationPrivate *AnnotationPrivate::get(Annotation *a)
@ -570,8 +578,9 @@ Annotation::Annotation(AnnotationPrivate &dd, const QDomNode &description)
Annotation::~Annotation()
{
if (d_ptr->m_disposeFunc)
if (d_ptr->m_disposeFunc) {
d_ptr->m_disposeFunc(this);
}
delete d_ptr;
}
@ -755,12 +764,14 @@ bool Annotation::canBeMoved() const
Q_D(const Annotation);
// Don't move annotations if they cannot be modified
if (!d->m_page || !d->m_page->m_doc->m_parent->canModifyPageAnnotation(this))
if (!d->m_page || !d->m_page->m_doc->m_parent->canModifyPageAnnotation(this)) {
return false;
}
// highlight "requires" to be "bounded" to text, and that's tricky for now
if (subType() == AHighlight)
if (subType() == AHighlight) {
return false;
}
return true;
}
@ -770,8 +781,9 @@ bool Annotation::canBeResized() const
Q_D(const Annotation);
// Don't resize annotations if they cannot be modified
if (!d->m_page || !d->m_page->m_doc->m_parent->canModifyPageAnnotation(this))
if (!d->m_page || !d->m_page->m_doc->m_parent->canModifyPageAnnotation(this)) {
return false;
}
return d->canBeResized();
}
@ -784,24 +796,32 @@ void Annotation::store(QDomNode &annNode, QDomDocument &document) const
annNode.appendChild(e);
// store -contents- attributes
if (!d->m_author.isEmpty())
if (!d->m_author.isEmpty()) {
e.setAttribute(QStringLiteral("author"), d->m_author);
if (!d->m_contents.isEmpty())
}
if (!d->m_contents.isEmpty()) {
e.setAttribute(QStringLiteral("contents"), d->m_contents);
if (!d->m_uniqueName.isEmpty())
}
if (!d->m_uniqueName.isEmpty()) {
e.setAttribute(QStringLiteral("uniqueName"), d->m_uniqueName);
if (d->m_modifyDate.isValid())
}
if (d->m_modifyDate.isValid()) {
e.setAttribute(QStringLiteral("modifyDate"), d->m_modifyDate.toString(Qt::ISODate));
if (d->m_creationDate.isValid())
}
if (d->m_creationDate.isValid()) {
e.setAttribute(QStringLiteral("creationDate"), d->m_creationDate.toString(Qt::ISODate));
}
// store -other- attributes
if (d->m_flags) // Strip internal flags
if (d->m_flags) { // Strip internal flags
e.setAttribute(QStringLiteral("flags"), d->m_flags & ~(External | ExternallyDrawn | BeingMoved | BeingResized));
if (d->m_style.color().isValid())
}
if (d->m_style.color().isValid()) {
e.setAttribute(QStringLiteral("color"), d->m_style.color().name(QColor::HexArgb));
if (d->m_style.opacity() != 1.0)
}
if (d->m_style.opacity() != 1.0) {
e.setAttribute(QStringLiteral("opacity"), QString::number(d->m_style.opacity()));
}
// Sub-Node-1 - boundary
QDomElement bE = document.createElement(QStringLiteral("boundary"));
@ -845,8 +865,9 @@ void Annotation::store(QDomNode &annNode, QDomDocument &document) const
}
// create [revision] element of the annotation node (if any)
if (d->m_revisions.isEmpty())
if (d->m_revisions.isEmpty()) {
return;
}
// add all revisions as children of revisions element
QLinkedList<Revision>::const_iterator it = d->m_revisions.begin(), end = d->m_revisions.end();
@ -950,28 +971,37 @@ void AnnotationPrivate::setAnnotationProperties(const QDomNode &node)
{
// get the [base] element of the annotation node
QDomElement e = AnnotationUtils::findChildElement(node, QStringLiteral("base"));
if (e.isNull())
if (e.isNull()) {
return;
}
// parse -contents- attributes
if (e.hasAttribute(QStringLiteral("author")))
if (e.hasAttribute(QStringLiteral("author"))) {
m_author = e.attribute(QStringLiteral("author"));
if (e.hasAttribute(QStringLiteral("contents")))
}
if (e.hasAttribute(QStringLiteral("contents"))) {
m_contents = e.attribute(QStringLiteral("contents"));
if (e.hasAttribute(QStringLiteral("uniqueName")))
}
if (e.hasAttribute(QStringLiteral("uniqueName"))) {
m_uniqueName = e.attribute(QStringLiteral("uniqueName"));
if (e.hasAttribute(QStringLiteral("modifyDate")))
}
if (e.hasAttribute(QStringLiteral("modifyDate"))) {
m_modifyDate = QDateTime::fromString(e.attribute(QStringLiteral("modifyDate")), Qt::ISODate);
if (e.hasAttribute(QStringLiteral("creationDate")))
}
if (e.hasAttribute(QStringLiteral("creationDate"))) {
m_creationDate = QDateTime::fromString(e.attribute(QStringLiteral("creationDate")), Qt::ISODate);
}
// parse -other- attributes
if (e.hasAttribute(QStringLiteral("flags")))
if (e.hasAttribute(QStringLiteral("flags"))) {
m_flags = e.attribute(QStringLiteral("flags")).toInt();
if (e.hasAttribute(QStringLiteral("color")))
}
if (e.hasAttribute(QStringLiteral("color"))) {
m_style.setColor(QColor(e.attribute(QStringLiteral("color"))));
if (e.hasAttribute(QStringLiteral("opacity")))
}
if (e.hasAttribute(QStringLiteral("opacity"))) {
m_style.setOpacity(e.attribute(QStringLiteral("opacity")).toDouble());
}
// parse -the-subnodes- (describing Style, Window, Revision(s) structures)
// Note: all subnodes if present must be 'attributes complete'
@ -1013,8 +1043,9 @@ void AnnotationPrivate::setAnnotationProperties(const QDomNode &node)
QDomNode revNode = node.firstChild();
for (; revNode.isElement(); revNode = revNode.nextSibling()) {
QDomElement revElement = revNode.toElement();
if (revElement.tagName() != QLatin1String("revision"))
if (revElement.tagName() != QLatin1String("revision")) {
continue;
}
// compile the Revision structure crating annotation
Annotation::Revision revision;
@ -1023,8 +1054,9 @@ void AnnotationPrivate::setAnnotationProperties(const QDomNode &node)
revision.setAnnotation(AnnotationUtils::createAnnotation(revElement));
// if annotation is valid, add revision to internal list
if (revision.annotation())
if (revision.annotation()) {
m_revisions.append(revision);
}
}
m_transformedBoundary = m_boundary;
@ -1149,8 +1181,9 @@ int TextAnnotation::inplaceAlignment() const
void TextAnnotation::setInplaceCallout(const NormalizedPoint &point, int index)
{
if (index < 0 || index > 2)
if (index < 0 || index > 2) {
return;
}
Q_D(TextAnnotation);
d->m_inplaceCallout[index] = point;
@ -1158,8 +1191,9 @@ void TextAnnotation::setInplaceCallout(const NormalizedPoint &point, int index)
NormalizedPoint TextAnnotation::inplaceCallout(int index) const
{
if (index < 0 || index > 2)
if (index < 0 || index > 2) {
return NormalizedPoint();
}
Q_D(const TextAnnotation);
return d->m_inplaceCallout[index];
@ -1167,8 +1201,9 @@ NormalizedPoint TextAnnotation::inplaceCallout(int index) const
NormalizedPoint TextAnnotation::transformedInplaceCallout(int index) const
{
if (index < 0 || index > 2)
if (index < 0 || index > 2) {
return NormalizedPoint();
}
Q_D(const TextAnnotation);
return d->m_transformedInplaceCallout[index];
@ -1202,18 +1237,24 @@ void TextAnnotation::store(QDomNode &node, QDomDocument &document) const
node.appendChild(textElement);
// store the optional attributes
if (d->m_textType != Linked)
if (d->m_textType != Linked) {
textElement.setAttribute(QStringLiteral("type"), (int)d->m_textType);
if (!d->m_textIcon.isEmpty())
}
if (!d->m_textIcon.isEmpty()) {
textElement.setAttribute(QStringLiteral("icon"), d->m_textIcon);
if (d->m_textFont != QApplication::font())
}
if (d->m_textFont != QApplication::font()) {
textElement.setAttribute(QStringLiteral("font"), d->m_textFont.toString());
if (d->m_textColor.isValid())
}
if (d->m_textColor.isValid()) {
textElement.setAttribute(QStringLiteral("fontColor"), d->m_textColor.name());
if (d->m_inplaceAlign)
}
if (d->m_inplaceAlign) {
textElement.setAttribute(QStringLiteral("align"), d->m_inplaceAlign);
if (d->m_inplaceIntent != Unknown)
}
if (d->m_inplaceIntent != Unknown) {
textElement.setAttribute(QStringLiteral("intent"), (int)d->m_inplaceIntent);
}
// Sub-Node - callout
if (d->m_inplaceCallout[0].x != 0.0) {
@ -1284,22 +1325,29 @@ void TextAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
while (subNode.isElement()) {
QDomElement e = subNode.toElement();
subNode = subNode.nextSibling();
if (e.tagName() != QLatin1String("text"))
if (e.tagName() != QLatin1String("text")) {
continue;
}
// parse the attributes
if (e.hasAttribute(QStringLiteral("type")))
if (e.hasAttribute(QStringLiteral("type"))) {
m_textType = (TextAnnotation::TextType)e.attribute(QStringLiteral("type")).toInt();
if (e.hasAttribute(QStringLiteral("icon")))
}
if (e.hasAttribute(QStringLiteral("icon"))) {
m_textIcon = e.attribute(QStringLiteral("icon"));
if (e.hasAttribute(QStringLiteral("font")))
}
if (e.hasAttribute(QStringLiteral("font"))) {
m_textFont.fromString(e.attribute(QStringLiteral("font")));
if (e.hasAttribute(QStringLiteral("fontColor")))
}
if (e.hasAttribute(QStringLiteral("fontColor"))) {
m_textColor = QColor(e.attribute(QStringLiteral("fontColor")));
if (e.hasAttribute(QStringLiteral("align")))
}
if (e.hasAttribute(QStringLiteral("align"))) {
m_inplaceAlign = e.attribute(QStringLiteral("align")).toInt();
if (e.hasAttribute(QStringLiteral("intent")))
}
if (e.hasAttribute(QStringLiteral("intent"))) {
m_inplaceIntent = (TextAnnotation::InplaceIntent)e.attribute(QStringLiteral("intent")).toInt();
}
// parse the subnodes
QDomNode eSubNode = e.firstChild();
@ -1323,8 +1371,9 @@ void TextAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
break;
}
for (int i = 0; i < 3; ++i)
for (int i = 0; i < 3; ++i) {
m_transformedInplaceCallout[i] = m_inplaceCallout[i];
}
}
bool TextAnnotationPrivate::canBeResized() const
@ -1521,22 +1570,30 @@ void LineAnnotation::store(QDomNode &node, QDomDocument &document) const
node.appendChild(lineElement);
// store the attributes
if (d->m_lineStartStyle != None)
if (d->m_lineStartStyle != None) {
lineElement.setAttribute(QStringLiteral("startStyle"), (int)d->m_lineStartStyle);
if (d->m_lineEndStyle != None)
}
if (d->m_lineEndStyle != None) {
lineElement.setAttribute(QStringLiteral("endStyle"), (int)d->m_lineEndStyle);
if (d->m_lineClosed)
}
if (d->m_lineClosed) {
lineElement.setAttribute(QStringLiteral("closed"), d->m_lineClosed);
if (d->m_lineInnerColor.isValid())
}
if (d->m_lineInnerColor.isValid()) {
lineElement.setAttribute(QStringLiteral("innerColor"), d->m_lineInnerColor.name());
if (d->m_lineLeadingFwdPt != 0.0)
}
if (d->m_lineLeadingFwdPt != 0.0) {
lineElement.setAttribute(QStringLiteral("leadFwd"), QString::number(d->m_lineLeadingFwdPt));
if (d->m_lineLeadingBackPt != 0.0)
}
if (d->m_lineLeadingBackPt != 0.0) {
lineElement.setAttribute(QStringLiteral("leadBack"), QString::number(d->m_lineLeadingBackPt));
if (d->m_lineShowCaption)
}
if (d->m_lineShowCaption) {
lineElement.setAttribute(QStringLiteral("showCaption"), d->m_lineShowCaption);
if (d->m_lineIntent != Unknown)
}
if (d->m_lineIntent != Unknown) {
lineElement.setAttribute(QStringLiteral("intent"), d->m_lineIntent);
}
// append the list of points
int points = d->m_linePoints.count();
@ -1558,8 +1615,9 @@ void LineAnnotationPrivate::transform(const QTransform &matrix)
AnnotationPrivate::transform(matrix);
QMutableLinkedListIterator<NormalizedPoint> it(m_transformedLinePoints);
while (it.hasNext())
while (it.hasNext()) {
it.next().transform(matrix);
}
}
void LineAnnotationPrivate::baseTransform(const QTransform &matrix)
@ -1567,8 +1625,9 @@ void LineAnnotationPrivate::baseTransform(const QTransform &matrix)
AnnotationPrivate::baseTransform(matrix);
QMutableLinkedListIterator<NormalizedPoint> it(m_linePoints);
while (it.hasNext())
while (it.hasNext()) {
it.next().transform(matrix);
}
}
void LineAnnotationPrivate::resetTransformation()
@ -1599,26 +1658,35 @@ void LineAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
while (subNode.isElement()) {
QDomElement e = subNode.toElement();
subNode = subNode.nextSibling();
if (e.tagName() != QLatin1String("line"))
if (e.tagName() != QLatin1String("line")) {
continue;
}
// parse the attributes
if (e.hasAttribute(QStringLiteral("startStyle")))
if (e.hasAttribute(QStringLiteral("startStyle"))) {
m_lineStartStyle = (LineAnnotation::TermStyle)e.attribute(QStringLiteral("startStyle")).toInt();
if (e.hasAttribute(QStringLiteral("endStyle")))
}
if (e.hasAttribute(QStringLiteral("endStyle"))) {
m_lineEndStyle = (LineAnnotation::TermStyle)e.attribute(QStringLiteral("endStyle")).toInt();
if (e.hasAttribute(QStringLiteral("closed")))
}
if (e.hasAttribute(QStringLiteral("closed"))) {
m_lineClosed = e.attribute(QStringLiteral("closed")).toInt();
if (e.hasAttribute(QStringLiteral("innerColor")))
}
if (e.hasAttribute(QStringLiteral("innerColor"))) {
m_lineInnerColor = QColor(e.attribute(QStringLiteral("innerColor")));
if (e.hasAttribute(QStringLiteral("leadFwd")))
}
if (e.hasAttribute(QStringLiteral("leadFwd"))) {
m_lineLeadingFwdPt = e.attribute(QStringLiteral("leadFwd")).toDouble();
if (e.hasAttribute(QStringLiteral("leadBack")))
}
if (e.hasAttribute(QStringLiteral("leadBack"))) {
m_lineLeadingBackPt = e.attribute(QStringLiteral("leadBack")).toDouble();
if (e.hasAttribute(QStringLiteral("showCaption")))
}
if (e.hasAttribute(QStringLiteral("showCaption"))) {
m_lineShowCaption = e.attribute(QStringLiteral("showCaption")).toInt();
if (e.hasAttribute(QStringLiteral("intent")))
}
if (e.hasAttribute(QStringLiteral("intent"))) {
m_lineIntent = (LineAnnotation::LineIntent)e.attribute(QStringLiteral("intent")).toInt();
}
// parse all 'point' subnodes
QDomNode pointNode = e.firstChild();
@ -1626,8 +1694,9 @@ void LineAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
QDomElement pe = pointNode.toElement();
pointNode = pointNode.nextSibling();
if (pe.tagName() != QLatin1String("point"))
if (pe.tagName() != QLatin1String("point")) {
continue;
}
NormalizedPoint p;
p.x = pe.attribute(QStringLiteral("x"), QStringLiteral("0.0")).toDouble();
@ -1651,16 +1720,19 @@ double LineAnnotationPrivate::distanceSqr(double x, double y, double xScale, dou
{
QLinkedList<NormalizedPoint> transformedLinePoints = m_transformedLinePoints;
if (m_lineClosed) // Close the path
if (m_lineClosed) { // Close the path
transformedLinePoints.append(transformedLinePoints.first());
}
if (m_lineInnerColor.isValid()) {
QPolygonF polygon;
for (const NormalizedPoint &p : qAsConst(transformedLinePoints))
for (const NormalizedPoint &p : qAsConst(transformedLinePoints)) {
polygon.append(QPointF(p.x, p.y));
}
if (polygon.containsPoint(QPointF(x, y), Qt::WindingFill))
if (polygon.containsPoint(QPointF(x, y), Qt::WindingFill)) {
return 0;
}
}
return strokeDistance(::distanceSqr(x, y, xScale, yScale, transformedLinePoints), m_style.width() * xScale / (m_page->m_width * 2));
@ -1739,10 +1811,12 @@ void GeomAnnotation::store(QDomNode &node, QDomDocument &document) const
node.appendChild(geomElement);
// append the optional attributes
if (d->m_geomType != InscribedSquare)
if (d->m_geomType != InscribedSquare) {
geomElement.setAttribute(QStringLiteral("type"), (int)d->m_geomType);
if (d->m_geomInnerColor.isValid())
}
if (d->m_geomInnerColor.isValid()) {
geomElement.setAttribute(QStringLiteral("color"), d->m_geomInnerColor.name());
}
}
void GeomAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
@ -1753,17 +1827,21 @@ void GeomAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
while (subNode.isElement()) {
QDomElement e = subNode.toElement();
subNode = subNode.nextSibling();
if (e.tagName() != QLatin1String("geom"))
if (e.tagName() != QLatin1String("geom")) {
continue;
}
// parse the attributes
if (e.hasAttribute(QStringLiteral("type")))
if (e.hasAttribute(QStringLiteral("type"))) {
m_geomType = (GeomAnnotation::GeomType)e.attribute(QStringLiteral("type")).toInt();
if (e.hasAttribute(QStringLiteral("color")))
}
if (e.hasAttribute(QStringLiteral("color"))) {
m_geomInnerColor = QColor(e.attribute(QStringLiteral("color")));
}
// compatibility
if (e.hasAttribute(QStringLiteral("width")))
if (e.hasAttribute(QStringLiteral("width"))) {
m_style.setWidth(e.attribute(QStringLiteral("width")).toInt());
}
// loading complete
break;
@ -1807,10 +1885,11 @@ double GeomAnnotationPrivate::distanceSqr(double x, double y, double xScale, dou
// if the ellipse is filled, we treat all points within as "on" it
if (lambda > 1) {
if (m_geomInnerColor.isValid())
if (m_geomInnerColor.isValid()) {
return 0;
else
} else {
withinShape = true;
}
}
// otherwise we calculate the squared distance from the projected point on the ellipse
@ -1824,8 +1903,9 @@ double GeomAnnotationPrivate::distanceSqr(double x, double y, double xScale, dou
case GeomAnnotation::InscribedSquare:
// if the square is filled, only check the bounding box
if (m_geomInnerColor.isValid())
if (m_geomInnerColor.isValid()) {
return AnnotationPrivate::distanceSqr(x, y, xScale, yScale);
}
QLinkedList<NormalizedPoint> edges;
edges << NormalizedPoint(m_transformedBoundary.left, m_transformedBoundary.top);
@ -1835,13 +1915,15 @@ double GeomAnnotationPrivate::distanceSqr(double x, double y, double xScale, dou
edges << NormalizedPoint(m_transformedBoundary.left, m_transformedBoundary.top);
distance = ::distanceSqr(x, y, xScale, yScale, edges);
if (m_transformedBoundary.contains(x, y))
if (m_transformedBoundary.contains(x, y)) {
withinShape = true;
}
break;
}
if (withinShape)
if (withinShape) {
distance = strokeDistance(distance, m_style.width() * xScale / m_page->m_width);
}
return distance;
}
@ -1880,32 +1962,36 @@ HighlightAnnotation::Quad::Quad(const Quad &other)
HighlightAnnotation::Quad &HighlightAnnotation::Quad::operator=(const Quad &other)
{
if (this != &other)
if (this != &other) {
*d = *other.d;
}
return *this;
}
void HighlightAnnotation::Quad::setPoint(const NormalizedPoint &point, int index)
{
if (index < 0 || index > 3)
if (index < 0 || index > 3) {
return;
}
d->m_points[index] = point;
}
NormalizedPoint HighlightAnnotation::Quad::point(int index) const
{
if (index < 0 || index > 3)
if (index < 0 || index > 3) {
return NormalizedPoint();
}
return d->m_points[index];
}
NormalizedPoint HighlightAnnotation::Quad::transformedPoint(int index) const
{
if (index < 0 || index > 3)
if (index < 0 || index > 3) {
return NormalizedPoint();
}
return d->m_transformedPoints[index];
}
@ -2016,10 +2102,12 @@ void HighlightAnnotation::store(QDomNode &node, QDomDocument &document) const
node.appendChild(hlElement);
// append the optional attributes
if (d->m_highlightType != Highlight)
if (d->m_highlightType != Highlight) {
hlElement.setAttribute(QStringLiteral("type"), (int)d->m_highlightType);
if (d->m_highlightQuads.count() < 1)
}
if (d->m_highlightQuads.count() < 1) {
return;
}
// append highlight quads, all children describe quads
QList<Quad>::const_iterator it = d->m_highlightQuads.begin(), end = d->m_highlightQuads.end();
for (; it != end; ++it) {
@ -2034,10 +2122,12 @@ void HighlightAnnotation::store(QDomNode &node, QDomDocument &document) const
quadElement.setAttribute(QStringLiteral("cy"), QString::number(q.point(2).y));
quadElement.setAttribute(QStringLiteral("dx"), QString::number(q.point(3).x));
quadElement.setAttribute(QStringLiteral("dy"), QString::number(q.point(3).y));
if (q.capStart())
if (q.capStart()) {
quadElement.setAttribute(QStringLiteral("start"), 1);
if (q.capEnd())
}
if (q.capEnd()) {
quadElement.setAttribute(QStringLiteral("end"), 1);
}
quadElement.setAttribute(QStringLiteral("feather"), QString::number(q.feather()));
}
}
@ -2052,8 +2142,9 @@ void HighlightAnnotationPrivate::transform(const QTransform &matrix)
AnnotationPrivate::transform(matrix);
QMutableListIterator<HighlightAnnotation::Quad> it(m_highlightQuads);
while (it.hasNext())
while (it.hasNext()) {
it.next().transform(matrix);
}
}
void HighlightAnnotationPrivate::baseTransform(const QTransform &matrix)
@ -2061,8 +2152,9 @@ void HighlightAnnotationPrivate::baseTransform(const QTransform &matrix)
AnnotationPrivate::baseTransform(matrix);
QMutableListIterator<HighlightAnnotation::Quad> it(m_highlightQuads);
while (it.hasNext())
while (it.hasNext()) {
it.next().transform(matrix);
}
}
void HighlightAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
@ -2075,19 +2167,22 @@ void HighlightAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
while (subNode.isElement()) {
QDomElement e = subNode.toElement();
subNode = subNode.nextSibling();
if (e.tagName() != QLatin1String("hl"))
if (e.tagName() != QLatin1String("hl")) {
continue;
}
// parse the attributes
if (e.hasAttribute(QStringLiteral("type")))
if (e.hasAttribute(QStringLiteral("type"))) {
m_highlightType = (HighlightAnnotation::HighlightType)e.attribute(QStringLiteral("type")).toInt();
}
// parse all 'quad' subnodes
QDomNode quadNode = e.firstChild();
for (; quadNode.isElement(); quadNode = quadNode.nextSibling()) {
QDomElement qe = quadNode.toElement();
if (qe.tagName() != QLatin1String("quad"))
if (qe.tagName() != QLatin1String("quad")) {
continue;
}
HighlightAnnotation::Quad q;
q.setPoint(NormalizedPoint(qe.attribute(QStringLiteral("ax"), QStringLiteral("0.0")).toDouble(), qe.attribute(QStringLiteral("ay"), QStringLiteral("0.0")).toDouble()), 0);
@ -2129,14 +2224,16 @@ double HighlightAnnotationPrivate::distanceSqr(double x, double y, double xScale
directionVote += (isLeftOfVector(pathPoints.back(), thisPoint, point)) ? 1 : -1;
pathPoints << thisPoint;
}
if (abs(directionVote) == 4)
if (abs(directionVote) == 4) {
return 0;
}
// if that's not the case, we treat the outline as path and simply determine
// the distance from the path to the point
const double thisOutsideDistance = ::distanceSqr(x, y, xScale, yScale, pathPoints);
if (thisOutsideDistance < outsideDistance)
if (thisOutsideDistance < outsideDistance) {
outsideDistance = thisOutsideDistance;
}
}
return outsideDistance;
@ -2201,8 +2298,9 @@ void StampAnnotation::store(QDomNode &node, QDomDocument &document) const
node.appendChild(stampElement);
// append the optional attributes
if (d->m_stampIconName != QLatin1String("Draft"))
if (d->m_stampIconName != QLatin1String("Draft")) {
stampElement.setAttribute(QStringLiteral("icon"), d->m_stampIconName);
}
}
void StampAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
@ -2214,12 +2312,14 @@ void StampAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
while (subNode.isElement()) {
QDomElement e = subNode.toElement();
subNode = subNode.nextSibling();
if (e.tagName() != QLatin1String("stamp"))
if (e.tagName() != QLatin1String("stamp")) {
continue;
}
// parse the attributes
if (e.hasAttribute(QStringLiteral("icon")))
if (e.hasAttribute(QStringLiteral("icon"))) {
m_stampIconName = e.attribute(QStringLiteral("icon"));
}
// loading complete
break;
@ -2306,8 +2406,9 @@ void InkAnnotation::store(QDomNode &node, QDomDocument &document) const
node.appendChild(inkElement);
// append the optional attributes
if (d->m_inkPaths.count() < 1)
if (d->m_inkPaths.count() < 1) {
return;
}
QList<QLinkedList<NormalizedPoint>>::const_iterator pIt = d->m_inkPaths.begin(), pEnd = d->m_inkPaths.end();
for (; pIt != pEnd; ++pIt) {
@ -2330,8 +2431,9 @@ double InkAnnotationPrivate::distanceSqr(double x, double y, double xScale, doub
double distance = DBL_MAX;
for (const QLinkedList<NormalizedPoint> &path : m_transformedInkPaths) {
const double thisDistance = ::distanceSqr(x, y, xScale, yScale, path);
if (thisDistance < distance)
if (thisDistance < distance) {
distance = thisDistance;
}
}
return strokeDistance(distance, m_style.width() * xScale / (m_page->m_width * 2));
}
@ -2342,8 +2444,9 @@ void InkAnnotationPrivate::transform(const QTransform &matrix)
for (int i = 0; i < m_transformedInkPaths.count(); ++i) {
QMutableLinkedListIterator<NormalizedPoint> it(m_transformedInkPaths[i]);
while (it.hasNext())
while (it.hasNext()) {
it.next().transform(matrix);
}
}
}
@ -2353,8 +2456,9 @@ void InkAnnotationPrivate::baseTransform(const QTransform &matrix)
for (int i = 0; i < m_inkPaths.count(); ++i) {
QMutableLinkedListIterator<NormalizedPoint> it(m_inkPaths[i]);
while (it.hasNext())
while (it.hasNext()) {
it.next().transform(matrix);
}
}
}
@ -2389,8 +2493,9 @@ void InkAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
while (subNode.isElement()) {
QDomElement e = subNode.toElement();
subNode = subNode.nextSibling();
if (e.tagName() != QLatin1String("ink"))
if (e.tagName() != QLatin1String("ink")) {
continue;
}
// parse the 'path' subnodes
QDomNode pathNode = e.firstChild();
@ -2398,8 +2503,9 @@ void InkAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
QDomElement pathElement = pathNode.toElement();
pathNode = pathNode.nextSibling();
if (pathElement.tagName() != QLatin1String("path"))
if (pathElement.tagName() != QLatin1String("path")) {
continue;
}
// build each path parsing 'point' subnodes
QLinkedList<NormalizedPoint> path;
@ -2408,8 +2514,9 @@ void InkAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
QDomElement pointElement = pointNode.toElement();
pointNode = pointNode.nextSibling();
if (pointElement.tagName() != QLatin1String("point"))
if (pointElement.tagName() != QLatin1String("point")) {
continue;
}
NormalizedPoint p;
p.x = pointElement.attribute(QStringLiteral("x"), QStringLiteral("0.0")).toDouble();
@ -2418,8 +2525,9 @@ void InkAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
}
// add the path to the path list if it contains at least 2 nodes
if (path.count() >= 2)
if (path.count() >= 2) {
m_inkPaths.append(path);
}
}
// loading complete
@ -2464,10 +2572,11 @@ static QString caretSymbolToString(CaretAnnotation::CaretSymbol symbol)
static CaretAnnotation::CaretSymbol caretSymbolFromString(const QString &symbol)
{
if (symbol == QLatin1String("None"))
if (symbol == QLatin1String("None")) {
return CaretAnnotation::None;
else if (symbol == QLatin1String("P"))
} else if (symbol == QLatin1String("P")) {
return CaretAnnotation::P;
}
return CaretAnnotation::None;
}
@ -2480,12 +2589,14 @@ void CaretAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
while (subNode.isElement()) {
QDomElement e = subNode.toElement();
subNode = subNode.nextSibling();
if (e.tagName() != QLatin1String("caret"))
if (e.tagName() != QLatin1String("caret")) {
continue;
}
// parse the attributes
if (e.hasAttribute(QStringLiteral("symbol")))
if (e.hasAttribute(QStringLiteral("symbol"))) {
m_symbol = caretSymbolFromString(e.attribute(QStringLiteral("symbol")));
}
// loading complete
break;
@ -2539,8 +2650,9 @@ void CaretAnnotation::store(QDomNode &node, QDomDocument &document) const
node.appendChild(caretElement);
// append the optional attributes
if (d->m_symbol != None)
if (d->m_symbol != None) {
caretElement.setAttribute(QStringLiteral("symbol"), caretSymbolToString(d->m_symbol));
}
}
/** FileAttachmentAnnotation [Annotation] */
@ -2576,8 +2688,9 @@ void FileAttachmentAnnotationPrivate::setAnnotationProperties(const QDomNode &no
while (subNode.isElement()) {
QDomElement e = subNode.toElement();
subNode = subNode.nextSibling();
if (e.tagName() != QLatin1String("fileattachment"))
if (e.tagName() != QLatin1String("fileattachment")) {
continue;
}
// loading complete
break;
@ -2675,8 +2788,9 @@ void SoundAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
while (subNode.isElement()) {
QDomElement e = subNode.toElement();
subNode = subNode.nextSibling();
if (e.tagName() != QLatin1String("sound"))
if (e.tagName() != QLatin1String("sound")) {
continue;
}
// loading complete
break;
@ -2772,8 +2886,9 @@ void MovieAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
while (subNode.isElement()) {
QDomElement e = subNode.toElement();
subNode = subNode.nextSibling();
if (e.tagName() != QLatin1String("movie"))
if (e.tagName() != QLatin1String("movie")) {
continue;
}
// loading complete
break;
@ -2861,8 +2976,9 @@ void ScreenAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
while (subNode.isElement()) {
QDomElement e = subNode.toElement();
subNode = subNode.nextSibling();
if (e.tagName() != QLatin1String("screen"))
if (e.tagName() != QLatin1String("screen")) {
continue;
}
// loading complete
break;
@ -2906,8 +3022,9 @@ Annotation::SubType ScreenAnnotation::subType() const
void ScreenAnnotation::setAdditionalAction(AdditionalActionType type, Action *action)
{
Q_D(ScreenAnnotation);
if (d->m_additionalActions.contains(type))
if (d->m_additionalActions.contains(type)) {
delete d->m_additionalActions.value(type);
}
d->m_additionalActions.insert(type, action);
}
@ -2915,10 +3032,11 @@ void ScreenAnnotation::setAdditionalAction(AdditionalActionType type, Action *ac
Action *ScreenAnnotation::additionalAction(AdditionalActionType type) const
{
Q_D(const ScreenAnnotation);
if (!d->m_additionalActions.contains(type))
if (!d->m_additionalActions.contains(type)) {
return nullptr;
else
} else {
return d->m_additionalActions.value(type);
}
}
void ScreenAnnotation::setAction(Action *action)
@ -2961,8 +3079,9 @@ void WidgetAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
while (subNode.isElement()) {
QDomElement e = subNode.toElement();
subNode = subNode.nextSibling();
if (e.tagName() != QLatin1String("widget"))
if (e.tagName() != QLatin1String("widget")) {
continue;
}
// loading complete
break;
@ -3006,8 +3125,9 @@ Annotation::SubType WidgetAnnotation::subType() const
void WidgetAnnotation::setAdditionalAction(AdditionalActionType type, Action *action)
{
Q_D(WidgetAnnotation);
if (d->m_additionalActions.contains(type))
if (d->m_additionalActions.contains(type)) {
delete d->m_additionalActions.value(type);
}
d->m_additionalActions.insert(type, action);
}
@ -3015,10 +3135,11 @@ void WidgetAnnotation::setAdditionalAction(AdditionalActionType type, Action *ac
Action *WidgetAnnotation::additionalAction(AdditionalActionType type) const
{
Q_D(const WidgetAnnotation);
if (!d->m_additionalActions.contains(type))
if (!d->m_additionalActions.contains(type)) {
return nullptr;
else
} else {
return d->m_additionalActions.value(type);
}
}
/** RichMediaAnnotation [Annotation] */
@ -3057,8 +3178,9 @@ void RichMediaAnnotationPrivate::setAnnotationProperties(const QDomNode &node)
while (subNode.isElement()) {
QDomElement e = subNode.toElement();
subNode = subNode.nextSibling();
if (e.tagName() != QLatin1String("richMedia"))
if (e.tagName() != QLatin1String("richMedia")) {
continue;
}
// loading complete
break;

View File

@ -198,8 +198,9 @@ NormalizedRect &NormalizedRect::operator|=(const NormalizedRect &r)
NormalizedRect NormalizedRect::operator&(const NormalizedRect &r) const
{
if (isNull() || r.isNull())
if (isNull() || r.isNull()) {
return NormalizedRect();
}
NormalizedRect ret;
ret.left = qMax(left, r.left);
@ -309,10 +310,11 @@ ObjectRect::ObjectRect(double l, double t, double r, double b, bool ellipse, Obj
{
// assign coordinates swapping them if negative width or height
QRectF rect(r > l ? l : r, b > t ? t : b, fabs(r - l), fabs(b - t));
if (ellipse)
if (ellipse) {
m_path.addEllipse(rect);
else
} else {
m_path.addRect(rect);
}
m_transformedPath = m_path;
}
@ -322,10 +324,11 @@ ObjectRect::ObjectRect(const NormalizedRect &r, bool ellipse, ObjectType type, v
, m_object(object)
{
QRectF rect(r.left, r.top, fabs(r.right - r.left), fabs(r.bottom - r.top));
if (ellipse)
if (ellipse) {
m_path.addEllipse(rect);
else
} else {
m_path.addRect(rect);
}
m_transformedPath = m_path;
}
@ -399,15 +402,17 @@ double ObjectRect::distanceSqr(double x, double y, double xScale, double yScale)
ObjectRect::~ObjectRect()
{
if (!m_object)
if (!m_object) {
return;
}
if (m_objectType == Action)
if (m_objectType == Action) {
delete static_cast<Okular::Action *>(m_object);
else if (m_objectType == SourceRef)
} else if (m_objectType == SourceRef) {
delete static_cast<Okular::SourceReference *>(m_object);
else
} else {
qCDebug(OkularCoreDebug).nospace() << "Object deletion not implemented for type '" << m_objectType << "'.";
}
}
/** class AnnotationObjectRect **/

View File

@ -382,16 +382,66 @@ public:
double distanceSqr(double x, double y, double xScale, double yScale) const
{
double distX = 0;
if (x < left)
distX = left - x;
else if (x > right)
distX = x - right;
if (x < left) {
{
{
{
{
{
{
distX = left - x;
}
}
}
}
}
}
} else if (x > right) {
{
{
{
{
{
{
distX = x - right;
}
}
}
}
}
}
}
double distY = 0;
if (top > y)
distY = top - y;
else if (bottom < y)
distY = y - bottom;
if (top > y) {
{
{
{
{
{
{
distY = top - y;
}
}
}
}
}
}
} else if (bottom < y) {
{
{
{
{
{
{
distY = y - bottom;
}
}
}
}
}
}
}
return pow(distX * xScale, 2) + pow(distY * yScale, 2);
}
@ -743,41 +793,145 @@ template<class NormalizedShape, class Shape> void RegularArea<NormalizedShape, S
template<class NormalizedShape, class Shape> bool RegularArea<NormalizedShape, Shape>::isNull() const
{
if (this->isEmpty())
return true;
if (this->isEmpty()) {
{
{
{
{
{
{
return true;
}
}
}
}
}
}
}
typename QList<NormalizedShape>::const_iterator it = this->begin(), itEnd = this->end();
for (; it != itEnd; ++it)
if (!givePtr(*it)->isNull())
return false;
for (; it != itEnd; ++it) {
{
{
{
{
{
{
if (!givePtr(*it)->isNull()) {
{
{
{
{
{
{
return false;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return true;
}
template<class NormalizedShape, class Shape> bool RegularArea<NormalizedShape, Shape>::intersects(const NormalizedShape &shape) const
{
if (this->isEmpty())
return false;
if (this->isEmpty()) {
{
{
{
{
{
{
return false;
}
}
}
}
}
}
}
typename QList<NormalizedShape>::const_iterator it = this->begin(), itEnd = this->end();
for (; it != itEnd; ++it)
if (!givePtr(*it)->isNull() && givePtr(*it)->intersects(shape))
return true;
for (; it != itEnd; ++it) {
{
{
{
{
{
{
if (!givePtr(*it)->isNull() && givePtr(*it)->intersects(shape)) {
{
{
{
{
{
{
return true;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return false;
}
template<class NormalizedShape, class Shape> bool RegularArea<NormalizedShape, Shape>::intersects(const RegularArea<NormalizedShape, Shape> *area) const
{
if (this->isEmpty())
return false;
if (this->isEmpty()) {
{
{
{
{
{
{
return false;
}
}
}
}
}
}
}
typename QList<NormalizedShape>::const_iterator it = this->begin(), itEnd = this->end();
for (; it != itEnd; ++it) {
typename QList<NormalizedShape>::const_iterator areaIt = area->begin(), areaItEnd = area->end();
for (; areaIt != areaItEnd; ++areaIt) {
if (!(*it).isNull() && (*it).intersects(*areaIt))
return true;
if (!(*it).isNull() && (*it).intersects(*areaIt)) {
{
{
{
{
{
{
return true;
}
}
}
}
}
}
}
}
}
@ -787,8 +941,21 @@ template<class NormalizedShape, class Shape> bool RegularArea<NormalizedShape, S
template<class NormalizedShape, class Shape> void RegularArea<NormalizedShape, Shape>::appendArea(const RegularArea<NormalizedShape, Shape> *area)
{
typename QList<NormalizedShape>::const_iterator areaIt = area->begin(), areaItEnd = area->end();
for (; areaIt != areaItEnd; ++areaIt)
this->append(*areaIt);
for (; areaIt != areaItEnd; ++areaIt) {
{
{
{
{
{
{
this->append(*areaIt);
}
}
}
}
}
}
}
}
template<class NormalizedShape, class Shape> void RegularArea<NormalizedShape, Shape>::appendShape(const NormalizedShape &shape, MergeSide side)
@ -841,36 +1008,114 @@ template<class NormalizedShape, class Shape> void RegularArea<NormalizedShape, S
// merge it with that and delete the shape
if (intersection) {
deref((*this)[size - 1]) |= deref(shape);
} else
this->append(shape);
} else {
{
{
{
{
{
{
this->append(shape);
}
}
}
}
}
}
}
}
}
template<class NormalizedShape, class Shape> bool RegularArea<NormalizedShape, Shape>::contains(double x, double y) const
{
if (this->isEmpty())
return false;
if (this->isEmpty()) {
{
{
{
{
{
{
return false;
}
}
}
}
}
}
}
typename QList<NormalizedShape>::const_iterator it = this->begin(), itEnd = this->end();
for (; it != itEnd; ++it)
if ((*it).contains(x, y))
return true;
for (; it != itEnd; ++it) {
{
{
{
{
{
{
if ((*it).contains(x, y)) {
{
{
{
{
{
{
return true;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return false;
}
template<class NormalizedShape, class Shape> bool RegularArea<NormalizedShape, Shape>::contains(const NormalizedShape &shape) const
{
if (this->isEmpty())
return false;
if (this->isEmpty()) {
{
{
{
{
{
{
return false;
}
}
}
}
}
}
}
return QList<NormalizedShape>::contains(shape);
}
template<class NormalizedShape, class Shape> QList<Shape> RegularArea<NormalizedShape, Shape>::geometry(int xScale, int yScale, int dx, int dy) const
{
if (this->isEmpty())
return QList<Shape>();
if (this->isEmpty()) {
{
{
{
{
{
{
return QList<Shape>();
}
}
}
}
}
}
}
QList<Shape> ret;
Shape t;
@ -886,11 +1131,37 @@ template<class NormalizedShape, class Shape> QList<Shape> RegularArea<Normalized
template<class NormalizedShape, class Shape> void RegularArea<NormalizedShape, Shape>::transform(const QTransform &matrix)
{
if (this->isEmpty())
return;
if (this->isEmpty()) {
{
{
{
{
{
{
return;
}
}
}
}
}
}
}
for (int i = 0; i < this->count(); ++i)
givePtr((*this)[i])->transform(matrix);
for (int i = 0; i < this->count(); ++i) {
{
{
{
{
{
{
givePtr((*this)[i])->transform(matrix);
}
}
}
}
}
}
}
}
/**

View File

@ -177,8 +177,9 @@ void AudioPlayerPrivate::stopPlayings()
void AudioPlayerPrivate::finished(int id)
{
QHash<int, PlayData *>::iterator it = m_playing.find(id);
if (it == m_playing.end())
if (it == m_playing.end()) {
return;
}
SoundInfo si = it.value()->m_info;
// if the sound must be repeated indefinitely, then start the playback
@ -213,20 +214,23 @@ AudioPlayer *AudioPlayer::instance()
void AudioPlayer::playSound(const Sound *sound, const SoundAction *linksound)
{
// we can't play null pointers ;)
if (!sound)
if (!sound) {
return;
}
// we don't play external sounds for remote documents
if (sound->soundType() == Sound::External && !d->m_currentDocument.isLocalFile())
if (sound->soundType() == Sound::External && !d->m_currentDocument.isLocalFile()) {
return;
}
qCDebug(OkularCoreDebug);
SoundInfo si(sound, linksound);
// if the mix flag of the new sound is false, then the currently playing
// sounds must be stopped.
if (!si.mix)
if (!si.mix) {
d->stopPlayings();
}
d->play(si);
}

View File

@ -47,8 +47,9 @@ public:
OkularBookmarkAction(const Okular::DocumentViewport &vp, const KBookmark &bk, KBookmarkOwner *owner, QObject *parent)
: KBookmarkAction(bk, owner, parent)
{
if (vp.isValid())
if (vp.isValid()) {
setText(QString::number(vp.pageNumber + 1) + QStringLiteral(" - ") + text());
}
setProperty("pageNumber", vp.pageNumber + 1);
setProperty("htmlRef", bk.url().fragment(QUrl::FullyDecoded));
}
@ -68,14 +69,17 @@ static inline bool documentViewportFuzzyCompare(const DocumentViewport &vp1, con
{
bool equal = vp1.isValid() && vp2.isValid() && (vp1.pageNumber == vp2.pageNumber) && (vp1.rePos.pos == vp2.rePos.pos);
if (!equal)
if (!equal) {
return false;
}
if (qAbs(vp1.rePos.normalizedX - vp2.rePos.normalizedX) >= 0.000001)
if (qAbs(vp1.rePos.normalizedX - vp2.rePos.normalizedX) >= 0.000001) {
return false;
}
if (qAbs(vp1.rePos.normalizedY - vp2.rePos.normalizedY) >= 0.000001)
if (qAbs(vp1.rePos.normalizedY - vp2.rePos.normalizedY) >= 0.000001) {
return false;
}
return true;
}
@ -98,8 +102,9 @@ static inline bool okularBookmarkActionLessThan(QAction *a1, QAction *a2)
static QUrl mostCanonicalUrl(const QUrl &url)
{
if (!url.isLocalFile())
if (!url.isLocalFile()) {
return url;
}
const QFileInfo fi(url.toLocalFile());
return QUrl::fromLocalFile(fi.canonicalFilePath());
@ -147,10 +152,11 @@ public:
static inline QUrl urlForGroup(const KBookmark &group)
{
if (group.url().isValid())
if (group.url().isValid()) {
return group.url();
else
} else {
return QUrl::fromUserInput(group.fullText());
}
}
BookmarkManager::BookmarkManager(DocumentPrivate *document)
@ -200,8 +206,9 @@ void BookmarkManager::Private::openBookmark(const KBookmark &bm, Qt::MouseButton
void BookmarkManager::Private::_o_changed(const QString &groupAddress, const QString &caller)
{
Q_UNUSED(caller);
if (groupAddress.isEmpty())
if (groupAddress.isEmpty()) {
return;
}
QUrl referurl;
// first, try to find the bookmark group whom change notification was just received
@ -216,8 +223,9 @@ void BookmarkManager::Private::_o_changed(const QString &groupAddress, const QSt
if (!referurl.isValid()) {
const KBookmark bm = manager->findByAddress(groupAddress);
// better be safe than sorry
if (bm.isNull())
if (bm.isNull()) {
return;
}
Q_ASSERT(bm.isGroup());
referurl = urlForGroup(bm);
}
@ -251,8 +259,9 @@ QList<QUrl> BookmarkManager::files() const
QList<QUrl> ret;
KBookmarkGroup group = d->manager->root();
for (KBookmark bm = group.first(); !bm.isNull(); bm = group.next(bm)) {
if (bm.isSeparator() || !bm.isGroup())
if (bm.isSeparator() || !bm.isGroup()) {
continue;
}
ret.append(urlForGroup(bm));
}
@ -265,13 +274,15 @@ KBookmark::List BookmarkManager::bookmarks(const QUrl &documentUrl) const
KBookmark::List ret;
KBookmarkGroup group = d->manager->root();
for (KBookmark bm = group.first(); !bm.isNull(); bm = group.next(bm)) {
if (!bm.isGroup() || urlForGroup(bm) != url)
if (!bm.isGroup() || urlForGroup(bm) != url) {
continue;
}
KBookmarkGroup group = bm.toGroup();
for (KBookmark b = group.first(); !b.isNull(); b = group.next(b)) {
if (b.isSeparator() || b.isGroup())
if (b.isSeparator() || b.isGroup()) {
continue;
}
ret.append(b);
}
@ -314,17 +325,20 @@ KBookmark BookmarkManager::bookmark(int page) const
KBookmark BookmarkManager::bookmark(const DocumentViewport &viewport) const
{
if (!viewport.isValid() || !isBookmarked(viewport.pageNumber))
if (!viewport.isValid() || !isBookmarked(viewport.pageNumber)) {
return KBookmark();
}
KBookmarkGroup thebg;
QHash<QUrl, QString>::iterator it = d->bookmarkFind(d->url, false, &thebg);
if (it == d->knownFiles.end())
if (it == d->knownFiles.end()) {
return KBookmark();
}
for (KBookmark bm = thebg.first(); !bm.isNull(); bm = thebg.next(bm)) {
if (bm.isSeparator() || bm.isGroup())
if (bm.isSeparator() || bm.isGroup()) {
continue;
}
DocumentViewport vp(bm.url().fragment(QUrl::FullyDecoded));
if (documentViewportFuzzyCompare(vp, viewport)) {
@ -351,8 +365,9 @@ QHash<QUrl, QString>::iterator BookmarkManager::Private::bookmarkFind(const QUrl
bool found = false;
KBookmarkGroup root = manager->root();
for (KBookmark bm = root.first(); !found && !bm.isNull(); bm = root.next(bm)) {
if (bm.isSeparator() || !bm.isGroup())
if (bm.isSeparator() || !bm.isGroup()) {
continue;
}
QUrl tmpurl(urlForGroup(bm));
if (tmpurl == url) {
@ -360,8 +375,9 @@ QHash<QUrl, QString>::iterator BookmarkManager::Private::bookmarkFind(const QUrl
KBookmarkGroup bg = bm.toGroup();
it = knownFiles.insert(url, bg.address());
found = true;
if (result)
if (result) {
*result = bg;
}
break;
}
}
@ -372,8 +388,9 @@ QHash<QUrl, QString>::iterator BookmarkManager::Private::bookmarkFind(const QUrl
KBookmarkGroup newbg = root.createNewFolder(purl);
newbg.setUrl(url);
it = knownFiles.insert(url, newbg.address());
if (result)
if (result) {
*result = newbg;
}
}
} else if (result) {
const KBookmark bm = manager->findByAddress(it.value());
@ -398,11 +415,13 @@ void BookmarkManager::addBookmark(const DocumentViewport &vp)
bool BookmarkManager::addBookmark(const QUrl &documentUrl, const Okular::DocumentViewport &vp, const QString &title)
{
if (!documentUrl.isValid() || !vp.isValid())
if (!documentUrl.isValid() || !vp.isValid()) {
return false;
}
if (vp.pageNumber < 0 || vp.pageNumber >= d->document->m_pagesVector.count())
if (vp.pageNumber < 0 || vp.pageNumber >= d->document->m_pagesVector.count()) {
return false;
}
const QUrl referurl = mostCanonicalUrl(documentUrl);
@ -414,20 +433,23 @@ bool BookmarkManager::addBookmark(const QUrl &documentUrl, const Okular::Documen
bool found = false;
// Check if the bookmark already exists
for (KBookmark bm = thebg.first(); !found && !bm.isNull(); bm = thebg.next(bm)) {
if (bm.isSeparator() || bm.isGroup())
if (bm.isSeparator() || bm.isGroup()) {
continue;
}
DocumentViewport bmViewport(bm.url().fragment(QUrl::FullyDecoded));
if (bmViewport.isValid() && bmViewport.pageNumber == vp.pageNumber) {
++count;
if (documentViewportFuzzyCompare(bmViewport, vp))
if (documentViewportFuzzyCompare(bmViewport, vp)) {
found = true;
}
}
}
if (found)
if (found) {
return false;
}
QString newtitle;
if (title.isEmpty()) {
@ -435,12 +457,14 @@ bool BookmarkManager::addBookmark(const QUrl &documentUrl, const Okular::Documen
// name '#p' where p is the page number where the bookmark is located.
// if there's more than one bookmark per page, give the name '#p-n'
// where n is the index of this bookmark among the ones of its page.
if (count > 0)
if (count > 0) {
newtitle = QStringLiteral("#%1-%2").arg(vp.pageNumber + 1).arg(count);
else
} else {
newtitle = QStringLiteral("#%1").arg(vp.pageNumber + 1);
} else
}
} else {
newtitle = title;
}
QUrl newurl = referurl;
newurl.setFragment(vp.toString(), QUrl::DecodedMode);
@ -474,8 +498,9 @@ void BookmarkManager::renameBookmark(KBookmark *bm, const QString &newName)
KBookmarkGroup thebg;
QHash<QUrl, QString>::iterator it = d->bookmarkFind(d->url, false, &thebg);
Q_ASSERT(it != d->knownFiles.end());
if (it == d->knownFiles.end())
if (it == d->knownFiles.end()) {
return;
}
bm->setFullText(newName);
d->manager->emitChanged(thebg);
@ -483,16 +508,18 @@ void BookmarkManager::renameBookmark(KBookmark *bm, const QString &newName)
void BookmarkManager::renameBookmark(const QUrl &documentUrl, const QString &newName)
{
if (!documentUrl.isValid())
if (!documentUrl.isValid()) {
return;
}
const QUrl referurl = mostCanonicalUrl(documentUrl);
KBookmarkGroup thebg;
QHash<QUrl, QString>::iterator it = d->bookmarkFind(referurl, false, &thebg);
Q_ASSERT(it != d->knownFiles.end());
if (it == d->knownFiles.end())
if (it == d->knownFiles.end()) {
return;
}
thebg.setFullText(newName);
d->manager->emitChanged(thebg);
@ -509,19 +536,22 @@ QString BookmarkManager::titleForUrl(const QUrl &documentUrl) const
int BookmarkManager::removeBookmark(const QUrl &documentUrl, const KBookmark &bm)
{
if (!documentUrl.isValid() || bm.isNull() || bm.isGroup() || bm.isSeparator())
if (!documentUrl.isValid() || bm.isNull() || bm.isGroup() || bm.isSeparator()) {
return -1;
}
DocumentViewport vp(bm.url().fragment(QUrl::FullyDecoded));
if (!vp.isValid())
if (!vp.isValid()) {
return -1;
}
const QUrl referurl = mostCanonicalUrl(documentUrl);
KBookmarkGroup thebg;
QHash<QUrl, QString>::iterator it = d->bookmarkFind(referurl, false, &thebg);
if (it == d->knownFiles.end())
if (it == d->knownFiles.end()) {
return -1;
}
thebg.deleteBookmark(bm);
@ -536,15 +566,17 @@ int BookmarkManager::removeBookmark(const QUrl &documentUrl, const KBookmark &bm
void BookmarkManager::removeBookmarks(const QUrl &documentUrl, const KBookmark::List &list)
{
if (!documentUrl.isValid() || list.isEmpty())
if (!documentUrl.isValid() || list.isEmpty()) {
return;
}
const QUrl referurl = mostCanonicalUrl(documentUrl);
KBookmarkGroup thebg;
QHash<QUrl, QString>::iterator it = d->bookmarkFind(referurl, false, &thebg);
if (it == d->knownFiles.end())
if (it == d->knownFiles.end()) {
return;
}
const QHash<int, int> oldUrlBookmarks = d->urlBookmarks;
bool deletedAny = false;
@ -572,8 +604,9 @@ void BookmarkManager::removeBookmarks(const QUrl &documentUrl, const KBookmark::
}
}
}
if (deletedAny)
if (deletedAny) {
d->manager->emitChanged(thebg);
}
}
QList<QAction *> BookmarkManager::actionsForUrl(const QUrl &documentUrl) const
@ -582,13 +615,15 @@ QList<QAction *> BookmarkManager::actionsForUrl(const QUrl &documentUrl) const
QList<QAction *> ret;
KBookmarkGroup group = d->manager->root();
for (KBookmark bm = group.first(); !bm.isNull(); bm = group.next(bm)) {
if (!bm.isGroup() || urlForGroup(bm) != url)
if (!bm.isGroup() || urlForGroup(bm) != url) {
continue;
}
KBookmarkGroup group = bm.toGroup();
for (KBookmark b = group.first(); !b.isNull(); b = group.next(b)) {
if (b.isSeparator() || b.isGroup())
if (b.isSeparator() || b.isGroup()) {
continue;
}
ret.append(new OkularBookmarkAction(DocumentViewport(b.url().fragment(QUrl::FullyDecoded)), b, d, nullptr));
}
@ -606,12 +641,14 @@ void BookmarkManager::setUrl(const QUrl &url)
QHash<QUrl, QString>::iterator it = d->bookmarkFind(d->url, false, &thebg);
if (it != d->knownFiles.end()) {
for (KBookmark bm = thebg.first(); !bm.isNull(); bm = thebg.next(bm)) {
if (bm.isSeparator() || bm.isGroup())
if (bm.isSeparator() || bm.isGroup()) {
continue;
}
DocumentViewport vp(bm.url().fragment(QUrl::FullyDecoded));
if (!vp.isValid())
if (!vp.isValid()) {
continue;
}
d->urlBookmarks[vp.pageNumber]++;
}
@ -627,12 +664,14 @@ bool BookmarkManager::setPageBookmark(int page)
bool found = false;
bool added = false;
for (KBookmark bm = thebg.first(); !found && !bm.isNull(); bm = thebg.next(bm)) {
if (bm.isSeparator() || bm.isGroup())
if (bm.isSeparator() || bm.isGroup()) {
continue;
}
DocumentViewport vp(bm.url().fragment(QUrl::FullyDecoded));
if (vp.isValid() && vp.pageNumber == page)
if (vp.isValid() && vp.pageNumber == page) {
found = true;
}
}
if (!found) {
d->urlBookmarks[page]++;
@ -651,13 +690,15 @@ bool BookmarkManager::removePageBookmark(int page)
{
KBookmarkGroup thebg;
QHash<QUrl, QString>::iterator it = d->bookmarkFind(d->url, false, &thebg);
if (it == d->knownFiles.end())
if (it == d->knownFiles.end()) {
return false;
}
bool found = false;
for (KBookmark bm = thebg.first(); !found && !bm.isNull(); bm = thebg.next(bm)) {
if (bm.isSeparator() || bm.isGroup())
if (bm.isSeparator() || bm.isGroup()) {
continue;
}
DocumentViewport vp(bm.url().fragment(QUrl::FullyDecoded));
if (vp.isValid() && vp.pageNumber == page) {

File diff suppressed because it is too large Load Diff

View File

@ -91,8 +91,9 @@ bool AddAnnotationCommand::refreshInternalPageReferences(const QVector<Okular::P
// 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)
if (a) {
m_annotation = a;
}
}
return true;
@ -136,8 +137,9 @@ bool RemoveAnnotationCommand::refreshInternalPageReferences(const QVector<Okular
// 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)
if (a) {
m_annotation = a;
}
}
return true;
@ -171,8 +173,9 @@ bool ModifyAnnotationPropertiesCommand::refreshInternalPageReferences(const QVec
{
// 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)
if (a) {
m_annotation = a;
}
return true;
}
@ -210,8 +213,9 @@ bool TranslateAnnotationCommand::mergeWith(const QUndoCommand *uc)
{
TranslateAnnotationCommand *tuc = (TranslateAnnotationCommand *)uc;
if (tuc->m_annotation != m_annotation)
if (tuc->m_annotation != m_annotation) {
return false;
}
if (m_completeDrag) {
return false;
@ -241,8 +245,9 @@ bool TranslateAnnotationCommand::refreshInternalPageReferences(const QVector<Pag
{
// 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)
if (a) {
m_annotation = a;
}
return true;
}
@ -283,8 +288,9 @@ bool AdjustAnnotationCommand::mergeWith(const QUndoCommand *uc)
{
AdjustAnnotationCommand *tuc = (AdjustAnnotationCommand *)uc;
if (tuc->m_annotation != m_annotation)
if (tuc->m_annotation != m_annotation) {
return false;
}
if (m_completeDrag) {
return false;
@ -309,8 +315,9 @@ bool AdjustAnnotationCommand::refreshInternalPageReferences(const QVector<Page *
{
// 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)
if (a) {
m_annotation = a;
}
return true;
}
@ -420,8 +427,9 @@ bool EditAnnotationContentsCommand::mergeWith(const QUndoCommand *uc)
bool EditAnnotationContentsCommand::refreshInternalPageReferences(const QVector<Page *> &newPagesVector)
{
auto a = newPagesVector[m_pageNumber]->annotation(m_annotation->uniqueName());
if (a)
if (a) {
m_annotation = a;
}
return true;
}
@ -598,8 +606,9 @@ void EditFormButtonsCommand::undo()
clearFormButtonStates();
for (int i = 0; i < m_formButtons.size(); i++) {
bool checked = m_prevButtonStates.at(i);
if (checked)
if (checked) {
m_formButtons.at(i)->setState(checked);
}
}
Okular::NormalizedRect boundingRect = buildBoundingRectangleForButtons(m_formButtons);
@ -613,8 +622,9 @@ void EditFormButtonsCommand::redo()
clearFormButtonStates();
for (int i = 0; i < m_formButtons.size(); i++) {
bool checked = m_newButtonStates.at(i);
if (checked)
if (checked) {
m_formButtons.at(i)->setState(checked);
}
}
Okular::NormalizedRect boundingRect = buildBoundingRectangleForButtons(m_formButtons);
@ -629,8 +639,9 @@ bool EditFormButtonsCommand::refreshInternalPageReferences(const QVector<Okular:
m_formButtons.clear();
for (FormFieldButton *oldFormButton : oldFormButtons) {
FormFieldButton *button = dynamic_cast<FormFieldButton *>(Okular::PagePrivate::findEquivalentForm(newPagesVector[m_pageNumber], oldFormButton));
if (!button)
if (!button) {
return false;
}
m_formButtons << button;
}

View File

@ -37,12 +37,15 @@ FilePrinter::printFile(QPrinter &printer, const QString &file, QPrinter::Orienta
static Document::PrintError doKProcessExecute(const QString &exe, const QStringList &argList)
{
const int ret = KProcess::execute(exe, argList);
if (ret == -1)
if (ret == -1) {
return Document::PrintingProcessCrashPrintError;
if (ret == -2)
}
if (ret == -2) {
return Document::PrintingProcessStartPrintError;
if (ret < 0)
}
if (ret < 0) {
return Document::UnknownPrintError;
}
return Document::NoPrintError;
}
@ -254,16 +257,21 @@ bool FilePrinter::detectCupsService()
bool FilePrinter::detectCupsConfig()
{
if (QFile::exists(QStringLiteral("/etc/cups/cupsd.conf")))
if (QFile::exists(QStringLiteral("/etc/cups/cupsd.conf"))) {
return true;
if (QFile::exists(QStringLiteral("/usr/etc/cups/cupsd.conf")))
}
if (QFile::exists(QStringLiteral("/usr/etc/cups/cupsd.conf"))) {
return true;
if (QFile::exists(QStringLiteral("/usr/local/etc/cups/cupsd.conf")))
}
if (QFile::exists(QStringLiteral("/usr/local/etc/cups/cupsd.conf"))) {
return true;
if (QFile::exists(QStringLiteral("/opt/etc/cups/cupsd.conf")))
}
if (QFile::exists(QStringLiteral("/opt/etc/cups/cupsd.conf"))) {
return true;
if (QFile::exists(QStringLiteral("/opt/local/etc/cups/cupsd.conf")))
}
if (QFile::exists(QStringLiteral("/opt/local/etc/cups/cupsd.conf"))) {
return true;
}
return false;
}

View File

@ -131,8 +131,9 @@ bool FontInfo::operator!=(const FontInfo &fi) const
FontInfo &FontInfo::operator=(const FontInfo &fi)
{
if (this == &fi)
if (this == &fi) {
return *this;
}
d = fi.d;
return *this;

View File

@ -247,11 +247,13 @@ public:
for (const QString &str : choices) {
bool ok = true;
int val = str.toInt(&ok);
if (ok)
if (ok) {
newchoices.append(val);
}
}
if (!newchoices.isEmpty())
if (!newchoices.isEmpty()) {
q->setCurrentChoices(newchoices);
}
}
QString value() const override

View File

@ -49,21 +49,24 @@ GeneratorPrivate::GeneratorPrivate()
GeneratorPrivate::~GeneratorPrivate()
{
if (mPixmapGenerationThread)
if (mPixmapGenerationThread) {
mPixmapGenerationThread->wait();
}
delete mPixmapGenerationThread;
if (mTextPageGenerationThread)
if (mTextPageGenerationThread) {
mTextPageGenerationThread->wait();
}
delete mTextPageGenerationThread;
}
PixmapGenerationThread *GeneratorPrivate::pixmapGenerationThread()
{
if (mPixmapGenerationThread)
if (mPixmapGenerationThread) {
return mPixmapGenerationThread;
}
Q_Q(Generator);
mPixmapGenerationThread = new PixmapGenerationThread(q);
@ -75,8 +78,9 @@ PixmapGenerationThread *GeneratorPrivate::pixmapGenerationThread()
TextPageGenerationThread *GeneratorPrivate::textPageGenerationThread()
{
if (mTextPageGenerationThread)
if (mTextPageGenerationThread) {
return mTextPageGenerationThread;
}
Q_Q(Generator);
mTextPageGenerationThread = new TextPageGenerationThread(q);
@ -109,8 +113,9 @@ void GeneratorPrivate::pixmapGenerationFinished()
request->page()->setPixmap(request->observer(), new QPixmap(QPixmap::fromImage(img)), request->normalizedRect());
const int pageNumber = request->page()->number();
if (mPixmapGenerationThread->calcBoundingBox())
if (mPixmapGenerationThread->calcBoundingBox()) {
q->updatePageBoundingBox(pageNumber, mPixmapGenerationThread->boundingBox());
}
} else {
// Cancel the text page generation too if it's still running
if (mTextPageGenerationThread && mTextPageGenerationThread->isRunning()) {
@ -303,8 +308,9 @@ void Generator::generatePixmap(PixmapRequest *request)
d->mPixmapReady = true;
signalPixmapRequestDone(request);
if (calcBoundingBox)
if (calcBoundingBox) {
updatePageBoundingBox(pageNumber, Utils::imageBoundingBox(&img));
}
}
bool Generator::canGenerateTextPage() const
@ -424,9 +430,9 @@ bool Generator::hasFeature(GeneratorFeature feature) const
void Generator::signalPixmapRequestDone(PixmapRequest *request)
{
Q_D(Generator);
if (d->m_document)
if (d->m_document) {
d->m_document->requestDone(request);
else {
} else {
delete request;
}
}
@ -434,16 +440,18 @@ void Generator::signalPixmapRequestDone(PixmapRequest *request)
void Generator::signalTextGenerationDone(Page *page, TextPage *textPage)
{
Q_D(Generator);
if (d->m_document)
if (d->m_document) {
d->m_document->textGenerationDone(page);
else
} else {
delete textPage;
}
}
void Generator::signalPartialPixmapRequest(PixmapRequest *request, const QImage &image)
{
if (request->shouldAbortRender())
if (request->shouldAbortRender()) {
return;
}
PagePrivate *pagePrivate = PagePrivate::get(request->page());
pagePrivate->setPixmap(request->observer(), new QPixmap(QPixmap::fromImage(image)), request->normalizedRect(), true /* isPartialPixmap */);
@ -464,17 +472,19 @@ const Document *Generator::document() const
void Generator::setFeature(GeneratorFeature feature, bool on)
{
Q_D(Generator);
if (on)
if (on) {
d->m_features.insert(feature);
else
} else {
d->m_features.remove(feature);
}
}
QVariant Generator::documentMetaData(const DocumentMetaDataKey key, const QVariant &option) const
{
Q_D(const Generator);
if (!d->m_document)
if (!d->m_document) {
return QVariant();
}
return d->m_document->documentMetaData(key, option);
}
@ -488,8 +498,9 @@ QMutex *Generator::userMutex() const
void Generator::updatePageBoundingBox(int page, const NormalizedRect &boundingBox)
{
Q_D(Generator);
if (d->m_document) // still connected to document?
if (d->m_document) { // still connected to document?
d->m_document->setPageBoundingBox(page, boundingBox);
}
}
QByteArray Generator::requestFontData(const Okular::FontInfo & /*font*/)
@ -626,8 +637,9 @@ bool PixmapRequest::isTile() const
void PixmapRequest::setNormalizedRect(const NormalizedRect &rect)
{
if (d->mNormalizedRect == rect)
if (d->mNormalizedRect == rect) {
return;
}
d->mNormalizedRect = rect;
}
@ -712,8 +724,9 @@ ExportFormat::ExportFormat(const ExportFormat &other)
ExportFormat &ExportFormat::operator=(const ExportFormat &other)
{
if (this == &other)
if (this == &other) {
return *this;
}
d = other.d;

View File

@ -58,8 +58,9 @@ void PixmapGenerationThread::run()
if (mRequest) {
PixmapRequestPrivate::get(mRequest)->mResultImage = mGenerator->image(mRequest);
if (mCalcBoundingBox)
if (mCalcBoundingBox) {
mBoundingBox = Utils::imageBoundingBox(&PixmapRequestPrivate::get(mRequest)->mResultImage);
}
}
}

View File

@ -23,10 +23,11 @@ public:
TextSelection::TextSelection(const NormalizedPoint &start, const NormalizedPoint &end)
: d(new Private)
{
if (end.y - start.y < 0 || (end.y - start.y == 0 && end.x - start.x < 0))
if (end.y - start.y < 0 || (end.y - start.y == 0 && end.x - start.x < 0)) {
d->direction = 1;
else
} else {
d->direction = 0;
}
d->cur[0] = start;
d->cur[1] = end;
@ -44,8 +45,9 @@ void TextSelection::end(const NormalizedPoint &p)
// changing direction as in 2b , assuming the bool->int conversion is correct
int dir1 = d->direction;
d->direction = (p.y - d->cur[0].y < 0 || (p.y - d->cur[0].y == 0 && p.x - d->cur[0].x < 0));
if (d->direction != dir1)
if (d->direction != dir1) {
qCDebug(OkularCoreDebug) << "changing direction in selection";
}
d->cur[1] = p;
}

View File

@ -65,8 +65,9 @@ Movie::Movie(const QString &fileName, const QByteArray &data)
if (d->m_tmp->open()) {
d->m_tmp->write(data);
d->m_tmp->flush();
} else
} else {
qCDebug(OkularCoreDebug) << "Failed to create temporary file for video data.";
}
}
Movie::~Movie()
@ -77,10 +78,11 @@ Movie::~Movie()
QString Movie::url() const
{
if (d->m_tmp)
if (d->m_tmp) {
return d->m_tmp->fileName();
else
} else {
return d->m_url;
}
}
void Movie::setSize(const QSize aspect)

View File

@ -54,12 +54,14 @@ static const double distanceConsideredEqual = 25; // 5px
static void deleteObjectRects(QLinkedList<ObjectRect *> &rects, const QSet<ObjectRect::ObjectType> &which)
{
QLinkedList<ObjectRect *>::iterator it = rects.begin(), end = rects.end();
for (; it != end;)
for (; it != end;) {
if (which.contains((*it)->objectType())) {
delete *it;
it = rects.erase(it);
} else
} else {
++it;
}
}
}
PagePrivate::PagePrivate(Page *page, uint n, double w, double h, Rotation o)
@ -80,11 +82,13 @@ PagePrivate::PagePrivate(Page *page, uint n, double w, double h, Rotation o)
, m_isBoundingBoxKnown(false)
{
// avoid Division-By-Zero problems in the program
if (m_width <= 0)
if (m_width <= 0) {
m_width = 1;
}
if (m_height <= 0)
if (m_height <= 0) {
m_height = 1;
}
}
PagePrivate::~PagePrivate()
@ -200,8 +204,9 @@ bool Page::isBoundingBoxKnown() const
void Page::setBoundingBox(const NormalizedRect &bbox)
{
if (d->m_isBoundingBoxKnown && d->m_boundingBox == bbox)
if (d->m_isBoundingBoxKnown && d->m_boundingBox == bbox) {
return;
}
// Allow tiny rounding errors (happens during rotation)
static const double epsilon = 0.00001;
@ -228,14 +233,17 @@ bool Page::hasPixmap(DocumentObserver *observer, int width, int height, const No
}
QMap<DocumentObserver *, PagePrivate::PixmapObject>::const_iterator it = d->m_pixmaps.constFind(observer);
if (it == d->m_pixmaps.constEnd())
if (it == d->m_pixmaps.constEnd()) {
return false;
}
if (width == -1 || height == -1)
if (width == -1 || height == -1) {
return true;
}
if (it.value().m_isPartialPixmap)
if (it.value().m_isPartialPixmap) {
return false;
}
const QPixmap *pixmap = it.value().m_pixmap;
@ -249,29 +257,34 @@ bool Page::hasTextPage() const
RegularAreaRect *Page::wordAt(const NormalizedPoint &p, QString *word) const
{
if (d->m_text)
if (d->m_text) {
return d->m_text->wordAt(p, word);
}
return nullptr;
}
RegularAreaRect *Page::textArea(TextSelection *selection) const
{
if (d->m_text)
if (d->m_text) {
return d->m_text->textArea(selection);
}
return nullptr;
}
bool Page::hasObjectRect(double x, double y, double xScale, double yScale) const
{
if (m_rects.isEmpty())
if (m_rects.isEmpty()) {
return false;
}
QLinkedList<ObjectRect *>::const_iterator it = m_rects.begin(), end = m_rects.end();
for (; it != end; ++it)
if ((*it)->distanceSqr(x, y, xScale, yScale) < distanceConsideredEqual)
for (; it != end; ++it) {
if ((*it)->distanceSqr(x, y, xScale, yScale) < distanceConsideredEqual) {
return true;
}
}
return false;
}
@ -279,16 +292,20 @@ bool Page::hasObjectRect(double x, double y, double xScale, double yScale) const
bool Page::hasHighlights(int s_id) const
{
// simple case: have no highlights
if (m_highlights.isEmpty())
if (m_highlights.isEmpty()) {
return false;
}
// simple case: we have highlights and no id to match
if (s_id == -1)
if (s_id == -1) {
return true;
}
// iterate on the highlights list to find an entry by id
QLinkedList<HighlightAreaRect *>::const_iterator it = m_highlights.begin(), end = m_highlights.end();
for (; it != end; ++it)
if ((*it)->s_id == s_id)
for (; it != end; ++it) {
if ((*it)->s_id == s_id) {
return true;
}
}
return false;
}
@ -305,8 +322,9 @@ bool Page::hasAnnotations() const
RegularAreaRect *Page::findText(int id, const QString &text, SearchDirection direction, Qt::CaseSensitivity caseSensitivity, const RegularAreaRect *lastRect) const
{
RegularAreaRect *rect = nullptr;
if (text.isEmpty() || !d->m_text)
if (text.isEmpty() || !d->m_text) {
return rect;
}
rect = d->m_text->findText(id, text, direction, caseSensitivity, lastRect);
return rect;
@ -321,16 +339,18 @@ QString Page::text(const RegularAreaRect *area, TextPage::TextAreaInclusionBehav
{
QString ret;
if (!d->m_text)
if (!d->m_text) {
return ret;
}
if (area) {
RegularAreaRect rotatedArea = *area;
rotatedArea.transform(d->rotationMatrix().inverted());
ret = d->m_text->text(&rotatedArea, b);
} else
} else {
ret = d->m_text->text(nullptr, b);
}
return ret;
}
@ -339,16 +359,18 @@ TextEntity::List Page::words(const RegularAreaRect *area, TextPage::TextAreaIncl
{
TextEntity::List ret;
if (!d->m_text)
if (!d->m_text) {
return ret;
}
if (area) {
RegularAreaRect rotatedArea = *area;
rotatedArea.transform(d->rotationMatrix().inverted());
ret = d->m_text->words(&rotatedArea, b);
} else
} else {
ret = d->m_text->words(nullptr, b);
}
for (auto &retI : ret) {
const TextEntity *orig = retI;
@ -361,13 +383,15 @@ TextEntity::List Page::words(const RegularAreaRect *area, TextPage::TextAreaIncl
void PagePrivate::rotateAt(Rotation orientation)
{
if (orientation == m_rotation)
if (orientation == m_rotation) {
return;
}
deleteTextSelections();
if (((int)m_orientation + (int)m_rotation) % 2 != ((int)m_orientation + (int)orientation) % 2)
if (((int)m_orientation + (int)m_rotation) % 2 != ((int)m_orientation + (int)orientation) % 2) {
qSwap(m_width, m_height);
}
Rotation oldRotation = m_rotation;
m_rotation = orientation;
@ -394,16 +418,18 @@ void PagePrivate::rotateAt(Rotation orientation)
i.next();
TilesManager *tm = i.value();
if (tm)
if (tm) {
tm->setRotation(m_rotation);
}
}
/**
* Rotate the object rects on the page.
*/
const QTransform matrix = rotationMatrix();
for (ObjectRect *objRect : qAsConst(m_page->m_rects))
for (ObjectRect *objRect : qAsConst(m_page->m_rects)) {
objRect->transform(matrix);
}
const QTransform highlightRotationMatrix = Okular::buildRotationMatrix((Rotation)(((int)m_rotation - (int)oldRotation + 4) % 4));
for (HighlightAreaRect *hlar : qAsConst(m_page->m_highlights)) {
@ -413,8 +439,9 @@ void PagePrivate::rotateAt(Rotation orientation)
void PagePrivate::changeSize(const PageSize &size)
{
if (size.isNull() || (size.width() == m_width && size.height() == m_height))
if (size.isNull() || (size.width() == m_width && size.height() == m_height)) {
return;
}
m_page->deletePixmaps();
// deleteHighlights();
@ -422,8 +449,9 @@ void PagePrivate::changeSize(const PageSize &size)
m_width = size.width();
m_height = size.height();
if (m_rotation % 2)
if (m_rotation % 2) {
qSwap(m_width, m_height);
}
}
const ObjectRect *Page::objectRect(ObjectRect::ObjectType type, double x, double y, double xScale, double yScale) const
@ -433,8 +461,9 @@ const ObjectRect *Page::objectRect(ObjectRect::ObjectType type, double x, double
it.toBack();
while (it.hasPrevious()) {
const ObjectRect *objrect = it.previous();
if ((objrect->objectType() == type) && objrect->distanceSqr(x, y, xScale, yScale) < distanceConsideredEqual)
if ((objrect->objectType() == type) && objrect->distanceSqr(x, y, xScale, yScale) < distanceConsideredEqual) {
return objrect;
}
}
return nullptr;
@ -448,8 +477,9 @@ QLinkedList<const ObjectRect *> Page::objectRects(ObjectRect::ObjectType type, d
it.toBack();
while (it.hasPrevious()) {
const ObjectRect *objrect = it.previous();
if ((objrect->objectType() == type) && objrect->distanceSqr(x, y, xScale, yScale) < distanceConsideredEqual)
if ((objrect->objectType() == type) && objrect->distanceSqr(x, y, xScale, yScale) < distanceConsideredEqual) {
result.append(objrect);
}
}
return result;
@ -471,8 +501,9 @@ const ObjectRect *Page::nearestObjectRect(ObjectRect::ObjectType type, double x,
}
}
if (distance)
if (distance) {
*distance = minDistance;
}
return res;
}
@ -489,8 +520,9 @@ QLinkedList<Annotation *> Page::annotations() const
Annotation *Page::annotation(const QString &uniqueName) const
{
for (Annotation *a : m_annotations) {
if (a->uniqueName() == uniqueName)
if (a->uniqueName() == uniqueName) {
return a;
}
}
return nullptr;
}
@ -576,8 +608,9 @@ void Page::setObjectRects(const QLinkedList<ObjectRect *> &rects)
const QTransform matrix = d->rotationMatrix();
QLinkedList<ObjectRect *>::const_iterator objectIt = rects.begin(), end = rects.end();
for (; objectIt != end; ++objectIt)
for (; objectIt != end; ++objectIt) {
(*objectIt)->transform(matrix);
}
m_rects << rects;
}
@ -667,20 +700,22 @@ void Page::addAnnotation(Annotation *annotation)
bool Page::removeAnnotation(Annotation *annotation)
{
if (!d->m_doc->m_parent->canRemovePageAnnotation(annotation))
if (!d->m_doc->m_parent->canRemovePageAnnotation(annotation)) {
return false;
}
QLinkedList<Annotation *>::iterator aIt = m_annotations.begin(), aEnd = m_annotations.end();
for (; aIt != aEnd; ++aIt) {
if ((*aIt) && (*aIt)->uniqueName() == annotation->uniqueName()) {
int rectfound = false;
QLinkedList<ObjectRect *>::iterator it = m_rects.begin(), end = m_rects.end();
for (; it != end && !rectfound; ++it)
for (; it != end && !rectfound; ++it) {
if (((*it)->objectType() == ObjectRect::OAnnotation) && ((*it)->object() == (*aIt))) {
delete *it;
it = m_rects.erase(it);
rectfound = true;
}
}
qCDebug(OkularCoreDebug) << "removed annotation:" << annotation->uniqueName();
annotation->d_ptr->m_page = nullptr;
m_annotations.erase(aIt);
@ -764,8 +799,9 @@ void PagePrivate::deleteHighlights(int s_id)
if (s_id == -1 || highlight->s_id == s_id) {
it = m_page->m_highlights.erase(it);
delete highlight;
} else
} else {
++it;
}
}
}
@ -824,8 +860,9 @@ bool PagePrivate::restoreLocalContents(const QDomNode &pageNode)
m_doc->performAddPageAnnotation(m_number, annotation);
qCDebug(OkularCoreDebug) << "restored annot:" << annotation->uniqueName();
loadedAnything = true;
} else
} else {
qCWarning(OkularCoreDebug).nospace() << "page (" << m_number << "): can't restore an annotation from XML.";
}
}
#ifdef PAGE_PROFILE
qCDebug(OkularCoreDebug).nospace() << "annots: XML Load time: " << time.elapsed() << "ms";
@ -837,8 +874,9 @@ bool PagePrivate::restoreLocalContents(const QDomNode &pageNode)
const QDomNode clonedNode = restoredFormFieldList.importNode(childElement, true);
restoredFormFieldList.appendChild(clonedNode);
if (formfields.isEmpty())
if (formfields.isEmpty()) {
continue;
}
QHash<int, FormField *> hashedforms;
for (FormField *ff : qAsConst(formfields)) {
@ -852,17 +890,20 @@ bool PagePrivate::restoreLocalContents(const QDomNode &pageNode)
QDomElement formElement = formsNode.toElement();
formsNode = formsNode.nextSibling();
if (formElement.tagName() != QLatin1String("form"))
if (formElement.tagName() != QLatin1String("form")) {
continue;
}
bool ok = true;
int index = formElement.attribute(QStringLiteral("id")).toInt(&ok);
if (!ok)
if (!ok) {
continue;
}
QHash<int, FormField *>::const_iterator wantedIt = hashedforms.constFind(index);
if (wantedIt == hashedforms.constEnd())
if (wantedIt == hashedforms.constEnd()) {
continue;
}
QString value = formElement.attribute(QStringLiteral("value"));
(*wantedIt)->d_ptr->setValue(value);
@ -908,8 +949,9 @@ void PagePrivate::saveLocalContents(QDomNode &parentNode, QDomDocument &document
}
// append the annotationList element if annotations have been set
if (annotListElement.hasChildNodes())
if (annotListElement.hasChildNodes()) {
pageElement.appendChild(annotListElement);
}
}
// add forms info if has got any
@ -931,8 +973,9 @@ void PagePrivate::saveLocalContents(QDomNode &parentNode, QDomDocument &document
const FormField *f = *fIt;
QString newvalue = f->d_ptr->value();
if (f->d_ptr->m_default == newvalue)
if (f->d_ptr->m_default == newvalue) {
continue;
}
// append an filled-up element called 'annotation' to the list
QDomElement formElement = document.createElement(QStringLiteral("form"));
@ -942,13 +985,15 @@ void PagePrivate::saveLocalContents(QDomNode &parentNode, QDomDocument &document
}
// append the annotationList element if annotations have been set
if (formListElement.hasChildNodes())
if (formListElement.hasChildNodes()) {
pageElement.appendChild(formListElement);
}
}
// append the page element only if has children
if (pageElement.hasChildNodes())
if (pageElement.hasChildNodes()) {
parentNode.appendChild(pageElement);
}
}
const QPixmap *Page::_o_nearestPixmap(DocumentObserver *observer, int w, int h) const
@ -959,10 +1004,10 @@ const QPixmap *Page::_o_nearestPixmap(DocumentObserver *observer, int w, int h)
// if a pixmap is present for given id, use it
QMap<DocumentObserver *, PagePrivate::PixmapObject>::const_iterator itPixmap = d->m_pixmaps.constFind(observer);
if (itPixmap != d->m_pixmaps.constEnd())
if (itPixmap != d->m_pixmaps.constEnd()) {
pixmap = itPixmap.value().m_pixmap;
// else find the closest match using pixmaps of other IDs (great optim!)
else if (!d->m_pixmaps.isEmpty()) {
} else if (!d->m_pixmaps.isEmpty()) {
// else find the closest match using pixmaps of other IDs (great optim!)
int minDistance = -1;
QMap<DocumentObserver *, PagePrivate::PixmapObject>::const_iterator it = d->m_pixmaps.constBegin(), end = d->m_pixmaps.constEnd();
for (; it != end; ++it) {
@ -985,10 +1030,11 @@ bool Page::hasTilesManager(const DocumentObserver *observer) const
QList<Tile> Page::tilesAt(const DocumentObserver *observer, const NormalizedRect &rect) const
{
TilesManager *tm = d->m_tilesManagers.value(observer);
if (tm)
if (tm) {
return tm->tilesAt(rect, TilesManager::PixmapTile);
else
} else {
return QList<Tile>();
}
}
TilesManager *PagePrivate::tilesManager(const DocumentObserver *observer) const
@ -1031,13 +1077,15 @@ FormField *PagePrivate::findEquivalentForm(const Page *p, FormField *oldField)
// given how id is not very good of id (at least for pdf) we do a few passes
// same rect, type and id
for (FormField *f : qAsConst(p->d->formfields)) {
if (f->rect() == oldField->rect() && f->type() == oldField->type() && f->id() == oldField->id())
if (f->rect() == oldField->rect() && f->type() == oldField->type() && f->id() == oldField->id()) {
return f;
}
}
// same rect and type
for (FormField *f : qAsConst(p->d->formfields)) {
if (f->rect() == oldField->rect() && f->type() == oldField->type())
if (f->rect() == oldField->rect() && f->type() == oldField->type()) {
return f;
}
}
// fuzzy rect, same type and id
for (FormField *f : qAsConst(p->d->formfields)) {

View File

@ -51,32 +51,36 @@ PageSize::~PageSize()
double PageSize::width() const
{
if (!d)
if (!d) {
return 0;
}
return d->m_width;
}
double PageSize::height() const
{
if (!d)
if (!d) {
return 0;
}
return d->m_height;
}
QString PageSize::name() const
{
if (!d)
if (!d) {
return QString();
}
return d->m_name;
}
bool PageSize::isNull() const
{
if (!d)
if (!d) {
return true;
}
return d->m_width == 0 && d->m_height == 0 && d->m_name.isEmpty();
}
@ -84,11 +88,13 @@ bool PageSize::isNull() const
bool PageSize::operator==(const PageSize &pageSize) const
{
// 1st: we're null: check if the other is null too
if (!d)
if (!d) {
return !pageSize.d;
}
// 2nd: we're not null, return if the other is null
if (!pageSize.d)
if (!pageSize.d) {
return false;
}
// 3rd: normal == check
return *d == *pageSize.d;
@ -101,8 +107,9 @@ bool PageSize::operator!=(const PageSize &pageSize) const
PageSize &PageSize::operator=(const PageSize &pageSize)
{
if (this == &pageSize)
if (this == &pageSize) {
return *this;
}
d = pageSize.d;
return *this;

View File

@ -46,8 +46,9 @@ PageTransition::PageTransition(const PageTransition &other)
PageTransition &PageTransition::operator=(const PageTransition &other)
{
if (this == &other)
if (this == &other) {
return *this;
}
*d = *other.d;

View File

@ -59,33 +59,37 @@ QTransform RotationJob::rotationMatrix(Rotation from, Rotation to)
QTransform matrix;
if (from == Rotation0) {
if (to == Rotation90)
if (to == Rotation90) {
matrix.rotate(90);
else if (to == Rotation180)
} else if (to == Rotation180) {
matrix.rotate(180);
else if (to == Rotation270)
} else if (to == Rotation270) {
matrix.rotate(270);
}
} else if (from == Rotation90) {
if (to == Rotation180)
if (to == Rotation180) {
matrix.rotate(90);
else if (to == Rotation270)
} else if (to == Rotation270) {
matrix.rotate(180);
else if (to == Rotation0)
} else if (to == Rotation0) {
matrix.rotate(270);
}
} else if (from == Rotation180) {
if (to == Rotation270)
if (to == Rotation270) {
matrix.rotate(90);
else if (to == Rotation0)
} else if (to == Rotation0) {
matrix.rotate(180);
else if (to == Rotation90)
} else if (to == Rotation90) {
matrix.rotate(270);
}
} else if (from == Rotation270) {
if (to == Rotation0)
if (to == Rotation0) {
matrix.rotate(90);
else if (to == Rotation90)
} else if (to == Rotation90) {
matrix.rotate(180);
else if (to == Rotation180)
} else if (to == Rotation180) {
matrix.rotate(270);
}
}
return matrix;

View File

@ -58,34 +58,35 @@ static KJSObject appGetLanguage(KJSContext *, void *)
QString lang = QLocale::languageToString(locale.language());
QString country = QLocale::countryToString(locale.country());
QString acroLang = QStringLiteral("ENU");
if (lang == QLatin1String("da"))
if (lang == QLatin1String("da")) {
acroLang = QStringLiteral("DAN"); // Danish
else if (lang == QLatin1String("de"))
} else if (lang == QLatin1String("de")) {
acroLang = QStringLiteral("DEU"); // German
else if (lang == QLatin1String("en"))
} else if (lang == QLatin1String("en")) {
acroLang = QStringLiteral("ENU"); // English
else if (lang == QLatin1String("es"))
} else if (lang == QLatin1String("es")) {
acroLang = QStringLiteral("ESP"); // Spanish
else if (lang == QLatin1String("fr"))
} else if (lang == QLatin1String("fr")) {
acroLang = QStringLiteral("FRA"); // French
else if (lang == QLatin1String("it"))
} else if (lang == QLatin1String("it")) {
acroLang = QStringLiteral("ITA"); // Italian
else if (lang == QLatin1String("ko"))
} else if (lang == QLatin1String("ko")) {
acroLang = QStringLiteral("KOR"); // Korean
else if (lang == QLatin1String("ja"))
} else if (lang == QLatin1String("ja")) {
acroLang = QStringLiteral("JPN"); // Japanese
else if (lang == QLatin1String("nl"))
} else if (lang == QLatin1String("nl")) {
acroLang = QStringLiteral("NLD"); // Dutch
else if (lang == QLatin1String("pt") && country == QLatin1String("BR"))
} else if (lang == QLatin1String("pt") && country == QLatin1String("BR")) {
acroLang = QStringLiteral("PTB"); // Brazilian Portuguese
else if (lang == QLatin1String("fi"))
} else if (lang == QLatin1String("fi")) {
acroLang = QStringLiteral("SUO"); // Finnish
else if (lang == QLatin1String("sv"))
} else if (lang == QLatin1String("sv")) {
acroLang = QStringLiteral("SVE"); // Swedish
else if (lang == QLatin1String("zh") && country == QLatin1String("CN"))
} else if (lang == QLatin1String("zh") && country == QLatin1String("CN")) {
acroLang = QStringLiteral("CHS"); // Chinese Simplified
else if (lang == QLatin1String("zh") && country == QLatin1String("TW"))
} else if (lang == QLatin1String("zh") && country == QLatin1String("TW")) {
acroLang = QStringLiteral("CHT"); // Chinese Traditional
}
return KJSString(acroLang);
}
@ -220,13 +221,15 @@ static KJSObject appAlert(KJSContext *context, void *, const KJSArguments &argum
KJSObject oMsg = oCheckbox.property(context, QStringLiteral("cMsg"));
QString msg = i18n("Do not show this message again");
if (oMsg.isString())
if (oMsg.isString()) {
msg = oMsg.toString(context);
}
bool bInitialValue = false;
KJSObject value = oCheckbox.property(context, QStringLiteral("bInitialValue"));
if (value.isBoolean())
if (value.isBoolean()) {
bInitialValue = value.toBoolean(context);
}
checkBox = new QCheckBox(msg);
checkBox->setChecked(bInitialValue);
box.setCheckBox(checkBox);
@ -261,8 +264,9 @@ static KJSObject appAlert(KJSContext *context, void *, const KJSArguments &argum
break;
}
if (checkBox)
if (checkBox) {
oCheckbox.setProperty(context, QStringLiteral("bAfterValue"), checkBox->isChecked());
}
delete checkBox;
@ -285,8 +289,9 @@ static KJSObject appGetNthPlugInName(KJSContext *context, void *, const KJSArgum
}
const int nIndex = arguments.at(0).toInt32(context);
if (nIndex < 0 || nIndex >= s_num_fake_plugins)
if (nIndex < 0 || nIndex >= s_num_fake_plugins) {
return context->throwException(QStringLiteral("PlugIn index out of bounds"));
}
const FakePluginInfo &info = s_fake_plugins[nIndex];
return KJSString(info.name);
@ -295,8 +300,9 @@ static KJSObject appGetNthPlugInName(KJSContext *context, void *, const KJSArgum
static KJSObject appGoBack(KJSContext *, void *object, const KJSArguments &)
{
const DocumentPrivate *doc = reinterpret_cast<DocumentPrivate *>(object);
if (doc->m_parent->historyAtBegin())
if (doc->m_parent->historyAtBegin()) {
return KJSUndefined();
}
doc->m_parent->setPrevViewport();
return KJSUndefined();
@ -305,8 +311,9 @@ static KJSObject appGoBack(KJSContext *, void *object, const KJSArguments &)
static KJSObject appGoForward(KJSContext *, void *object, const KJSArguments &)
{
const DocumentPrivate *doc = reinterpret_cast<DocumentPrivate *>(object);
if (doc->m_parent->historyAtEnd())
if (doc->m_parent->historyAtEnd()) {
return KJSUndefined();
}
doc->m_parent->setNextViewport();
return KJSUndefined();
@ -379,8 +386,9 @@ static KJSObject appClearTimeOut(KJSContext *ctx, void *, const KJSArguments &ar
void JSApp::initType(KJSContext *ctx)
{
static bool initialized = false;
if (initialized)
if (initialized) {
return;
}
initialized = true;
g_appProto = new KJSPrototype();

View File

@ -126,8 +126,9 @@ static KJSObject consoleShow(KJSContext *, void *, const KJSArguments &)
void JSConsole::initType(KJSContext *ctx)
{
static bool initialized = false;
if (initialized)
if (initialized) {
return;
}
initialized = true;
g_consoleProto = new KJSPrototype();

View File

@ -65,12 +65,14 @@ static KJSObject dataGetSize(KJSContext *, void *object)
void JSData::initType(KJSContext *ctx)
{
static bool initialized = false;
if (initialized)
if (initialized) {
return;
}
initialized = true;
if (!g_dataProto)
if (!g_dataProto) {
g_dataProto = new KJSPrototype();
}
g_dataProto->defineProperty(ctx, QStringLiteral("creationDate"), dataGetCreationDate);
g_dataProto->defineProperty(ctx, QStringLiteral("description"), dataGetDescription);

View File

@ -43,8 +43,9 @@ static KJSObject displayGetNoPrint(KJSContext *, void *)
void JSDisplay::initType(KJSContext *ctx)
{
static bool initialized = false;
if (initialized)
if (initialized) {
return;
}
initialized = true;
g_displayProto = new KJSPrototype();

View File

@ -50,8 +50,9 @@ static void docSetPageNum(KJSContext *ctx, void *object, KJSObject value)
int page = value.toInt32(ctx);
if (page == (int)doc->m_parent->currentPage())
if (page == (int)doc->m_parent->currentPage()) {
return;
}
doc->m_parent->setViewportPage(page);
}
@ -226,8 +227,9 @@ static KJSObject docGotoNamedDest(KJSContext *ctx, void *object, const KJSArgume
QString dest = arguments.at(0).toString(ctx);
DocumentViewport viewport(doc->m_generator->metaData(QStringLiteral("NamedViewport"), dest).toString());
if (!viewport.isValid())
if (!viewport.isValid()) {
return KJSUndefined();
}
doc->m_parent->setViewport(viewport);
@ -290,8 +292,9 @@ void JSDocument::initType(KJSContext *ctx)
assert(g_docProto);
static bool initialized = false;
if (initialized)
if (initialized) {
return;
}
initialized = true;
g_docProto->defineProperty(ctx, QStringLiteral("numPages"), docGetNumPages);
@ -325,7 +328,8 @@ void JSDocument::initType(KJSContext *ctx)
KJSGlobalObject JSDocument::wrapDocument(DocumentPrivate *doc)
{
if (!g_docProto)
if (!g_docProto) {
g_docProto = new KJSPrototype();
}
return g_docProto->constructGlobalObject(doc);
}

View File

@ -59,8 +59,9 @@ static KJSObject eventGetSource(KJSContext *ctx, void *object)
const Event *event = reinterpret_cast<Event *>(object);
if (event->eventType() == Event::FieldCalculate) {
FormField *src = event->source();
if (src)
if (src) {
return JSField::wrapField(ctx, src, event->sourcePage());
}
}
return KJSUndefined();
}
@ -76,8 +77,9 @@ static KJSObject eventGetTarget(KJSContext *ctx, void *object)
case Event::FieldFocus:
case Event::FieldValidate: {
FormField *target = static_cast<FormField *>(event->target());
if (target)
if (target) {
return JSField::wrapField(ctx, target, event->targetPage());
}
break;
}
default: {
@ -124,12 +126,14 @@ static KJSObject eventGetWillCommit(KJSContext *, void *object)
void JSEvent::initType(KJSContext *ctx)
{
static bool initialized = false;
if (initialized)
if (initialized) {
return;
}
initialized = true;
if (!g_eventProto)
if (!g_eventProto) {
g_eventProto = new KJSPrototype();
}
g_eventProto->defineProperty(ctx, QStringLiteral("name"), eventGetName);
g_eventProto->defineProperty(ctx, QStringLiteral("type"), eventGetType);

View File

@ -278,12 +278,14 @@ static KJSObject fieldButtonSetIcon(KJSContext *ctx, void *object, const KJSArgu
void JSField::initType(KJSContext *ctx)
{
static bool initialized = false;
if (initialized)
if (initialized) {
return;
}
initialized = true;
if (!g_fieldProto)
if (!g_fieldProto) {
g_fieldProto = new KJSPrototype();
}
g_fieldProto->defineProperty(ctx, QStringLiteral("doc"), fieldGetDoc);
g_fieldProto->defineProperty(ctx, QStringLiteral("name"), fieldGetName);
@ -308,9 +310,11 @@ KJSObject JSField::wrapField(KJSContext *ctx, FormField *field, Page *page)
void JSField::clearCachedFields()
{
if (g_fieldCache.exists())
if (g_fieldCache.exists()) {
g_fieldCache->clear();
}
if (g_buttonCache.exists())
if (g_buttonCache.exists()) {
g_buttonCache->clear();
}
}

View File

@ -54,12 +54,14 @@ static void fsSetTimeDelay(KJSContext *ctx, void *, KJSObject value)
void JSFullscreen::initType(KJSContext *ctx)
{
static bool initialized = false;
if (initialized)
if (initialized) {
return;
}
initialized = true;
if (!g_fsProto)
if (!g_fsProto) {
g_fsProto = new KJSPrototype();
}
g_fsProto->defineProperty(ctx, QStringLiteral("loop"), fsGetLoop, fsSetLoop);
g_fsProto->defineProperty(ctx, QStringLiteral("useTimer"), fsGetUseTimer, fsSetUseTimer);

View File

@ -51,8 +51,9 @@ static void OCGSetState(KJSContext *ctx, void *object, KJSObject value)
void JSOCG::initType(KJSContext *ctx)
{
static bool initialized = false;
if (initialized)
if (initialized) {
return;
}
initialized = true;
g_OCGProto = new KJSPrototype();

View File

@ -25,8 +25,9 @@ static KJSObject spellGetAvailable(KJSContext *, void *)
void JSSpell::initType(KJSContext *ctx)
{
static bool initialized = false;
if (initialized)
if (initialized) {
return;
}
initialized = true;
g_spellProto = new KJSPrototype();

View File

@ -39,16 +39,19 @@ static KJSObject crackURL(KJSContext *context, void *, const KJSArguments &argum
KJSObject obj;
obj.setProperty(context, QStringLiteral("cScheme"), url.scheme());
if (!url.userName().isEmpty())
if (!url.userName().isEmpty()) {
obj.setProperty(context, QStringLiteral("cUser"), url.userName());
if (!url.password().isEmpty())
}
if (!url.password().isEmpty()) {
obj.setProperty(context, QStringLiteral("cPassword"), url.password());
}
obj.setProperty(context, QStringLiteral("cHost"), url.host());
obj.setProperty(context, QStringLiteral("nPort"), url.port(80));
// TODO cPath (Optional) The path portion of the URL.
// TODO cParameters (Optional) The parameter string portion of the URL.
if (url.hasFragment())
if (url.hasFragment()) {
obj.setProperty(context, QStringLiteral("cFragments"), url.fragment(QUrl::FullyDecoded));
}
return obj;
}
@ -74,18 +77,20 @@ static KJSObject printd(KJSContext *context, void *, const KJSArguments &argumen
break;
case 2:
format = defaultLocale.dateTimeFormat(QLocale::ShortFormat);
if (!format.contains(QStringLiteral("ss")))
if (!format.contains(QStringLiteral("ss"))) {
format.insert(format.indexOf(QStringLiteral("mm")) + 2, QStringLiteral(":ss"));
}
break;
}
} else {
format = arguments.at(0).toString(context).replace(QLatin1String("tt"), QLatin1String("ap"));
format.replace('t', 'a');
for (QChar &formatChar : format) {
if (formatChar == 'M')
if (formatChar == 'M') {
formatChar = 'm';
else if (formatChar == 'm')
} else if (formatChar == 'm') {
formatChar = 'M';
}
}
}
@ -173,8 +178,9 @@ static KJSObject stringToNumber(KJSContext *context, void *, const KJSArguments
void JSUtil::initType(KJSContext *ctx)
{
static bool initialized = false;
if (initialized)
if (initialized) {
return;
}
initialized = true;
g_utilProto = new KJSPrototype();

View File

@ -60,8 +60,9 @@ bool Okular::extractLilyPondSourceReference(const QUrl &url, QString *file, int
// Example URL is: textedit:///home/foo/bar.ly:42:42:42
// The three numbers are apparently: line:beginning of column:end of column
if (url.scheme() != QStringLiteral("textedit"))
if (url.scheme() != QStringLiteral("textedit")) {
return false;
}
// There can be more, in case the filename contains :
if (url.fileName().count(':') < 3) {

View File

@ -102,8 +102,9 @@ Okular::TextPage *TextDocumentGeneratorPrivate::createTextPage(int pageNumber) c
if (text.length() == 1) {
QRectF rect;
TextDocumentUtils::calculateBoundingRect(mDocument, i, i + 1, rect, pageNumber);
if (pageNumber == -1)
if (pageNumber == -1) {
text = QStringLiteral("\n");
}
textPage->append(text, new Okular::NormalizedRect(rect.left(), rect.top(), rect.right(), rect.bottom()));
}
@ -118,8 +119,9 @@ Okular::TextPage *TextDocumentGeneratorPrivate::createTextPage(int pageNumber) c
void TextDocumentGeneratorPrivate::addAction(Action *action, int cursorBegin, int cursorEnd)
{
if (!action)
if (!action) {
return;
}
LinkPosition position;
position.link = action;
@ -131,8 +133,9 @@ void TextDocumentGeneratorPrivate::addAction(Action *action, int cursorBegin, in
void TextDocumentGeneratorPrivate::addAnnotation(Annotation *annotation, int cursorBegin, int cursorEnd)
{
if (!annotation)
if (!annotation) {
return;
}
annotation->setFlags(annotation->flags() | Okular::Annotation::External);
@ -195,8 +198,9 @@ QList<TextDocumentGeneratorPrivate::AnnotationInfo> TextDocumentGeneratorPrivate
TextDocumentUtils::calculateBoundingRect(mDocument, annotationPosition.startPosition, annotationPosition.endPosition, info.boundingRect, info.page);
if (info.page >= 0)
if (info.page >= 0) {
result.append(info);
}
}
return result;
@ -312,8 +316,9 @@ Document::OpenResult TextDocumentGenerator::loadDocumentWithPassword(const QStri
QVector<QLinkedList<Okular::ObjectRect *>> objects(d->mDocument->pageCount());
for (const TextDocumentGeneratorPrivate::LinkInfo &info : linkInfos) {
// in case that the converter report bogus link info data, do not assert here
if (info.page < 0 || info.page >= objects.count())
if (info.page < 0 || info.page >= objects.count()) {
continue;
}
const QRectF rect = info.boundingRect;
if (info.ownsLink) {
@ -372,8 +377,9 @@ void TextDocumentGenerator::generatePixmap(Okular::PixmapRequest *request)
QImage TextDocumentGeneratorPrivate::image(PixmapRequest *request)
{
if (!mDocument)
if (!mDocument) {
return QImage();
}
#ifdef OKULAR_TEXTDOCUMENT_THREADED_RENDERING
Q_Q(TextDocumentGenerator);
@ -425,8 +431,9 @@ Okular::TextPage *TextDocumentGenerator::textPage(Okular::TextRequest *request)
Document::PrintError TextDocumentGenerator::print(QPrinter &printer)
{
Q_D(TextDocumentGenerator);
if (!d->mDocument)
if (!d->mDocument) {
return Document::UnknownPrintError;
}
d->mDocument->print(&printer);
@ -442,10 +449,11 @@ Okular::DocumentInfo TextDocumentGenerator::generateDocumentInfo(const QSet<Docu
const Okular::DocumentSynopsis *TextDocumentGenerator::generateDocumentSynopsis()
{
Q_D(TextDocumentGenerator);
if (!d->mDocumentSynopsis.hasChildNodes())
if (!d->mDocumentSynopsis.hasChildNodes()) {
return nullptr;
else
} else {
return &d->mDocumentSynopsis;
}
}
QVariant TextDocumentGeneratorPrivate::metaData(const QString &key, const QVariant &option) const
@ -477,13 +485,15 @@ Okular::ExportFormat::List TextDocumentGenerator::exportFormats() const
bool TextDocumentGenerator::exportTo(const QString &fileName, const Okular::ExportFormat &format)
{
Q_D(TextDocumentGenerator);
if (!d->mDocument)
if (!d->mDocument) {
return false;
}
if (format.mimeType().name() == QLatin1String("application/pdf")) {
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly))
if (!file.open(QIODevice::WriteOnly)) {
return false;
}
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
@ -493,8 +503,9 @@ bool TextDocumentGenerator::exportTo(const QString &fileName, const Okular::Expo
return true;
} else if (format.mimeType().name() == QLatin1String("text/plain")) {
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly))
if (!file.open(QIODevice::WriteOnly)) {
return false;
}
QTextStream out(&file);
out << d->mDocument->toPlainText();

View File

@ -76,11 +76,13 @@ static bool segmentsOverlap(double left1, double right1, double left2, double ri
{
// check if one consumes another fully (speed optimization)
if (left1 <= left2 && right1 >= right2)
if (left1 <= left2 && right1 >= right2) {
return true;
}
if (left1 >= left2 && right1 <= right2)
if (left1 >= left2 && right1 <= right2) {
return true;
}
// check if there is overlap above threshold
if (right2 >= left1 && right1 >= left2) {
@ -229,8 +231,9 @@ TextPage::TextPage(const TextEntity::List &words)
TextEntity::List::ConstIterator it = words.constBegin(), itEnd = words.constEnd();
for (; it != itEnd; ++it) {
TextEntity *e = *it;
if (!e->text().isEmpty())
if (!e->text().isEmpty()) {
d->m_words.append(new TinyTextEntity(e->text(), *e->area()));
}
delete e;
}
}
@ -336,8 +339,9 @@ private:
RegularAreaRect *TextPage::textArea(TextSelection *sel) const
{
if (d->m_words.isEmpty())
if (d->m_words.isEmpty()) {
return new RegularAreaRect();
}
/**
It works like this:
@ -414,33 +418,38 @@ RegularAreaRect *TextPage::textArea(TextSelection *sel) const
const NormalizedRect start_end = (startC.y < endC.y) ? NormalizedRect(startC.x, startC.y, endC.x, endC.y) : NormalizedRect(startC.x, endC.y, endC.x, startC.y);
// Case 1(a)
if (!boundingRect.intersects(start_end))
if (!boundingRect.intersects(start_end)) {
return ret;
// case 1(b)
/**
note that, after swapping of start and end, we know that,
start is always left to end. but, we cannot say start is
positioned upper than end.
**/
else {
} else {
// case 1(b)
/**
note that, after swapping of start and end, we know that,
start is always left to end. but, we cannot say start is
positioned upper than end.
**/
// if start is left to content rect take it to content rect boundary
if (startC.x * scaleX < minX)
if (startC.x * scaleX < minX) {
startC.x = minX / scaleX;
if (endC.x * scaleX > maxX)
}
if (endC.x * scaleX > maxX) {
endC.x = maxX / scaleX;
}
// if start is top to end (selection type 01)
if (startC.y * scaleY < minY)
if (startC.y * scaleY < minY) {
startC.y = minY / scaleY;
if (endC.y * scaleY > maxY)
}
if (endC.y * scaleY > maxY) {
endC.y = maxY / scaleY;
}
// if start is bottom to end (selection type 02)
if (startC.y * scaleY > maxY)
if (startC.y * scaleY > maxY) {
startC.y = maxY / scaleY;
if (endC.y * scaleY < minY)
}
if (endC.y * scaleY < minY) {
endC.y = minY / scaleY;
}
}
TextList::ConstIterator it = d->m_words.constBegin(), itEnd = d->m_words.constEnd();
@ -465,8 +474,9 @@ RegularAreaRect *TextPage::textArea(TextSelection *sel) const
for (; it != itEnd; ++it) {
// is there any text rectangle within the start_end rect
tmp = (*it)->area;
if (start_end.intersects(tmp))
if (start_end.intersects(tmp)) {
break;
}
}
// we have searched every text entities, but none is within the rectangle created by start and end
@ -513,10 +523,12 @@ RegularAreaRect *TextPage::textArea(TextSelection *sel) const
ydist = entRect.center().y() - startC.y * scaleY;
// make them positive
if (xdist < 0)
if (xdist < 0) {
xdist = -xdist;
if (ydist < 0)
}
if (ydist < 0) {
ydist = -ydist;
}
if ((xdist + ydist) < distance) {
distance = xdist + ydist;
@ -559,10 +571,12 @@ RegularAreaRect *TextPage::textArea(TextSelection *sel) const
ydist = entRect.center().y() - endC.y * scaleY;
// make them positive
if (xdist < 0)
if (xdist < 0) {
xdist = -xdist;
if (ydist < 0)
}
if (ydist < 0) {
ydist = -ydist;
}
if ((xdist + ydist) < distance) {
distance = xdist + ydist;
@ -591,8 +605,9 @@ RegularAreaRect *TextPage::textArea(TextSelection *sel) const
}
// removes the possibility of crash, in case none of 1 to 3 is true
if (end == d->m_words.constEnd())
if (end == d->m_words.constEnd()) {
end--;
}
for (; start <= end; start++) {
ret->appendShape((*start)->transformedArea(matrix), side);
@ -605,8 +620,9 @@ RegularAreaRect *TextPage::findText(int searchID, const QString &query, SearchDi
{
SearchDirection dir = direct;
// invalid search request
if (d->m_words.isEmpty() || query.isEmpty() || (area && area->isNull()))
if (d->m_words.isEmpty() || query.isEmpty() || (area && area->isNull())) {
return nullptr;
}
TextList::ConstIterator start;
int start_offset = 0;
TextList::ConstIterator end;
@ -614,10 +630,11 @@ RegularAreaRect *TextPage::findText(int searchID, const QString &query, SearchDi
if (sIt == d->m_searchPoints.constEnd()) {
// if no previous run of this search is found, then set it to start
// from the beginning (respecting the search direction)
if (dir == NextResult)
if (dir == NextResult) {
dir = FromTop;
else if (dir == PreviousResult)
} else if (dir == PreviousResult) {
dir = FromBottom;
}
}
bool forward = true;
switch (dir) {
@ -926,8 +943,9 @@ QString TextPage::text(const RegularAreaRect *area) const
QString TextPage::text(const RegularAreaRect *area, TextAreaInclusionBehaviour b) const
{
if (area && area->isNull())
if (area && area->isNull()) {
return QString();
}
TextList::ConstIterator it = d->m_words.constBegin(), itEnd = d->m_words.constEnd();
QString ret;
@ -945,8 +963,9 @@ QString TextPage::text(const RegularAreaRect *area, TextAreaInclusionBehaviour b
}
}
} else {
for (; it != itEnd; ++it)
for (; it != itEnd; ++it) {
ret += (*it)->text();
}
}
return ret;
}
@ -1048,8 +1067,9 @@ static WordsWithCharacters makeWordFromCharacters(const TextList &characters, in
we must have to put this line before the if condition of it==itEnd
otherwise the last character can be missed
*/
if (it == itEnd)
if (it == itEnd) {
break;
}
elementArea = (*it)->area.roundedGeometry(pageWidth, pageHeight);
if (!doesConsumeY(elementArea, lineArea, 60)) {
--it;
@ -1088,8 +1108,9 @@ static WordsWithCharacters makeWordFromCharacters(const TextList &characters, in
index++;
}
if (it == itEnd)
if (it == itEnd) {
break;
}
}
return wordsWithCharacters;
@ -1156,8 +1177,9 @@ QList<QPair<WordsWithCharacters, QRect>> makeAndSortLines(const WordsWithCharact
found = true;
}
if (found)
if (found) {
break;
}
}
/* when we have found a new line create a new TextList containing
@ -1203,18 +1225,21 @@ static void calculateStatisticalInformation(const QList<WordWithCharacters> &wor
for (int i = 0; i < sortedLines.length(); i++) {
const QRect rectUpper = sortedLines.at(i).second;
if (i + 1 == sortedLines.length())
if (i + 1 == sortedLines.length()) {
break;
}
const QRect rectLower = sortedLines.at(i + 1).second;
int linespace = rectLower.top() - (rectUpper.top() + rectUpper.height());
if (linespace < 0)
if (linespace < 0) {
linespace = -linespace;
}
if (line_space_stat.contains(linespace))
if (line_space_stat.contains(linespace)) {
line_space_stat[linespace]++;
else
} else {
line_space_stat[linespace] = 1;
}
}
*line_spacing = 0;
@ -1226,8 +1251,9 @@ static void calculateStatisticalInformation(const QList<WordWithCharacters> &wor
*line_spacing += iterate_linespace.value() * iterate_linespace.key();
weighted_count += iterate_linespace.value();
}
if (*line_spacing != 0)
if (*line_spacing != 0) {
*line_spacing = (int)((double)*line_spacing / (double)weighted_count + 0.5);
}
/**
* Step 2
@ -1252,8 +1278,9 @@ static void calculateStatisticalInformation(const QList<WordWithCharacters> &wor
// for every line
for (; it != itEnd; it++) {
const QRect area1 = (*it).area().roundedGeometry(pageWidth, pageHeight);
if (it + 1 == itEnd)
if (it + 1 == itEnd) {
break;
}
const QRect area2 = (*(it + 1)).area().roundedGeometry(pageWidth, pageHeight);
int space = area2.left() - area1.right();
@ -1266,16 +1293,18 @@ static void calculateStatisticalInformation(const QList<WordWithCharacters> &wor
after_max = (*(it + 1)).text();
}
if (space < minSpace && space != 0)
if (space < minSpace && space != 0) {
minSpace = space;
}
// if we found a real space, whose length is not zero and also less than the pageWidth
if (space != 0 && space != pageWidth) {
// increase the count of the space amount
if (hor_space_stat.contains(space))
if (hor_space_stat.contains(space)) {
hor_space_stat[space]++;
else
} else {
hor_space_stat[space] = 1;
}
int left, right, top, bottom;
@ -1293,17 +1322,19 @@ static void calculateStatisticalInformation(const QList<WordWithCharacters> &wor
space_rects.append(line_space_rects);
if (hor_space_stat.contains(maxSpace)) {
if (hor_space_stat[maxSpace] != 1)
if (hor_space_stat[maxSpace] != 1) {
hor_space_stat[maxSpace]--;
else
} else {
hor_space_stat.remove(maxSpace);
}
}
if (maxSpace != 0) {
if (col_space_stat.contains(maxSpace))
if (col_space_stat.contains(maxSpace)) {
col_space_stat[maxSpace]++;
else
} else {
col_space_stat[maxSpace] = 1;
}
// store the max rect of each line
const int left = max_area1.right();
@ -1313,8 +1344,9 @@ static void calculateStatisticalInformation(const QList<WordWithCharacters> &wor
const QRect rect(left, top, right - left, bottom - top);
max_hor_space_rects.append(rect);
} else
} else {
max_hor_space_rects.append(QRect(0, 0, 0, 0));
}
}
// All the between word space counts are in hor_space_stat
@ -1330,22 +1362,25 @@ static void calculateStatisticalInformation(const QList<WordWithCharacters> &wor
weighted_count += iterate.value();
}
}
if (weighted_count)
if (weighted_count) {
*word_spacing = (int)((double)*word_spacing / (double)weighted_count + 0.5);
}
*col_spacing = 0;
QMapIterator<int, int> iterate_col(col_space_stat);
while (iterate_col.hasNext()) {
iterate_col.next();
if (iterate_col.value() > *col_spacing)
if (iterate_col.value() > *col_spacing) {
*col_spacing = iterate_col.value();
}
}
*col_spacing = col_space_stat.key(*col_spacing);
// if there is just one line in a region, there is no point in dividing it
if (sortedLines.length() == 1)
if (sortedLines.length() == 1) {
*word_spacing = *col_spacing;
}
}
/**
@ -1379,10 +1414,12 @@ static RegionTextList XYCutForBoundingBoxes(const QList<WordWithCharacters> &wor
QVarLengthArray<int> proj_on_xaxis(size_proj_x);
QVarLengthArray<int> proj_on_yaxis(size_proj_y);
for (int j = 0; j < size_proj_y; ++j)
for (int j = 0; j < size_proj_y; ++j) {
proj_on_yaxis[j] = 0;
for (int j = 0; j < size_proj_x; ++j)
}
for (int j = 0; j < size_proj_x; ++j) {
proj_on_xaxis[j] = 0;
}
const QList<WordWithCharacters> list = node.text();
@ -1404,47 +1441,56 @@ static RegionTextList XYCutForBoundingBoxes(const QList<WordWithCharacters> &wor
// calculate vertical projection profile proj_on_xaxis1
for (int k = entRect.left(); k <= entRect.left() + entRect.width(); ++k) {
if ((k - regionRect.left()) < size_proj_x && (k - regionRect.left()) >= 0)
if ((k - regionRect.left()) < size_proj_x && (k - regionRect.left()) >= 0) {
proj_on_xaxis[k - regionRect.left()] += entRect.height();
}
}
// calculate horizontal projection profile in the same way
for (int k = entRect.top(); k <= entRect.top() + entRect.height(); ++k) {
if ((k - regionRect.top()) < size_proj_y && (k - regionRect.top()) >= 0)
if ((k - regionRect.top()) < size_proj_y && (k - regionRect.top()) >= 0) {
proj_on_yaxis[k - regionRect.top()] += entRect.width();
}
}
}
for (int j = 0; j < size_proj_y; ++j) {
if (proj_on_yaxis[j] > maxY)
if (proj_on_yaxis[j] > maxY) {
maxY = proj_on_yaxis[j];
}
}
avgX = count = 0;
for (int j = 0; j < size_proj_x; ++j) {
if (proj_on_xaxis[j] > maxX)
if (proj_on_xaxis[j] > maxX) {
maxX = proj_on_xaxis[j];
}
if (proj_on_xaxis[j]) {
count++;
avgX += proj_on_xaxis[j];
}
}
if (count)
if (count) {
avgX /= count;
}
/**
* 2. Cleanup Boundary White Spaces and removal of noise
*/
int xbegin = 0, xend = size_proj_x - 1;
int ybegin = 0, yend = size_proj_y - 1;
while (xbegin < size_proj_x && proj_on_xaxis[xbegin] <= 0)
while (xbegin < size_proj_x && proj_on_xaxis[xbegin] <= 0) {
xbegin++;
while (xend >= 0 && proj_on_xaxis[xend] <= 0)
}
while (xend >= 0 && proj_on_xaxis[xend] <= 0) {
xend--;
while (ybegin < size_proj_y && proj_on_yaxis[ybegin] <= 0)
}
while (ybegin < size_proj_y && proj_on_yaxis[ybegin] <= 0) {
ybegin++;
while (yend >= 0 && proj_on_yaxis[yend] <= 0)
}
while (yend >= 0 && proj_on_yaxis[yend] <= 0) {
yend--;
}
// update the regionRect
int old_left = regionRect.left(), old_top = regionRect.top();
@ -1454,10 +1500,12 @@ static RegionTextList XYCutForBoundingBoxes(const QList<WordWithCharacters> &wor
regionRect.setBottom(old_top + yend);
int tnx = (int)((double)avgX * 10.0 / 100.0 + 0.5), tny = 0;
for (int j = 0; j < size_proj_x; ++j)
for (int j = 0; j < size_proj_x; ++j) {
proj_on_xaxis[j] -= tnx;
for (int j = 0; j < size_proj_y; ++j)
}
for (int j = 0; j < size_proj_y; ++j) {
proj_on_yaxis[j] -= tny;
}
/**
* 3. Find the Widest gap
@ -1468,12 +1516,14 @@ static RegionTextList XYCutForBoundingBoxes(const QList<WordWithCharacters> &wor
// find all hor_gaps and find the maximum between them
for (int j = 1; j < size_proj_y; ++j) {
// transition from white to black
if (begin >= 0 && proj_on_yaxis[j - 1] <= 0 && proj_on_yaxis[j] > 0)
if (begin >= 0 && proj_on_yaxis[j - 1] <= 0 && proj_on_yaxis[j] > 0) {
end = j;
}
// transition from black to white
if (proj_on_yaxis[j - 1] > 0 && proj_on_yaxis[j] <= 0)
if (proj_on_yaxis[j - 1] > 0 && proj_on_yaxis[j] <= 0) {
begin = j;
}
if (begin > 0 && end > 0 && end - begin > gap_hor) {
gap_hor = end - begin;
@ -1494,8 +1544,9 @@ static RegionTextList XYCutForBoundingBoxes(const QList<WordWithCharacters> &wor
}
// transition from black to white
if (proj_on_xaxis[j - 1] > 0 && proj_on_xaxis[j] <= 0)
if (proj_on_xaxis[j - 1] > 0 && proj_on_xaxis[j] <= 0) {
begin = j;
}
if (begin > 0 && end > 0 && end - begin > gap_ver) {
gap_ver = end - begin;
@ -1523,16 +1574,16 @@ static RegionTextList XYCutForBoundingBoxes(const QList<WordWithCharacters> &wor
const QRect leftRect(regionRect.left(), regionRect.top(), leftWidth, regionRect.height());
const QRect rightRect(regionRect.left() + leftWidth, regionRect.top(), regionRect.width() - leftWidth, regionRect.height());
if (gap_y >= gap_x && gap_y >= tcy)
if (gap_y >= gap_x && gap_y >= tcy) {
cut_hor = true;
else if (gap_y >= gap_x && gap_y <= tcy && gap_x >= tcx)
} else if (gap_y >= gap_x && gap_y <= tcy && gap_x >= tcx) {
cut_ver = true;
else if (gap_x >= gap_y && gap_x >= tcx)
} else if (gap_x >= gap_y && gap_x >= tcx) {
cut_ver = true;
else if (gap_x >= gap_y && gap_x <= tcx && gap_y >= tcy)
} else if (gap_x >= gap_y && gap_x <= tcx && gap_y >= tcy) {
cut_hor = true;
// no cut possible
else {
} else {
// no cut possible
// we can now update the node rectangle with the shrinked rectangle
RegionText tmpNode = tree.at(i);
tmpNode.setArea(regionRect);
@ -1548,10 +1599,11 @@ static RegionTextList XYCutForBoundingBoxes(const QList<WordWithCharacters> &wor
for (const WordWithCharacters &word : list) {
const QRect wordRect = word.area().geometry(pageWidth, pageHeight);
if (topRect.intersects(wordRect))
if (topRect.intersects(wordRect)) {
list1.append(word);
else
} else {
list2.append(word);
}
}
RegionText node1(list1, topRect);
@ -1566,10 +1618,11 @@ static RegionTextList XYCutForBoundingBoxes(const QList<WordWithCharacters> &wor
for (const WordWithCharacters &word : list) {
const QRect wordRect = word.area().geometry(pageWidth, pageHeight);
if (leftRect.intersects(wordRect))
if (leftRect.intersects(wordRect)) {
list1.append(word);
else
} else {
list2.append(word);
}
}
RegionText node1(list1, leftRect);
@ -1604,8 +1657,9 @@ WordsWithCharacters addNecessarySpace(RegionTextList tree, int pageWidth, int pa
WordsWithCharacters &list = sortedLine.first;
for (int k = 0; k < list.length(); k++) {
const QRect area1 = list.at(k).area().roundedGeometry(pageWidth, pageHeight);
if (k + 1 >= list.length())
if (k + 1 >= list.length()) {
break;
}
const QRect area2 = list.at(k + 1).area().roundedGeometry(pageWidth, pageHeight);
const int space = area2.left() - area1.right();
@ -1695,8 +1749,9 @@ void TextPagePrivate::correctTextOrder()
TextEntity::List TextPage::words(const RegularAreaRect *area, TextAreaInclusionBehaviour b) const
{
if (area && area->isNull())
if (area && area->isNull()) {
return TextEntity::List();
}
TextEntity::List ret;
if (area) {

View File

@ -19,8 +19,9 @@ using namespace Okular;
static bool rankedTilesLessThan(TileNode *t1, TileNode *t2)
{
// Order tiles by its dirty state and then by distance from the viewport.
if (t1->dirty == t2->dirty)
if (t1->dirty == t2->dirty) {
return t1->distance < t2->distance;
}
return !t1->dirty;
}
@ -106,8 +107,9 @@ TilesManager::TilesManager(int pageNumber, int width, int height, Rotation rotat
TilesManager::~TilesManager()
{
for (const TileNode &tile : d->tiles)
for (const TileNode &tile : d->tiles) {
d->deleteTiles(tile);
}
delete d;
}
@ -120,8 +122,9 @@ void TilesManager::Private::deleteTiles(const TileNode &tile)
}
if (tile.nTiles > 0) {
for (int i = 0; i < tile.nTiles; ++i)
for (int i = 0; i < tile.nTiles; ++i) {
deleteTiles(tile.tiles[i]);
}
delete[] tile.tiles;
}
@ -129,8 +132,9 @@ void TilesManager::Private::deleteTiles(const TileNode &tile)
void TilesManager::setSize(int width, int height)
{
if (width == d->width && height == d->height)
if (width == d->width && height == d->height) {
return;
}
d->width = width;
d->height = height;
@ -150,8 +154,9 @@ int TilesManager::height() const
void TilesManager::setRotation(Rotation rotation)
{
if (rotation == d->rotation)
if (rotation == d->rotation) {
return;
}
d->rotation = rotation;
}
@ -181,8 +186,9 @@ void TilesManager::setPixmap(const QPixmap *pixmap, const NormalizedRect &rect,
{
const NormalizedRect rotatedRect = TilesManager::fromRotatedRect(rect, d->rotation);
if (!d->requestRect.isNull()) {
if (!(d->requestRect == rect))
if (!(d->requestRect == rect)) {
return;
}
if (pixmap) {
// Check whether the pixmap has the same absolute size of the expected
@ -199,8 +205,9 @@ void TilesManager::setPixmap(const QPixmap *pixmap, const NormalizedRect &rect,
pixmapSize.transpose();
}
if (rotatedRect.geometry(w, h).size() != pixmapSize)
if (rotatedRect.geometry(w, h).size() != pixmapSize) {
return;
}
}
d->requestRect = NormalizedRect();
@ -216,16 +223,18 @@ void TilesManager::Private::setPixmap(const QPixmap *pixmap, const NormalizedRec
QRect pixmapRect = TilesManager::toRotatedRect(rect, rotation).geometry(width, height);
// Exclude tiles outside the viewport
if (!tile.rect.intersects(rect))
if (!tile.rect.intersects(rect)) {
return;
}
// if the tile is not entirely within the viewport (the tile intersects an
// edged of the viewport), attempt to set the pixmap in the children tiles
if (!((tile.rect & rect) == tile.rect)) {
// paint children tiles
if (tile.nTiles > 0) {
for (int i = 0; i < tile.nTiles; ++i)
for (int i = 0; i < tile.nTiles; ++i) {
setPixmap(pixmap, rect, tile.tiles[i], isPartialPixmap);
}
delete tile.pixmap;
tile.pixmap = nullptr;
@ -259,8 +268,9 @@ void TilesManager::Private::setPixmap(const QPixmap *pixmap, const NormalizedRec
tile.pixmap = nullptr;
}
for (int i = 0; i < tile.nTiles; ++i)
for (int i = 0; i < tile.nTiles; ++i) {
setPixmap(pixmap, rect, tile.tiles[i], isPartialPixmap);
}
}
} else {
QRect tileRect = tile.rect.geometry(width, height);
@ -274,8 +284,9 @@ void TilesManager::Private::setPixmap(const QPixmap *pixmap, const NormalizedRec
tile.pixmap = nullptr;
}
for (int i = 0; i < tile.nTiles; ++i)
for (int i = 0; i < tile.nTiles; ++i) {
setPixmap(pixmap, rect, tile.tiles[i], isPartialPixmap);
}
} else {
// remove children tiles
for (int i = 0; i < tile.nTiles; ++i) {
@ -309,8 +320,9 @@ bool TilesManager::hasPixmap(const NormalizedRect &rect)
{
NormalizedRect rotatedRect = fromRotatedRect(rect, d->rotation);
for (const TileNode &tile : qAsConst(d->tiles)) {
if (!d->hasPixmap(rotatedRect, tile))
if (!d->hasPixmap(rotatedRect, tile)) {
return false;
}
}
return true;
@ -319,19 +331,23 @@ bool TilesManager::hasPixmap(const NormalizedRect &rect)
bool TilesManager::Private::hasPixmap(const NormalizedRect &rect, const TileNode &tile) const
{
const NormalizedRect rectIntersection = tile.rect & rect;
if (rectIntersection.width() <= 0 || rectIntersection.height() <= 0)
if (rectIntersection.width() <= 0 || rectIntersection.height() <= 0) {
return true;
}
if (tile.nTiles == 0)
if (tile.nTiles == 0) {
return tile.isValid();
}
// all children tiles are clean. doesn't need to go deeper
if (!tile.dirty)
if (!tile.dirty) {
return true;
}
for (int i = 0; i < tile.nTiles; ++i) {
if (!hasPixmap(rect, tile.tiles[i]))
if (!hasPixmap(rect, tile.tiles[i])) {
return false;
}
}
return true;
@ -351,8 +367,9 @@ QList<Tile> TilesManager::tilesAt(const NormalizedRect &rect, TileLeaf tileLeaf)
void TilesManager::Private::tilesAt(const NormalizedRect &rect, TileNode &tile, QList<Tile> &result, TileLeaf tileLeaf)
{
if (!tile.rect.intersects(rect))
if (!tile.rect.intersects(rect)) {
return;
}
// split big tiles before the requests are made, otherwise we would end up
// requesting huge areas unnecessarily
@ -360,10 +377,11 @@ void TilesManager::Private::tilesAt(const NormalizedRect &rect, TileNode &tile,
if ((tileLeaf == TerminalTile && tile.nTiles == 0) || (tileLeaf == PixmapTile && tile.pixmap)) {
NormalizedRect rotatedRect;
if (rotation != Rotation0)
if (rotation != Rotation0) {
rotatedRect = TilesManager::toRotatedRect(tile.rect, rotation);
else
} else {
rotatedRect = tile.rect;
}
if (tile.pixmap && tileLeaf == PixmapTile && tile.rotation != rotation) {
// Lazy tiles rotation
@ -412,8 +430,9 @@ void TilesManager::Private::tilesAt(const NormalizedRect &rect, TileNode &tile,
}
result.append(Tile(rotatedRect, tile.pixmap, tile.isValid()));
} else {
for (int i = 0; i < tile.nTiles; ++i)
for (int i = 0; i < tile.nTiles; ++i) {
tilesAt(rect, tile.tiles[i], result, tileLeaf);
}
}
}
@ -432,19 +451,22 @@ void TilesManager::cleanupPixmapMemory(qulonglong numberOfBytes, const Normalize
while (numberOfBytes > 0 && !rankedTiles.isEmpty()) {
TileNode *tile = rankedTiles.takeLast();
if (!tile->pixmap)
if (!tile->pixmap) {
continue;
}
// do not evict visible pixmaps
if (tile->rect.intersects(visibleRect))
if (tile->rect.intersects(visibleRect)) {
continue;
}
qulonglong pixels = tile->pixmap->width() * tile->pixmap->height();
d->totalPixels -= pixels;
if (numberOfBytes < 4 * pixels)
if (numberOfBytes < 4 * pixels) {
numberOfBytes = 0;
else
} else {
numberOfBytes -= 4 * pixels;
}
delete tile->pixmap;
tile->pixmap = nullptr;
@ -455,8 +477,9 @@ void TilesManager::cleanupPixmapMemory(qulonglong numberOfBytes, const Normalize
void TilesManager::Private::markParentDirty(const TileNode &tile)
{
if (!tile.parent)
if (!tile.parent) {
return;
}
if (!tile.parent->dirty) {
tile.parent->dirty = true;
@ -472,8 +495,9 @@ void TilesManager::Private::rankTiles(TileNode &tile, QList<TileNode *> &rankedT
// Note that the current page may be visible and yet its pageNumber is
// different from visiblePageNumber. Since we only use this value on hidden
// pages, any visible page number will fit.
if (visibleRect.isNull() && visiblePageNumber < 0)
if (visibleRect.isNull() && visiblePageNumber < 0) {
return;
}
if (tile.pixmap) {
// Update distance
@ -484,10 +508,11 @@ void TilesManager::Private::rankTiles(TileNode &tile, QList<TileNode *> &rankedT
tile.distance = qAbs(viewportCenter.x - tileCenter.x) + qAbs(viewportCenter.y - tileCenter.y);
} else {
// For non visible pages only the vertical distance is used
if (pageNumber < visiblePageNumber)
if (pageNumber < visiblePageNumber) {
tile.distance = 1 - tile.rect.bottom;
else
} else {
tile.distance = tile.rect.top;
}
}
rankedTiles.append(&tile);
} else {
@ -512,8 +537,9 @@ void TilesManager::setRequest(const NormalizedRect &rect, int pageWidth, int pag
bool TilesManager::Private::splitBigTiles(TileNode &tile, const NormalizedRect &rect)
{
QRect tileRect = tile.rect.geometry(width, height);
if (tileRect.width() * tileRect.height() < TILES_MAXSIZE)
if (tileRect.width() * tileRect.height() < TILES_MAXSIZE) {
return false;
}
split(tile, rect);
return true;
@ -521,11 +547,13 @@ bool TilesManager::Private::splitBigTiles(TileNode &tile, const NormalizedRect &
void TilesManager::Private::split(TileNode &tile, const NormalizedRect &rect)
{
if (tile.nTiles != 0)
if (tile.nTiles != 0) {
return;
}
if (rect.isNull() || !tile.rect.intersects(rect))
if (rect.isNull() || !tile.rect.intersects(rect)) {
return;
}
tile.nTiles = 4;
tile.tiles = new TileNode[4];
@ -545,8 +573,9 @@ void TilesManager::Private::split(TileNode &tile, const NormalizedRect &rect)
NormalizedRect TilesManager::fromRotatedRect(const NormalizedRect &rect, Rotation rotation)
{
if (rotation == Rotation0)
if (rotation == Rotation0) {
return rect;
}
NormalizedRect newRect;
switch (rotation) {
@ -569,8 +598,9 @@ NormalizedRect TilesManager::fromRotatedRect(const NormalizedRect &rect, Rotatio
NormalizedRect TilesManager::toRotatedRect(const NormalizedRect &rect, Rotation rotation)
{
if (rotation == Rotation0)
if (rotation == Rotation0) {
return rect;
}
NormalizedRect newRect;
switch (rotation) {
@ -641,8 +671,9 @@ Tile::Tile(const Tile &t)
Tile &Tile::operator=(const Tile &other)
{
if (this == &other)
if (this == &other) {
return *this;
}
d->rect = other.d->rect;
d->pixmap = other.d->pixmap;

View File

@ -68,8 +68,9 @@ inline static bool isPaperColor(QRgb argb, QRgb paperColor)
NormalizedRect Utils::imageBoundingBox(const QImage *image)
{
if (!image)
if (!image) {
return NormalizedRect();
}
const int width = image->width();
const int height = image->height();
@ -82,34 +83,46 @@ NormalizedRect Utils::imageBoundingBox(const QImage *image)
#endif
// Scan pixels for top non-white
for (top = 0; top < height; ++top)
for (x = 0; x < width; ++x)
if (!isPaperColor(image->pixel(x, top), paperColor))
for (top = 0; top < height; ++top) {
for (x = 0; x < width; ++x) {
if (!isPaperColor(image->pixel(x, top), paperColor)) {
goto got_top;
}
}
}
return NormalizedRect(0, 0, 0, 0); // the image is blank
got_top:
left = right = x;
// Scan pixels for bottom non-white
for (bottom = height - 1; bottom >= top; --bottom)
for (x = width - 1; x >= 0; --x)
if (!isPaperColor(image->pixel(x, bottom), paperColor))
for (bottom = height - 1; bottom >= top; --bottom) {
for (x = width - 1; x >= 0; --x) {
if (!isPaperColor(image->pixel(x, bottom), paperColor)) {
goto got_bottom;
}
}
}
Q_ASSERT(0); // image changed?!
got_bottom:
if (x < left)
if (x < left) {
left = x;
if (x > right)
}
if (x > right) {
right = x;
}
// Scan for leftmost and rightmost (we already found some bounds on these):
for (y = top; y <= bottom && (left > 0 || right < width - 1); ++y) {
for (x = 0; x < left; ++x)
if (!isPaperColor(image->pixel(x, y), paperColor))
for (x = 0; x < left; ++x) {
if (!isPaperColor(image->pixel(x, y), paperColor)) {
left = x;
for (x = width - 1; x > right + 1; --x)
if (!isPaperColor(image->pixel(x, y), paperColor))
}
}
for (x = width - 1; x > right + 1; --x) {
if (!isPaperColor(image->pixel(x, y), paperColor)) {
right = x;
}
}
}
NormalizedRect bbox(QRect(left, top, (right - left + 1), (bottom - top + 1)), image->width(), image->height());
@ -128,8 +141,9 @@ void Okular::copyQIODevice(QIODevice *from, QIODevice *to)
qint64 written = 0;
while ((read = from->read(buffer.data(), buffer.size())) > 0) {
written = to->write(buffer.constData(), read);
if (read != written)
if (read != written) {
break;
}
}
}

View File

@ -83,10 +83,11 @@ bool CHMGenerator::loadDocument(const QString &fileName, QVector<Okular::Page *>
}
}
item.setAttribute(QStringLiteral("Icon"), e.iconid);
if (e.indent == 0)
if (e.indent == 0) {
m_docSyn.appendChild(item);
else
} else {
lastIndentElement[e.indent - 1].appendChild(item);
}
lastIndentElement[e.indent] = item;
}
@ -94,23 +95,26 @@ bool CHMGenerator::loadDocument(const QString &fileName, QVector<Okular::Page *>
QList<QUrl> pageList;
m_file->enumerateFiles(pageList);
const QUrl home = m_file->homeUrl();
if (home.path() != QLatin1String("/"))
if (home.path() != QLatin1String("/")) {
pageList.prepend(home);
}
m_pageUrl.resize(pageNum);
for (const QUrl &qurl : qAsConst(pageList)) {
QString url = qurl.toString();
const QString urlLower = url.toLower();
if (!urlLower.endsWith(QLatin1String(".html")) && !urlLower.endsWith(QLatin1String(".htm")))
if (!urlLower.endsWith(QLatin1String(".html")) && !urlLower.endsWith(QLatin1String(".htm"))) {
continue;
}
int pos = url.indexOf(QLatin1Char(('#')));
// insert the url into the maps, but insert always the variant without the #ref part
QString tmpUrl = pos == -1 ? url : url.left(pos);
// url already there, abort insertion
if (m_urlPage.contains(tmpUrl))
if (m_urlPage.contains(tmpUrl)) {
continue;
}
int foundPage = tmpPageList.value(tmpUrl, -1);
if (foundPage != -1) {
@ -179,8 +183,9 @@ void CHMGenerator::preparePageForSyncOperation(const QString &url)
void CHMGenerator::slotCompleted()
{
if (!m_request)
if (!m_request) {
return;
}
QImage image(m_request->width(), m_request->height(), QImage::Format_ARGB32);
image.fill(Qt::white);
@ -206,8 +211,9 @@ void CHMGenerator::slotCompleted()
Okular::PixmapRequest *req = m_request;
m_request = nullptr;
if (!req->page()->isBoundingBoxKnown())
if (!req->page()->isBoundingBoxKnown()) {
updatePageBoundingBox(req->page()->number(), Okular::Utils::imageBoundingBox(&image));
}
req->page()->setPixmap(req->observer(), new QPixmap(QPixmap::fromImage(image)));
signalPixmapRequestDone(req);
}
@ -215,10 +221,12 @@ void CHMGenerator::slotCompleted()
Okular::DocumentInfo CHMGenerator::generateDocumentInfo(const QSet<Okular::DocumentInfo::Key> &keys) const
{
Okular::DocumentInfo docInfo;
if (keys.contains(Okular::DocumentInfo::MimeType))
if (keys.contains(Okular::DocumentInfo::MimeType)) {
docInfo.set(Okular::DocumentInfo::MimeType, QStringLiteral("application/x-chm"));
if (keys.contains(Okular::DocumentInfo::Title))
}
if (keys.contains(Okular::DocumentInfo::Title)) {
docInfo.set(Okular::DocumentInfo::Title, m_file->title());
}
return docInfo;
}
@ -327,9 +335,9 @@ void CHMGenerator::recursiveExploreNodes(DOM::Node node, Okular::TextPage *tp)
QString url = n.attributes().getNamedItem("href").nodeValue().string();
r = n.getRect();
// there is no way for us to support javascript properly
if (url.startsWith(QLatin1String("JavaScript:")), Qt::CaseInsensitive)
if (url.startsWith(QLatin1String("JavaScript:")), Qt::CaseInsensitive) {
continue;
else if (url.contains(QStringLiteral(":"))) {
} else if (url.contains(QStringLiteral(":"))) {
objRects.push_back(new Okular::ObjectRect(Okular::NormalizedRect(r, xScale, yScale), false, Okular::ObjectRect::Action, new Okular::BrowseAction(QUrl(url))));
} else {
Okular::DocumentViewport viewport(metaData(QStringLiteral("NamedViewport"), absolutePath(m_chmUrl, url)).toString());

View File

@ -56,8 +56,9 @@ ProtocolMSITS::ProtocolMSITS(const QByteArray &pool_socket, const QByteArray &ap
ProtocolMSITS::~ProtocolMSITS()
{
if (!m_chmFile)
if (!m_chmFile) {
return;
}
chm_close(m_chmFile);
m_chmFile = nullptr;
@ -77,8 +78,9 @@ void ProtocolMSITS::get(const QUrl &url)
qCDebug(KIO_MITS_LOG) << "kio_msits::get() " << url.path();
if (!parseLoadAndLookup(url, fileName))
if (!parseLoadAndLookup(url, fileName)) {
return; // error() has been called by parseLoadAndLookup
}
qCDebug(KIO_MITS_LOG) << "kio_msits::get: parseLoadAndLookup returned " << fileName;
@ -135,8 +137,9 @@ bool ProtocolMSITS::parseLoadAndLookup(const QUrl &url, QString &abspath)
abspath = url.path().mid(pos + 2); // skip ::
// Some buggy apps add ms-its:/ to the path as well
if (abspath.startsWith(QLatin1String("ms-its:")))
if (abspath.startsWith(QLatin1String("ms-its:"))) {
abspath = abspath.mid(7);
}
qCDebug(KIO_MITS_LOG) << "ProtocolMSITS::parseLoadAndLookup: filename " << filename << ", path " << abspath;
@ -146,8 +149,9 @@ bool ProtocolMSITS::parseLoadAndLookup(const QUrl &url, QString &abspath)
}
// If the file has been already loaded, nothing to do.
if (m_chmFile && filename == m_openedFile)
if (m_chmFile && filename == m_openedFile) {
return true;
}
qCDebug(KIO_MITS_LOG) << "Opening a new CHM file " << QFile::encodeName(QDir::toNativeSeparators(filename));
@ -160,8 +164,9 @@ bool ProtocolMSITS::parseLoadAndLookup(const QUrl &url, QString &abspath)
}
// Replace an existing file by a new one
if (m_chmFile)
if (m_chmFile) {
chm_close(m_chmFile);
}
m_chmFile = tmpchm;
m_openedFile = filename;
@ -211,8 +216,9 @@ void ProtocolMSITS::stat(const QUrl &url)
qCDebug(KIO_MITS_LOG) << "kio_msits::stat (const KUrl& url) " << url.path();
if (!parseLoadAndLookup(url, fileName))
if (!parseLoadAndLookup(url, fileName)) {
return; // error() has been called by parseLoadAndLookup
}
if (!ResolveObject(fileName, &ui)) {
error(KIO::ERR_DOES_NOT_EXIST, url.toString());
@ -222,10 +228,11 @@ void ProtocolMSITS::stat(const QUrl &url)
qCDebug(KIO_MITS_LOG) << "kio_msits::stat: adding an entry for " << fileName;
UDSEntry entry;
if (isDirectory(fileName))
if (isDirectory(fileName)) {
app_dir(entry, fileName);
else
} else {
app_file(entry, fileName, ui.length);
}
statEntry(entry);
@ -245,8 +252,9 @@ void ProtocolMSITS::listDir(const QUrl &url)
qCDebug(KIO_MITS_LOG) << "kio_msits::listDir (const KUrl& url) " << url.path();
if (!parseLoadAndLookup(url, filepath))
if (!parseLoadAndLookup(url, filepath)) {
return; // error() has been called by parseLoadAndLookup
}
filepath += QLatin1Char('/');
@ -271,10 +279,11 @@ void ProtocolMSITS::listDir(const QUrl &url)
// Strip the directory name
const QString ename = iListing.mid(striplength);
if (isDirectory(ename))
if (isDirectory(ename)) {
app_dir(entry, ename);
else
} else {
app_file(entry, ename, 0);
}
}
finished();

View File

@ -56,9 +56,9 @@ inline int ffus(unsigned char *byte, int *bit, size_t &length)
length = 0;
while (*byte & (1 << *bit)) {
if (*bit)
if (*bit) {
--(*bit);
else {
} else {
++byte;
++length;
*bit = 7;
@ -66,9 +66,9 @@ inline int ffus(unsigned char *byte, int *bit, size_t &length)
++bits;
}
if (*bit)
if (*bit) {
--(*bit);
else {
} else {
++length;
*bit = 7;
}
@ -84,8 +84,9 @@ inline quint64 sr_int(unsigned char *byte, int *bit, unsigned char s, unsigned c
length = 0;
size_t fflen;
if (!bit || *bit > 7 || s != 2)
if (!bit || *bit > 7 || s != 2) {
return ~(quint64)0;
}
ret = 0;
count = ffus(byte, bit, fflen);
@ -142,8 +143,9 @@ inline quint64 sr_int(unsigned char *byte, int *bit, unsigned char s, unsigned c
}
}
if (count)
if (count) {
ret |= (quint64)1 << n_bits;
}
return ret;
}

View File

@ -21,15 +21,17 @@ EBook *EBook::loadFile(const QString &archiveName)
{
EBook_CHM *cbook = new EBook_CHM();
if (cbook->load(archiveName))
if (cbook->load(archiveName)) {
return cbook;
}
delete cbook;
EBook_EPUB *ebook = new EBook_EPUB();
if (ebook->load(archiveName))
if (ebook->load(archiveName)) {
return ebook;
}
delete ebook;
return nullptr;

View File

@ -46,8 +46,9 @@ EBook_CHM::~EBook_CHM()
void EBook_CHM::close()
{
if (m_chmFile == nullptr)
if (m_chmFile == nullptr) {
return;
}
chm_close(m_chmFile);
@ -92,14 +93,16 @@ bool EBook_CHM::hasFeature(EBook::Feature code) const
bool EBook_CHM::getTableOfContents(QList<EBookTocEntry> &toc) const
{
if (parseBinaryTOC(toc))
if (parseBinaryTOC(toc)) {
return true;
}
// Parse the plain text TOC
QList<ParsedEntry> parsed;
if (!parseFileAndFillArray(m_topicsFile, parsed, false))
if (!parseFileAndFillArray(m_topicsFile, parsed, false)) {
return false;
}
// Find out the root offset, and reduce the indent level to it
// so the toc starts from zero offset.
@ -108,16 +111,18 @@ bool EBook_CHM::getTableOfContents(QList<EBookTocEntry> &toc) const
// Fill up the real toc
toc.reserve(parsed.size());
for (const ParsedEntry &e : qAsConst(parsed)) {
if (root_offset == -1)
if (root_offset == -1) {
root_offset = e.indent;
}
EBookTocEntry entry;
entry.iconid = (EBookTocEntry::Icon)e.iconid;
entry.indent = e.indent - root_offset;
entry.name = e.name;
if (!e.urls.empty())
if (!e.urls.empty()) {
entry.url = e.urls[0];
}
toc.append(entry);
}
@ -130,8 +135,9 @@ bool EBook_CHM::getIndex(QList<EBookIndexEntry> &index) const
// Parse the plain text index
QList<ParsedEntry> parsed;
if (!parseFileAndFillArray(m_indexFile, parsed, true))
if (!parseFileAndFillArray(m_indexFile, parsed, true)) {
return false;
}
// Find out the root offset, and reduce the indent level to it
// so the index starts from zero offset.
@ -143,16 +149,18 @@ bool EBook_CHM::getIndex(QList<EBookIndexEntry> &index) const
// Find the index root offset
const QList<ParsedEntry> &parsedList = parsed;
for (const ParsedEntry &e : parsedList) {
if (e.urls.empty())
if (e.urls.empty()) {
continue;
}
root_offset = qMin(root_offset, e.indent);
}
// And apply the index
for (const ParsedEntry &e : parsedList) {
if (e.urls.empty())
if (e.urls.empty()) {
continue;
}
EBookIndexEntry entry;
entry.name = e.name;
@ -160,10 +168,11 @@ bool EBook_CHM::getIndex(QList<EBookIndexEntry> &index) const
entry.seealso = e.seealso;
// If the index array is empty, make sure the first entry is on root offset
if (index.isEmpty())
if (index.isEmpty()) {
entry.indent = root_offset;
else
} else {
entry.indent = e.indent - root_offset;
}
index.append(entry);
printf("%d: %s\n", entry.indent, qPrintable(entry.name));
@ -186,13 +195,15 @@ bool EBook_CHM::getBinaryContent(QByteArray &data, const QString &url) const
{
chmUnitInfo ui;
if (!ResolveObject(url, &ui))
if (!ResolveObject(url, &ui)) {
return false;
}
data.resize(ui.length);
if (RetrieveObject(&ui, (unsigned char *)data.data(), 0, ui.length))
if (RetrieveObject(&ui, (unsigned char *)data.data(), 0, ui.length)) {
return true;
}
return false;
}
@ -220,8 +231,9 @@ int EBook_CHM::getContentSize(const QString &url)
{
chmUnitInfo ui;
if (!ResolveObject(url, &ui))
if (!ResolveObject(url, &ui)) {
return -1;
}
return ui.length;
}
@ -231,13 +243,15 @@ bool EBook_CHM::load(const QString &archiveName)
QString filename;
// If the file has a file:// prefix, remove it
if (archiveName.startsWith(QLatin1String("file://")))
if (archiveName.startsWith(QLatin1String("file://"))) {
filename = archiveName.mid(7); // strip it
else
} else {
filename = archiveName;
}
if (m_chmFile)
if (m_chmFile) {
close();
}
#if defined(WIN32)
// chm_open on Windows OS uses the following prototype:
@ -251,8 +265,9 @@ bool EBook_CHM::load(const QString &archiveName)
m_chmFile = chm_open(QFile::encodeName(filename));
#endif
if (m_chmFile == nullptr)
if (m_chmFile == nullptr) {
return false;
}
m_filename = filename;
@ -272,26 +287,31 @@ bool EBook_CHM::load(const QString &archiveName)
ResolveObject(QStringLiteral("/#URLSTR"), &m_chmURLSTR)) {
m_lookupTablesValid = true;
fillTopicsUrlMap();
} else
} else {
m_lookupTablesValid = false;
}
// Some CHM files have toc and index files, but do not set the name properly.
// Some heuristics here.
if (m_topicsFile.isEmpty() && hasFile(QStringLiteral("/toc.hhc")))
if (m_topicsFile.isEmpty() && hasFile(QStringLiteral("/toc.hhc"))) {
m_topicsFile = "/toc.hhc";
}
if (m_indexFile.isEmpty() && hasFile(QStringLiteral("/index.hhk")))
if (m_indexFile.isEmpty() && hasFile(QStringLiteral("/index.hhk"))) {
m_indexFile = "/index.hhk";
}
if (!m_topicsFile.isEmpty() || (m_lookupTablesValid && hasFile(QStringLiteral("/#TOCIDX"))))
if (!m_topicsFile.isEmpty() || (m_lookupTablesValid && hasFile(QStringLiteral("/#TOCIDX")))) {
m_tocAvailable = true;
else
} else {
m_tocAvailable = false;
}
if (!m_indexFile.isEmpty() || (m_lookupTablesValid && hasFile(QStringLiteral("/$WWKeywordLinks/BTree"))))
if (!m_indexFile.isEmpty() || (m_lookupTablesValid && hasFile(QStringLiteral("/$WWKeywordLinks/BTree")))) {
m_indexAvailable = true;
else
} else {
m_indexAvailable = false;
}
return true;
}
@ -300,13 +320,15 @@ int EBook_CHM::findStringInQuotes(const QString &tag, int offset, QString &value
{
int qbegin = tag.indexOf('"', offset);
if (qbegin == -1)
if (qbegin == -1) {
qFatal("EBook_CHMImpl::findStringInQuotes: cannot find first quote in <param> tag: '%s'", qPrintable(tag));
}
int qend = firstquote ? tag.indexOf('"', qbegin + 1) : tag.lastIndexOf('"');
if (qend == -1 || qend <= qbegin)
if (qend == -1 || qend <= qbegin) {
qFatal("EBook_CHMImpl::findStringInQuotes: cannot find last quote in <param> tag: '%s'", qPrintable(tag));
}
// If we do not need to decode HTML entities, just return.
if (decodeentities) {
@ -317,28 +339,32 @@ int EBook_CHM::findStringInQuotes(const QString &tag, int offset, QString &value
for (int i = qbegin + 1; i < qend; i++) {
if (!fill_entity) {
if (tag[i] == '&') // HTML entity starts
if (tag[i] == '&') { // HTML entity starts
fill_entity = true;
else
} else {
value.append(tag[i]);
}
} else {
if (tag[i] == ';') // HTML entity ends
{
// If entity is an ASCII code, just decode it
QString decode = m_htmlEntityDecoder.decode(htmlentity);
if (decode.isNull())
if (decode.isNull()) {
break;
}
value.append(decode);
htmlentity = QString();
fill_entity = false;
} else
} else {
htmlentity.append(tag[i]);
}
}
}
} else
} else {
value = tag.mid(qbegin + 1, qend - qbegin - 1);
}
return qend + 1;
}
@ -348,8 +374,9 @@ bool EBook_CHM::parseFileAndFillArray(const QString &file, QList<ParsedEntry> &d
QString src;
const int MAX_NEST_DEPTH = 256;
if (!getTextContent(src, file) || src.isEmpty())
if (!getTextContent(src, file) || src.isEmpty()) {
return false;
}
/*
// Save the index for debugging purposes
@ -387,39 +414,43 @@ bool EBook_CHM::parseFileAndFillArray(const QString &file, QList<ParsedEntry> &d
}
i = nextpos;
} else if (src[i] == '>')
} else if (src[i] == '>') {
break;
else if (!src[i].isLetterOrNumber() && src[i] != '/' && !word_end)
} else if (!src[i].isLetterOrNumber() && src[i] != '/' && !word_end) {
word_end = i;
}
}
QString tagword, tag = src.mid(pos, i - pos);
if (word_end)
if (word_end) {
tagword = src.mid(pos, word_end - pos).toLower();
else
} else {
tagword = tag.toLower();
}
// DEBUGPARSER(("tag: '%s', tagword: '%s'\n", qPrintable( tag ), qPrintable( tagword ) ));
// <OBJECT type="text/sitemap"> - a topic entry
if (tagword == QLatin1String("object") && tag.indexOf(QLatin1String("text/sitemap"), 0, Qt::CaseInsensitive) != -1)
if (tagword == QLatin1String("object") && tag.indexOf(QLatin1String("text/sitemap"), 0, Qt::CaseInsensitive) != -1) {
in_object = true;
else if (tagword == QLatin1String("/object") && in_object) {
} else if (tagword == QLatin1String("/object") && in_object) {
// a topic entry closed. Add a tree item
if (entry.name.isEmpty() && entry.urls.isEmpty()) {
qWarning("EBook_CHMImpl::ParseAndFillTopicsTree: <object> tag is parsed, but both name and url are empty.");
} else {
// If the name is empty, use the URL as name
if (entry.name.isEmpty())
if (entry.name.isEmpty()) {
entry.name = entry.urls[0].toString();
}
if (!root_indent_offset_set) {
root_indent_offset_set = true;
root_indent_offset = indent;
if (root_indent_offset > 1)
if (root_indent_offset > 1) {
qWarning("CHM has improper index; root indent offset is %d", root_indent_offset);
}
}
// Trim the entry name
@ -442,15 +473,17 @@ bool EBook_CHM::parseFileAndFillArray(const QString &file, QList<ParsedEntry> &d
const QString name_pattern = QStringLiteral("name="), value_pattern = QStringLiteral("value=");
QString pname, pvalue;
if ((offset = tag.indexOf(name_pattern, 0, Qt::CaseInsensitive)) == -1)
if ((offset = tag.indexOf(name_pattern, 0, Qt::CaseInsensitive)) == -1) {
qFatal("EBook_CHMImpl::ParseAndFillTopicsTree: bad <param> tag '%s': no name=\n", qPrintable(tag));
}
// offset+5 skips 'name='
offset = findStringInQuotes(tag, offset + name_pattern.length(), pname, true, false);
pname = pname.toLower();
if ((offset = tag.indexOf(value_pattern, offset, Qt::CaseInsensitive)) == -1)
if ((offset = tag.indexOf(value_pattern, offset, Qt::CaseInsensitive)) == -1) {
qFatal("EBook_CHMImpl::ParseAndFillTopicsTree: bad <param> tag '%s': no value=\n", qPrintable(tag));
}
// offset+6 skips 'value='
findStringInQuotes(tag, offset + value_pattern.length(), pvalue, false, true);
@ -459,8 +492,9 @@ bool EBook_CHM::parseFileAndFillArray(const QString &file, QList<ParsedEntry> &d
if (pname == QLatin1String("name") || pname == QLatin1String("keyword")) {
// Some help files contain duplicate names, where the second name is empty. Work it around by keeping the first one
if (!pvalue.isEmpty())
if (!pvalue.isEmpty()) {
entry.name = pvalue;
}
} else if (pname == QLatin1String("merge")) {
// MERGE implementation is experimental
QUrl mergeurl = pathToUrl(pvalue);
@ -474,14 +508,16 @@ bool EBook_CHM::parseFileAndFillArray(const QString &file, QList<ParsedEntry> &d
src = mergecontent + src.mid(i);
pos = 0;
stringlen = src.length();
} else
} else {
qWarning("MERGE is used in index but file %s was not found in CHM archive", qPrintable(pvalue));
}
} else if (pname == QLatin1String("local")) {
// Check for URL duplication
QUrl url = pathToUrl(pvalue);
if (!entry.urls.contains(url))
if (!entry.urls.contains(url)) {
entry.urls.push_back(url);
}
} else if (pname == QLatin1String("see also") && asIndex && entry.name != pvalue) {
entry.urls.push_back(QUrl(QStringLiteral("seealso")));
entry.seealso = pvalue;
@ -489,20 +525,23 @@ bool EBook_CHM::parseFileAndFillArray(const QString &file, QList<ParsedEntry> &d
bool bok;
int imgnum = pvalue.toInt(&bok);
if (bok && imgnum >= 0 && imgnum < EBookTocEntry::MAX_BUILTIN_ICONS)
if (bok && imgnum >= 0 && imgnum < EBookTocEntry::MAX_BUILTIN_ICONS) {
entry.iconid = (EBookTocEntry::Icon)imgnum;
}
}
} else if (tagword == QLatin1String("ul")) // increase indent level
{
// Fix for buggy help files
if (++indent >= MAX_NEST_DEPTH)
if (++indent >= MAX_NEST_DEPTH) {
qFatal("EBook_CHMImpl::ParseAndFillTopicsTree: max nest depth (%d) is reached, error in help file", MAX_NEST_DEPTH);
}
DEBUGPARSER(("<ul>: new intent is %d\n", indent - root_indent_offset));
} else if (tagword == QLatin1String("/ul")) // decrease indent level
{
if (--indent < root_indent_offset)
if (--indent < root_indent_offset) {
indent = root_indent_offset;
}
DEBUGPARSER(("</ul>: new intent is %d\n", indent - root_indent_offset));
}
@ -543,8 +582,9 @@ bool EBook_CHM::getInfoFromWindows()
long size = 0;
if (ResolveObject(QStringLiteral("/#WINDOWS"), &ui)) {
if (!RetrieveObject(&ui, buffer, 0, WIN_HEADER_LEN))
if (!RetrieveObject(&ui, buffer, 0, WIN_HEADER_LEN)) {
return false;
}
unsigned int entries = get_int32_le(reinterpret_cast<unsigned int *>(buffer));
unsigned int entry_size = get_int32_le(reinterpret_cast<unsigned int *>(buffer + 0x04));
@ -552,11 +592,13 @@ bool EBook_CHM::getInfoFromWindows()
QVector<unsigned char> uptr(entries * entry_size);
unsigned char *raw = (unsigned char *)uptr.data();
if (!RetrieveObject(&ui, raw, 8, entries * entry_size))
if (!RetrieveObject(&ui, raw, 8, entries * entry_size)) {
return false;
}
if (!ResolveObject(QStringLiteral("/#STRINGS"), &ui))
if (!ResolveObject(QStringLiteral("/#STRINGS"), &ui)) {
return false;
}
for (unsigned int i = 0; i < entries; ++i) {
unsigned int offset = i * entry_size;
@ -568,35 +610,40 @@ bool EBook_CHM::getInfoFromWindows()
factor = off_title / 4096;
if (size == 0)
if (size == 0) {
size = RetrieveObject(&ui, buffer, factor * 4096, BUF_SIZE);
}
if (size && off_title)
if (size && off_title) {
m_title = QByteArray((const char *)(buffer + off_title % 4096));
}
if (factor != off_home / 4096) {
factor = off_home / 4096;
size = RetrieveObject(&ui, buffer, factor * 4096, BUF_SIZE);
}
if (size && off_home)
if (size && off_home) {
m_home = QByteArray("/") + QByteArray((const char *)buffer + off_home % 4096);
}
if (factor != off_hhc / 4096) {
factor = off_hhc / 4096;
size = RetrieveObject(&ui, buffer, factor * 4096, BUF_SIZE);
}
if (size && off_hhc)
if (size && off_hhc) {
m_topicsFile = QByteArray("/") + QByteArray((const char *)buffer + off_hhc % 4096);
}
if (factor != off_hhk / 4096) {
factor = off_hhk / 4096;
size = RetrieveObject(&ui, buffer, factor * 4096, BUF_SIZE);
}
if (size && off_hhk)
if (size && off_hhk) {
m_indexFile = QByteArray("/") + QByteArray((const char *)buffer + off_hhk % 4096);
}
}
}
return true;
@ -614,12 +661,14 @@ bool EBook_CHM::getInfoFromSystem()
// Run the first loop to detect the encoding. We need this, because title could be
// already encoded in user encoding. Same for file names
if (!ResolveObject(QStringLiteral("/#SYSTEM"), &ui))
if (!ResolveObject(QStringLiteral("/#SYSTEM"), &ui)) {
return false;
}
// Can we pull BUFF_SIZE bytes of the #SYSTEM file?
if ((size = RetrieveObject(&ui, buffer, 4, BUF_SIZE)) == 0)
if ((size = RetrieveObject(&ui, buffer, 4, BUF_SIZE)) == 0) {
return false;
}
buffer[size - 1] = 0;
@ -633,8 +682,9 @@ bool EBook_CHM::getInfoFromSystem()
index += 2;
cursor = buffer + index;
if (m_topicsFile.isEmpty())
if (m_topicsFile.isEmpty()) {
m_topicsFile = QByteArray("/") + QByteArray((const char *)buffer + index + 2);
}
break;
@ -642,16 +692,18 @@ bool EBook_CHM::getInfoFromSystem()
index += 2;
cursor = buffer + index;
if (m_indexFile.isEmpty())
if (m_indexFile.isEmpty()) {
m_indexFile = QByteArray("/") + QByteArray((const char *)buffer + index + 2);
}
break;
case 2:
index += 2;
cursor = buffer + index;
if (m_home.isEmpty() || m_home == "/")
if (m_home.isEmpty() || m_home == "/") {
m_home = QByteArray("/") + QByteArray((const char *)buffer + index + 2);
}
break;
case 3:
@ -679,13 +731,15 @@ bool EBook_CHM::getInfoFromSystem()
QString tmp = topicAttempt + ".hhc";
if (ResolveObject(tmp, &ui))
if (ResolveObject(tmp, &ui)) {
m_topicsFile = qPrintable(tmp);
}
tmp = topicAttempt + ".hhk";
if (ResolveObject(tmp, &ui))
if (ResolveObject(tmp, &ui)) {
m_indexFile = qPrintable(tmp);
}
}
break;
@ -712,8 +766,9 @@ QString EBook_CHM::getTopicByUrl(const QUrl &url)
{
QMap<QUrl, QString>::const_iterator it = m_url2topics.constFind(url);
if (it == m_url2topics.constEnd())
if (it == m_url2topics.constEnd()) {
return QString();
}
return it.value();
}
@ -802,15 +857,17 @@ bool EBook_CHM::changeFileEncoding(const QString &qtencoding)
void EBook_CHM::fillTopicsUrlMap()
{
if (!m_lookupTablesValid)
if (!m_lookupTablesValid) {
return;
}
// Read those tables
QVector<unsigned char> topics(m_chmTOPICS.length), urltbl(m_chmURLTBL.length), urlstr(m_chmURLSTR.length), strings(m_chmSTRINGS.length);
if (!RetrieveObject(&m_chmTOPICS, (unsigned char *)topics.data(), 0, m_chmTOPICS.length) || !RetrieveObject(&m_chmURLTBL, (unsigned char *)urltbl.data(), 0, m_chmURLTBL.length) ||
!RetrieveObject(&m_chmURLSTR, (unsigned char *)urlstr.data(), 0, m_chmURLSTR.length) || !RetrieveObject(&m_chmSTRINGS, (unsigned char *)strings.data(), 0, m_chmSTRINGS.length))
!RetrieveObject(&m_chmURLSTR, (unsigned char *)urlstr.data(), 0, m_chmURLSTR.length) || !RetrieveObject(&m_chmSTRINGS, (unsigned char *)strings.data(), 0, m_chmSTRINGS.length)) {
return;
}
for (LONGUINT64 i = 0; i < m_chmTOPICS.length; i += TOPICS_ENTRY_LEN) {
unsigned int off_title = get_int32_le(reinterpret_cast<unsigned int *>(topics.data() + i + 4));
@ -819,24 +876,27 @@ void EBook_CHM::fillTopicsUrlMap()
QUrl url = pathToUrl((const char *)urlstr.data() + off_url);
if (off_title < (unsigned int)strings.size())
if (off_title < (unsigned int)strings.size()) {
m_url2topics[url] = encodeWithCurrentCodec((const char *)strings.data() + off_title);
else
} else {
m_url2topics[url] = QStringLiteral("Untitled");
}
}
}
bool EBook_CHM::parseBinaryTOC(QList<EBookTocEntry> &toc) const
{
if (!m_lookupTablesValid)
if (!m_lookupTablesValid) {
return false;
}
QByteArray tocidx, topics, urltbl, urlstr, strings;
// Read the index tables
if (!getBinaryContent(tocidx, QStringLiteral("/#TOCIDX")) || !getBinaryContent(topics, QStringLiteral("/#TOPICS")) || !getBinaryContent(urltbl, QStringLiteral("/#URLTBL")) || !getBinaryContent(urlstr, QStringLiteral("/#URLSTR")) ||
!getBinaryContent(strings, QStringLiteral("/#STRINGS")))
!getBinaryContent(strings, QStringLiteral("/#STRINGS"))) {
return false;
}
// Shamelessly stolen from xchm
if (!RecurseLoadBTOC(tocidx, topics, urltbl, urlstr, strings, UINT32ARRAY(tocidx.data()), toc, 0)) {
@ -855,8 +915,9 @@ bool EBook_CHM::RecurseLoadBTOC(const QByteArray &tocidx, const QByteArray &topi
{
while (offset) {
// If this is end of TOCIDX, return.
if (tocidx.size() < offset + 20)
if (tocidx.size() < offset + 20) {
return true;
}
unsigned int flags = UINT32ARRAY(tocidx.data() + offset + 4);
int index = UINT32ARRAY(tocidx.data() + offset + 8);
@ -884,10 +945,11 @@ bool EBook_CHM::RecurseLoadBTOC(const QByteArray &tocidx, const QByteArray &topi
return false;
}
if (tocoffset < 0)
if (tocoffset < 0) {
name.clear();
else
} else {
name = encodeWithCurrentCodec(strings.data() + tocoffset);
}
// #URLTBL index
tocoffset = (int)UINT32ARRAY(topics.data() + (index * 16) + 8);
@ -911,8 +973,9 @@ bool EBook_CHM::RecurseLoadBTOC(const QByteArray &tocidx, const QByteArray &topi
entry.name = name.trimmed();
if (!entry.name.isEmpty()) {
if (!value.isEmpty())
if (!value.isEmpty()) {
entry.url = pathToUrl(value);
}
entry.iconid = EBookTocEntry::IMAGE_AUTO;
entry.indent = level;
@ -930,8 +993,9 @@ bool EBook_CHM::RecurseLoadBTOC(const QByteArray &tocidx, const QByteArray &topi
unsigned int childoffset = UINT32ARRAY(tocidx.data() + offset + 20);
if (childoffset) {
if (!RecurseLoadBTOC(tocidx, topics, urltbl, urlstr, strings, childoffset, entries, level + 1))
if (!RecurseLoadBTOC(tocidx, topics, urltbl, urlstr, strings, childoffset, entries, level + 1)) {
return false;
}
}
}
@ -943,16 +1007,18 @@ bool EBook_CHM::RecurseLoadBTOC(const QByteArray &tocidx, const QByteArray &topi
bool EBook_CHM::hasOption(const QString &name) const
{
if (!m_envOptions.isEmpty() && m_envOptions.contains(name))
if (!m_envOptions.isEmpty() && m_envOptions.contains(name)) {
return true;
}
return false;
}
QUrl EBook_CHM::pathToUrl(const QString &link) const
{
if (link.startsWith(QLatin1String("http://")) || link.startsWith(QLatin1String("https://")))
if (link.startsWith(QLatin1String("http://")) || link.startsWith(QLatin1String("https://"))) {
return QUrl(link);
}
QUrl url;
url.setScheme(URL_SCHEME_CHM);
@ -965,11 +1031,13 @@ QUrl EBook_CHM::pathToUrl(const QString &link) const
if (off != -1) {
path = link.left(off);
url.setFragment(link.mid(off + 1));
} else
} else {
path = link;
}
if (!path.startsWith('/'))
if (!path.startsWith('/')) {
path.prepend('/');
}
url.setPath(QUrl::fromPercentEncoding(path.toUtf8()));
return url;
@ -978,8 +1046,9 @@ QUrl EBook_CHM::pathToUrl(const QString &link) const
QString EBook_CHM::urlToPath(const QUrl &link) const
{
if (link.scheme() == URL_SCHEME_CHM) {
if (link.path() == QLatin1String("/") || link.path().isEmpty())
if (link.path() == QLatin1String("/") || link.path().isEmpty()) {
return m_home;
}
return link.path();
}

View File

@ -121,9 +121,11 @@ static const EbookChmTextEncodingEntry text_encoding_table[] = {{"CP1256", lcid_
QString Ebook_CHM_Encoding::guessByLCID(unsigned short lcid)
{
for (const EbookChmTextEncodingEntry *t = text_encoding_table; t->qtcodec; ++t) {
for (const short *lcids = t->lcids; *lcids; lcids++)
if (*lcids == lcid)
for (const short *lcids = t->lcids; *lcids; lcids++) {
if (*lcids == lcid) {
return t->qtcodec;
}
}
}
return QStringLiteral("UTF-8");

View File

@ -64,8 +64,9 @@ bool EBook_EPUB::load(const QString &archiveName)
}
// Parse the book descriptor file
if (!parseBookinfo())
if (!parseBookinfo()) {
return false;
}
return true;
}
@ -136,8 +137,9 @@ bool EBook_EPUB::getIndex(QList<EBookIndexEntry> &) const
QString EBook_EPUB::getTopicByUrl(const QUrl &url)
{
if (m_urlTitleMap.contains(url))
if (m_urlTitleMap.contains(url)) {
return m_urlTitleMap[url];
}
return QLatin1String("");
}
@ -183,38 +185,44 @@ bool EBook_EPUB::parseBookinfo()
// Parse the container.xml to find the content descriptor
HelperXmlHandler_EpubContainer container_parser;
if (!parseXML(QStringLiteral("META-INF/container.xml"), &container_parser) || container_parser.contentPath.isEmpty())
if (!parseXML(QStringLiteral("META-INF/container.xml"), &container_parser) || container_parser.contentPath.isEmpty()) {
return false;
}
// Parse the content.opf
HelperXmlHandler_EpubContent content_parser;
if (!parseXML(container_parser.contentPath, &content_parser))
if (!parseXML(container_parser.contentPath, &content_parser)) {
return false;
}
// At least title and the TOC must be present
if (!content_parser.metadata.contains(QStringLiteral("title")) || content_parser.tocname.isEmpty())
if (!content_parser.metadata.contains(QStringLiteral("title")) || content_parser.tocname.isEmpty()) {
return false;
}
// All the files, including TOC, are relative to the container_parser.contentPath
m_documentRoot.clear();
int sep = container_parser.contentPath.lastIndexOf('/');
if (sep != -1)
if (sep != -1) {
m_documentRoot = container_parser.contentPath.left(sep + 1); // Keep the trailing slash
}
// Parse the TOC
HelperXmlHandler_EpubTOC toc_parser(this);
if (!parseXML(content_parser.tocname, &toc_parser))
if (!parseXML(content_parser.tocname, &toc_parser)) {
return false;
}
// Get the data
m_title = content_parser.metadata[QStringLiteral("title")];
// Move the manifest entries into the list
for (const QString &f : qAsConst(content_parser.manifest))
for (const QString &f : qAsConst(content_parser.manifest)) {
m_ebookManifest.push_back(pathToUrl(f));
}
// Copy the manifest information and fill up the other maps if we have it
if (!toc_parser.entries.isEmpty()) {
@ -228,8 +236,9 @@ bool EBook_EPUB::parseBookinfo()
for (QString url : qAsConst(content_parser.spine)) {
EBookTocEntry e;
if (content_parser.manifest.contains(url))
if (content_parser.manifest.contains(url)) {
url = content_parser.manifest[url];
}
e.name = url;
e.url = pathToUrl(url);
@ -243,8 +252,9 @@ bool EBook_EPUB::parseBookinfo()
}
// EPub with an empty TOC is not valid
if (m_tocEntries.isEmpty())
if (m_tocEntries.isEmpty()) {
return false;
}
return true;
}
@ -262,11 +272,13 @@ QUrl EBook_EPUB::pathToUrl(const QString &link) const
if (off != -1) {
path = link.left(off);
url.setFragment(link.mid(off + 1));
} else
} else {
path = link;
}
if (!path.startsWith('/'))
if (!path.startsWith('/')) {
path.prepend('/');
}
url.setPath(QUrl::fromPercentEncoding(path.toUtf8()));
@ -275,8 +287,9 @@ QUrl EBook_EPUB::pathToUrl(const QString &link) const
QString EBook_EPUB::urlToPath(const QUrl &link) const
{
if (link.scheme() == URL_SCHEME_EPUB)
if (link.scheme() == URL_SCHEME_EPUB) {
return link.path();
}
return QLatin1String("");
}
@ -285,8 +298,9 @@ bool EBook_EPUB::getFileAsString(QString &str, const QString &path) const
{
QByteArray data;
if (!getFileAsBinary(data, path))
if (!getFileAsBinary(data, path)) {
return false;
}
// I have never seen yet an UTF16 epub
if (data.startsWith("<?xml")) {
@ -309,10 +323,11 @@ bool EBook_EPUB::getFileAsBinary(QByteArray &data, const QString &path) const
struct zip_stat fileinfo;
QString completeUrl;
if (!path.isEmpty() && path[0] == '/')
if (!path.isEmpty() && path[0] == '/') {
completeUrl = m_documentRoot + path.mid(1);
else
} else {
completeUrl = m_documentRoot + path;
}
// qDebug("URL requested: %s (%s)", qPrintable(path), qPrintable(completeUrl));
@ -323,14 +338,16 @@ bool EBook_EPUB::getFileAsBinary(QByteArray &data, const QString &path) const
}
// Make sure the size field is valid
if ((fileinfo.valid & ZIP_STAT_SIZE) == 0 || (fileinfo.valid & ZIP_STAT_INDEX) == 0)
if ((fileinfo.valid & ZIP_STAT_SIZE) == 0 || (fileinfo.valid & ZIP_STAT_INDEX) == 0) {
return false;
}
// Open the file
struct zip_file *file = zip_fopen_index(m_zipFile, fileinfo.index, 0);
if (!file)
if (!file) {
return false;
}
// Allocate the memory and read the file
data.resize(fileinfo.size);

View File

@ -42,8 +42,9 @@ public:
if (!term.isEmpty()) {
terms.push_back(term);
if (m_inPhrase)
if (m_inPhrase) {
phrase_terms.push_back(term);
}
}
}
@ -88,11 +89,13 @@ bool EBookSearch::generateIndex(EBook *ebookFile, QDataStream &stream)
processEvents();
// Enumerate the documents
if (!ebookFile->enumerateFiles(alldocuments))
if (!ebookFile->enumerateFiles(alldocuments)) {
return false;
}
if (m_Index)
if (m_Index) {
delete m_Index;
}
m_Index = new QtAs::Index();
connect(m_Index, &QtAs::Index::indexingProgress, this, &EBookSearch::updateProgress);
@ -101,8 +104,9 @@ bool EBookSearch::generateIndex(EBook *ebookFile, QDataStream &stream)
for (const QUrl &allDocumentsI : qAsConst(alldocuments)) {
const QString docpath = allDocumentsI.path();
if (docpath.endsWith(QLatin1String(".html"), Qt::CaseInsensitive) || docpath.endsWith(QLatin1String(".htm"), Qt::CaseInsensitive) || docpath.endsWith(QLatin1String(".xhtml"), Qt::CaseInsensitive))
if (docpath.endsWith(QLatin1String(".html"), Qt::CaseInsensitive) || docpath.endsWith(QLatin1String(".htm"), Qt::CaseInsensitive) || docpath.endsWith(QLatin1String(".xhtml"), Qt::CaseInsensitive)) {
documents.push_back(allDocumentsI);
}
}
if (!m_Index->makeIndex(documents, ebookFile)) {
@ -130,15 +134,17 @@ void EBookSearch::updateProgress(int value, const QString &stepName)
void EBookSearch::processEvents()
{
// Do it up to ten times; some events generate other events
for (int i = 0; i < 10; i++)
for (int i = 0; i < 10; i++) {
qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
}
}
bool EBookSearch::searchQuery(const QString &query, QList<QUrl> *results, EBook *ebookFile, unsigned int limit)
{
// We should have index
if (!m_Index)
if (!m_Index) {
return false;
}
// Characters which split the words. We need to make them separate tokens
QString splitChars = m_Index->getCharsSplit();
@ -157,10 +163,11 @@ bool EBookSearch::searchQuery(const QString &query, QList<QUrl> *results, EBook
if (ch == '"') {
keeper.addTerm(term);
if (keeper.isInPhrase())
if (keeper.isInPhrase()) {
keeper.endPhrase();
else
} else {
keeper.beginPhrase();
}
continue;
}
@ -187,13 +194,15 @@ bool EBookSearch::searchQuery(const QString &query, QList<QUrl> *results, EBook
keeper.addTerm(term);
if (keeper.isInPhrase())
if (keeper.isInPhrase()) {
return false;
}
QList<QUrl> foundDocs = m_Index->query(keeper.terms, keeper.phrases, keeper.phrasewords, ebookFile);
for (QList<QUrl>::iterator it = foundDocs.begin(); it != foundDocs.end() && limit > 0; ++it, limit--)
for (QList<QUrl>::iterator it = foundDocs.begin(); it != foundDocs.end() && limit > 0; ++it, limit--) {
results->push_back(*it);
}
return true;
}

View File

@ -72,32 +72,37 @@ void Index::setLastWinClosed()
bool Index::makeIndex(const QList<QUrl> &docs, EBook *chmFile)
{
if (docs.isEmpty())
if (docs.isEmpty()) {
return false;
}
docList = docs;
if (chmFile->hasFeature(EBook::FEATURE_ENCODING))
if (chmFile->hasFeature(EBook::FEATURE_ENCODING)) {
entityDecoder.changeEncoding(QTextCodec::codecForName(chmFile->currentEncoding().toUtf8()));
}
QList<QUrl>::ConstIterator it = docList.constBegin();
int steps = docList.count() / 100;
if (!steps)
if (!steps) {
steps++;
}
int prog = 0;
for (int i = 0; it != docList.constEnd(); ++it, ++i) {
if (lastWindowClosed)
if (lastWindowClosed) {
return false;
}
QUrl filename = *it;
QStringList terms;
if (parseDocumentToStringlist(chmFile, filename, terms)) {
for (QStringList::ConstIterator tit = terms.constBegin(); tit != terms.constEnd(); ++tit)
for (QStringList::ConstIterator tit = terms.constBegin(); tit != terms.constEnd(); ++tit) {
insertInDict(*tit, i);
}
}
if (i % steps == 0) {
@ -114,14 +119,16 @@ bool Index::makeIndex(const QList<QUrl> &docs, EBook *chmFile)
void Index::insertInDict(const QString &str, int docNum)
{
Entry *e = nullptr;
if (!dict.isEmpty())
if (!dict.isEmpty()) {
e = dict[str];
}
if (e) {
if (e->documents.last().docNumber != docNum)
if (e->documents.last().docNumber != docNum) {
e->documents.append(Document(docNum, 1));
else
} else {
e->documents.last().frequency++;
}
} else {
dict.insert(str, new Entry(docNum));
}
@ -155,8 +162,9 @@ bool Index::parseDocumentToStringlist(EBook *chmFile, const QUrl &filename, QStr
for (int j = 0; j < text.length(); j++) {
QChar ch = text[j];
if ((j % 20000) == 0)
if ((j % 20000) == 0) {
qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
}
if (state == STATE_IN_HTML_TAG) {
// We are inside HTML tag.
@ -164,15 +172,17 @@ bool Index::parseDocumentToStringlist(EBook *chmFile, const QUrl &filename, QStr
if (ch == '"' || ch == '\'') {
state = STATE_IN_QUOTES;
QuoteChar = ch;
} else if (ch == '>')
} else if (ch == '>') {
state = STATE_OUTSIDE_TAGS;
}
continue;
} else if (state == STATE_IN_QUOTES) {
// We are inside quoted text inside HTML tag.
// Ignore everything until we see the quote character again
if (ch == QuoteChar)
if (ch == QuoteChar) {
state = STATE_IN_HTML_TAG;
}
continue;
} else if (state == STATE_IN_HTML_ENTITY) {
@ -192,8 +202,9 @@ bool Index::parseDocumentToStringlist(EBook *chmFile, const QUrl &filename, QStr
if (parseentity.isEmpty()) {
// straight '&' symbol. Add and continue.
parsedbuf += QLatin1String("&");
} else
} else {
qWarning("Index::parseDocument: incorrectly terminated HTML entity '&%s%c', ignoring", qPrintable(parseentity), ch.toLatin1());
}
j--; // parse this character again, but in different state
continue;
@ -211,8 +222,9 @@ bool Index::parseDocumentToStringlist(EBook *chmFile, const QUrl &filename, QStr
parsedbuf += entity;
continue;
} else
} else {
ch = ' '; // We got a space, so treat it like it, and not add it to parsebuf
}
}
//
@ -233,8 +245,9 @@ bool Index::parseDocumentToStringlist(EBook *chmFile, const QUrl &filename, QStr
}
// Replace quote by ' - quotes are used in search window to set the phrase
if (ch == '"')
if (ch == '"') {
ch = '\'';
}
// Ok, we have a valid character outside HTML tags, and probably some in buffer already.
// If it is char or letter, add it and continue
@ -245,8 +258,9 @@ bool Index::parseDocumentToStringlist(EBook *chmFile, const QUrl &filename, QStr
// If it is a split char, add the word to the dictionary, and then add the char itself.
if (m_charssplit.indexOf(ch) != -1) {
if (!parsedbuf.isEmpty())
if (!parsedbuf.isEmpty()) {
tokenlist.push_back(parsedbuf.toLower());
}
tokenlist.push_back(ch.toLower());
parsedbuf = QString();
@ -262,8 +276,9 @@ bool Index::parseDocumentToStringlist(EBook *chmFile, const QUrl &filename, QStr
}
// Add the last word if still here - for broken htmls.
if (!parsedbuf.isEmpty())
if (!parsedbuf.isEmpty()) {
tokenlist.push_back(parsedbuf.toLower());
}
return true;
}
@ -295,8 +310,9 @@ bool Index::readDict(QDataStream &stream)
stream >> version;
if (version < 2)
if (version < 2) {
return false;
}
stream >> m_charssplit;
stream >> m_charsword;
@ -333,8 +349,9 @@ QList<QUrl> Index::query(const QStringList &terms, const QStringList &termSeq, c
}
}
if (termList.isEmpty())
if (termList.isEmpty()) {
return QList<QUrl>();
}
std::sort(termList.begin(), termList.end());
@ -350,26 +367,29 @@ QList<QUrl> Index::query(const QStringList &terms, const QStringList &termSeq, c
break;
}
}
if (!found)
if (!found) {
minDoc_it = minDocs.erase(minDoc_it);
else
} else {
++minDoc_it;
}
}
}
QList<QUrl> results;
std::sort(minDocs.begin(), minDocs.end());
if (termSeq.isEmpty()) {
for (const Document &doc : qAsConst(minDocs))
for (const Document &doc : qAsConst(minDocs)) {
results << docList.at((int)doc.docNumber);
}
return results;
}
QUrl fileName;
for (const Document &doc : qAsConst(minDocs)) {
fileName = docList[(int)doc.docNumber];
if (searchForPhrases(termSeq, seqWords, fileName, chmFile))
if (searchForPhrases(termSeq, seqWords, fileName, chmFile)) {
results << fileName;
}
}
return results;
@ -379,22 +399,25 @@ bool Index::searchForPhrases(const QStringList &phrases, const QStringList &word
{
QStringList parsed_document;
if (!parseDocumentToStringlist(chmFile, filename, parsed_document))
if (!parseDocumentToStringlist(chmFile, filename, parsed_document)) {
return false;
}
miniDict.clear();
// Initialize the dictionary with the words in phrase(s)
for (const QString &word : words)
for (const QString &word : words) {
miniDict.insert(word, new PosEntry(0));
}
// Fill the dictionary with the words from the document
unsigned int word_offset = 3;
for (QStringList::ConstIterator it = parsed_document.constBegin(); it != parsed_document.constEnd(); it++, word_offset++) {
PosEntry *entry = miniDict[*it];
if (entry)
if (entry) {
entry->positions.append(word_offset);
}
}
// Dump it
@ -425,8 +448,9 @@ bool Index::searchForPhrases(const QStringList &phrases, const QStringList &word
if (next_word_it.indexOf(*dict_it + 1) != -1) {
(*dict_it)++;
++dict_it;
} else
} else {
dict_it = first_word_positions.erase(dict_it);
}
}
}
}

View File

@ -12,8 +12,9 @@ bool HelperXmlHandler_EpubContainer::startElement(const QString &, const QString
if (qName == QLatin1String("rootfile")) {
int idx = atts.index(QLatin1String("full-path"));
if (idx == -1)
if (idx == -1) {
return false;
}
contentPath = atts.value(idx);
}

View File

@ -15,34 +15,37 @@ HelperXmlHandler_EpubContent::HelperXmlHandler_EpubContent()
bool HelperXmlHandler_EpubContent::startElement(const QString &, const QString &localName, const QString &, const QXmlAttributes &atts)
{
// <metadata> tag contains the medatada which goes into m_metadata
if (localName == QLatin1String("metadata"))
if (localName == QLatin1String("metadata")) {
m_state = STATE_IN_METADATA;
else if (localName == QLatin1String("manifest"))
} else if (localName == QLatin1String("manifest")) {
m_state = STATE_IN_MANIFEST;
else if (localName == QLatin1String("spine"))
} else if (localName == QLatin1String("spine")) {
m_state = STATE_IN_SPINE;
// Now handle the states
else if (m_state == STATE_IN_METADATA) // we don't need to store the first 'metadata' here
} else if (m_state == STATE_IN_METADATA) { // we don't need to store the first 'metadata' here
// Now handle the states
m_tagname = localName;
else if (m_state == STATE_IN_MANIFEST && localName == QLatin1String("item")) {
} else if (m_state == STATE_IN_MANIFEST && localName == QLatin1String("item")) {
int idx_id = atts.index(QLatin1String("id"));
int idx_href = atts.index(QLatin1String("href"));
int idx_mtype = atts.index(QLatin1String("media-type"));
if (idx_id == -1 || idx_href == -1 || idx_mtype == -1)
if (idx_id == -1 || idx_href == -1 || idx_mtype == -1) {
return false;
}
manifest[atts.value(idx_id)] = atts.value(idx_href);
if (atts.value(idx_mtype) == QLatin1String("application/x-dtbncx+xml"))
if (atts.value(idx_mtype) == QLatin1String("application/x-dtbncx+xml")) {
tocname = atts.value(idx_href);
}
// qDebug() << "MANIFEST: " << atts.value( idx_id ) << "->" << atts.value( idx_href );
} else if (m_state == STATE_IN_SPINE && localName == QLatin1String("itemref")) {
int idx = atts.index(QLatin1String("idref"));
if (idx == -1)
if (idx == -1) {
return false;
}
spine.push_back(atts.value(idx));
// qDebug() << "SPINE: " << atts.value( idx );
@ -58,8 +61,9 @@ bool HelperXmlHandler_EpubContent::characters(const QString &ch)
if (metadata.contains(m_tagname)) {
metadata[m_tagname].append("|");
metadata[m_tagname].append(ch.trimmed());
} else
} else {
metadata[m_tagname] = ch.trimmed();
}
// qDebug() << "METATAG: " << m_tagname << " " << metadata[ m_tagname ];
}
@ -69,8 +73,9 @@ bool HelperXmlHandler_EpubContent::characters(const QString &ch)
bool HelperXmlHandler_EpubContent::endElement(const QString &, const QString &, const QString &qName)
{
if (qName == QLatin1String("manifest") || qName == QLatin1String("metadata") || qName == QLatin1String("spine"))
if (qName == QLatin1String("manifest") || qName == QLatin1String("metadata") || qName == QLatin1String("spine")) {
m_state = STATE_NONE;
}
return true;
}

View File

@ -28,20 +28,24 @@ bool HelperXmlHandler_EpubTOC::startElement(const QString &, const QString &loca
return true;
}
if (!m_inNavMap)
if (!m_inNavMap) {
return true;
}
if (localName == QLatin1String("navPoint"))
if (localName == QLatin1String("navPoint")) {
m_indent++;
}
if (localName == QLatin1String("text"))
if (localName == QLatin1String("text")) {
m_inText = true;
}
if (localName == QLatin1String("content")) {
int idx = atts.index(QLatin1String("src"));
if (idx == -1)
if (idx == -1) {
return false;
}
m_lastId = atts.value(idx);
checkNewTocEntry();
@ -53,8 +57,9 @@ bool HelperXmlHandler_EpubTOC::startElement(const QString &, const QString &loca
bool HelperXmlHandler_EpubTOC::characters(const QString &ch)
{
// qDebug() << "characters" << " " << ch;
if (m_inText)
if (m_inText) {
m_lastTitle = ch;
}
checkNewTocEntry();
return true;
@ -69,11 +74,13 @@ bool HelperXmlHandler_EpubTOC::endElement(const QString &, const QString &localN
return true;
}
if (localName == QLatin1String("navPoint"))
if (localName == QLatin1String("navPoint")) {
m_indent--;
}
if (localName == QLatin1String("text"))
if (localName == QLatin1String("text")) {
m_inText = false;
}
return true;
}

View File

@ -65,8 +65,9 @@ static inline QString makeURLabsoluteIfNeeded(const QString &url)
newurl = QDir::cleanPath(url);
// Normalize url, so it becomes absolute
if (newurl[0] != QLatin1Char('/'))
if (newurl[0] != QLatin1Char('/')) {
newurl = QLatin1Char('/') + newurl;
}
}
// qDebug ("makeURLabsolute (%s) -> (%s)", url.ascii(), newurl.ascii());
@ -84,8 +85,9 @@ static inline bool handleFileType(const QString &link, QString &generated)
{
QString intext = getInternalUriExtension();
if (!link.endsWith(intext))
if (!link.endsWith(intext)) {
return false;
}
QString filelink = link.left(link.length() - intext.length());
generated = QStringLiteral("<html><body><img src=\"") + filelink + QStringLiteral("\"></body></html>");

View File

@ -56,8 +56,9 @@ QStringList Directory::list() const
QIODevice *Directory::createDevice(const QString &path) const
{
std::unique_ptr<QFile> file(new QFile(path));
if (!file->open(QIODevice::ReadOnly))
if (!file->open(QIODevice::ReadOnly)) {
return nullptr;
}
return file.release();
}

View File

@ -138,8 +138,9 @@ void Document::close()
{
mLastErrorString.clear();
if (!(mArchive || mUnrar || mDirectory))
if (!(mArchive || mUnrar || mDirectory)) {
return;
}
delete mArchive;
mArchive = nullptr;
@ -206,8 +207,9 @@ void Document::pages(QVector<Okular::Page *> *pagesVector)
}
if (!pageSize.isValid()) {
const QImage i = reader.read();
if (!i.isNull())
if (!i.isNull()) {
pageSize = i.size();
}
}
if (pageSize.isValid()) {
pagesVector->replace(count, new Okular::Page(count, pageSize.width(), pageSize.height(), Okular::Rotation0));

View File

@ -36,8 +36,9 @@ bool ComicBookGenerator::loadDocument(const QString &fileName, QVector<Okular::P
{
if (!mDocument.open(fileName)) {
const QString errString = mDocument.lastErrorString();
if (!errString.isEmpty())
if (!errString.isEmpty()) {
emit error(errString, -1);
}
return false;
}
@ -71,12 +72,13 @@ Okular::Document::PrintError ComicBookGenerator::print(QPrinter &printer)
for (int i = 0; i < pageList.count(); ++i) {
QImage image = mDocument.pageImage(pageList[i] - 1);
if ((image.width() > printer.width()) || (image.height() > printer.height()))
if ((image.width() > printer.width()) || (image.height() > printer.height())) {
image = image.scaled(printer.width(), printer.height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
}
if (i != 0)
if (i != 0) {
printer.newPage();
}
p.drawImage(0, 0, image);
}

View File

@ -19,26 +19,29 @@ static int compare_right(const QString &leftStr, int left, const QString &rightS
* remember it in BIAS.
*/
for (;; left++, right++) {
if (left >= leftStr.length() && right < rightStr.length())
if (left >= leftStr.length() && right < rightStr.length()) {
return -1;
else if (right >= rightStr.length() && left < leftStr.length())
} else if (right >= rightStr.length() && left < leftStr.length()) {
return +1;
else if (right >= rightStr.length() && left >= leftStr.length())
} else if (right >= rightStr.length() && left >= leftStr.length()) {
return bias;
else if (!leftStr[left].isDigit() && !rightStr[right].isDigit())
} else if (!leftStr[left].isDigit() && !rightStr[right].isDigit()) {
return bias;
else if (!leftStr[left].isDigit())
} else if (!leftStr[left].isDigit()) {
return -1;
else if (!rightStr[right].isDigit())
} else if (!rightStr[right].isDigit()) {
return +1;
else if (leftStr[left] < rightStr[right]) {
if (!bias)
} else if (leftStr[left] < rightStr[right]) {
if (!bias) {
bias = -1;
}
} else if (leftStr[left] > rightStr[right]) {
if (!bias)
if (!bias) {
bias = +1;
} else if (leftStr[left].isNull() && rightStr[right].isNull())
}
} else if (leftStr[left].isNull() && rightStr[right].isNull()) {
return bias;
}
}
return 0;
@ -51,22 +54,23 @@ static int compare_left(const QString &leftStr, int left, const QString &rightSt
* different value wins.
*/
for (;; left++, right++) {
if (left >= leftStr.length() && right < rightStr.length())
if (left >= leftStr.length() && right < rightStr.length()) {
return -1;
else if (right >= rightStr.length() && left < leftStr.length())
} else if (right >= rightStr.length() && left < leftStr.length()) {
return +1;
else if (right >= rightStr.length() && left >= leftStr.length())
} else if (right >= rightStr.length() && left >= leftStr.length()) {
return 0;
else if (!leftStr[left].isDigit() && !rightStr[right].isDigit())
} else if (!leftStr[left].isDigit() && !rightStr[right].isDigit()) {
return 0;
else if (!leftStr[left].isDigit())
} else if (!leftStr[left].isDigit()) {
return -1;
else if (!rightStr[right].isDigit())
} else if (!rightStr[right].isDigit()) {
return +1;
else if (leftStr[left] < rightStr[right])
} else if (leftStr[left] < rightStr[right]) {
return -1;
else if (leftStr[left] > rightStr[right])
} else if (leftStr[left] > rightStr[right]) {
return +1;
}
}
return 0;
@ -74,8 +78,9 @@ static int compare_left(const QString &leftStr, int left, const QString &rightSt
static int natural_order_compare(const QString &leftStr, const QString &rightStr, bool fold_case)
{
if (leftStr.isEmpty() && rightStr.isEmpty())
if (leftStr.isEmpty() && rightStr.isEmpty()) {
return 0;
}
int ai, bi;
QChar ca, cb;
@ -90,22 +95,26 @@ static int natural_order_compare(const QString &leftStr, const QString &rightStr
cb = rightStr[bi];
/* skip over leading spaces or zeros */
while (ca.isSpace() && ++ai < aSize)
while (ca.isSpace() && ++ai < aSize) {
ca = leftStr[ai];
}
while (cb.isSpace() && ++bi < bSize)
while (cb.isSpace() && ++bi < bSize) {
cb = rightStr[bi];
}
/* process run of digits */
if (ca.isDigit() && cb.isDigit()) {
fractional = (ca == QLatin1Char('0') || cb == QLatin1Char('0'));
if (fractional) {
if ((result = compare_left(leftStr, ai, rightStr, bi)) != 0)
if ((result = compare_left(leftStr, ai, rightStr, bi)) != 0) {
return result;
}
} else {
if ((result = compare_right(leftStr, ai, rightStr, bi)) != 0)
if ((result = compare_right(leftStr, ai, rightStr, bi)) != 0) {
return result;
}
}
}
@ -120,10 +129,11 @@ static int natural_order_compare(const QString &leftStr, const QString &rightStr
cb = cb.toUpper();
}
if (ca < cb)
if (ca < cb) {
return -1;
else if (ca > cb)
} else if (ca > cb) {
return +1;
}
++ai;
++bi;

View File

@ -48,14 +48,15 @@ static UnrarFlavour *detectUnrar(const QString &unrarPath, const QString &versio
const QRegularExpression regex(QStringLiteral("[\r\n]"));
const QStringList lines = QString::fromLocal8Bit(proc.readAllStandardOutput()).split(regex, QString::SkipEmptyParts);
if (!lines.isEmpty()) {
if (lines.first().startsWith(QLatin1String("UNRAR ")))
if (lines.first().startsWith(QLatin1String("UNRAR "))) {
kind = new NonFreeUnrarFlavour();
else if (lines.first().startsWith(QLatin1String("RAR ")))
} else if (lines.first().startsWith(QLatin1String("RAR "))) {
kind = new NonFreeUnrarFlavour();
else if (lines.first().startsWith(QLatin1String("unrar ")))
} else if (lines.first().startsWith(QLatin1String("unrar "))) {
kind = new FreeUnrarFlavour();
else if (lines.first().startsWith(QLatin1String("v")))
} else if (lines.first().startsWith(QLatin1String("v"))) {
kind = new UnarFlavour();
}
}
return kind;
}
@ -71,18 +72,23 @@ UnrarHelper::UnrarHelper()
path = QStandardPaths::findExecutable(QStringLiteral("unrar-nonfree"));
if (path.isEmpty())
if (path.isEmpty()) {
path = QStandardPaths::findExecutable(QStringLiteral("unrar"));
if (path.isEmpty())
}
if (path.isEmpty()) {
path = QStandardPaths::findExecutable(QStringLiteral("rar"));
if (path.isEmpty())
}
if (path.isEmpty()) {
path = QStandardPaths::findExecutable(QStringLiteral("unar"));
}
if (!path.isEmpty())
if (!path.isEmpty()) {
kind = detectUnrar(path, QStringLiteral("--version"));
}
if (!kind)
if (!kind) {
kind = detectUnrar(path, QStringLiteral("-v"));
}
if (!kind) {
// no luck, print that
@ -112,8 +118,9 @@ Unrar::~Unrar()
bool Unrar::open(const QString &fileName)
{
if (!isSuitableVersionAvailable())
if (!isSuitableVersionAvailable()) {
return false;
}
delete mTempDir;
mTempDir = new QTemporaryDir();
@ -137,8 +144,9 @@ QStringList Unrar::list()
mStdOutData.clear();
mStdErrData.clear();
if (!isSuitableVersionAvailable())
if (!isSuitableVersionAvailable()) {
return QStringList();
}
startSyncProcess(helper->kind->processListArgs(mFileName));
@ -167,24 +175,28 @@ QStringList Unrar::list()
QByteArray Unrar::contentOf(const QString &fileName) const
{
if (!isSuitableVersionAvailable())
if (!isSuitableVersionAvailable()) {
return QByteArray();
}
QFile file(mTempDir->path() + QLatin1Char('/') + fileName);
if (!file.open(QIODevice::ReadOnly))
if (!file.open(QIODevice::ReadOnly)) {
return QByteArray();
}
return file.readAll();
}
QIODevice *Unrar::createDevice(const QString &fileName) const
{
if (!isSuitableVersionAvailable())
if (!isSuitableVersionAvailable()) {
return nullptr;
}
std::unique_ptr<QFile> file(new QFile(mTempDir->path() + QLatin1Char('/') + fileName));
if (!file->open(QIODevice::ReadOnly))
if (!file->open(QIODevice::ReadOnly)) {
return nullptr;
}
return file.release();
}
@ -196,27 +208,31 @@ bool Unrar::isAvailable()
bool Unrar::isSuitableVersionAvailable()
{
if (!isAvailable())
if (!isAvailable()) {
return false;
}
if (dynamic_cast<NonFreeUnrarFlavour *>(helper->kind) || dynamic_cast<UnarFlavour *>(helper->kind))
if (dynamic_cast<NonFreeUnrarFlavour *>(helper->kind) || dynamic_cast<UnarFlavour *>(helper->kind)) {
return true;
else
} else {
return false;
}
}
void Unrar::readFromStdout()
{
if (!mProcess)
if (!mProcess) {
return;
}
mStdOutData += mProcess->readAllStandardOutput();
}
void Unrar::readFromStderr()
{
if (!mProcess)
if (!mProcess) {
return;
}
mStdErrData += mProcess->readAllStandardError();
if (!mStdErrData.isEmpty()) {
@ -283,8 +299,9 @@ int Unrar::startSyncProcess(const ProcessArgs &args)
void Unrar::writeToProcess(const QByteArray &data)
{
if (!mProcess || data.isNull())
if (!mProcess || data.isNull()) {
return;
}
#if !defined(WITH_KPTY)
mProcess->write(data);

View File

@ -66,8 +66,9 @@ DjVuGenerator::DjVuGenerator(QObject *parent, const QVariantList &args)
setFeature(TextExtraction);
setFeature(Threaded);
setFeature(PrintPostscript);
if (Okular::FilePrinter::ps2pdfAvailable())
if (Okular::FilePrinter::ps2pdfAvailable()) {
setFeature(PrintToFile);
}
m_djvu = new KDjVu();
m_djvu->setCacheEnabled(false);
@ -81,8 +82,9 @@ DjVuGenerator::~DjVuGenerator()
bool DjVuGenerator::loadDocument(const QString &fileName, QVector<Okular::Page *> &pagesVector)
{
QMutexLocker locker(userMutex());
if (!m_djvu->openFile(fileName))
if (!m_djvu->openFile(fileName)) {
return false;
}
locker.unlock();
@ -115,17 +117,21 @@ Okular::DocumentInfo DjVuGenerator::generateDocumentInfo(const QSet<Okular::Docu
{
Okular::DocumentInfo docInfo;
if (keys.contains(Okular::DocumentInfo::MimeType))
if (keys.contains(Okular::DocumentInfo::MimeType)) {
docInfo.set(Okular::DocumentInfo::MimeType, QStringLiteral("image/vnd.djvu"));
}
if (m_djvu) {
// compile internal structure reading properties from KDjVu
if (keys.contains(Okular::DocumentInfo::Author))
if (keys.contains(Okular::DocumentInfo::Author)) {
docInfo.set(Okular::DocumentInfo::Title, m_djvu->metaData(QStringLiteral("title")).toString());
if (keys.contains(Okular::DocumentInfo::Author))
}
if (keys.contains(Okular::DocumentInfo::Author)) {
docInfo.set(Okular::DocumentInfo::Author, m_djvu->metaData(QStringLiteral("author")).toString());
if (keys.contains(Okular::DocumentInfo::CreationDate))
}
if (keys.contains(Okular::DocumentInfo::CreationDate)) {
docInfo.set(Okular::DocumentInfo::CreationDate, m_djvu->metaData(QStringLiteral("year")).toString());
}
if (keys.contains(Okular::DocumentInfo::CustomKeys)) {
docInfo.set(QStringLiteral("editor"), m_djvu->metaData(QStringLiteral("editor")).toString(), i18n("Editor"));
docInfo.set(QStringLiteral("publisher"), m_djvu->metaData(QStringLiteral("publisher")).toString(), i18n("Publisher"));
@ -142,8 +148,9 @@ Okular::DocumentInfo DjVuGenerator::generateDocumentInfo(const QSet<Okular::Docu
const Okular::DocumentSynopsis *DjVuGenerator::generateDocumentSynopsis()
{
QMutexLocker locker(userMutex());
if (m_docSyn)
if (m_docSyn) {
return m_docSyn;
}
const QDomDocument *doc = m_djvu->documentBookmarks();
if (doc) {
@ -159,8 +166,9 @@ Okular::Document::PrintError DjVuGenerator::print(QPrinter &printer)
{
// Create tempfile to write to
QTemporaryFile tf(QDir::tempPath() + QLatin1String("/okular_XXXXXX.ps"));
if (!tf.open())
if (!tf.open()) {
return Okular::Document::TemporaryFileOpenPrintError;
}
const QString fileName = tf.fileName();
QMutexLocker locker(userMutex());
@ -189,10 +197,12 @@ Okular::TextPage *DjVuGenerator::textPage(Okular::TextRequest *request)
userMutex()->lock();
const Okular::Page *page = request->page();
QList<KDjVu::TextEntity> te;
if (te.isEmpty())
if (te.isEmpty()) {
te = m_djvu->textEntities(page->number(), QStringLiteral("word"));
if (te.isEmpty())
}
if (te.isEmpty()) {
te = m_djvu->textEntities(page->number(), QStringLiteral("line"));
}
userMutex()->unlock();
QList<KDjVu::TextEntity>::ConstIterator it = te.constBegin();
QList<KDjVu::TextEntity>::ConstIterator itEnd = te.constEnd();
@ -214,12 +224,14 @@ void DjVuGenerator::loadPages(QVector<Okular::Page *> &pagesVector, int rotation
for (int i = 0; i < numofpages; ++i) {
const KDjVu::Page *p = djvu_pages.at(i);
if (pagesVector[i])
if (pagesVector[i]) {
delete pagesVector[i];
}
int w = p->width();
int h = p->height();
if (rotation % 2 == 1)
if (rotation % 2 == 1) {
qSwap(w, h);
}
Okular::Page *page = new Okular::Page(i, w, h, (Okular::Rotation)(p->orientation() + rotation));
pagesVector[i] = page;
@ -235,13 +247,15 @@ void DjVuGenerator::loadPages(QVector<Okular::Page *> &pagesVector, int rotation
for (; it != itEnd; ++it) {
KDjVu::Link *curlink = (*it);
Okular::ObjectRect *newrect = convertKDjVuLink(i, curlink);
if (newrect)
if (newrect) {
rects.append(newrect);
}
// delete the links as soon as we process them
delete curlink;
}
if (rects.count() > 0)
if (rects.count() > 0) {
page->setObjectRects(rects);
}
}
if (!annots.isEmpty()) {
QList<KDjVu::Annotation *>::ConstIterator it = annots.constBegin();
@ -249,8 +263,9 @@ void DjVuGenerator::loadPages(QVector<Okular::Page *> &pagesVector, int rotation
for (; it != itEnd; ++it) {
KDjVu::Annotation *ann = (*it);
Okular::Annotation *newann = convertKDjVuAnnotation(w, h, ann);
if (newann)
if (newann) {
page->addAnnotation(newann);
}
// delete the annotations as soon as we process them
delete ann;
}
@ -267,13 +282,15 @@ Okular::ObjectRect *DjVuGenerator::convertKDjVuLink(int page, KDjVu::Link *link)
KDjVu::PageLink *l = static_cast<KDjVu::PageLink *>(link);
bool ok = true;
QString target = l->page();
if ((target.length() > 0) && target.at(0) == QLatin1Char('#'))
if ((target.length() > 0) && target.at(0) == QLatin1Char('#')) {
target.remove(0, 1);
}
int tmppage = target.toInt(&ok);
if (ok || target.isEmpty()) {
Okular::DocumentViewport vp;
if (!target.isEmpty())
if (!target.isEmpty()) {
vp.pageNumber = (target.at(0) == QLatin1Char('+') || target.at(0) == QLatin1Char('-')) ? page + tmppage : tmppage - 1;
}
newlink = new Okular::GotoAction(QString(), vp);
}
break;
@ -290,8 +307,9 @@ Okular::ObjectRect *DjVuGenerator::convertKDjVuLink(int page, KDjVu::Link *link)
int width = p->width();
int height = p->height();
bool scape_orientation = false; // hack by tokoe, should always create default page
if (scape_orientation)
if (scape_orientation) {
qSwap(width, height);
}
switch (link->areaType()) {
case KDjVu::Link::RectArea:
case KDjVu::Link::EllipseArea: {
@ -306,9 +324,9 @@ Okular::ObjectRect *DjVuGenerator::convertKDjVuLink(int page, KDjVu::Link *link)
for (int i = 0; i < poly.count(); ++i) {
int x = poly.at(i).x();
int y = poly.at(i).y();
if (scape_orientation)
if (scape_orientation) {
qSwap(x, y);
else {
} else {
y = height - y;
}
newpoly << QPointF((double)(x) / width, (double)(y) / height);
@ -360,8 +378,9 @@ Okular::Annotation *DjVuGenerator::convertKDjVuAnnotation(int w, int h, KDjVu::A
points.append(Okular::NormalizedPoint(b.x(), b.y(), w, h));
newlineann->setLinePoints(points);
// arrow?
if (lineann->isArrow())
if (lineann->isArrow()) {
newlineann->setLineEndStyle(Okular::LineAnnotation::OpenArrow);
}
// width
newlineann->style().setWidth(lineann->width());
newann = newlineann;

View File

@ -60,8 +60,9 @@ static void which_ddjvu_message(const ddjvu_message_t *msg)
static void handle_ddjvu_messages(ddjvu_context_t *ctx, int wait)
{
const ddjvu_message_t *msg;
if (wait)
if (wait) {
ddjvu_message_wait(ctx);
}
while ((msg = ddjvu_message_peek(ctx))) {
which_ddjvu_message(msg);
ddjvu_message_pop(ctx);
@ -101,8 +102,9 @@ static miniexp_t find_second_in_pair(miniexp_t theexp, const char *which)
}
const QString id = QString::fromUtf8(miniexp_to_name(miniexp_car(cur)));
if (id == QLatin1String(which))
if (id == QLatin1String(which)) {
return miniexp_cadr(cur);
}
exp = miniexp_cdr(exp);
}
return miniexp_nil;
@ -288,12 +290,14 @@ KDjVu::TextAnnotation::TextAnnotation(miniexp_t anno)
const int num = miniexp_length(m_anno);
for (int j = 4; j < num; ++j) {
miniexp_t curelem = miniexp_nth(j, m_anno);
if (!miniexp_listp(curelem))
if (!miniexp_listp(curelem)) {
continue;
}
QString id = QString::fromUtf8(miniexp_to_name(miniexp_nth(0, curelem)));
if (id == QLatin1String("pushpin"))
if (id == QLatin1String("pushpin")) {
m_inlineText = false;
}
}
}
@ -313,8 +317,9 @@ int KDjVu::TextAnnotation::type() const
QColor KDjVu::TextAnnotation::color() const
{
miniexp_t col = find_second_in_pair(m_anno, "backclr");
if (!miniexp_symbolp(col))
if (!miniexp_symbolp(col)) {
return Qt::transparent;
}
return QColor(QString::fromUtf8(miniexp_to_name(col)));
}
@ -340,14 +345,16 @@ KDjVu::LineAnnotation::LineAnnotation(miniexp_t anno)
const int num = miniexp_length(m_anno);
for (int j = 4; j < num; ++j) {
miniexp_t curelem = miniexp_nth(j, m_anno);
if (!miniexp_listp(curelem))
if (!miniexp_listp(curelem)) {
continue;
}
QString id = QString::fromUtf8(miniexp_to_name(miniexp_nth(0, curelem)));
if (id == QLatin1String("arrow"))
if (id == QLatin1String("arrow")) {
m_isArrow = true;
else if (id == QLatin1String("width"))
} else if (id == QLatin1String("width")) {
m_width = curelem;
}
}
}
@ -359,8 +366,9 @@ int KDjVu::LineAnnotation::type() const
QColor KDjVu::LineAnnotation::color() const
{
miniexp_t col = find_second_in_pair(m_anno, "lineclr");
if (!miniexp_symbolp(col))
if (!miniexp_symbolp(col)) {
return Qt::black;
}
return QColor(QString::fromUtf8(miniexp_to_name(col)));
}
@ -386,8 +394,9 @@ bool KDjVu::LineAnnotation::isArrow() const
int KDjVu::LineAnnotation::width() const
{
if (m_width == miniexp_nil)
if (m_width == miniexp_nil) {
return 1;
}
return miniexp_to_int(miniexp_cadr(m_width));
}
@ -498,12 +507,14 @@ QImage KDjVu::Private::generateImageTile(ddjvu_page_t *djvupage, int &res, int w
void KDjVu::Private::readBookmarks()
{
if (!m_djvu_document)
if (!m_djvu_document) {
return;
}
miniexp_t outline;
while ((outline = ddjvu_document_get_outline(m_djvu_document)) == miniexp_dummy)
while ((outline = ddjvu_document_get_outline(m_djvu_document)) == miniexp_dummy) {
handle_ddjvu_messages(m_djvu_cxt, true);
}
if (miniexp_listp(outline) && (miniexp_length(outline) > 0) && miniexp_symbolp(miniexp_nth(0, outline)) && (QString::fromUtf8(miniexp_to_name(miniexp_nth(0, outline))) == QLatin1String("bookmarks"))) {
m_docBookmarks = new QDomDocument(QStringLiteral("KDjVuBookmarks"));
@ -514,8 +525,9 @@ void KDjVu::Private::readBookmarks()
void KDjVu::Private::fillBookmarksRecurse(QDomDocument &maindoc, QDomNode &curnode, miniexp_t exp, int offset)
{
if (!miniexp_listp(exp))
if (!miniexp_listp(exp)) {
return;
}
int l = miniexp_length(exp);
for (int i = qMax(offset, 0); i < l; ++i) {
@ -557,25 +569,30 @@ void KDjVu::Private::fillBookmarksRecurse(QDomDocument &maindoc, QDomNode &curno
void KDjVu::Private::readMetaData(int page)
{
if (!m_djvu_document)
if (!m_djvu_document) {
return;
}
miniexp_t annots;
while ((annots = ddjvu_document_get_pageanno(m_djvu_document, page)) == miniexp_dummy)
while ((annots = ddjvu_document_get_pageanno(m_djvu_document, page)) == miniexp_dummy) {
handle_ddjvu_messages(m_djvu_cxt, true);
}
if (!miniexp_listp(annots) || miniexp_length(annots) == 0)
if (!miniexp_listp(annots) || miniexp_length(annots) == 0) {
return;
}
miniexp_t exp = miniexp_nth(0, annots);
int size = miniexp_length(exp);
if (size <= 1 || qstrncmp(miniexp_to_name(miniexp_nth(0, exp)), "metadata", 8))
if (size <= 1 || qstrncmp(miniexp_to_name(miniexp_nth(0, exp)), "metadata", 8)) {
return;
}
for (int i = 1; i < size; ++i) {
miniexp_t cur = miniexp_nth(i, exp);
if (miniexp_length(cur) != 2)
if (miniexp_length(cur) != 2) {
continue;
}
QString id = QString::fromUtf8(miniexp_to_name(miniexp_nth(0, cur)));
QString value = QString::fromUtf8(miniexp_to_str(miniexp_nth(1, cur)));
@ -586,17 +603,20 @@ void KDjVu::Private::readMetaData(int page)
int KDjVu::Private::pageWithName(const QString &name)
{
const int pageNo = m_pageNamesCache.value(name, -1);
if (pageNo != -1)
if (pageNo != -1) {
return pageNo;
}
const QByteArray utfName = name.toUtf8();
const int fileNum = ddjvu_document_get_filenum(m_djvu_document);
ddjvu_fileinfo_t info;
for (int i = 0; i < fileNum; ++i) {
if (DDJVU_JOB_OK != ddjvu_document_get_fileinfo(m_djvu_document, i, &info))
if (DDJVU_JOB_OK != ddjvu_document_get_fileinfo(m_djvu_document, i, &info)) {
continue;
if (info.type != 'P')
}
if (info.type != 'P') {
continue;
}
if ((utfName == info.id) || (utfName == info.name) || (utfName == info.title)) {
m_pageNamesCache.insert(name, info.pageno);
return info.pageno;
@ -633,13 +653,15 @@ KDjVu::~KDjVu()
bool KDjVu::openFile(const QString &fileName)
{
// first, close the old file
if (d->m_djvu_document)
if (d->m_djvu_document) {
closeFile();
}
// load the document..., use UTF-8 variant to work on Windows, too, see bug 422500
d->m_djvu_document = ddjvu_document_create_by_filename_utf8(d->m_djvu_cxt, fileName.toUtf8().constData(), true);
if (!d->m_djvu_document)
if (!d->m_djvu_document) {
return false;
}
// ...and wait for its loading
wait_for_ddjvu_message(d->m_djvu_cxt, DDJVU_DOCINFO);
if (ddjvu_document_decoding_error(d->m_djvu_document)) {
@ -677,8 +699,9 @@ bool KDjVu::openFile(const QString &fileName)
doctype = i18nc("Type of DjVu document", "Indexed (old)");
break;
}
if (!doctype.isEmpty())
if (!doctype.isEmpty()) {
d->m_metaData[QStringLiteral("documentType")] = doctype;
}
// get the number of components
d->m_metaData[QStringLiteral("componentFile")] = ddjvu_document_get_filenum(d->m_djvu_document);
@ -686,8 +709,9 @@ bool KDjVu::openFile(const QString &fileName)
for (int i = 0; i < numofpages; ++i) {
ddjvu_status_t sts;
ddjvu_pageinfo_t info;
while ((sts = ddjvu_document_get_pageinfo(d->m_djvu_document, i, &info)) < DDJVU_JOB_OK)
while ((sts = ddjvu_document_get_pageinfo(d->m_djvu_document, i, &info)) < DDJVU_JOB_OK) {
handle_ddjvu_messages(d->m_djvu_cxt, true);
}
if (sts >= DDJVU_JOB_FAILED) {
qDebug().nospace() << "\t>>> page " << i << " failed: " << sts;
return false;
@ -706,8 +730,9 @@ bool KDjVu::openFile(const QString &fileName)
}
// reading the metadata from the first page only should be enough
if (numofpages > 0)
if (numofpages > 0) {
d->readMetaData(0);
}
return true;
}
@ -722,8 +747,9 @@ void KDjVu::closeFile()
d->m_pages.clear();
// releasing the djvu pages
QVector<ddjvu_page_t *>::Iterator it = d->m_pages_cache.begin(), itEnd = d->m_pages_cache.end();
for (; it != itEnd; ++it)
for (; it != itEnd; ++it) {
ddjvu_page_release(*it);
}
d->m_pages_cache.clear();
// clearing the image cache
qDeleteAll(d->mImgCache);
@ -733,8 +759,9 @@ void KDjVu::closeFile()
// cleaning the page names mapping
d->m_pageNamesCache.clear();
// releasing the old document
if (d->m_djvu_document)
if (d->m_djvu_document) {
ddjvu_document_release(d->m_djvu_document);
}
d->m_djvu_document = nullptr;
}
@ -746,39 +773,47 @@ QVariant KDjVu::metaData(const QString &key) const
const QDomDocument *KDjVu::documentBookmarks() const
{
if (!d->m_docBookmarks)
if (!d->m_docBookmarks) {
d->readBookmarks();
}
return d->m_docBookmarks;
}
void KDjVu::linksAndAnnotationsForPage(int pageNum, QList<KDjVu::Link *> *links, QList<KDjVu::Annotation *> *annotations) const
{
if ((pageNum < 0) || (pageNum >= d->m_pages.count()) || (!links && !annotations))
if ((pageNum < 0) || (pageNum >= d->m_pages.count()) || (!links && !annotations)) {
return;
}
miniexp_t annots;
while ((annots = ddjvu_document_get_pageanno(d->m_djvu_document, pageNum)) == miniexp_dummy)
while ((annots = ddjvu_document_get_pageanno(d->m_djvu_document, pageNum)) == miniexp_dummy) {
handle_ddjvu_messages(d->m_djvu_cxt, true);
}
if (!miniexp_listp(annots))
if (!miniexp_listp(annots)) {
return;
}
if (links)
if (links) {
links->clear();
if (annotations)
}
if (annotations) {
annotations->clear();
}
int l = miniexp_length(annots);
for (int i = 0; i < l; ++i) {
miniexp_t cur = miniexp_nth(i, annots);
int num = miniexp_length(cur);
if ((num < 4) || !miniexp_symbolp(miniexp_nth(0, cur)) || (qstrncmp(miniexp_to_name(miniexp_nth(0, cur)), "maparea", 7) != 0))
if ((num < 4) || !miniexp_symbolp(miniexp_nth(0, cur)) || (qstrncmp(miniexp_to_name(miniexp_nth(0, cur)), "maparea", 7) != 0)) {
continue;
}
QString target;
QString type;
if (miniexp_symbolp(miniexp_nth(0, miniexp_nth(3, cur))))
if (miniexp_symbolp(miniexp_nth(0, miniexp_nth(3, cur)))) {
type = QString::fromUtf8(miniexp_to_name(miniexp_nth(0, miniexp_nth(3, cur))));
}
KDjVu::Link *link = nullptr;
KDjVu::Annotation *ann = nullptr;
miniexp_t urlexp = miniexp_nth(1, cur);
@ -827,8 +862,9 @@ void KDjVu::linksAndAnnotationsForPage(int pageNum, QList<KDjVu::Link *> *links,
link->m_poly = poly;
}
if (link->m_area != KDjVu::Link::UnknownArea)
if (link->m_area != KDjVu::Link::UnknownArea) {
links->append(link);
}
} else if (ann /* safety check */ && annotations) {
annotations->append(ann);
}
@ -847,8 +883,9 @@ QImage KDjVu::image(int page, int width, int height, int rotation)
QList<ImageCacheItem *>::Iterator it = d->mImgCache.begin(), itEnd = d->mImgCache.end();
for (; (it != itEnd) && !found; ++it) {
ImageCacheItem *cur = *it;
if ((cur->page == page) && (rotation % 2 == 0 ? cur->width == width && cur->height == height : cur->width == height && cur->height == width))
if ((cur->page == page) && (rotation % 2 == 0 ? cur->width == width && cur->height == height : cur->width == height && cur->height == width)) {
found = true;
}
}
if (found) {
// taking the element and pushing to the top of the list
@ -865,8 +902,9 @@ QImage KDjVu::image(int page, int width, int height, int rotation)
ddjvu_page_t *newpage = ddjvu_page_create_by_pageno(d->m_djvu_document, page);
// wait for the new page to be loaded
ddjvu_status_t sts;
while ((sts = ddjvu_page_decoding_status(newpage)) < DDJVU_JOB_OK)
while ((sts = ddjvu_page_decoding_status(newpage)) < DDJVU_JOB_OK) {
handle_ddjvu_messages(d->m_djvu_cxt, true);
}
d->m_pages_cache[page] = newpage;
}
ddjvu_page_t *djvupage = d->m_pages_cache[page];
@ -920,8 +958,9 @@ QImage KDjVu::image(int page, int width, int height, int rotation)
if ((cur->page == page) && (abs(cur->img.width() * cur->img.height() - imgsize) < imgsize * 0.35)) {
d->mImgCache.removeAt(i);
delete cur;
} else
} else {
++i;
}
}
}
@ -939,8 +978,9 @@ QImage KDjVu::image(int page, int width, int height, int rotation)
bool KDjVu::exportAsPostScript(const QString &fileName, const QList<int> &pageList) const
{
if (!d->m_djvu_document || fileName.trimmed().isEmpty() || pageList.isEmpty())
if (!d->m_djvu_document || fileName.trimmed().isEmpty() || pageList.isEmpty()) {
return false;
}
QFile f(fileName);
f.open(QIODevice::ReadWrite);
@ -953,8 +993,9 @@ bool KDjVu::exportAsPostScript(const QString &fileName, const QList<int> &pageLi
bool KDjVu::exportAsPostScript(QFile *file, const QList<int> &pageList) const
{
if (!d->m_djvu_document || !file || pageList.isEmpty())
if (!d->m_djvu_document || !file || pageList.isEmpty()) {
return false;
}
FILE *f = fdopen(file->handle(), "w+");
if (!f) {
@ -964,8 +1005,9 @@ bool KDjVu::exportAsPostScript(QFile *file, const QList<int> &pageList) const
QString pl;
for (const int p : pageList) {
if (!pl.isEmpty())
if (!pl.isEmpty()) {
pl += QLatin1String(",");
}
pl += QString::number(p);
}
pl.prepend(QStringLiteral("-page="));
@ -977,8 +1019,9 @@ bool KDjVu::exportAsPostScript(QFile *file, const QList<int> &pageList) const
optv[0] = plb.constData();
ddjvu_job_t *printjob = ddjvu_document_print(d->m_djvu_document, f, optc, optv);
while (!ddjvu_job_done(printjob))
while (!ddjvu_job_done(printjob)) {
handle_ddjvu_messages(d->m_djvu_cxt, true);
}
free(optv);
@ -987,15 +1030,18 @@ bool KDjVu::exportAsPostScript(QFile *file, const QList<int> &pageList) const
QList<KDjVu::TextEntity> KDjVu::textEntities(int page, const QString &granularity) const
{
if ((page < 0) || (page >= d->m_pages.count()))
if ((page < 0) || (page >= d->m_pages.count())) {
return QList<KDjVu::TextEntity>();
}
miniexp_t r;
while ((r = ddjvu_document_get_pagetext(d->m_djvu_document, page, nullptr)) == miniexp_dummy)
while ((r = ddjvu_document_get_pagetext(d->m_djvu_document, page, nullptr)) == miniexp_dummy) {
handle_ddjvu_messages(d->m_djvu_cxt, true);
}
if (r == miniexp_nil)
if (r == miniexp_nil) {
return QList<KDjVu::TextEntity>();
}
QList<KDjVu::TextEntity> ret;
@ -1023,8 +1069,9 @@ QList<KDjVu::TextEntity> KDjVu::textEntities(int page, const QString &granularit
ret.append(entity);
}
} else {
for (int i = 5; i < size; ++i)
for (int i = 5; i < size; ++i) {
queue.enqueue(miniexp_nth(i, cur));
}
}
}
}
@ -1034,8 +1081,9 @@ QList<KDjVu::TextEntity> KDjVu::textEntities(int page, const QString &granularit
void KDjVu::setCacheEnabled(bool enable)
{
if (enable == d->m_cacheEnabled)
if (enable == d->m_cacheEnabled) {
return;
}
d->m_cacheEnabled = enable;
if (!d->m_cacheEnabled) {
@ -1051,8 +1099,9 @@ bool KDjVu::isCacheEnabled() const
int KDjVu::pageNumber(const QString &name) const
{
if (!d->m_djvu_document)
if (!d->m_djvu_document) {
return -1;
}
return d->pageWithName(name);
}

View File

@ -28,8 +28,9 @@ public:
void setDisplayResolution()
{
for (glyph &g : glyphtable)
for (glyph &g : glyphtable) {
g.shrunkenCharacter = QImage();
}
}
virtual glyph *getGlyph(quint16 character, bool generateCharacterPixmap = false, const QColor &color = Qt::black) = 0;

View File

@ -76,8 +76,9 @@ TeXFontDefinition::~TeXFontDefinition()
fclose(file);
file = nullptr;
}
if (flags & FONT_VIRTUAL)
if (flags & FONT_VIRTUAL) {
vf_table.clear();
}
}
}
@ -104,32 +105,36 @@ void TeXFontDefinition::fontNameReceiver(const QString &fname)
if (file == nullptr) {
qCCritical(OkularDviDebug) << i18n("Cannot find font %1, file %2.", fontname, filename) << endl;
return;
} else
} else {
filename = filename_test;
}
}
set_char_p = &dviRenderer::set_char;
int magic = two(file);
if (fname.endsWith(QLatin1String("pk")))
if (fname.endsWith(QLatin1String("pk"))) {
if (magic == PK_MAGIC) {
fclose(file);
file = nullptr;
font = new TeXFont_PK(this);
set_char_p = &dviRenderer::set_char;
if ((checksum != 0) && (checksum != font->checksum))
if ((checksum != 0) && (checksum != font->checksum)) {
qCWarning(OkularDviDebug) << i18n("Checksum mismatch for font file %1", filename);
}
fontType = TEX_PK;
return;
}
}
if (fname.endsWith(QLatin1String(".vf")))
if (fname.endsWith(QLatin1String(".vf"))) {
if (magic == VF_MAGIC) {
read_VF_index();
set_char_p = &dviRenderer::set_vf_char;
fontType = TEX_VIRTUAL;
return;
}
}
if (fname.endsWith(QLatin1String(".tfm"))) {
fclose(file);
@ -187,8 +192,9 @@ void TeXFontDefinition::reset()
fclose(file);
file = nullptr;
}
if (flags & FONT_VIRTUAL)
if (flags & FONT_VIRTUAL) {
vf_table.clear();
}
}
filename.clear();
@ -199,8 +205,9 @@ void TeXFontDefinition::reset()
void TeXFontDefinition::setDisplayResolution(double _displayResolution_in_dpi)
{
displayResolution_in_dpi = _displayResolution_in_dpi;
if (font != nullptr)
if (font != nullptr) {
font->setDisplayResolution();
}
}
/** mark_as_used marks the font, and all the fonts it refers to, as
@ -212,8 +219,9 @@ void TeXFontDefinition::mark_as_used()
qCDebug(OkularDviDebug) << "TeXFontDefinition::mark_as_used()";
#endif
if (flags & TeXFontDefinition::FONT_IN_USE)
if (flags & TeXFontDefinition::FONT_IN_USE) {
return;
}
flags |= TeXFontDefinition::FONT_IN_USE;
@ -237,6 +245,7 @@ macro::macro()
macro::~macro()
{
if ((pos != nullptr) && (free_me == true))
if ((pos != nullptr) && (free_me == true)) {
delete[] pos;
}
}

View File

@ -63,8 +63,9 @@ TeXFont_PFB::TeXFont_PFB(TeXFontDefinition *parent, fontEncoding *enc, double sl
FT_Set_Transform(face, &transformationMatrix, nullptr);
}
if (face->family_name != nullptr)
if (face->family_name != nullptr) {
parent->fullFontName = QString::fromLocal8Bit(face->family_name);
}
// Finally, we need to set up the charMap array, which maps TeX
// character codes to glyph indices in the font. (Remark: the
@ -107,22 +108,25 @@ TeXFont_PFB::TeXFont_PFB(TeXFontDefinition *parent, fontEncoding *enc, double sl
#ifdef DEBUG_PFB
qCDebug(OkularDviDebug) << "No encoding given: using charmap platform=7, encoding=2 that is contained in the font.";
#endif
for (int i = 0; i < 256; i++)
for (int i = 0; i < 256; i++) {
charMap[i] = FT_Get_Char_Index(face, i);
}
} else {
if ((found == nullptr) && (face->charmap != nullptr)) {
#ifdef DEBUG_PFB
qCDebug(OkularDviDebug) << "No encoding given: using charmap platform=" << face->charmap->platform_id << ", encoding=" << face->charmap->encoding_id << " that is contained in the font." << endl;
#endif
for (int i = 0; i < 256; i++)
for (int i = 0; i < 256; i++) {
charMap[i] = FT_Get_Char_Index(face, i);
}
} else {
// As a last resort, we use the identity map.
#ifdef DEBUG_PFB
qCDebug(OkularDviDebug) << "No encoding given, no suitable charmaps found in the font: using identity charmap.";
#endif
for (int i = 0; i < 256; i++)
for (int i = 0; i < 256; i++) {
charMap[i] = i;
}
}
}
}
@ -148,8 +152,9 @@ glyph *TeXFont_PFB::getGlyph(quint16 ch, bool generateCharacterPixmap, const QCo
// This is the address of the glyph that will be returned.
glyph *g = glyphtable + ch;
if (fatalErrorInFontLoading == true)
if (fatalErrorInFontLoading == true) {
return g;
}
if ((generateCharacterPixmap == true) && ((g->shrunkenCharacter.isNull()) || (color != g->color))) {
int error;
@ -163,8 +168,9 @@ glyph *TeXFont_PFB::getGlyph(quint16 ch, bool generateCharacterPixmap, const QCo
error = FT_Set_Char_Size(face, 0, characterSize_in_printers_points_by_64, res, res);
if (error) {
QString msg = i18n("FreeType reported an error when setting the character size for font file %1.", parent->filename);
if (errorMessage.isEmpty())
if (errorMessage.isEmpty()) {
errorMessage = msg;
}
qCCritical(OkularDviDebug) << msg << endl;
g->shrunkenCharacter = QImage(1, 1, QImage::Format_RGB32);
g->shrunkenCharacter.fill(qRgb(255, 255, 255));
@ -172,15 +178,17 @@ glyph *TeXFont_PFB::getGlyph(quint16 ch, bool generateCharacterPixmap, const QCo
}
// load glyph image into the slot and erase the previous one
if (parent->font_pool->getUseFontHints() == true)
if (parent->font_pool->getUseFontHints() == true) {
error = FT_Load_Glyph(face, charMap[ch], FT_LOAD_DEFAULT);
else
} else {
error = FT_Load_Glyph(face, charMap[ch], FT_LOAD_NO_HINTING);
}
if (error) {
QString msg = i18n("FreeType is unable to load glyph #%1 from font file %2.", ch, parent->filename);
if (errorMessage.isEmpty())
if (errorMessage.isEmpty()) {
errorMessage = msg;
}
qCCritical(OkularDviDebug) << msg << endl;
g->shrunkenCharacter = QImage(1, 1, QImage::Format_RGB32);
g->shrunkenCharacter.fill(qRgb(255, 255, 255));
@ -191,8 +199,9 @@ glyph *TeXFont_PFB::getGlyph(quint16 ch, bool generateCharacterPixmap, const QCo
error = FT_Render_Glyph(face->glyph, ft_render_mode_normal);
if (error) {
QString msg = i18n("FreeType is unable to render glyph #%1 from font file %2.", ch, parent->filename);
if (errorMessage.isEmpty())
if (errorMessage.isEmpty()) {
errorMessage = msg;
}
qCCritical(OkularDviDebug) << msg << endl;
g->shrunkenCharacter = QImage(1, 1, QImage::Format_RGB32);
g->shrunkenCharacter.fill(qRgb(255, 255, 255));
@ -202,8 +211,9 @@ glyph *TeXFont_PFB::getGlyph(quint16 ch, bool generateCharacterPixmap, const QCo
FT_GlyphSlot slot = face->glyph;
if ((slot->bitmap.width == 0) || (slot->bitmap.rows == 0)) {
if (errorMessage.isEmpty())
if (errorMessage.isEmpty()) {
errorMessage = i18n("Glyph #%1 is empty.", ch);
}
qCCritical(OkularDviDebug) << i18n("Glyph #%1 from font file %2 is empty.", ch, parent->filename) << endl;
g->shrunkenCharacter = QImage(15, 15, QImage::Format_RGB32);
g->shrunkenCharacter.fill(qRgb(255, 0, 0));
@ -270,8 +280,9 @@ glyph *TeXFont_PFB::getGlyph(quint16 ch, bool generateCharacterPixmap, const QCo
int error = FT_Load_Glyph(face, charMap[ch], FT_LOAD_NO_SCALE);
if (error) {
QString msg = i18n("FreeType is unable to load metric for glyph #%1 from font file %2.", ch, parent->filename);
if (errorMessage.isEmpty())
if (errorMessage.isEmpty()) {
errorMessage = msg;
}
qCCritical(OkularDviDebug) << msg << endl;
g->dvi_advance_in_units_of_design_size_by_2e20 = 1;
}

View File

@ -61,11 +61,13 @@ TeXFont_PK::TeXFont_PK(TeXFontDefinition *parent)
qCDebug(OkularDviDebug) << "TeXFont_PK::TeXFont_PK( parent=" << parent << ")";
#endif
for (auto &characterBitmap : characterBitmaps)
for (auto &characterBitmap : characterBitmaps) {
characterBitmap = nullptr;
}
file = fopen(QFile::encodeName(parent->filename).constData(), "r");
if (file == nullptr)
if (file == nullptr) {
qCCritical(OkularDviDebug) << i18n("Cannot open font file %1.", parent->filename) << endl;
}
#ifdef DEBUG_PK
else
qCDebug(OkularDviDebug) << "TeXFont_PK::TeXFont_PK(): file opened successfully";
@ -118,8 +120,9 @@ glyph *TeXFont_PK::getGlyph(quint16 ch, bool generateCharacterPixmap, const QCol
// If the character has already been marked as missing, just
// return a pointer to the glyph (which will then be empty)
if (g->addr == -1)
if (g->addr == -1) {
return g;
}
// Otherwise, try to load the character
fseek(file, g->addr, 0);
@ -183,13 +186,14 @@ glyph *TeXFont_PK::getGlyph(quint16 ch, bool generateCharacterPixmap, const QCol
// Turn the image into 8 bit
QByteArray translated(characterBitmaps[ch]->w * characterBitmaps[ch]->h, '\0');
quint8 *data = (quint8 *)translated.data();
for (int x = 0; x < characterBitmaps[ch]->w; x++)
for (int x = 0; x < characterBitmaps[ch]->w; x++) {
for (int y = 0; y < characterBitmaps[ch]->h; y++) {
quint8 bit = *(characterBitmaps[ch]->bits + characterBitmaps[ch]->bytes_wide * y + (x >> 3));
bit = bit >> (x & 7);
bit = bit & 1;
data[characterBitmaps[ch]->w * y + x] = bit;
}
}
// Now shrink the image. We shrink the X-direction first
QByteArray xshrunk(shrunk_width * characterBitmaps[ch]->h, '\0');
@ -202,42 +206,52 @@ glyph *TeXFont_PK::getGlyph(quint16 ch, bool generateCharacterPixmap, const QCol
//
// The trouble is, these numbers are in general no integers.
for (int y = 0; y < characterBitmaps[ch]->h; y++)
for (int y = 0; y < characterBitmaps[ch]->h; y++) {
for (int x = 0; x < shrunk_width; x++) {
quint32 value = 0;
double destStartX = shrinkFactor * x + srcXTrans;
double destEndX = shrinkFactor * (x + 1) + srcXTrans;
for (int srcX = (int)ceil(destStartX); srcX < floor(destEndX); srcX++)
if ((srcX >= 0) && (srcX < characterBitmaps[ch]->w))
for (int srcX = (int)ceil(destStartX); srcX < floor(destEndX); srcX++) {
if ((srcX >= 0) && (srcX < characterBitmaps[ch]->w)) {
value += data[characterBitmaps[ch]->w * y + srcX] * 255;
}
}
if (destStartX >= 0.0)
if (destStartX >= 0.0) {
value += (quint32)(255.0 * (ceil(destStartX) - destStartX) * data[characterBitmaps[ch]->w * y + (int)floor(destStartX)]);
if (floor(destEndX) < characterBitmaps[ch]->w)
}
if (floor(destEndX) < characterBitmaps[ch]->w) {
value += (quint32)(255.0 * (destEndX - floor(destEndX)) * data[characterBitmaps[ch]->w * y + (int)floor(destEndX)]);
}
xdata[shrunk_width * y + x] = (int)(value / shrinkFactor + 0.5);
}
}
// Now shrink the Y-direction
QByteArray xyshrunk(shrunk_width * shrunk_height, '\0');
quint8 *xydata = (quint8 *)xyshrunk.data();
for (int x = 0; x < shrunk_width; x++)
for (int x = 0; x < shrunk_width; x++) {
for (int y = 0; y < shrunk_height; y++) {
quint32 value = 0;
double destStartY = shrinkFactor * y + srcYTrans;
double destEndY = shrinkFactor * (y + 1) + srcYTrans;
for (int srcY = (int)ceil(destStartY); srcY < floor(destEndY); srcY++)
if ((srcY >= 0) && (srcY < characterBitmaps[ch]->h))
for (int srcY = (int)ceil(destStartY); srcY < floor(destEndY); srcY++) {
if ((srcY >= 0) && (srcY < characterBitmaps[ch]->h)) {
value += xdata[shrunk_width * srcY + x];
}
}
if (destStartY >= 0.0)
if (destStartY >= 0.0) {
value += (quint32)((ceil(destStartY) - destStartY) * xdata[shrunk_width * (int)floor(destStartY) + x]);
if (floor(destEndY) < characterBitmaps[ch]->h)
}
if (floor(destEndY) < characterBitmaps[ch]->h) {
value += (quint32)((destEndY - floor(destEndY)) * xdata[shrunk_width * (int)floor(destEndY) + x]);
}
xydata[shrunk_width * y + x] = (int)(value / shrinkFactor);
}
}
QImage im32(shrunk_width, shrunk_height, QImage::Format_ARGB32);
// Do QPixmaps fully support the alpha channel? If yes, we use
@ -250,8 +264,9 @@ glyph *TeXFont_PK::getGlyph(quint16 ch, bool generateCharacterPixmap, const QCol
im32.fill(qRgb(color.red(), color.green(), color.blue()));
for (int y = 0; y < shrunk_height; y++) {
quint8 *destScanLine = (quint8 *)im32.scanLine(y);
for (int col = 0; col < shrunk_width; col++)
for (int col = 0; col < shrunk_width; col++) {
destScanLine[4 * col + 3] = xydata[shrunk_width * y + col];
}
}
} else {
// If the alpha channel is not supported... QT seems to turn the
@ -349,14 +364,17 @@ int TeXFont_PK::PK_packed_num(FILE *fp)
}
return (j - 15 + ((13 - PK_dyn_f) << 4) + PK_dyn_f);
} else {
if (i <= PK_dyn_f)
if (i <= PK_dyn_f) {
return i;
if (i < 14)
}
if (i < 14) {
return (((i - PK_dyn_f - 1) << 4) + PK_get_nyb(fp) + PK_dyn_f + 1);
if (i == 14)
}
if (i == 14) {
PK_repeat_count = PK_packed_num(fp);
else
} else {
PK_repeat_count = 1;
}
return PK_packed_num(fp);
}
}
@ -384,10 +402,12 @@ void TeXFont_PK::PK_skip_specials()
case PK_X3:
case PK_X4:
i = 0;
for (j = PK_CMD_START; j <= PK_flag_byte; ++j)
for (j = PK_CMD_START; j <= PK_flag_byte; ++j) {
i = (i << 8) | one(fp);
while (i--)
}
while (i--) {
(void)one(fp);
}
break;
case PK_Y:
(void)four(fp);
@ -429,26 +449,28 @@ void TeXFont_PK::read_PK_char(unsigned int ch)
PK_dyn_f = PK_flag_byte >> 4;
paint_switch = ((PK_flag_byte & 8) != 0);
PK_flag_byte &= 0x7;
if (PK_flag_byte == 7)
if (PK_flag_byte == 7) {
n = 4;
else if (PK_flag_byte > 3)
} else if (PK_flag_byte > 3) {
n = 2;
else
} else {
n = 1;
}
#ifdef DEBUG_PK
qCDebug(OkularDviDebug) << "loading pk char " << ch << ", char type " << n;
#endif
if (characterBitmaps[ch] == nullptr)
if (characterBitmaps[ch] == nullptr) {
characterBitmaps[ch] = new bitmap();
}
/*
* now read rest of character preamble
*/
if (n != 4)
if (n != 4) {
fpwidth = num(fp, 3);
else {
} else {
fpwidth = sfour(fp);
(void)four(fp); /* horizontal escapement */
}
@ -458,8 +480,9 @@ void TeXFont_PK::read_PK_char(unsigned int ch)
w = num(fp, n);
h = num(fp, n);
if (w > 0x7fff || h > 0x7fff)
if (w > 0x7fff || h > 0x7fff) {
oops(i18n("The character %1 is too large in file %2", ch, parent->filename));
}
characterBitmaps[ch]->w = w;
characterBitmaps[ch]->h = h;
}
@ -512,8 +535,9 @@ void TeXFont_PK::read_PK_char(unsigned int ch)
cp++;
row_bit_pos = 32 - 1;
}
if (word & (1 << PK_bitpos))
if (word & (1 << PK_bitpos)) {
*cp |= 1 << row_bit_pos;
}
}
}
} else { /* get packed raster */
@ -528,12 +552,14 @@ void TeXFont_PK::read_PK_char(unsigned int ch)
if (count < word_weight && count < h_bit) {
h_bit -= count;
word_weight -= count;
if (paint_switch)
if (paint_switch) {
word |= bit_masks[count] << word_weight;
}
count = 0;
} else if (count >= h_bit && h_bit <= word_weight) {
if (paint_switch)
if (paint_switch) {
word |= bit_masks[h_bit] << (word_weight - h_bit);
}
*cp++ = word;
/* "output" row(s) */
for (i = PK_repeat_count * bytes_wide / 4; i > 0; --i) {
@ -547,8 +573,9 @@ void TeXFont_PK::read_PK_char(unsigned int ch)
count -= h_bit;
h_bit = characterBitmaps[ch]->w;
} else {
if (paint_switch)
if (paint_switch) {
word |= bit_masks[word_weight];
}
*cp++ = word;
word = 0;
count -= word_weight;
@ -558,10 +585,12 @@ void TeXFont_PK::read_PK_char(unsigned int ch)
}
paint_switch = 1 - paint_switch;
}
if (cp != (reinterpret_cast<quint32 *>(characterBitmaps[ch]->bits + bytes_wide * characterBitmaps[ch]->h)))
if (cp != (reinterpret_cast<quint32 *>(characterBitmaps[ch]->bits + bytes_wide * characterBitmaps[ch]->h))) {
oops(i18n("Wrong number of bits stored: char. %1, font %2", ch, parent->filename));
if (rows_left != 0 || h_bit != characterBitmaps[ch]->w)
}
if (rows_left != 0 || h_bit != characterBitmaps[ch]->w) {
oops(i18n("Bad pk file (%1), too many bits", parent->filename));
}
}
// The data in the bitmap is now in the processor's bit order,
@ -596,8 +625,9 @@ void TeXFont_PK::read_PK_char(unsigned int ch)
cp++;
row_bit_pos = 0;
}
if (word & (1 << PK_bitpos))
if (word & (1 << PK_bitpos)) {
*cp |= 1 << row_bit_pos;
}
}
}
} else { /* get packed raster */
@ -610,14 +640,16 @@ void TeXFont_PK::read_PK_char(unsigned int ch)
count = PK_packed_num(fp);
while (count > 0) {
if (count < word_weight && count < h_bit) {
if (paint_switch)
if (paint_switch) {
word |= bit_masks[count] << (32 - word_weight);
}
h_bit -= count;
word_weight -= count;
count = 0;
} else if (count >= h_bit && h_bit <= word_weight) {
if (paint_switch)
if (paint_switch) {
word |= bit_masks[h_bit] << (32 - word_weight);
}
*cp++ = word;
/* "output" row(s) */
for (i = PK_repeat_count * bytes_wide / 4; i > 0; --i) {
@ -631,8 +663,9 @@ void TeXFont_PK::read_PK_char(unsigned int ch)
count -= h_bit;
h_bit = characterBitmaps[ch]->w;
} else {
if (paint_switch)
if (paint_switch) {
word |= bit_masks[word_weight] << (32 - word_weight);
}
*cp++ = word;
word = 0;
count -= word_weight;
@ -642,10 +675,12 @@ void TeXFont_PK::read_PK_char(unsigned int ch)
}
paint_switch = 1 - paint_switch;
}
if (cp != (reinterpret_cast<quint32 *>(characterBitmaps[ch]->bits + bytes_wide * characterBitmaps[ch]->h)))
if (cp != (reinterpret_cast<quint32 *>(characterBitmaps[ch]->bits + bytes_wide * characterBitmaps[ch]->h))) {
oops(i18n("Wrong number of bits stored: char. %1, font %2", ch, parent->filename));
if (rows_left != 0 || h_bit != characterBitmaps[ch]->w)
}
if (rows_left != 0 || h_bit != characterBitmaps[ch]->w) {
oops(i18n("Bad pk file (%1), too many bits", parent->filename));
}
}
} // endif: big or small Endian?
}
@ -674,8 +709,9 @@ void TeXFont_PK::read_PK_index()
int hppp = sfour(file);
int vppp = sfour(file);
if (hppp != vppp)
if (hppp != vppp) {
qCWarning(OkularDviDebug) << i18n("Font has non-square aspect ratio ") << vppp << ":" << hppp;
}
// Read glyph directory (really a whole pass over the file).
for (;;) {
@ -683,8 +719,9 @@ void TeXFont_PK::read_PK_index()
unsigned int ch;
PK_skip_specials();
if (PK_flag_byte == PK_POST)
if (PK_flag_byte == PK_POST) {
break;
}
flag_low_bits = PK_flag_byte & 0x7;
if (flag_low_bits == 7) {
bytes_left = four(file);

View File

@ -53,8 +53,9 @@ TeXFont_TFM::TeXFont_TFM(TeXFontDefinition *parent)
// Width table
fix_word widthTable_in_units_of_design_size[TeXFontDefinition::max_num_of_chars_in_font];
for (fix_word &fw : widthTable_in_units_of_design_size)
for (fix_word &fw : widthTable_in_units_of_design_size) {
fw.value = 0;
}
file.seek(24 + 4 * lh + 4 * (ec - bc));
for (unsigned int i = 0; i < nw; i++) {
@ -64,14 +65,16 @@ TeXFont_TFM::TeXFont_TFM(TeXFontDefinition *parent)
// depends on the preceding character. We cannot calculate the
// real width here and take 0.4 times the design size as an
// approximation.
if (widthTable_in_units_of_design_size[i].value == 0)
if (widthTable_in_units_of_design_size[i].value == 0) {
widthTable_in_units_of_design_size[i].fromDouble(0.4);
}
}
// Height table
fix_word heightTable_in_units_of_design_size[16];
for (fix_word &fw : heightTable_in_units_of_design_size)
for (fix_word &fw : heightTable_in_units_of_design_size) {
fw.value = 0;
}
for (unsigned int i = 0; i < nh; i++) {
stream >> heightTable_in_units_of_design_size[i].value;
}
@ -83,19 +86,20 @@ TeXFont_TFM::TeXFont_TFM(TeXFontDefinition *parent)
quint8 byte;
stream >> byte;
if (byte >= nw)
if (byte >= nw) {
qCCritical(OkularDviDebug) << "TeXFont_TFM::TeXFont_TFM( filename=" << parent->filename << " ): The font has an invalid Char-Info table." << endl;
else {
} else {
characterWidth_in_units_of_design_size[characterCode] = widthTable_in_units_of_design_size[byte];
g->dvi_advance_in_units_of_design_size_by_2e20 = widthTable_in_units_of_design_size[byte].value;
}
stream >> byte;
byte = byte >> 4;
if (byte >= nh)
if (byte >= nh) {
qCCritical(OkularDviDebug) << "TeXFont_TFM::TeXFont_TFM( filename=" << parent->filename << " ): The font has an invalid Char-Info table." << endl;
else
} else {
characterHeight_in_units_of_design_size[characterCode] = heightTable_in_units_of_design_size[byte];
}
stream >> byte;
stream >> byte;
@ -129,10 +133,12 @@ glyph *TeXFont_TFM::getGlyph(quint16 characterCode, bool generateCharacterPixmap
// Just make sure that weird TFM files never lead to giant
// pixmaps that eat all system memory...
if (pixelWidth > 50)
if (pixelWidth > 50) {
pixelWidth = 50;
if (pixelHeight > 50)
}
if (pixelHeight > 50) {
pixelHeight = 50;
}
g->shrunkenCharacter = QImage(pixelWidth, pixelHeight, QImage::Format_RGB32);
g->shrunkenCharacter.fill(color.rgba());

View File

@ -34,8 +34,9 @@ quint16 bigEndianByteReader::readUINT16()
{
// This check saveguards us against segmentation fault. It is also
// necessary for virtual fonts, which do not end with EOP.
if (command_pointer >= end_pointer)
if (command_pointer >= end_pointer) {
return EOP;
}
quint16 a;
a = *(command_pointer++);
@ -47,8 +48,9 @@ quint32 bigEndianByteReader::readUINT32()
{
// This check saveguards us against segmentation fault. It is also
// necessary for virtual fonts, which do not end with EOP.
if (command_pointer >= end_pointer)
if (command_pointer >= end_pointer) {
return EOP;
}
quint32 a;
a = *(command_pointer++);
@ -62,8 +64,9 @@ void bigEndianByteReader::writeUINT32(quint32 a)
{
// This check saveguards us against segmentation fault. It is also
// necessary for virtual fonts, which do not end with EOP.
if (command_pointer >= end_pointer)
if (command_pointer >= end_pointer) {
return;
}
command_pointer[3] = (quint8)(a & 0xFF);
a = a >> 8;
@ -81,8 +84,9 @@ quint32 bigEndianByteReader::readUINT(quint8 size)
{
// This check saveguards us against segmentation fault. It is also
// necessary for virtual fonts, which do not end with EOP.
if (command_pointer >= end_pointer)
if (command_pointer >= end_pointer) {
return EOP;
}
quint32 a = 0;
while (size > 0) {
@ -96,16 +100,19 @@ qint32 bigEndianByteReader::readINT(quint8 length)
{
// This check saveguards us against segmentation fault. It is also
// necessary for virtual fonts, which do not end with EOP.
if (command_pointer >= end_pointer)
if (command_pointer >= end_pointer) {
return EOP;
}
qint32 a = *(command_pointer++);
if (a & 0x80)
if (a & 0x80) {
a -= 0x100;
}
while ((--length) > 0)
while ((--length) > 0) {
a = (a << 8) | *(command_pointer++);
}
return a;
}

View File

@ -127,8 +127,9 @@ void dvifile::find_postamble()
{
// Move backwards through the TRAILER bytes
command_pointer = dvi_Data() + size_of_file - 1;
while ((*command_pointer == TRAILER) && (command_pointer > dvi_Data()))
while ((*command_pointer == TRAILER) && (command_pointer > dvi_Data())) {
command_pointer--;
}
if (command_pointer == dvi_Data()) {
errorMsg = i18n("The DVI file is badly corrupted. Okular was not able to find the postamble.");
return;
@ -185,10 +186,11 @@ void dvifile::read_postamble()
// Insert font in dictionary and make sure the dictionary is big
// enough.
if (tn_table.capacity() - 2 <= tn_table.count())
if (tn_table.capacity() - 2 <= tn_table.count()) {
// Not quite optimal. The size of the dictionary should be a
// prime for optimal performance. I don't care.
tn_table.reserve(tn_table.capacity() * 2);
}
tn_table.insert(TeXnumber, fontp);
}
@ -203,8 +205,9 @@ void dvifile::read_postamble()
// Now we remove all those fonts from the memory which are no longer
// in use.
if (font_pool != nullptr)
if (font_pool != nullptr) {
font_pool->release_fonts();
}
}
void dvifile::prepare_pages()
@ -212,16 +215,18 @@ void dvifile::prepare_pages()
#ifdef DEBUG_DVIFILE
qCDebug(OkularDviDebug) << "prepare_pages";
#endif
if (total_pages == 0)
if (total_pages == 0) {
return;
}
page_offset.resize(total_pages + 1);
if (page_offset.size() < (total_pages + 1)) {
qCCritical(OkularDviDebug) << "No memory for page list!";
return;
}
for (int i = 0; i <= total_pages; i++)
for (int i = 0; i <= total_pages; i++) {
page_offset[i] = 0;
}
page_offset[int(total_pages)] = beginning_of_postamble;
int j = total_pages - 1;
@ -237,8 +242,9 @@ void dvifile::prepare_pages()
}
command_pointer += 10 * 4;
page_offset[j] = readUINT32();
if ((dvi_Data() + page_offset[j] < dvi_Data()) || (dvi_Data() + page_offset[j] > dvi_Data() + size_of_file))
if ((dvi_Data() + page_offset[j] < dvi_Data()) || (dvi_Data() + page_offset[j] > dvi_Data() + size_of_file)) {
break;
}
}
}
@ -301,10 +307,12 @@ dvifile::~dvifile()
QFile::remove(i.value());
}
if (suggestedPageSize != nullptr)
if (suggestedPageSize != nullptr) {
delete suggestedPageSize;
if (font_pool != nullptr)
}
if (font_pool != nullptr) {
font_pool->mark_fonts_as_unused();
}
}
void dvifile::renumber()
@ -318,7 +326,7 @@ void dvifile::renumber()
for (int i = 1; i <= total_pages; i++) {
quint8 *ptr = dviData.data() + page_offset[i - 1] + 1;
quint8 *num = (quint8 *)&i;
for (quint8 j = 0; j < 4; j++)
for (quint8 j = 0; j < 4; j++) {
if (bigEndian) {
*(ptr++) = num[0];
*(ptr++) = num[1];
@ -330,6 +338,7 @@ void dvifile::renumber()
*(ptr++) = num[1];
*(ptr++) = num[0];
}
}
}
}
@ -419,14 +428,17 @@ QString dvifile::convertPDFtoPS(const QString &PDFFilename, QString *converrorms
bool dvifile::saveAs(const QString &filename)
{
if (dvi_Data() == nullptr)
if (dvi_Data() == nullptr) {
return false;
}
QFile out(filename);
if (out.open(QIODevice::WriteOnly) == false)
if (out.open(QIODevice::WriteOnly) == false) {
return false;
if (out.write((char *)(dvi_Data()), size_of_file) == -1)
}
if (out.write((char *)(dvi_Data()), size_of_file) == -1) {
return false;
}
out.close();
return true;
}

View File

@ -132,8 +132,9 @@ void dviRenderer::drawPage(RenderedDocumentPagePixmap *page)
double resolution = page->resolution;
if (resolution != resolutionInDPI)
if (resolution != resolutionInDPI) {
setResolution(resolution);
}
currentlyDrawnPage = page;
shrinkfactor = 1200 / resolutionInDPI;
@ -169,8 +170,9 @@ void dviRenderer::drawPage(RenderedDocumentPagePixmap *page)
j = i;
j++;
if (j == page->hyperLinkList.end())
if (j == page->hyperLinkList.end()) {
break;
}
Hyperlink &hi = *i;
Hyperlink &hj = *j;
@ -183,8 +185,9 @@ void dviRenderer::drawPage(RenderedDocumentPagePixmap *page)
hi.box = hi.box.united(hj.box);
j++;
if (j == page->hyperLinkList.end())
if (j == page->hyperLinkList.end()) {
break;
}
hj = *j;
}
@ -282,15 +285,17 @@ void dviRenderer::embedPostScript()
qCDebug(OkularDviDebug) << "dviRenderer::embedPostScript()";
#endif
if (!dviFile)
if (!dviFile) {
return;
}
/* embedPS_progress = new QProgressDialog(parentWidget);
embedPS_progress->setWindowTitle(i18n("Embedding PostScript Files"));
embedPS_progress->setLabelText(QString());
*/
if (!embedPS_progress)
if (!embedPS_progress) {
return;
}
embedPS_progress->setCancelButton(nullptr);
embedPS_progress->setCancelButton(nullptr);
embedPS_progress->setMinimumDuration(400);
@ -304,8 +309,9 @@ void dviRenderer::embedPostScript()
if (current_page < dviFile->total_pages) {
command_pointer = dviFile->dvi_Data() + dviFile->page_offset[int(current_page)];
end_pointer = dviFile->dvi_Data() + dviFile->page_offset[int(current_page + 1)];
} else
} else {
command_pointer = end_pointer = nullptr;
}
memset((char *)&currinf.data, 0, sizeof(currinf.data));
currinf.fonttable = &(dviFile->tn_table);
@ -337,8 +343,9 @@ void dviRenderer::embedPostScript()
if (current_page < dviFile->total_pages) {
command_pointer = dviFile->dvi_Data() + dviFile->page_offset[int(current_page)];
end_pointer = dviFile->dvi_Data() + dviFile->page_offset[int(current_page + 1)];
} else
} else {
command_pointer = end_pointer = nullptr;
}
memset((char *)&currinf.data, 0, sizeof(currinf.data));
currinf.fonttable = &(dviFile->tn_table);
@ -346,8 +353,9 @@ void dviRenderer::embedPostScript()
prescan(&dviRenderer::prescan_parseSpecials);
if (!PostScriptOutPutString->isEmpty())
if (!PostScriptOutPutString->isEmpty()) {
PS_interface->setPostScript(current_page, *PostScriptOutPutString);
}
delete PostScriptOutPutString;
}
PostScriptOutPutString = nullptr;
@ -362,22 +370,26 @@ void dviRenderer::embedPostScript()
bool dviRenderer::isValidFile(const QString &filename) const
{
QFile f(filename);
if (!f.open(QIODevice::ReadOnly))
if (!f.open(QIODevice::ReadOnly)) {
return false;
}
unsigned char test[4];
if (f.read((char *)test, 2) < 2 || test[0] != 247 || test[1] != 2)
if (f.read((char *)test, 2) < 2 || test[0] != 247 || test[1] != 2) {
return false;
}
int n = f.size();
if (n < 134) // Too short for a dvi file
if (n < 134) { // Too short for a dvi file
return false;
}
f.seek(n - 4);
unsigned char trailer[4] = {0xdf, 0xdf, 0xdf, 0xdf};
if (f.read((char *)test, 4) < 4 || strncmp((char *)test, (char *)trailer, 4) != 0)
if (f.read((char *)test, 4) < 4 || strncmp((char *)test, (char *)trailer, 4) != 0) {
return false;
}
// We suppose now that the dvi file is complete and OK
return true;
}
@ -411,15 +423,17 @@ bool dviRenderer::setFile(const QString &fname, const QUrl &base)
QApplication::setOverrideCursor(Qt::WaitCursor);
dvifile *dviFile_new = new dvifile(filename, &font_pool);
if ((dviFile == nullptr) || (dviFile->filename != filename))
if ((dviFile == nullptr) || (dviFile->filename != filename)) {
dviFile_new->sourceSpecialMarker = true;
else
} else {
dviFile_new->sourceSpecialMarker = false;
}
if ((dviFile_new->dvi_Data() == nullptr) || (dviFile_new->errorMsg.isEmpty() != true)) {
QApplication::restoreOverrideCursor();
if (dviFile_new->errorMsg.isEmpty() != true)
if (dviFile_new->errorMsg.isEmpty() != true) {
emit error(i18n("File corruption. %1", dviFile_new->errorMsg), -1);
}
delete dviFile_new;
return false;
}
@ -456,17 +470,18 @@ bool dviRenderer::setFile(const QString &fname, const QUrl &base)
// bookmarks.clear();
prebookmarks.clear();
if (dviFile->page_offset.isEmpty() == true)
if (dviFile->page_offset.isEmpty() == true) {
return false;
}
// We should pre-scan the document now (to extract embedded,
// PostScript, Hyperlinks, ets).
// We should pre-scan the document now (to extract embedded,
// PostScript, Hyperlinks, ets).
// PRESCAN STARTS HERE
// PRESCAN STARTS HERE
#ifdef PERFORMANCE_MEASUREMENT
// qCDebug(OkularDviDebug) << "Time elapsed till prescan phase starts " << performanceTimer.elapsed() << "ms";
// QTime preScanTimer;
// preScanTimer.start();
// qCDebug(OkularDviDebug) << "Time elapsed till prescan phase starts " << performanceTimer.elapsed() << "ms";
// QTime preScanTimer;
// preScanTimer.start();
#endif
dviFile->numberOfExternalPSFiles = 0;
quint16 currPageSav = current_page;
@ -478,16 +493,18 @@ bool dviRenderer::setFile(const QString &fname, const QUrl &base)
if (current_page < dviFile->total_pages) {
command_pointer = dviFile->dvi_Data() + dviFile->page_offset[int(current_page)];
end_pointer = dviFile->dvi_Data() + dviFile->page_offset[int(current_page + 1)];
} else
} else {
command_pointer = end_pointer = nullptr;
}
memset((char *)&currinf.data, 0, sizeof(currinf.data));
currinf.fonttable = &(dviFile->tn_table);
currinf._virtual = nullptr;
prescan(&dviRenderer::prescan_parseSpecials);
if (!PostScriptOutPutString->isEmpty())
if (!PostScriptOutPutString->isEmpty()) {
PS_interface->setPostScript(current_page, *PostScriptOutPutString);
}
delete PostScriptOutPutString;
}
PostScriptOutPutString = nullptr;
@ -515,18 +532,21 @@ Anchor dviRenderer::parseReference(const QString &reference)
qCCritical(OkularDviDebug) << "dviRenderer::parseReference( " << reference << " ) called" << endl;
#endif
if (dviFile == nullptr)
if (dviFile == nullptr) {
return Anchor();
}
// case 1: The reference is a number, which we'll interpret as a
// page number.
bool ok;
int page = reference.toInt(&ok);
if (ok == true) {
if (page < 0)
if (page < 0) {
page = 0;
if (page > dviFile->total_pages)
}
if (page > dviFile->total_pages) {
page = dviFile->total_pages;
}
return Anchor(page, Length());
}
@ -568,24 +588,27 @@ Anchor dviRenderer::parseReference(const QString &reference)
QVector<DVI_SourceFileAnchor>::iterator bestMatch = sourceHyperLinkAnchors.end();
QVector<DVI_SourceFileAnchor>::iterator it;
for (it = sourceHyperLinkAnchors.begin(); it != sourceHyperLinkAnchors.end(); ++it)
for (it = sourceHyperLinkAnchors.begin(); it != sourceHyperLinkAnchors.end(); ++it) {
if (refFileName.trimmed() == it->fileName.trimmed() || refFileName.trimmed() == it->fileName.trimmed() + QStringLiteral(".tex")) {
anchorForRefFileFound = true;
if ((it->line <= refLineNumber) && ((bestMatch == sourceHyperLinkAnchors.end()) || (it->line > bestMatch->line)))
if ((it->line <= refLineNumber) && ((bestMatch == sourceHyperLinkAnchors.end()) || (it->line > bestMatch->line))) {
bestMatch = it;
}
}
}
if (bestMatch != sourceHyperLinkAnchors.end())
if (bestMatch != sourceHyperLinkAnchors.end()) {
return Anchor(bestMatch->page, bestMatch->distance_from_top);
else if (anchorForRefFileFound == false) {
} else if (anchorForRefFileFound == false) {
emit warning(i18n("Okular was not able to locate the place in the DVI file which corresponds to "
"line %1 in the TeX-file %2.",
refLineNumber,
refFileName),
-1);
} else
} else {
return Anchor();
}
return Anchor();
}
return Anchor();
@ -597,8 +620,9 @@ void dviRenderer::setResolution(double resolution_in_DPI)
// hardly be visible anyway. That saves a lot of re-painting,
// e.g. when the user resizes the window, and a flickery mouse
// changes the window size by 1 pixel all the time.
if (fabs(resolutionInDPI - resolution_in_DPI) < 1)
if (fabs(resolutionInDPI - resolution_in_DPI) < 1) {
return;
}
resolutionInDPI = resolution_in_DPI;
@ -659,8 +683,9 @@ void dviRenderer::exportPDF()
void dviRenderer::exportPS(const QString &fname, const QStringList &options, QPrinter *printer, QPrinter::Orientation orientation)
{
QExplicitlySharedDataPointer<DVIExport> exporter(new DVIExportToPS(*this, fname, options, printer, font_pool.getUseFontHints(), orientation));
if (exporter->started())
if (exporter->started()) {
all_exports_[exporter.data()] = exporter;
}
}
/*
@ -674,8 +699,9 @@ void dviRenderer::export_finished(const DVIExport *key)
{
typedef QMap<const DVIExport *, QExplicitlySharedDataPointer<DVIExport>> ExportMap;
ExportMap::iterator it = all_exports_.find(key);
if (it != all_exports_.end())
if (it != all_exports_.end()) {
all_exports_.remove(key);
}
}
void dviRenderer::setEventLoop(QEventLoop *el)
@ -683,6 +709,7 @@ void dviRenderer::setEventLoop(QEventLoop *el)
if (el == nullptr) {
delete m_eventLoop;
m_eventLoop = nullptr;
} else
} else {
m_eventLoop = el;
}
}

View File

@ -21,13 +21,16 @@ SimplePageSize dviRenderer::sizeOfPage(const PageNumber page)
// QMutexLocker locker(&mutex);
#endif
if (!page.isValid())
if (!page.isValid()) {
return SimplePageSize();
if (page > totalPages())
}
if (page > totalPages()) {
return SimplePageSize();
}
const quint16 pageNumber = static_cast<quint16>(page);
if (pageNumber > pageSizes.size())
if (pageNumber > pageSizes.size()) {
return SimplePageSize();
}
return pageSizes[pageNumber - 1];
}
@ -35,10 +38,11 @@ SimplePageSize dviRenderer::sizeOfPage(const PageNumber page)
Anchor dviRenderer::findAnchor(const QString &locallink)
{
QMap<QString, Anchor>::Iterator it = anchorList.find(locallink);
if (it != anchorList.end())
if (it != anchorList.end()) {
return *it;
else
} else {
return Anchor();
}
}
PageNumber dviRenderer::totalPages() const

View File

@ -60,12 +60,14 @@ void dviRenderer::set_char(unsigned int cmd, unsigned int ch)
#endif
glyph *g;
if (colorStack.isEmpty())
if (colorStack.isEmpty()) {
g = ((TeXFont *)(currinf.fontp->font))->getGlyph(ch, true, globalColor);
else
} else {
g = ((TeXFont *)(currinf.fontp->font))->getGlyph(ch, true, colorStack.top());
if (g == nullptr)
}
if (g == nullptr) {
return;
}
long dvi_h_sav = currinf.data.dvi_h;
@ -107,10 +109,11 @@ void dviRenderer::set_char(unsigned int cmd, unsigned int ch)
Hyperlink dhl;
dhl.baseline = currinf.data.pxl_v;
dhl.box.setRect(x, y, pix.width(), pix.height());
if (source_href != nullptr)
if (source_href != nullptr) {
dhl.linkText = *source_href;
else
} else {
dhl.linkText = QLatin1String("");
}
currentDVIPage->sourceHyperLinkList.push_back(dhl);
} else {
QRect dshunion = currentDVIPage->sourceHyperLinkList[currentDVIPage->sourceHyperLinkList.size() - 1].box.united(QRect(x, y, pix.width(), pix.height()));
@ -159,17 +162,19 @@ void dviRenderer::set_char(unsigned int cmd, unsigned int ch)
break;
default:
if ((ch >= 0x21) && (ch <= 0x7a))
if ((ch >= 0x21) && (ch <= 0x7a)) {
currentlyDrawnPage->textBoxList[currentlyDrawnPage->textBoxList.size() - 1].text += QChar(ch);
else
} else {
currentlyDrawnPage->textBoxList[currentlyDrawnPage->textBoxList.size() - 1].text += QLatin1Char('?');
}
break;
}
if (cmd == PUT1)
if (cmd == PUT1) {
currinf.data.dvi_h = dvi_h_sav;
else
} else {
currinf.data.dvi_h += (int)(currinf.fontp->scaled_size_in_DVI_units * dviFile->getCmPerDVIunit() * (1200.0 / 2.54) / 16.0 * g->dvi_advance_in_units_of_design_size_by_2e20 + 0.5);
}
word_boundary_encountered = false;
line_boundary_encountered = false;
@ -213,10 +218,11 @@ void dviRenderer::set_vf_char(unsigned int cmd, unsigned int ch)
end_pointer = end_ptr_sav;
currinf = oldinfo;
if (cmd == PUT1)
if (cmd == PUT1) {
currinf.data.dvi_h = dvi_h_sav;
else
} else {
currinf.data.dvi_h += (int)(currinf.fontp->scaled_size_in_DVI_units * dviFile->getCmPerDVIunit() * (1200.0 / 2.54) / 16.0 * m->dvi_advance_in_units_of_design_size_by_2e20 + 0.5);
}
}
void dviRenderer::set_no_char(unsigned int cmd, unsigned int ch)
@ -288,10 +294,11 @@ void dviRenderer::draw_part(double current_dimconv, bool is_vfmacro)
int h = ((int)ROUNDUP(((long)(a * current_dimconv)), shrinkfactor * 65536));
int w = ((int)ROUNDUP(b, shrinkfactor * 65536));
if (colorStack.isEmpty())
if (colorStack.isEmpty()) {
foreGroundPainter->fillRect(((int)((currinf.data.dvi_h) / (shrinkfactor * 65536))), currinf.data.pxl_v - h + 1, w ? w : 1, h ? h : 1, globalColor);
else
} else {
foreGroundPainter->fillRect(((int)((currinf.data.dvi_h) / (shrinkfactor * 65536))), currinf.data.pxl_v - h + 1, w ? w : 1, h ? h : 1, colorStack.top());
}
}
currinf.data.dvi_h += b;
break;
@ -308,10 +315,11 @@ void dviRenderer::draw_part(double current_dimconv, bool is_vfmacro)
if (a > 0 && b > 0) {
int h = ((int)ROUNDUP(a, shrinkfactor * 65536));
int w = ((int)ROUNDUP(b, shrinkfactor * 65536));
if (colorStack.isEmpty())
if (colorStack.isEmpty()) {
foreGroundPainter->fillRect(((int)((currinf.data.dvi_h) / (shrinkfactor * 65536))), currinf.data.pxl_v - h + 1, w ? w : 1, h ? h : 1, globalColor);
else
} else {
foreGroundPainter->fillRect(((int)((currinf.data.dvi_h) / (shrinkfactor * 65536))), currinf.data.pxl_v - h + 1, w ? w : 1, h ? h : 1, colorStack.top());
}
}
break;
@ -356,8 +364,9 @@ void dviRenderer::draw_part(double current_dimconv, bool is_vfmacro)
if (stack.isEmpty()) {
errorMsg = i18n("The stack was empty when a POP command was encountered.");
return;
} else
} else {
currinf.data = stack.pop();
}
word_boundary_encountered = true;
line_boundary_encountered = true;
break;
@ -424,8 +433,9 @@ void dviRenderer::draw_part(double current_dimconv, bool is_vfmacro)
word_boundary_encountered = true;
line_boundary_encountered = true;
space_encountered = true;
if (abs(DDtmp) >= 10 * (currinf.fontp->scaled_size_in_DVI_units / 6))
if (abs(DDtmp) >= 10 * (currinf.fontp->scaled_size_in_DVI_units / 6)) {
currentlyDrawnPage->textBoxList[currentlyDrawnPage->textBoxList.size() - 1].text += QLatin1Char('\n');
}
}
currinf.data.dvi_v += ((long)(DDtmp * current_dimconv)) / 65536;
currinf.data.pxl_v = int(currinf.data.dvi_v / shrinkfactor);
@ -443,8 +453,9 @@ void dviRenderer::draw_part(double current_dimconv, bool is_vfmacro)
word_boundary_encountered = true;
line_boundary_encountered = true;
space_encountered = true;
if (abs(YYtmp) >= 10 * (currinf.fontp->scaled_size_in_DVI_units / 6))
if (abs(YYtmp) >= 10 * (currinf.fontp->scaled_size_in_DVI_units / 6)) {
currentlyDrawnPage->textBoxList[currentlyDrawnPage->textBoxList.size() - 1].text += QLatin1Char('\n');
}
}
currinf.data.dvi_v += currinf.data.y / 65536;
currinf.data.pxl_v = int(currinf.data.dvi_v / shrinkfactor);
@ -462,8 +473,9 @@ void dviRenderer::draw_part(double current_dimconv, bool is_vfmacro)
word_boundary_encountered = true;
line_boundary_encountered = true;
space_encountered = true;
if (abs(ZZtmp) >= 10 * (currinf.fontp->scaled_size_in_DVI_units / 6))
if (abs(ZZtmp) >= 10 * (currinf.fontp->scaled_size_in_DVI_units / 6)) {
currentlyDrawnPage->textBoxList[currentlyDrawnPage->textBoxList.size() - 1].text += QLatin1Char('\n');
}
}
currinf.data.dvi_v += currinf.data.z / 65536;
currinf.data.pxl_v = int(currinf.data.dvi_v / shrinkfactor);
@ -542,8 +554,9 @@ void dviRenderer::draw_part(double current_dimconv, bool is_vfmacro)
/* heuristic to properly detect newlines; a space is needed */
if (after_space && line_boundary_encountered && word_boundary_encountered) {
if (currentlyDrawnPage->textBoxList.last().text.endsWith(QLatin1Char('\n')))
if (currentlyDrawnPage->textBoxList.last().text.endsWith(QLatin1Char('\n'))) {
currentlyDrawnPage->textBoxList.last().text.chop(1);
}
currentlyDrawnPage->textBoxList.last().text += QLatin1String(" \n");
after_space = false;
}
@ -608,13 +621,15 @@ void dviRenderer::draw_page()
}
// Now really write the text
if (dviFile->page_offset.isEmpty() == true)
if (dviFile->page_offset.isEmpty() == true) {
return;
}
if (current_page < dviFile->total_pages) {
command_pointer = dviFile->dvi_Data() + dviFile->page_offset[int(current_page)];
end_pointer = dviFile->dvi_Data() + dviFile->page_offset[int(current_page + 1)];
} else
} else {
command_pointer = end_pointer = nullptr;
}
memset((char *)&currinf.data, 0, sizeof(currinf.data));
currinf.fonttable = &(dviFile->tn_table);

View File

@ -43,8 +43,9 @@ void dviRenderer::prescan_embedPS(char *cp, quint8 *beginningOfSpecialCommand)
#endif
// Encapsulated Postscript File
if (qstrnicmp(cp, "PSfile=", 7) != 0)
if (qstrnicmp(cp, "PSfile=", 7) != 0) {
return;
}
QString command = QString::fromLocal8Bit(cp + 7);
@ -62,8 +63,9 @@ void dviRenderer::prescan_embedPS(char *cp, quint8 *beginningOfSpecialCommand)
// macro packages (but not by others). This probably means that
// graphic files are no longer found if the filename really does
// contain quotes, but we don't really care that much.
if ((EPSfilename.at(0) == QLatin1Char('"')) && (EPSfilename.at(EPSfilename.length() - 1) == QLatin1Char('"')))
if ((EPSfilename.at(0) == QLatin1Char('"')) && (EPSfilename.at(EPSfilename.length() - 1) == QLatin1Char('"'))) {
EPSfilename = EPSfilename.mid(1, EPSfilename.length() - 2);
}
// Now locate the Gfx file on the hard disk...
EPSfilename = ghostscript_interface::locateEPSfile(EPSfilename, baseURL);
@ -76,8 +78,9 @@ void dviRenderer::prescan_embedPS(char *cp, quint8 *beginningOfSpecialCommand)
bool const is_ps_file = (mime_type_name == QLatin1String("application/postscript") || mime_type_name == QLatin1String("image/x-eps"));
bool const is_pdf_file = (!is_ps_file && mime_type_name == QLatin1String("application/pdf"));
if (!(is_ps_file || is_pdf_file))
if (!(is_ps_file || is_pdf_file)) {
return;
}
QString originalFName = EPSfilename;
@ -85,20 +88,24 @@ void dviRenderer::prescan_embedPS(char *cp, quint8 *beginningOfSpecialCommand)
qApp->processEvents();
// If the EPSfilename really points to a PDF file, convert that file now.
if (is_pdf_file)
if (is_pdf_file) {
EPSfilename = dviFile->convertPDFtoPS(EPSfilename);
}
if (!QFile::exists(EPSfilename)) {
// Find the number of the page
quint32 currentOffset = beginningOfSpecialCommand - dviFile->dvi_Data();
int page = 0;
for (; page < dviFile->total_pages; page++)
if ((dviFile->page_offset[page] <= currentOffset) && (currentOffset <= dviFile->page_offset[page + 1]))
for (; page < dviFile->total_pages; page++) {
if ((dviFile->page_offset[page] <= currentOffset) && (currentOffset <= dviFile->page_offset[page + 1])) {
break;
if (is_pdf_file)
}
}
if (is_pdf_file) {
errorMsg += i18n("Page %1: The PDF file <strong>%2</strong> could not be converted to PostScript.<br>", page + 1, originalFName);
else
} else {
errorMsg += i18n("Page %1: The PostScript file <strong>%2</strong> could not be found.<br>", page + 1, originalFName);
}
embedPS_progress->setValue(embedPS_progress->value() + 1);
qApp->processEvents();
return;
@ -128,14 +135,18 @@ void dviRenderer::prescan_embedPS(char *cp, quint8 *beginningOfSpecialCommand)
// Generate the PostScript commands to be included
QString PS = QStringLiteral("ps: @beginspecial %1 @llx %2 @lly %3 @urx %4 @ury").arg(llx).arg(lly).arg(urx).arg(ury);
if (rwi != 0)
if (rwi != 0) {
PS.append(QStringLiteral(" %1 @rwi").arg(rwi));
if (rhi != 0)
}
if (rhi != 0) {
PS.append(QStringLiteral(" %1 @rhi").arg(rhi));
if (angle != 0)
}
if (angle != 0) {
PS.append(QStringLiteral(" %1 @angle").arg(angle));
if (clip != -1)
}
if (clip != -1) {
PS.append(QStringLiteral(" @clip"));
}
PS.append(QStringLiteral(" @setspecial\n"));
QFile file(EPSfilename);
@ -197,8 +208,9 @@ void dviRenderer::prescan_embedPS(char *cp, quint8 *beginningOfSpecialCommand)
}
command_pointer = newDVI.data() + dviFile->size_of_file - 1;
while ((*command_pointer == TRAILER) && (command_pointer > newDVI.data()))
while ((*command_pointer == TRAILER) && (command_pointer > newDVI.data())) {
command_pointer--;
}
command_pointer -= 4;
writeUINT32(dviFile->beginning_of_postamble);
command_pointer -= 4;
@ -224,11 +236,13 @@ void dviRenderer::prescan_removePageSizeInfo(char *cp, quint8 *beginningOfSpecia
#endif
// Encapsulated Postscript File
if (qstrnicmp(cp, "papersize=", 10) != 0)
if (qstrnicmp(cp, "papersize=", 10) != 0) {
return;
}
for (quint8 *ptr = beginningOfSpecialCommand; ptr < command_pointer; ptr++)
for (quint8 *ptr = beginningOfSpecialCommand; ptr < command_pointer; ptr++) {
*ptr = NOP;
}
}
void dviRenderer::prescan_ParsePapersizeSpecial(const QString &_cp)
@ -243,8 +257,9 @@ void dviRenderer::prescan_ParsePapersizeSpecial(const QString &_cp)
cp = cp.mid(1);
dviFile->suggestedPageSize = new pageSize;
dviFile->suggestedPageSize->setPageSize(cp);
} else
} else {
printErrorMsgForSpecials(i18n("The papersize data '%1' could not be parsed.", cp));
}
return;
}
@ -252,9 +267,11 @@ void dviRenderer::prescan_ParsePapersizeSpecial(const QString &_cp)
void dviRenderer::prescan_ParseBackgroundSpecial(const QString &cp)
{
QColor col = parseColorSpecification(cp.trimmed());
if (col.isValid())
for (quint16 page = current_page; page < dviFile->total_pages; page++)
if (col.isValid()) {
for (quint16 page = current_page; page < dviFile->total_pages; page++) {
PS_interface->setBackgroundColor(page, col);
}
}
return;
}
@ -290,8 +307,9 @@ void dviRenderer::prescan_ParsePSHeaderSpecial(const QString &cp)
}
}
if (QFile::exists(_file))
if (QFile::exists(_file)) {
PS_interface->PostScriptHeaderString->append(QStringLiteral(" (%1) run\n").arg(_file));
}
}
void dviRenderer::prescan_ParsePSBangSpecial(const QString &cp)
@ -335,16 +353,21 @@ void dviRenderer::prescan_ParsePSSpecial(const QString &cp)
if (cp.startsWith(QLatin1String("ps:SDict begin"))) {
// We suspect this may be hyperref generated nonsense. Let's check
// for some known code that hyperref generates.
if (cp == QLatin1String("ps:SDict begin H.S end"))
if (cp == QLatin1String("ps:SDict begin H.S end")) {
return; // start of hyperref rectangle
if (cp == QLatin1String("ps:SDict begin H.R end"))
}
if (cp == QLatin1String("ps:SDict begin H.R end")) {
return; // end of hyperref rectangle
if (cp.endsWith(QLatin1String("H.A end")))
}
if (cp.endsWith(QLatin1String("H.A end"))) {
return; // end of hyperref anchor
if (cp.endsWith(QLatin1String("H.L end")))
}
if (cp.endsWith(QLatin1String("H.L end"))) {
return; // end of hyperref link
if (cp.startsWith(QLatin1String("ps:SDict begin /product where{pop product(Distiller)")))
return; // hyperref tries to work around Distiller bug
}
if (cp.startsWith(QLatin1String("ps:SDict begin /product where{pop product(Distiller)"))) {
return; // hyperref tries to work around Distiller bug
}
if (cp.startsWith(QLatin1String("ps:SDict begin [")) && cp.endsWith(QLatin1String(" pdfmark end"))) { // hyperref definition of link/anchor/bookmark/etc
if (cp.contains(QStringLiteral("/DEST"))) { // The PostScript code defines an anchor
QString anchorName = cp.section(QLatin1Char('('), 1, 1).section(QLatin1Char(')'), 0, 0);
@ -357,10 +380,11 @@ void dviRenderer::prescan_ParsePSSpecial(const QString &cp)
const QString childrenNumberAndMoreStuff = cp.section(QLatin1Char('-'), 1, 1); // Contains from the - symbol to the end of cp, effectively containing the number of children and some stuff after it
int indexOfFirstNonDigit = 0;
for (const QChar &c : childrenNumberAndMoreStuff) {
if (c.isDigit())
if (c.isDigit()) {
++indexOfFirstNonDigit;
else
} else {
break;
}
}
prebookmarks.append(PreBookmark(PDFencodingToQString(cp.section(QLatin1Char('('), 2, 2).section(QLatin1Char(')'), 0, 0)),
cp.section(QLatin1Char('('), 1, 1).section(QLatin1Char(')'), 0, 0),
@ -469,14 +493,18 @@ void dviRenderer::prescan_ParsePSFileSpecial(const QString &cp)
PostScriptOutPutString->append(QStringLiteral(" %1 @lly").arg(lly));
PostScriptOutPutString->append(QStringLiteral(" %1 @urx").arg(urx));
PostScriptOutPutString->append(QStringLiteral(" %1 @ury").arg(ury));
if (rwi != 0)
if (rwi != 0) {
PostScriptOutPutString->append(QStringLiteral(" %1 @rwi").arg(rwi));
if (rhi != 0)
}
if (rhi != 0) {
PostScriptOutPutString->append(QStringLiteral(" %1 @rhi").arg(rhi));
if (angle != 0)
}
if (angle != 0) {
PostScriptOutPutString->append(QStringLiteral(" %1 @angle").arg(angle));
if (clip != -1)
}
if (clip != -1) {
PostScriptOutPutString->append(QStringLiteral(" @clip"));
}
PostScriptOutPutString->append(QStringLiteral(" @setspecial \n"));
PostScriptOutPutString->append(QStringLiteral(" (%1) run\n").arg(EPSfilename));
PostScriptOutPutString->append(QStringLiteral("@endspecial \n"));
@ -494,9 +522,11 @@ void dviRenderer::prescan_ParseSourceSpecial(const QString &cp)
// extract the file name and the numeral part from the string
qint32 j;
for (j = 0; j < cp.length(); j++)
if (!cp.at(j).isNumber())
for (j = 0; j < cp.length(); j++) {
if (!cp.at(j).isNumber()) {
break;
}
}
quint32 sourceLineNumber = cp.leftRef(j).toUInt();
QFileInfo fi1(dviFile->filename);
QString sourceFileName = QFileInfo(fi1.dir(), cp.mid(j).trimmed()).absoluteFilePath();
@ -582,21 +612,24 @@ void dviRenderer::prescan_parseSpecials(char *cp, quint8 *)
void dviRenderer::prescan_setChar(unsigned int ch)
{
TeXFontDefinition *fontp = currinf.fontp;
if (fontp == nullptr)
if (fontp == nullptr) {
return;
}
if (currinf.set_char_p == &dviRenderer::set_char) {
glyph *g = ((TeXFont *)(currinf.fontp->font))->getGlyph(ch, true, globalColor);
if (g == nullptr)
if (g == nullptr) {
return;
}
currinf.data.dvi_h += (int)(currinf.fontp->scaled_size_in_DVI_units * dviFile->getCmPerDVIunit() * (1200.0 / 2.54) / 16.0 * g->dvi_advance_in_units_of_design_size_by_2e20 + 0.5);
return;
}
if (currinf.set_char_p == &dviRenderer::set_vf_char) {
macro *m = &currinf.fontp->macrotable[ch];
if (m->pos == nullptr)
if (m->pos == nullptr) {
return;
}
currinf.data.dvi_h += (int)(currinf.fontp->scaled_size_in_DVI_units * dviFile->getCmPerDVIunit() * (1200.0 / 2.54) / 16.0 * m->dvi_advance_in_units_of_design_size_by_2e20 + 0.5);
return;
}
@ -608,8 +641,9 @@ void dviRenderer::prescan(parseSpecials specialParser)
qCDebug(OkularDviDebug) << "dviRenderer::prescan( ... )";
#endif
if (resolutionInDPI == 0.0)
if (resolutionInDPI == 0.0) {
setResolution(100);
}
qint32 RRtmp = 0, WWtmp = 0, XXtmp = 0, YYtmp = 0, ZZtmp = 0;
quint8 ch;
@ -676,10 +710,11 @@ void dviRenderer::prescan(parseSpecials specialParser)
break;
case POP:
if (stack.isEmpty())
if (stack.isEmpty()) {
return;
else
} else {
currinf.data = stack.pop();
}
break;
case RIGHT1:
@ -750,8 +785,9 @@ void dviRenderer::prescan(parseSpecials specialParser)
case FNT3:
case FNT4:
currinf.fontp = currinf.fonttable->value(readUINT(ch - FNT1 + 1));
if (currinf.fontp == nullptr)
if (currinf.fontp == nullptr) {
return;
}
currinf.set_char_p = currinf.fontp->set_char_p;
break;

View File

@ -62,19 +62,22 @@ void DVIExport::start(const QString &command, const QStringList &args, const QSt
*process_ << command << args;
if (!working_directory.isEmpty())
if (!working_directory.isEmpty()) {
process_->setWorkingDirectory(working_directory);
}
error_message_ = error_message;
process_->start();
if (!process_->waitForStarted(-1))
if (!process_->waitForStarted(-1)) {
qCCritical(OkularDviDebug) << command << " failed to start" << endl;
else
} else {
started_ = true;
}
if (parent_->m_eventLoop)
if (parent_->m_eventLoop) {
parent_->m_eventLoop->exec();
}
}
void DVIExport::abort_process_impl()
@ -87,8 +90,9 @@ void DVIExport::abort_process_impl()
void DVIExport::finished_impl(int exit_code)
{
if (process_ && exit_code != 0)
if (process_ && exit_code != 0) {
emit error(error_message_, -1);
}
// Remove this from the store of all export processes.
parent_->m_eventLoop->exit(exit_code);
parent_->export_finished(this);
@ -105,13 +109,15 @@ DVIExportToPDF::DVIExportToPDF(dviRenderer &parent, const QString &output_name)
: DVIExport(parent)
{
// Neither of these should happen. Paranoia checks.
if (!parent.dviFile)
if (!parent.dviFile) {
return;
}
const dvifile &dvi = *(parent.dviFile);
const QFileInfo input(dvi.filename);
if (!input.exists() || !input.isReadable())
if (!input.exists() || !input.isReadable()) {
return;
}
if (QStandardPaths::findExecutable(QStringLiteral("dvipdfm")).isEmpty()) {
emit error(i18n("<qt><p>Okular could not locate the program <em>dvipdfm</em> on your computer. This program is "
@ -126,8 +132,9 @@ DVIExportToPDF::DVIExportToPDF(dviRenderer &parent, const QString &output_name)
return;
}
if (output_name.isEmpty())
if (output_name.isEmpty()) {
return;
}
start(QStringLiteral("dvipdfm"),
QStringList() << QStringLiteral("-o") << output_name << dvi.filename,
@ -143,16 +150,19 @@ DVIExportToPS::DVIExportToPS(dviRenderer &parent, const QString &output_name, co
, orientation_(orientation)
{
// None of these should happen. Paranoia checks.
if (!parent.dviFile)
if (!parent.dviFile) {
return;
}
const dvifile &dvi = *(parent.dviFile);
const QFileInfo input(dvi.filename);
if (!input.exists() || !input.isReadable())
if (!input.exists() || !input.isReadable()) {
return;
}
if (dvi.page_offset.isEmpty())
if (dvi.page_offset.isEmpty()) {
return;
}
if (dvi.numberOfExternalNONPSFiles != 0) {
emit error(i18n("<qt>This DVI file refers to external graphic files which are not in PostScript format, and cannot be handled by the "
@ -171,8 +181,9 @@ DVIExportToPS::DVIExportToPS(dviRenderer &parent, const QString &output_name, co
return;
}
if (output_name.isEmpty())
if (output_name.isEmpty()) {
return;
}
output_name_ = output_name;
@ -242,12 +253,14 @@ DVIExportToPS::DVIExportToPS(dviRenderer &parent, const QString &output_name, co
}
QStringList args;
if (!printer)
if (!printer) {
// Export hyperlinks
args << QStringLiteral("-z");
}
if (!options.isEmpty())
if (!options.isEmpty()) {
args += options;
}
args << input_name << QStringLiteral("-o") << output_name_;

View File

@ -29,20 +29,24 @@ DVI_SourceFileSplitter::DVI_SourceFileSplitter(const QString &srclink, const QSt
#endif
// remove src: if necessary
if (filepart.left(4) == QLatin1String("src:"))
if (filepart.left(4) == QLatin1String("src:")) {
filepart = srclink.mid(4);
}
// split first
quint32 max = filepart.length(), i = 0;
for (i = 0; i < max; ++i)
if (!filepart[i].isDigit())
for (i = 0; i < max; ++i) {
if (!filepart[i].isDigit()) {
break;
}
}
linepart = filepart.left(i);
filepart = filepart.mid(i);
// check for number mix up
if (filepart[0] != QLatin1Char(' ') && (linepart.length() != 1))
if (filepart[0] != QLatin1Char(' ') && (linepart.length() != 1)) {
possibleNumberMixUp = true;
}
// remove a spaces
filepart = filepart.trimmed();
@ -57,8 +61,9 @@ DVI_SourceFileSplitter::DVI_SourceFileSplitter(const QString &srclink, const QSt
bool fiExists = m_fileInfo.exists();
// if it doesn't exist, but adding ".tex"
if (!fiExists && QFileInfo::exists(m_fileInfo.absoluteFilePath() + QStringLiteral(".tex")))
if (!fiExists && QFileInfo::exists(m_fileInfo.absoluteFilePath() + QStringLiteral(".tex"))) {
m_fileInfo.setFile(m_fileInfo.absoluteFilePath() + QStringLiteral(".tex"));
}
// if that doesn't help either, perhaps the file started with a
// number: move the numbers from the sourceline to the filename
@ -95,8 +100,9 @@ DVI_SourceFileSplitter::DVI_SourceFileSplitter(const QString &srclink, const QSt
bool ok;
m_line = linepart.toInt(&ok);
if (!ok)
if (!ok) {
m_line = 0;
}
#ifdef DEBUG_SOURCESPLITTER
qCDebug(OkularDviDebug) << "DVI_SourceSplitter: result: file " << m_fileInfo.absoluteFilePath() << " line " << m_line;

View File

@ -65,8 +65,9 @@ fontEncoding::fontEncoding(const QString &encName)
// 'fileContent'
QTextStream stream(&file);
QString fileContent;
while (!stream.atEnd())
while (!stream.atEnd()) {
fileContent += stream.readLine().section(QLatin1Char('%'), 0, 0); // line of text excluding '\n' until first '%'-sign
}
file.close();
fileContent = fileContent.trimmed();
@ -88,8 +89,9 @@ fontEncoding::fontEncoding(const QString &encName)
#endif
i++;
}
for (; i < 256; i++)
for (; i < 256; i++) {
glyphNameVector[i] = QStringLiteral(".notdef");
}
} else {
qCCritical(OkularDviDebug) << QStringLiteral("fontEncoding::fontEncoding(...): The file '%1' could not be opened.").arg(encFileName) << endl;
return;

View File

@ -27,9 +27,9 @@ fontEncoding *fontEncodingPool::findByName(const QString &name)
if (ptr == nullptr) {
ptr = new fontEncoding(name);
if (ptr->isValid())
if (ptr->isValid()) {
dictionary.insert(name, ptr);
else {
} else {
delete ptr;
ptr = nullptr;
}

View File

@ -75,8 +75,9 @@ fontMap::fontMap()
QString line;
while (!stream.atEnd()) {
line = stream.readLine().simplified();
if (line.isEmpty() || (line.at(0) == QLatin1Char('%')))
if (line.isEmpty() || (line.at(0) == QLatin1Char('%'))) {
continue;
}
QString TeXName = line.section(QLatin1Char(' '), 0, 0);
QString FullName = line.section(QLatin1Char(' '), 1, 1);
@ -84,16 +85,18 @@ fontMap::fontMap()
QString encodingName = line.section(QLatin1Char('<'), -2, -2).trimmed().section(QLatin1Char(' '), 0, 0);
// It seems that sometimes the encoding is prepended by the
// letter '[', which we ignore
if ((!encodingName.isEmpty()) && (encodingName[0] == QLatin1Char('[')))
if ((!encodingName.isEmpty()) && (encodingName[0] == QLatin1Char('['))) {
encodingName = encodingName.mid(1);
}
double slant = 0.0;
int i = line.indexOf(QStringLiteral("SlantFont"));
if (i >= 0) {
bool ok;
slant = line.left(i).section(QLatin1Char(' '), -1, -1, QString::SectionSkipEmpty).toDouble(&ok);
if (ok == false)
if (ok == false) {
slant = 0.0;
}
}
fontMapEntry &entry = fontMapEntries[TeXName];
@ -101,14 +104,16 @@ fontMap::fontMap()
entry.slant = slant;
entry.fontFileName = fontFileName;
entry.fullFontName = FullName;
if (encodingName.endsWith(QLatin1String(".enc")))
if (encodingName.endsWith(QLatin1String(".enc"))) {
entry.fontEncoding = encodingName;
else
} else {
entry.fontEncoding.clear();
}
}
file.close();
} else
} else {
qCCritical(OkularDviDebug) << QStringLiteral("fontMap::fontMap(): The file '%1' could not be opened.").arg(map_fileName) << endl;
}
#ifdef DEBUG_FONTMAP
qCDebug(OkularDviDebug) << "FontMap file parsed. Results:";
@ -123,8 +128,9 @@ const QString &fontMap::findFileName(const QString &TeXName)
{
QMap<QString, fontMapEntry>::Iterator it = fontMapEntries.find(TeXName);
if (it != fontMapEntries.end())
if (it != fontMapEntries.end()) {
return it.value().fontFileName;
}
static const QString nullstring;
return nullstring;
@ -134,8 +140,9 @@ const QString &fontMap::findFontName(const QString &TeXName)
{
QMap<QString, fontMapEntry>::Iterator it = fontMapEntries.find(TeXName);
if (it != fontMapEntries.end())
if (it != fontMapEntries.end()) {
return it.value().fullFontName;
}
static const QString nullstring;
return nullstring;
@ -145,8 +152,9 @@ const QString &fontMap::findEncoding(const QString &TeXName)
{
QMap<QString, fontMapEntry>::Iterator it = fontMapEntries.find(TeXName);
if (it != fontMapEntries.end())
if (it != fontMapEntries.end()) {
return it.value().fontEncoding;
}
static const QString nullstring;
return nullstring;
@ -156,10 +164,11 @@ double fontMap::findSlant(const QString &TeXName)
{
QMap<QString, fontMapEntry>::Iterator it = fontMapEntries.find(TeXName);
if (it != fontMapEntries.end())
if (it != fontMapEntries.end()) {
return it.value().slant;
else
} else {
return 0.0;
}
}
#endif // HAVE_FREETYPE

View File

@ -51,8 +51,9 @@ fontPool::fontPool(bool useFontHinting)
if (FT_Init_FreeType(&FreeType_library) != 0) {
qCCritical(OkularDviDebug) << "Cannot load the FreeType library. KDVI proceeds without FreeType support." << endl;
FreeType_could_be_loaded = false;
} else
} else {
FreeType_could_be_loaded = true;
}
#endif
// Check if the QT library supports the alpha channel of
@ -96,8 +97,9 @@ fontPool::~fontPool()
fontList.clear();
#ifdef HAVE_FREETYPE
if (FreeType_could_be_loaded == true)
if (FreeType_could_be_loaded == true) {
FT_Done_FreeType(FreeType_library);
}
#endif
}
@ -161,8 +163,9 @@ bool fontPool::areFontsLocated()
QList<TeXFontDefinition *>::const_iterator cit_fontp = fontList.constBegin();
for (; cit_fontp != fontList.constEnd(); ++cit_fontp) {
TeXFontDefinition *fontp = *cit_fontp;
if (!fontp->isLocated())
if (!fontp->isLocated()) {
return false;
}
}
#ifdef DEBUG_FONTPOOL
@ -187,14 +190,16 @@ void fontPool::locateFonts()
// If still not all fonts are found, look again, this time with
// on-demand generation of PK fonts enabled.
if (!areFontsLocated())
if (!areFontsLocated()) {
locateFonts(true, false);
}
// If still not all fonts are found, we look for TFM files as a last
// resort, so that we can at least draw filled rectangles for
// characters.
if (!areFontsLocated())
if (!areFontsLocated()) {
locateFonts(false, true);
}
// If still not all fonts are found, we give up. We mark all fonts
// as 'located', so that we won't look for them any more, and
@ -241,14 +246,15 @@ void fontPool::locateFonts(bool makePK, bool locateTFMonly, bool *virtualFontsFo
if (!fontp->isLocated()) {
numFontsInJob++;
if (locateTFMonly == true)
if (locateTFMonly == true) {
kpsewhich_args << QStringLiteral("%1.tfm").arg(fontp->fontname);
else {
} else {
#ifdef HAVE_FREETYPE
if (FreeType_could_be_loaded == true) {
const QString &filename = fontsByTeXName.findFileName(fontp->fontname);
if (!filename.isEmpty())
if (!filename.isEmpty()) {
kpsewhich_args << QStringLiteral("%1").arg(filename);
}
}
#endif
kpsewhich_args << QStringLiteral("%1.vf").arg(fontp->fontname) << QStringLiteral("%1.1200pk").arg(fontp->fontname);
@ -256,8 +262,9 @@ void fontPool::locateFonts(bool makePK, bool locateTFMonly, bool *virtualFontsFo
}
}
if (numFontsInJob == 0)
if (numFontsInJob == 0) {
return;
}
// If PK fonts are generated, the kpsewhich command will re-route
// the output of MetaFont into its stderr. Here we make sure this
@ -302,8 +309,9 @@ void fontPool::locateFonts(bool makePK, bool locateTFMonly, bool *virtualFontsFo
-1);
// This makes sure the we don't try to run kpsewhich again
if (makePK == false)
if (makePK == false) {
markFontsAsLocated();
}
}
// Create a list with all filenames found by the kpsewhich program.
@ -318,11 +326,13 @@ void fontPool::locateFonts(bool makePK, bool locateTFMonly, bool *virtualFontsFo
QStringList matchingFiles;
#ifdef HAVE_FREETYPE
const QString &fn = fontsByTeXName.findFileName(fontp->fontname);
if (!fn.isEmpty())
if (!fn.isEmpty()) {
matchingFiles = fileNameList.filter(fn);
}
#endif
if (matchingFiles.isEmpty() == true)
if (matchingFiles.isEmpty() == true) {
matchingFiles += fileNameList.filter(QLatin1Char('/') + fontp->fontname + QLatin1Char('.'));
}
if (matchingFiles.isEmpty() != true) {
#ifdef DEBUG_FONTPOOL
@ -332,8 +342,9 @@ void fontPool::locateFonts(bool makePK, bool locateTFMonly, bool *virtualFontsFo
fontp->fontNameReceiver(fname);
fontp->flags |= TeXFontDefinition::FONT_KPSE_NAME;
if (fname.endsWith(QLatin1String(".vf"))) {
if (virtualFontsFound != nullptr)
if (virtualFontsFound != nullptr) {
*virtualFontsFound = true;
}
// Constructing a virtual font will most likely insert other
// fonts into the fontList. After that, fontList.next() will
// no longer work. It is therefore safer to start over.
@ -352,8 +363,9 @@ void fontPool::setCMperDVIunit(double _CMperDVI)
qCDebug(OkularDviDebug) << "fontPool::setCMperDVIunit( " << _CMperDVI << " )";
#endif
if (CMperDVIunit == _CMperDVI)
if (CMperDVIunit == _CMperDVI) {
return;
}
CMperDVIunit = _CMperDVI;

View File

@ -49,8 +49,9 @@ DviGenerator::DviGenerator(QObject *parent, const QVariantList &args)
setFeature(TextExtraction);
setFeature(FontInfo);
setFeature(PrintPostscript);
if (Okular::FilePrinter::ps2pdfAvailable())
if (Okular::FilePrinter::ps2pdfAvailable()) {
setFeature(PrintToFile);
}
}
bool DviGenerator::loadDocument(const QString &fileName, QVector<Okular::Page *> &pagesVector)
@ -123,10 +124,11 @@ void DviGenerator::fillViewportFromAnchor(Okular::DocumentViewport &vp, const An
SimplePageSize ps = m_dviRenderer->sizeOfPage(PageNumber(vp.pageNumber));
double resolution = 0;
if (ps.isValid())
if (ps.isValid()) {
resolution = (double)(pW) / ps.width().getLength_in_inch();
else
} else {
resolution = m_resolution;
}
double py = (double)anch.distance_from_top.getLength_in_inch() * resolution + 0.5;
@ -147,8 +149,9 @@ QLinkedList<Okular::ObjectRect *> DviGenerator::generateDviLinks(const dviPageIn
double nl = (double)boxArea.left() / pageWidth, nt = (double)boxArea.top() / pageHeight, nr = (double)boxArea.right() / pageWidth, nb = (double)boxArea.bottom() / pageHeight;
QString linkText = dviLink.linkText;
if (linkText.startsWith(QLatin1String("#")))
if (linkText.startsWith(QLatin1String("#"))) {
linkText = linkText.mid(1);
}
Anchor anch = m_dviRenderer->findAnchor(linkText);
Okular::Action *okuLink = nullptr;
@ -275,8 +278,9 @@ Okular::DocumentInfo DviGenerator::generateDocumentInfo(const QSet<Okular::Docum
{
Okular::DocumentInfo docInfo;
if (keys.contains(Okular::DocumentInfo::MimeType))
if (keys.contains(Okular::DocumentInfo::MimeType)) {
docInfo.set(Okular::DocumentInfo::MimeType, QStringLiteral("application/x-dvi"));
}
QMutexLocker lock(userMutex());
@ -285,18 +289,21 @@ Okular::DocumentInfo DviGenerator::generateDocumentInfo(const QSet<Okular::Docum
// read properties from dvif
// docInfo.set( "filename", dvif->filename, i18n("Filename") );
if (keys.contains(Okular::DocumentInfo::CustomKeys))
if (keys.contains(Okular::DocumentInfo::CustomKeys)) {
docInfo.set(QStringLiteral("generatorDate"), dvif->generatorString, i18n("Generator/Date"));
if (keys.contains(Okular::DocumentInfo::Pages))
}
if (keys.contains(Okular::DocumentInfo::Pages)) {
docInfo.set(Okular::DocumentInfo::Pages, QString::number(dvif->total_pages));
}
}
return docInfo;
}
const Okular::DocumentSynopsis *DviGenerator::generateDocumentSynopsis()
{
if (m_docSynopsis)
if (m_docSynopsis) {
return m_docSynopsis;
}
m_docSynopsis = new Okular::DocumentSynopsis();
@ -306,8 +313,9 @@ const Okular::DocumentSynopsis *DviGenerator::generateDocumentSynopsis()
userMutex()->unlock();
if (prebookmarks.isEmpty())
if (prebookmarks.isEmpty()) {
return m_docSynopsis;
}
QStack<QDomElement> stack;
@ -324,14 +332,15 @@ const Okular::DocumentSynopsis *DviGenerator::generateDocumentSynopsis()
fillViewportFromAnchor(vp, a, (int)p->width(), (int)p->height());
domel.setAttribute(QStringLiteral("Viewport"), vp.toString());
}
if (stack.isEmpty())
if (stack.isEmpty()) {
m_docSynopsis->appendChild(domel);
else {
} else {
stack.top().appendChild(domel);
stack.pop();
}
for (int i = 0; i < (*it).noOfChildren; ++i)
for (int i = 0; i < (*it).noOfChildren; ++i) {
stack.push(domel);
}
}
return m_docSynopsis;
@ -344,8 +353,9 @@ Okular::FontInfo::List DviGenerator::fontsForPage(int page)
Okular::FontInfo::List list;
// the list of the fonts is extracted once
if (m_fontExtracted)
if (m_fontExtracted) {
return list;
}
if (m_dviRenderer && m_dviRenderer->dviFile && m_dviRenderer->dviFile->font_pool) {
const QList<TeXFontDefinition *> fonts = m_dviRenderer->dviFile->font_pool->fontList;
@ -366,13 +376,15 @@ Okular::FontInfo::List DviGenerator::fontsForPage(int page)
QString fontFileName;
if (!(font->flags & TeXFontDefinition::FONT_VIRTUAL)) {
if (font->font != nullptr)
if (font->font != nullptr) {
fontFileName = font->font->errorMessage;
else
} else {
fontFileName = i18n("Font file not found");
}
if (fontFileName.isEmpty())
if (fontFileName.isEmpty()) {
fontFileName = font->filename;
}
}
of.setFile(fontFileName);
@ -443,24 +455,28 @@ void DviGenerator::loadPages(QVector<Okular::Page *> &pagesVector)
const QVector<DVI_SourceFileAnchor> &sourceAnchors = m_dviRenderer->sourceAnchors();
QVector<QLinkedList<Okular::SourceRefObjectRect *>> refRects(numofpages);
for (const DVI_SourceFileAnchor &sfa : sourceAnchors) {
if (sfa.page < 1 || (int)sfa.page > numofpages)
if (sfa.page < 1 || (int)sfa.page > numofpages) {
continue;
}
Okular::NormalizedPoint p(-1.0, (double)sfa.distance_from_top.getLength_in_pixel(dpi().height()) / (double)pageRequiredSize.height());
Okular::SourceReference *sourceRef = new Okular::SourceReference(sfa.fileName, sfa.line);
refRects[sfa.page - 1].append(new Okular::SourceRefObjectRect(p, sourceRef));
}
for (int i = 0; i < refRects.size(); ++i)
if (!refRects.at(i).isEmpty())
for (int i = 0; i < refRects.size(); ++i) {
if (!refRects.at(i).isEmpty()) {
pagesVector[i]->setSourceReferences(refRects.at(i));
}
}
}
Okular::Document::PrintError DviGenerator::print(QPrinter &printer)
{
// Create tempfile to write to
QTemporaryFile tf(QDir::tempPath() + QLatin1String("/okular_XXXXXX.ps"));
if (!tf.open())
if (!tf.open()) {
return Okular::Document::TemporaryFileOpenPrintError;
}
const QList<int> pageList = Okular::FilePrinter::pageList(printer, static_cast<quint16>(m_dviRenderer->totalPages()), document()->currentPage() + 1, document()->bookmarkedPageList());
QString pages;
@ -469,8 +485,9 @@ Okular::Document::PrintError DviGenerator::print(QPrinter &printer)
for (const int p : pageList) {
pages += QStringLiteral(",%1").arg(p);
}
if (!pages.isEmpty())
if (!pages.isEmpty()) {
printOptions << QStringLiteral("-pp") << pages.mid(1);
}
QEventLoop el;
m_dviRenderer->setEventLoop(&el);

View File

@ -55,16 +55,18 @@ float Length::convertToMM(const QString &distance, bool *ok)
// the value. Store the number of mm per unit in 'MMperUnit'.
for (int i = 0; MMperUnit == 0.0 && distanceUnitTable[i].name != nullptr; i++) {
unitPos = distance.lastIndexOf(QString::fromLocal8Bit(distanceUnitTable[i].name));
if (unitPos != -1)
if (unitPos != -1) {
MMperUnit = distanceUnitTable[i].mmPerUnit;
}
}
// If no unit has been found -> error message, set *ok to false and
// return 0.0.
if (MMperUnit == 0.0) {
qCCritical(OkularDviShellDebug) << "distance::convertToMM: no known unit found in the string '" << distance << "'." << endl;
if (ok)
if (ok) {
*ok = false;
}
return 0.0;
}

View File

@ -127,8 +127,9 @@ void pageSize::setPageSize(double width, double height)
rectifySizes();
reconstructCurrentSize();
if (!isNearlyEqual(oldPage))
if (!isNearlyEqual(oldPage)) {
emit sizeChanged(*this);
}
}
void pageSize::setPageSize(const QString &width, const QString &_widthUnits, const QString &height, const QString &_heightUnits)
@ -144,10 +145,12 @@ void pageSize::setPageSize(const QString &width, const QString &_widthUnits, con
widthUnits = QStringLiteral("mm");
}
pageWidth.setLength_in_mm(w);
if (widthUnits == QLatin1String("cm"))
if (widthUnits == QLatin1String("cm")) {
pageWidth.setLength_in_cm(w);
if (widthUnits == QLatin1String("in"))
}
if (widthUnits == QLatin1String("in")) {
pageWidth.setLength_in_inch(w);
}
QString heightUnits = _heightUnits;
if ((heightUnits != QLatin1String("cm")) && (heightUnits != QLatin1String("mm")) && (heightUnits != QLatin1String("in"))) {
@ -155,54 +158,66 @@ void pageSize::setPageSize(const QString &width, const QString &_widthUnits, con
heightUnits = QStringLiteral("mm");
}
pageHeight.setLength_in_mm(h);
if (heightUnits == QLatin1String("cm"))
if (heightUnits == QLatin1String("cm")) {
pageHeight.setLength_in_cm(h);
if (heightUnits == QLatin1String("in"))
}
if (heightUnits == QLatin1String("in")) {
pageHeight.setLength_in_inch(h);
}
rectifySizes();
reconstructCurrentSize();
if (!isNearlyEqual(oldPage))
if (!isNearlyEqual(oldPage)) {
emit sizeChanged(*this);
}
}
void pageSize::rectifySizes()
{
// Now do some sanity checks to make sure that values are not
// outrageous. We allow values between 5cm and 50cm.
if (pageWidth.getLength_in_mm() < 50)
if (pageWidth.getLength_in_mm() < 50) {
pageWidth.setLength_in_mm(50.0);
if (pageWidth.getLength_in_mm() > 1200)
}
if (pageWidth.getLength_in_mm() > 1200) {
pageWidth.setLength_in_mm(1200);
if (pageHeight.getLength_in_mm() < 50)
}
if (pageHeight.getLength_in_mm() < 50) {
pageHeight.setLength_in_mm(50);
if (pageHeight.getLength_in_mm() > 1200)
}
if (pageHeight.getLength_in_mm() > 1200) {
pageHeight.setLength_in_mm(1200);
}
return;
}
QString pageSize::preferredUnit() const
{
if (currentSize >= 0)
if (currentSize >= 0) {
return QString::fromLocal8Bit(staticList[currentSize].preferredUnit);
}
// User-defined size. Give a preferred unit depending on the locale.
if (QLocale::system().measurementSystem() == QLocale::MetricSystem)
if (QLocale::system().measurementSystem() == QLocale::MetricSystem) {
return QStringLiteral("mm");
else
} else {
return QStringLiteral("in");
}
}
QString pageSize::widthString(const QString &unit) const
{
QString answer = QStringLiteral("--");
if (unit == QLatin1String("cm"))
if (unit == QLatin1String("cm")) {
answer.setNum(pageWidth.getLength_in_cm());
if (unit == QLatin1String("mm"))
}
if (unit == QLatin1String("mm")) {
answer.setNum(pageWidth.getLength_in_mm());
if (unit == QLatin1String("in"))
}
if (unit == QLatin1String("in")) {
answer.setNum(pageWidth.getLength_in_inch());
}
return answer;
}
@ -211,12 +226,15 @@ QString pageSize::heightString(const QString &unit) const
{
QString answer = QStringLiteral("--");
if (unit == QLatin1String("cm"))
if (unit == QLatin1String("cm")) {
answer.setNum(pageHeight.getLength_in_cm());
if (unit == QLatin1String("mm"))
}
if (unit == QLatin1String("mm")) {
answer.setNum(pageHeight.getLength_in_mm());
if (unit == QLatin1String("in"))
}
if (unit == QLatin1String("in")) {
answer.setNum(pageHeight.getLength_in_inch());
}
return answer;
}
@ -225,18 +243,20 @@ QStringList pageSize::pageSizeNames()
{
QStringList names;
for (int i = 0; staticList[i].name != nullptr; i++)
for (int i = 0; staticList[i].name != nullptr; i++) {
names << QString::fromLocal8Bit(staticList[i].name);
}
return names;
}
QString pageSize::formatName() const
{
if (currentSize >= 0)
if (currentSize >= 0) {
return QString::fromLocal8Bit(staticList[currentSize].name);
else
} else {
return QString();
}
}
int pageSize::getOrientation() const
@ -246,10 +266,11 @@ int pageSize::getOrientation() const
return 0;
}
if (pageWidth.getLength_in_mm() == staticList[currentSize].width)
if (pageWidth.getLength_in_mm() == staticList[currentSize].width) {
return 0;
else
} else {
return 1;
}
}
void pageSize::setOrientation(int orient)
@ -271,29 +292,33 @@ void pageSize::setOrientation(int orient)
QString pageSize::serialize() const
{
if ((currentSize >= 0) && (fabs(staticList[currentSize].height - pageHeight.getLength_in_mm()) <= 0.5))
if ((currentSize >= 0) && (fabs(staticList[currentSize].height - pageHeight.getLength_in_mm()) <= 0.5)) {
return QString::fromLocal8Bit(staticList[currentSize].name);
else
} else {
return QStringLiteral("%1x%2").arg(pageWidth.getLength_in_mm()).arg(pageHeight.getLength_in_mm());
}
}
QString pageSize::description() const
{
if (!isValid())
if (!isValid()) {
return QString();
}
QString size = QStringLiteral(" ");
if (formatNumber() == -1) {
if (QLocale::system().measurementSystem() == QLocale::MetricSystem)
if (QLocale::system().measurementSystem() == QLocale::MetricSystem) {
size += QStringLiteral("%1x%2 mm").arg(width().getLength_in_mm(), 0, 'f', 0).arg(height().getLength_in_mm(), 0, 'f', 0);
else
} else {
size += QStringLiteral("%1x%2 in").arg(width().getLength_in_inch(), 0, 'g', 2).arg(height().getLength_in_inch(), 0, 'g', 2);
}
} else {
size += formatName() + QLatin1Char('/');
if (getOrientation() == 0)
if (getOrientation() == 0) {
size += i18n("portrait");
else
} else {
size += i18n("landscape");
}
}
return size + QLatin1Char(' ');
}
@ -323,8 +348,9 @@ int pageSize::defaultPageSize()
// FIXME: static_cast<QPrinter::PageSize>(KLocale::global()->pageSize())
// is the proper solution here. Then you can determine the values
// without using your hardcoded table too!
if (QLocale::system().measurementSystem() == QLocale::MetricSystem)
if (QLocale::system().measurementSystem() == QLocale::MetricSystem) {
return defaultMetricPaperSize;
else
} else {
return defaultImperialPaperSize;
}
}

View File

@ -41,8 +41,9 @@ pageInfo::pageInfo(const QString &_PostScriptString)
pageInfo::~pageInfo()
{
if (PostScriptString != nullptr)
if (PostScriptString != nullptr) {
delete PostScriptString;
}
}
// ======================================================
@ -60,8 +61,9 @@ ghostscript_interface::ghostscript_interface()
ghostscript_interface::~ghostscript_interface()
{
if (PostScriptHeaderString != nullptr)
if (PostScriptHeaderString != nullptr) {
delete PostScriptHeaderString;
}
qDeleteAll(pageList);
}
@ -74,19 +76,22 @@ void ghostscript_interface::setPostScript(const quint16 page, const QString &Pos
if (pageList.value(page) == nullptr) {
pageInfo *info = new pageInfo(PostScript);
// Check if dict is big enough
if (pageList.count() > pageList.capacity() - 2)
if (pageList.count() > pageList.capacity() - 2) {
pageList.reserve(pageList.capacity() * 2);
}
pageList.insert(page, info);
} else
} else {
*(pageList.value(page)->PostScriptString) = PostScript;
}
}
void ghostscript_interface::setIncludePath(const QString &_includePath)
{
if (_includePath.isEmpty())
if (_includePath.isEmpty()) {
includePath = QLatin1Char('*'); // Allow all files
else
} else {
includePath = _includePath + QStringLiteral("/*");
}
}
void ghostscript_interface::setBackgroundColor(const quint16 page, const QColor &background_color, bool permanent)
@ -98,16 +103,19 @@ void ghostscript_interface::setBackgroundColor(const quint16 page, const QColor
if (pageList.value(page) == nullptr) {
pageInfo *info = new pageInfo(QString());
info->background = background_color;
if (permanent)
if (permanent) {
info->permanentBackground = background_color;
}
// Check if dict is big enough
if (pageList.count() > pageList.capacity() - 2)
if (pageList.count() > pageList.capacity() - 2) {
pageList.reserve(pageList.capacity() * 2);
}
pageList.insert(page, info);
} else {
pageList.value(page)->background = background_color;
if (permanent)
if (permanent) {
pageList.value(page)->permanentBackground = background_color;
}
}
}
@ -116,8 +124,9 @@ void ghostscript_interface::restoreBackgroundColor(const quint16 page)
#ifdef DEBUG_PSGS
qCDebug(OkularDviDebug) << "ghostscript_interface::restoreBackgroundColor( " << page << " )";
#endif
if (pageList.value(page) == nullptr)
if (pageList.value(page) == nullptr) {
return;
}
pageInfo *info = pageList.value(page);
info->background = info->permanentBackground;
@ -132,10 +141,11 @@ QColor ghostscript_interface::getBackgroundColor(const quint16 page) const
qCDebug(OkularDviDebug) << "ghostscript_interface::getBackgroundColor( " << page << " )";
#endif
if (pageList.value(page) == nullptr)
if (pageList.value(page) == nullptr) {
return Qt::white;
else
} else {
return pageList.value(page)->background;
}
}
void ghostscript_interface::clear()
@ -203,16 +213,18 @@ void ghostscript_interface::gs_generate_graphics_file(const quint16 page, const
// Start page
<< "1 0 bop 0 0 a \n";
if (!PostScriptHeaderString->toLatin1().isNull())
if (!PostScriptHeaderString->toLatin1().isNull()) {
os << PostScriptHeaderString->toLatin1();
}
if (info->background != Qt::white) {
QString colorCommand = QStringLiteral("gsave %1 %2 %3 setrgbcolor clippath fill grestore\n").arg(info->background.red() / 255.0).arg(info->background.green() / 255.0).arg(info->background.blue() / 255.0);
os << colorCommand.toLatin1();
}
if (!info->PostScriptString->isNull())
if (!info->PostScriptString->isNull()) {
os << *(info->PostScriptString);
}
os << "end\n"
<< "showpage \n";
@ -268,13 +280,13 @@ void ghostscript_interface::gs_generate_graphics_file(const quint16 page, const
<< endl;
knownDevices.erase(gsDevice);
gsDevice = knownDevices.begin();
if (knownDevices.isEmpty())
if (knownDevices.isEmpty()) {
// TODO: show a requestor of some sort.
emit error(i18n("The version of Ghostview that is installed on this computer does not contain "
"any of the Ghostview device drivers that are known to Okular. PostScript "
"support has therefore been turned off in Okular."),
-1);
else {
} else {
qCDebug(OkularDviDebug) << QStringLiteral("Okular will now try to use the '%1' device driver.").arg(*gsDevice);
gs_generate_graphics_file(page, filename, magnification);
}
@ -331,8 +343,9 @@ QString ghostscript_interface::locateEPSfile(const QString &filename, const QUrl
QString path = base.path(); // -> "/bar/foo.dvi"
QFileInfo fi1(path);
QFileInfo fi2(fi1.dir(), filename);
if (fi2.exists())
if (fi2.exists()) {
return fi2.absoluteFilePath();
}
}
// Otherwise, use kpsewhich to find the eps file.

View File

@ -32,8 +32,9 @@ void dviRenderer::printErrorMsgForSpecials(const QString &msg)
if (dviFile->errorCounter < 25) {
qCCritical(OkularDviDebug) << msg << endl;
dviFile->errorCounter++;
if (dviFile->errorCounter == 25)
if (dviFile->errorCounter == 25) {
qCCritical(OkularDviDebug) << i18n("That makes 25 errors. Further error messages will not be printed.") << endl;
}
}
}
@ -121,16 +122,19 @@ QColor dviRenderer::parseColorSpecification(const QString &colorSpec)
bool ok;
double r = colorSpec.section(QLatin1Char(' '), 1, 1).toDouble(&ok);
if ((ok == false) || (r < 0.0) || (r > 1.0))
if ((ok == false) || (r < 0.0) || (r > 1.0)) {
return QColor();
}
double g = colorSpec.section(QLatin1Char(' '), 2, 2).toDouble(&ok);
if ((ok == false) || (g < 0.0) || (g > 1.0))
if ((ok == false) || (g < 0.0) || (g > 1.0)) {
return QColor();
}
double b = colorSpec.section(QLatin1Char(' '), 3, 3).toDouble(&ok);
if ((ok == false) || (b < 0.0) || (b > 1.0))
if ((ok == false) || (b < 0.0) || (b > 1.0)) {
return QColor();
}
return QColor((int)(r * 255.0 + 0.5), (int)(g * 255.0 + 0.5), (int)(b * 255.0 + 0.5));
}
@ -139,16 +143,19 @@ QColor dviRenderer::parseColorSpecification(const QString &colorSpec)
bool ok;
double h = colorSpec.section(QLatin1Char(' '), 1, 1).toDouble(&ok);
if ((ok == false) || (h < 0.0) || (h > 1.0))
if ((ok == false) || (h < 0.0) || (h > 1.0)) {
return QColor();
}
double s = colorSpec.section(QLatin1Char(' '), 2, 2).toDouble(&ok);
if ((ok == false) || (s < 0.0) || (s > 1.0))
if ((ok == false) || (s < 0.0) || (s > 1.0)) {
return QColor();
}
double b = colorSpec.section(QLatin1Char(' '), 3, 3).toDouble(&ok);
if ((ok == false) || (b < 0.0) || (b > 1.0))
if ((ok == false) || (b < 0.0) || (b > 1.0)) {
return QColor();
}
return QColor::fromHsv((int)(h * 359.0 + 0.5), (int)(s * 255.0 + 0.5), (int)(b * 255.0 + 0.5));
}
@ -157,31 +164,38 @@ QColor dviRenderer::parseColorSpecification(const QString &colorSpec)
bool ok;
double c = colorSpec.section(QLatin1Char(' '), 1, 1).toDouble(&ok);
if ((ok == false) || (c < 0.0) || (c > 1.0))
if ((ok == false) || (c < 0.0) || (c > 1.0)) {
return QColor();
}
double m = colorSpec.section(QLatin1Char(' '), 2, 2).toDouble(&ok);
if ((ok == false) || (m < 0.0) || (m > 1.0))
if ((ok == false) || (m < 0.0) || (m > 1.0)) {
return QColor();
}
double y = colorSpec.section(QLatin1Char(' '), 3, 3).toDouble(&ok);
if ((ok == false) || (y < 0.0) || (y > 1.0))
if ((ok == false) || (y < 0.0) || (y > 1.0)) {
return QColor();
}
double k = colorSpec.section(QLatin1Char(' '), 3, 3).toDouble(&ok);
if ((ok == false) || (k < 0.0) || (k > 1.0))
if ((ok == false) || (k < 0.0) || (k > 1.0)) {
return QColor();
}
// Convert cmyk coordinates to rgb.
double r = 1.0 - c - k;
if (r < 0.0)
if (r < 0.0) {
r = 0.0;
}
double g = 1.0 - m - k;
if (g < 0.0)
if (g < 0.0) {
g = 0.0;
}
double b = 1.0 - y - k;
if (b < 0.0)
if (b < 0.0) {
b = 0.0;
}
return QColor((int)(r * 255.0 + 0.5), (int)(g * 255.0 + 0.5), (int)(b * 255.0 + 0.5));
}
@ -190,16 +204,18 @@ QColor dviRenderer::parseColorSpecification(const QString &colorSpec)
bool ok;
double g = colorSpec.section(QLatin1Char(' '), 1, 1).toDouble(&ok);
if ((ok == false) || (g < 0.0) || (g > 1.0))
if ((ok == false) || (g < 0.0) || (g > 1.0)) {
return QColor();
}
return QColor((int)(g * 255.0 + 0.5), (int)(g * 255.0 + 0.5), (int)(g * 255.0 + 0.5));
}
// Check if the color is one of the known named colors.
QMap<QString, QColor>::Iterator f = namedColors.find(specType);
if (f != namedColors.end())
if (f != namedColors.end()) {
return *f;
}
return QColor(specType);
}
@ -212,10 +228,11 @@ void dviRenderer::color_special(const QString &msg)
if (command == QLatin1String("pop")) {
// Take color off the stack
if (colorStack.isEmpty())
if (colorStack.isEmpty()) {
printErrorMsgForSpecials(i18n("Error in DVIfile '%1', page %2. Color pop command issued when the color stack is empty.", dviFile->filename, current_page));
else
} else {
colorStack.pop();
}
return;
}
@ -223,10 +240,11 @@ void dviRenderer::color_special(const QString &msg)
// Get color specification
const QColor col = parseColorSpecification(cp.section(QLatin1Char(' '), 1));
// Set color
if (col.isValid())
if (col.isValid()) {
colorStack.push(col);
else
} else {
colorStack.push(Qt::black);
}
return;
}
@ -234,10 +252,11 @@ void dviRenderer::color_special(const QString &msg)
// page
QColor col = parseColorSpecification(cp);
// Set color
if (col.isValid())
if (col.isValid()) {
globalColor = col;
else
} else {
globalColor = Qt::black;
}
return;
}
@ -271,10 +290,11 @@ void dviRenderer::source_special(const QString &cp)
// rendering routine will then generate a DVI_HyperLink and add it
// to the proper list. This DVI_HyperLink is used to match mouse
// positions with the hyperlinks for inverse search.
if (source_href)
if (source_href) {
*source_href = cp;
else
} else {
source_href = new QString(cp);
}
}
void parse_special_argument(const QString &strg, const char *argument_name, int *variable)
@ -283,15 +303,16 @@ void parse_special_argument(const QString &strg, const char *argument_name, int
if (index >= 0) {
QString tmp = strg.mid(index + strlen(argument_name));
index = tmp.indexOf(QLatin1Char(' '));
if (index >= 0)
if (index >= 0) {
tmp.truncate(index);
}
bool OK;
float const tmp_float = tmp.toFloat(&OK);
if (OK)
if (OK) {
*variable = int(tmp_float + 0.5);
else
} else {
// Maybe we should open a dialog here.
qCCritical(OkularDviDebug) << i18n(
"Malformed parameter in the epsf special command.\n"
@ -299,6 +320,7 @@ void parse_special_argument(const QString &strg, const char *argument_name, int
QString::fromLocal8Bit(argument_name),
strg)
<< endl;
}
}
}
@ -405,10 +427,11 @@ void dviRenderer::epsf_special(const QString &cp)
foreGroundPainter->save();
if (QFile::exists(EPSfilename))
if (QFile::exists(EPSfilename)) {
foreGroundPainter->setBrush(Qt::lightGray);
else
} else {
foreGroundPainter->setBrush(Qt::red);
}
foreGroundPainter->setPen(Qt::black);
foreGroundPainter->drawRoundedRect(bbox, 2, 2);
QFont f = foreGroundPainter->font();
@ -418,10 +441,11 @@ void dviRenderer::epsf_special(const QString &cp)
the call to drawText() in the non-GUI thread will produce a crash.
Ensure that the rendering of the text is performed only if
the threaded font rendering is available */
if (QFile::exists(EPSfilename))
if (QFile::exists(EPSfilename)) {
foreGroundPainter->drawText(bbox, (int)(Qt::AlignCenter), EPSfilename);
else
} else {
foreGroundPainter->drawText(bbox, (int)(Qt::AlignCenter), i18n("File not found: \n %1", EPSfilename_orig));
}
foreGroundPainter->restore();
}
@ -471,10 +495,12 @@ void dviRenderer::TPIC_addPath_special(const QString &cp)
int y = (int)(currinf.data.pxl_v + mag * yKoord * resolutionInDPI / 1000.0 + 0.5);
// Initialize the point array used to store the path
if (TPIC_path.size() == 0)
if (TPIC_path.size() == 0) {
number_of_elements_in_path = 0;
if (TPIC_path.size() == number_of_elements_in_path)
}
if (TPIC_path.size() == number_of_elements_in_path) {
TPIC_path.resize(number_of_elements_in_path + 100);
}
TPIC_path.setPoint(number_of_elements_in_path++, x, y);
}
@ -573,11 +599,13 @@ void dviRenderer::applicationDoSpecial(char *cp)
// 'glopglyph'). As a protection against bad DVI files, we make
// sure to remove all link rectangles which point to
// 'glopglyph'.
while (!currentlyDrawnPage->hyperLinkList.isEmpty())
if (currentlyDrawnPage->hyperLinkList.last().linkText == QLatin1String("glopglyph"))
while (!currentlyDrawnPage->hyperLinkList.isEmpty()) {
if (currentlyDrawnPage->hyperLinkList.last().linkText == QLatin1String("glopglyph")) {
currentlyDrawnPage->hyperLinkList.pop_back();
else
} else {
break;
}
}
HTML_href = new QString(QStringLiteral("glopglyph"));
return;
@ -615,11 +643,13 @@ void dviRenderer::applicationDoSpecial(char *cp)
delete HTML_href;
HTML_href = nullptr;
}
while (!currentlyDrawnPage->hyperLinkList.isEmpty())
if (currentlyDrawnPage->hyperLinkList.last().linkText == QLatin1String("glopglyph"))
while (!currentlyDrawnPage->hyperLinkList.isEmpty()) {
if (currentlyDrawnPage->hyperLinkList.last().linkText == QLatin1String("glopglyph")) {
currentlyDrawnPage->hyperLinkList.pop_back();
else
} else {
break;
}
}
return; // end of hyperref anchor
}
@ -636,9 +666,11 @@ void dviRenderer::applicationDoSpecial(char *cp)
if (!currentlyDrawnPage->hyperLinkList.isEmpty()) {
QString targetName = special_command.section(QLatin1Char('('), 1, 1).section(QLatin1Char(')'), 0, 0);
QVector<Hyperlink>::iterator it;
for (it = currentlyDrawnPage->hyperLinkList.begin(); it != currentlyDrawnPage->hyperLinkList.end(); ++it)
if (it->linkText == QLatin1String("glopglyph"))
for (it = currentlyDrawnPage->hyperLinkList.begin(); it != currentlyDrawnPage->hyperLinkList.end(); ++it) {
if (it->linkText == QLatin1String("glopglyph")) {
it->linkText = targetName;
}
}
}
return; // hyperref definition of link/anchor/bookmark/etc
}
@ -660,8 +692,9 @@ void dviRenderer::applicationDoSpecial(char *cp)
foreGroundPainter->translate(x, y);
foreGroundPainter->rotate(-angle);
foreGroundPainter->translate(-x, -y);
} else
} else {
printErrorMsgForSpecials(i18n("Error in DVIfile '%1', page %2. Could not interpret angle in text rotation special.", dviFile->filename, current_page));
}
}
// The graphicx package marks the end of rotated text with this
@ -674,8 +707,10 @@ void dviRenderer::applicationDoSpecial(char *cp)
// interest only during the prescan phase. We recognize them here
// anyway, to make sure that KDVI doesn't complain about
// unrecognized special commands.
if ((cp[0] == '!') || (cp[0] == '"') || (qstrnicmp(cp, "html:<A name=", 13) == 0) || (qstrnicmp(cp, "ps:", 3) == 0) || (qstrnicmp(cp, "papersize", 9) == 0) || (qstrnicmp(cp, "header", 6) == 0) || (qstrnicmp(cp, "background", 10) == 0))
if ((cp[0] == '!') || (cp[0] == '"') || (qstrnicmp(cp, "html:<A name=", 13) == 0) || (qstrnicmp(cp, "ps:", 3) == 0) || (qstrnicmp(cp, "papersize", 9) == 0) || (qstrnicmp(cp, "header", 6) == 0) ||
(qstrnicmp(cp, "background", 10) == 0)) {
return;
}
printErrorMsgForSpecials(i18n("The special command '%1' is not implemented.", special_command));
return;

View File

@ -73,8 +73,9 @@ unsigned long num(FILE *fp, int size)
{
long x = 0;
while (size--)
while (size--) {
x = (x << 8) | one(fp);
}
return x;
}
@ -89,7 +90,8 @@ long snum(FILE *fp, int size)
if (x & 0x80)
x -= 0x100;
#endif
while (--size)
while (--size) {
x = (x << 8) | one(fp);
}
return x;
}

View File

@ -64,8 +64,9 @@ void TeXFontDefinition::read_VF_index()
fseek(VF_file, (long)one(VF_file), 1); /* skip comment */
quint32 const file_checksum = four(VF_file);
if (file_checksum && checksum && file_checksum != checksum)
if (file_checksum && checksum && file_checksum != checksum) {
qCCritical(OkularDviDebug) << "Checksum mismatch dvi = " << checksum << "u, vf = " << file_checksum << "u) in font file" << filename << endl;
}
(void)four(VF_file); /* skip design size */
// Read the fonts.
@ -97,14 +98,16 @@ void TeXFontDefinition::read_VF_index()
// Insert font in dictionary and make sure the dictionary is big
// enough.
if (vf_table.capacity() - 2 <= vf_table.count())
if (vf_table.capacity() - 2 <= vf_table.count()) {
// Not quite optimal. The size of the dictionary should be a
// prime. I don't care.
vf_table.reserve(vf_table.capacity() * 2);
}
vf_table.insert(TeXnumber, newfontp);
if (first_font == nullptr)
if (first_font == nullptr) {
first_font = newfontp;
}
}
// Prepare macro array.
@ -149,15 +152,17 @@ void TeXFontDefinition::read_VF_index()
m->pos = avail = new unsigned char[VF_PARM_2];
availend = avail + VF_PARM_2;
avail += len;
} else
} else {
m->pos = new unsigned char[len];
}
}
fread((char *)m->pos, 1, len, VF_file);
m->end = m->pos + len;
}
}
if (cmnd != POST)
if (cmnd != POST) {
oops(i18n("Wrong command byte found in VF macro list: %1", cmnd));
}
fclose(VF_file);
file = nullptr;

View File

@ -58,8 +58,9 @@ void Converter::_emitData(Okular::DocumentInfo::Key key, enum epub_metadata type
if (data) {
emit addMetaData(key, _strPack((char **)data, size));
for (int i = 0; i < size; i++)
for (int i = 0; i < size; i++) {
free(data[i]);
}
free(data);
}
}
@ -86,18 +87,20 @@ void Converter::_handle_anchors(const QTextBlock &start, const QString &name)
QUrl href(hrefString);
if (href.isValid() && !href.isEmpty()) {
if (href.isRelative()) { // Inside document link
if (!hrefString.indexOf(QLatin1Char('#')))
if (!hrefString.indexOf(QLatin1Char('#'))) {
hrefString = name + hrefString;
else if (QFileInfo(hrefString).path() == QLatin1String(".") && curDir != QLatin1String("."))
} else if (QFileInfo(hrefString).path() == QLatin1String(".") && curDir != QLatin1String(".")) {
hrefString = curDir + QLatin1Char('/') + hrefString;
}
// QTextCharFormat sometimes splits a link in two
// if there's no white space between words & the first one is an anchor
// consider whole word to be an anchor
++fit;
int fragLen = frag.length();
if (!fit.atEnd() && ((fit.fragment().position() - frag.position()) == 1))
if (!fit.atEnd() && ((fit.fragment().position() - frag.position()) == 1)) {
fragLen += fit.fragment().length();
}
--fit;
_insert_local_links(hrefString, QPair<int, int>(frag.position(), frag.position() + fragLen));
@ -230,14 +233,18 @@ QTextDocument *Converter::convert(const QString &fileName)
int ht = images.at(i).toElement().attribute(QStringLiteral("height")).toInt();
int wd = images.at(i).toElement().attribute(QStringLiteral("width")).toInt();
QImage img = mTextDocument->loadResource(QTextDocument::ImageResource, QUrl(lnk)).value<QImage>();
if (ht == 0)
if (ht == 0) {
ht = img.height();
if (wd == 0)
}
if (wd == 0) {
wd = img.width();
if (ht > maxHeight)
}
if (ht > maxHeight) {
ht = maxHeight;
if (wd > maxWidth)
}
if (wd > maxWidth) {
wd = maxWidth;
}
mTextDocument->addResource(QTextDocument::ImageResource, QUrl(lnk), img);
QDomDocument newDoc;
newDoc.setContent(QStringLiteral("<img src=\"%1\" height=\"%2\" width=\"%3\" />").arg(lnk).arg(ht).arg(wd));
@ -346,8 +353,9 @@ QTextDocument *Converter::convert(const QString &fileName)
// useful when the last line had a bullet
_cursor->insertBlock(QTextBlockFormat());
while (mTextDocument->pageCount() == page)
while (mTextDocument->pageCount() == page) {
_cursor->insertText(QStringLiteral("\n"));
}
} while (epub_it_get_next(it));
@ -358,8 +366,9 @@ QTextDocument *Converter::convert(const QString &fileName)
// FIXME: support other method beside NAVMAP and GUIDE
tit = epub_get_titerator(mTextDocument->getEpub(), TITERATOR_NAVMAP, 0);
if (!tit)
if (!tit) {
tit = epub_get_titerator(mTextDocument->getEpub(), TITERATOR_GUIDE, 0);
}
if (tit) {
do {
@ -396,8 +405,9 @@ QTextDocument *Converter::convert(const QString &fileName)
// Start new file in a new page
int page = mTextDocument->pageCount();
while (mTextDocument->pageCount() == page)
while (mTextDocument->pageCount() == page) {
_cursor->insertText(QStringLiteral("\n"));
}
}
free(data);
@ -409,10 +419,12 @@ QTextDocument *Converter::convert(const QString &fileName)
qDebug() << "Error: no block found for" << link;
}
if (clink)
if (clink) {
free(clink);
if (label)
}
if (label) {
free(label);
}
}
} while (epub_tit_next(tit));

View File

@ -34,8 +34,9 @@ bool EpubDocument::isValid()
EpubDocument::~EpubDocument()
{
if (mEpub)
if (mEpub) {
epub_close(mEpub);
}
epub_cleanup();
}
@ -110,10 +111,12 @@ QVariant EpubDocument::loadResource(int type, const QUrl &name)
QImage img = QImage::fromData((unsigned char *)data, size);
const int maxHeight = maxContentHeight();
const int maxWidth = maxContentWidth();
if (img.height() > maxHeight)
if (img.height() > maxHeight) {
img = img.scaledToHeight(maxHeight, Qt::SmoothTransformation);
if (img.width() > maxWidth)
}
if (img.width() > maxWidth) {
img = img.scaledToWidth(maxWidth, Qt::SmoothTransformation);
}
resource.setValue(img);
break;
}
@ -124,10 +127,12 @@ QVariant EpubDocument::loadResource(int type, const QUrl &name)
}
case EpubDocument::MovieResource: {
QTemporaryFile *tmp = new QTemporaryFile(QStringLiteral("%1/okrXXXXXX").arg(QDir::tempPath()), this);
if (!tmp->open())
if (!tmp->open()) {
qCWarning(OkularEpuDebug) << "EPUB : error creating temporary video file";
if (tmp->write(data, size) == -1)
}
if (tmp->write(data, size) == -1) {
qCWarning(OkularEpuDebug) << "EPUB : error writing data" << tmp->errorString();
}
tmp->flush();
resource.setValue(tmp->fileName());
break;

View File

@ -74,8 +74,9 @@ static unsigned char *getstrip(pagenode *pn, int strip)
so.s = 1; /* XXX */
QFile file(pn->filename);
if (!file.open(QIODevice::ReadOnly))
if (!file.open(QIODevice::ReadOnly)) {
return nullptr;
}
if (pn->strips == nullptr) {
offset = 0;
@ -83,8 +84,9 @@ static unsigned char *getstrip(pagenode *pn, int strip)
} else if (strip < pn->nstrips) {
offset = pn->strips[strip].offset;
pn->length = pn->strips[strip].size;
} else
} else {
return nullptr;
}
/* round size to full boundary plus t32bits */
roundup = (pn->length + 7) & ~3;
@ -113,8 +115,9 @@ static unsigned char *getstrip(pagenode *pn, int strip)
}
normalize(pn, !pn->lsbfirst, ShortOrder, roundup);
if (pn->size.height() == 0)
if (pn->size.height() == 0) {
pn->size.setHeight(G3count(pn, pn->expander == g32expand));
}
if (pn->size.height() == 0) {
delete[] data;
@ -122,8 +125,9 @@ static unsigned char *getstrip(pagenode *pn, int strip)
return nullptr;
}
if (pn->strips == nullptr)
if (pn->strips == nullptr) {
pn->rowsperstrip = pn->size.height();
}
pn->dataOrig = reinterpret_cast<t16bits *>(data);
@ -141,8 +145,9 @@ static void draw_line(pixnum *run, int lineNum, pagenode *pn)
int n;
lineNum += pn->stripnum * pn->rowsperstrip;
if (lineNum >= pn->size.height())
if (lineNum >= pn->size.height()) {
return;
}
p = reinterpret_cast<t32bits *>(pn->imageData + lineNum * (2 - pn->vres) * pn->bytes_per_line);
p1 = reinterpret_cast<t32bits *>(pn->vres ? nullptr : p + pn->bytes_per_line / sizeof(*p));
@ -156,28 +161,32 @@ static void draw_line(pixnum *run, int lineNum, pagenode *pn)
n = *r++;
tot += n;
/* Watch out for buffer overruns, e.g. when n == 65535. */
if (tot > pn->size.width())
if (tot > pn->size.width()) {
break;
if (pix)
}
if (pix) {
acc |= (~(t32bits)0 >> nacc);
else if (nacc)
} else if (nacc) {
acc &= (~(t32bits)0 << (32 - nacc));
else
} else {
acc = 0;
}
if (nacc + n < 32) {
nacc += n;
pix = ~pix;
continue;
}
*p++ = acc;
if (p1)
if (p1) {
*p1++ = acc;
}
n -= 32 - nacc;
while (n >= 32) {
n -= 32;
*p++ = pix;
if (p1)
if (p1) {
*p1++ = pix;
}
}
acc = pix;
nacc = n;
@ -185,19 +194,22 @@ static void draw_line(pixnum *run, int lineNum, pagenode *pn)
}
if (nacc) {
*p++ = acc;
if (p1)
if (p1) {
*p1++ = acc;
}
}
}
static bool get_image(pagenode *pn)
{
unsigned char *data = getstrip(pn, 0);
if (!data)
if (!data) {
return false;
}
if (!new_image(pn, pn->size.width(), (pn->vres ? 1 : 2) * pn->size.height()))
if (!new_image(pn, pn->size.width(), (pn->vres ? 1 : 2) * pn->size.height())) {
return false;
}
(*pn->expander)(pn, draw_line);
@ -232,10 +244,11 @@ FaxDocument::FaxDocument(const QString &fileName, DocumentType type)
d->mPageNode.imageData = nullptr;
d->mType = type;
if (d->mType == G3)
if (d->mType == G3) {
d->mPageNode.expander = g31expand; // or g32expand?!?
else if (d->mType == G4)
} else if (d->mType == G4) {
d->mPageNode.expander = g4expand;
}
}
FaxDocument::~FaxDocument()
@ -250,8 +263,9 @@ bool FaxDocument::load()
fax_init_tables();
bool ok = get_image(&(d->mPageNode));
if (!ok)
if (!ok) {
return false;
}
// byte-swapping the image
int height = d->mPageNode.size.height();

View File

@ -334,8 +334,9 @@ const char *StateNames[] = {
static void unexpected(const char *what, int LineNum)
{
if (verbose)
if (verbose) {
qCCritical(FAX_LOG) << "Line " << LineNum << ": Unexpected state in " << what << endl;
}
}
/* Expand tiff modified huffman data (g3-1d without EOLs) */
@ -368,19 +369,24 @@ void MHexpand(pagenode *pn, drawfunc df)
pa = runs;
a0 = 0;
EOLcnt = 0;
if (BitsAvail & 7) /* skip to byte boundary */
if (BitsAvail & 7) { /* skip to byte boundary */
ClrBits(BitsAvail & 7);
}
expand1d();
if (RunLength)
if (RunLength) {
SETVAL(0);
}
if (a0 != lastx) {
if (verbose)
if (verbose) {
qCWarning(FAX_LOG) << "Line " << LineNum << ": length is " << a0 << " (expected " << lastx << ")\n";
while (a0 > lastx)
}
while (a0 > lastx) {
a0 -= *--pa;
}
if (a0 < lastx) {
if ((pa - runs) & 1)
if ((pa - runs) & 1) {
SETVAL(0);
}
SETVAL(lastx - a0);
}
}
@ -417,29 +423,34 @@ void g31expand(pagenode *pn, drawfunc df)
fprintf(stderr, "-------------------- %d\n", LineNum);
fflush(stderr);
#endif
if (EOLcnt == 0)
if (EOLcnt == 0) {
while (!EndOfData(pn)) {
/* skip over garbage after a coding error */
NeedBits(11);
if (GetBits(11) == 0)
if (GetBits(11) == 0) {
break;
}
ClrBits(1);
}
}
for (EOLcnt = 1; !EndOfData(pn); EOLcnt++) {
/* we have seen 11 zeros, which implies EOL,
skip possible fill bits too */
while (true) {
NeedBits(8);
if (GetBits(8))
if (GetBits(8)) {
break;
}
ClrBits(8);
}
while (GetBits(1) == 0)
while (GetBits(1) == 0) {
ClrBits(1);
}
ClrBits(1); /* the eol flag */
NeedBits(11);
if (GetBits(11))
if (GetBits(11)) {
break;
}
ClrBits(11);
}
if (EOLcnt > 1 && EOLcnt != 6 && verbose) {
@ -454,16 +465,20 @@ void g31expand(pagenode *pn, drawfunc df)
a0 = 0;
EOLcnt = 0;
expand1d();
if (RunLength)
if (RunLength) {
SETVAL(0);
}
if (a0 != lastx) {
if (verbose)
if (verbose) {
qCWarning(FAX_LOG) << "Line " << LineNum << ": length is " << a0 << " (expected " << lastx << ")\n";
while (a0 > lastx)
}
while (a0 > lastx) {
a0 -= *--pa;
}
if (a0 < lastx) {
if ((pa - runs) & 1)
if ((pa - runs) & 1) {
SETVAL(0);
}
SETVAL(lastx - a0);
}
}
@ -504,41 +519,48 @@ void g32expand(pagenode *pn, drawfunc df)
printf("-------------------- %d\n", LineNum);
fflush(stdout);
#endif
if (EOLcnt == 0)
if (EOLcnt == 0) {
while (!EndOfData(pn)) {
/* skip over garbage after a coding error */
NeedBits(11);
if (GetBits(11) == 0)
if (GetBits(11) == 0) {
break;
}
ClrBits(1);
}
}
for (EOLcnt = 1; !EndOfData(pn); EOLcnt++) {
/* we have seen 11 zeros, which implies EOL,
skip possible fill bits too */
while (true) {
NeedBits(8);
if (GetBits(8))
if (GetBits(8)) {
break;
}
ClrBits(8);
}
while (GetBits(1) == 0)
while (GetBits(1) == 0) {
ClrBits(1);
}
ClrBits(1); /* the eol flag */
NeedBits(12);
refline = GetBits(1); /* 1D / 2D flag */
ClrBits(1);
if (GetBits(11))
if (GetBits(11)) {
break;
}
ClrBits(11);
}
if (EOLcnt > 1 && EOLcnt != 6 && verbose)
if (EOLcnt > 1 && EOLcnt != 6 && verbose) {
qCCritical(FAX_LOG) << "Line " << LineNum << ": bad RTC (" << EOLcnt << " EOLs)\n";
}
if (EOLcnt >= 6 || EndOfData(pn)) {
free(run0);
return;
}
if (LineNum == 0 && refline == 0 && verbose)
if (LineNum == 0 && refline == 0 && verbose) {
qCDebug(FAX_LOG) << "First line is 2-D encoded\n";
}
RunLength = 0;
if (LineNum & 1) {
pa = run1;
@ -557,16 +579,20 @@ void g32expand(pagenode *pn, drawfunc df)
} else {
expand2d(EOL2);
}
if (RunLength)
if (RunLength) {
SETVAL(0);
}
if (a0 != lastx) {
if (verbose)
if (verbose) {
qCWarning(FAX_LOG) << "Line " << LineNum << ": length is " << a0 << " (expected " << lastx << ")\n";
while (a0 > lastx)
}
while (a0 > lastx) {
a0 -= *--pa;
}
if (a0 < lastx) {
if ((pa - run0) & 1)
if ((pa - run0) & 1) {
SETVAL(0);
}
SETVAL(lastx - a0);
}
}
@ -633,8 +659,9 @@ void g4expand(pagenode *pn, drawfunc df)
b1 = *pb++;
expand2d(EOFB);
if (a0 < lastx) {
if ((pa - run0) & 1)
if ((pa - run0) & 1) {
SETVAL(0);
}
SETVAL(lastx - a0);
}
SETVAL(0); /* imaginary change at end of line for reference */
@ -642,8 +669,9 @@ void g4expand(pagenode *pn, drawfunc df)
continue;
EOFB:
NeedBits(13);
if (GetBits(13) != 0x1001 && verbose)
if (GetBits(13) != 0x1001 && verbose) {
qCCritical(FAX_LOG) << "Bad RTC\n";
}
break;
}
free(run0);
@ -695,13 +723,15 @@ int G3count(pagenode *pn, int twoD)
t16bits bits = *p++;
check(bits & 255);
if (twoD && (prezeros + postzeros == 7)) {
if (postzeros || ((bits & 0x100) == 0))
if (postzeros || ((bits & 0x100) == 0)) {
zeros--;
}
}
check(bits >> 8);
if (twoD && (prezeros + postzeros == 7)) {
if (postzeros || ((p < end) && ((*p & 1) == 0)))
if (postzeros || ((p < end) && ((*p & 1) == 0))) {
zeros--;
}
}
}
return lines - EOLcnt; /* don't count trailing EOLs */

View File

@ -30,10 +30,11 @@ FaxGenerator::~FaxGenerator()
bool FaxGenerator::loadDocument(const QString &fileName, QVector<Okular::Page *> &pagesVector)
{
if (fileName.endsWith(QLatin1String(".g3"), Qt::CaseInsensitive))
if (fileName.endsWith(QLatin1String(".g3"), Qt::CaseInsensitive)) {
m_type = FaxDocument::G3;
else
} else {
m_type = FaxDocument::G4;
}
FaxDocument faxDocument(fileName, m_type);
@ -64,8 +65,9 @@ QImage FaxGenerator::image(Okular::PixmapRequest *request)
// perform a smooth scaled generation
int width = request->width();
int height = request->height();
if (request->page()->rotation() % 2 == 1)
if (request->page()->rotation() % 2 == 1) {
qSwap(width, height);
}
return m_img.scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
}
@ -74,10 +76,11 @@ Okular::DocumentInfo FaxGenerator::generateDocumentInfo(const QSet<Okular::Docum
{
Okular::DocumentInfo docInfo;
if (keys.contains(Okular::DocumentInfo::MimeType)) {
if (m_type == FaxDocument::G3)
if (m_type == FaxDocument::G3) {
docInfo.set(Okular::DocumentInfo::MimeType, QStringLiteral("image/fax-g3"));
else
} else {
docInfo.set(Okular::DocumentInfo::MimeType, QStringLiteral("image/fax-g4"));
}
}
return docInfo;
}
@ -88,9 +91,9 @@ Okular::Document::PrintError FaxGenerator::print(QPrinter &printer)
QImage image(m_img);
if ((image.width() > printer.width()) || (image.height() > printer.height()))
if ((image.width() > printer.width()) || (image.height() > printer.height())) {
image = image.scaled(printer.width(), printer.height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
}
p.drawImage(0, 0, image);

View File

@ -189,22 +189,27 @@ QTextDocument *Converter::convert(const QString &fileName)
* Add document info.
*/
if (mTitleInfo) {
if (!mTitleInfo->mTitle.isEmpty())
if (!mTitleInfo->mTitle.isEmpty()) {
emit addMetaData(Okular::DocumentInfo::Title, mTitleInfo->mTitle);
}
if (!mTitleInfo->mAuthor.isEmpty())
if (!mTitleInfo->mAuthor.isEmpty()) {
emit addMetaData(Okular::DocumentInfo::Author, mTitleInfo->mAuthor);
}
if (!mTitleInfo->mKeywords.isEmpty())
if (!mTitleInfo->mKeywords.isEmpty()) {
emit addMetaData(Okular::DocumentInfo::Keywords, mTitleInfo->mKeywords);
}
}
if (mDocumentInfo) {
if (!mDocumentInfo->mProducer.isEmpty())
if (!mDocumentInfo->mProducer.isEmpty()) {
emit addMetaData(Okular::DocumentInfo::Producer, mDocumentInfo->mProducer);
}
if (mDocumentInfo->mDate.isValid())
if (mDocumentInfo->mDate.isValid()) {
emit addMetaData(Okular::DocumentInfo::CreationDate, QLocale().toString(mDocumentInfo->mDate, QLocale::ShortFormat));
}
}
QMapIterator<QString, QPair<int, int>> it(mLocalLinks);
@ -212,8 +217,9 @@ QTextDocument *Converter::convert(const QString &fileName)
it.next();
const QTextBlock block = mSectionMap[it.key()];
if (!block.isValid()) // local link without existing target
if (!block.isValid()) { // local link without existing target
continue;
}
Okular::DocumentViewport viewport = calculateViewport(mTextDocument, block);
@ -233,17 +239,21 @@ bool Converter::convertBody(const QDomElement &element)
while (!child.isNull()) {
if (child.tagName() == QLatin1String("section")) {
mCursor->insertBlock();
if (!convertSection(child))
if (!convertSection(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("image")) {
if (!convertImage(child))
if (!convertImage(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("title")) {
if (!convertTitle(child))
if (!convertTitle(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("epigraph")) {
if (!convertEpigraph(child))
if (!convertEpigraph(child)) {
return false;
}
}
child = child.nextSiblingElement();
@ -257,12 +267,14 @@ bool Converter::convertDescription(const QDomElement &element)
QDomElement child = element.firstChildElement();
while (!child.isNull()) {
if (child.tagName() == QLatin1String("title-info")) {
if (!convertTitleInfo(child))
if (!convertTitleInfo(child)) {
return false;
}
}
if (child.tagName() == QLatin1String("document-info")) {
if (!convertDocumentInfo(child))
if (!convertDocumentInfo(child)) {
return false;
}
}
child = child.nextSiblingElement();
@ -280,41 +292,50 @@ bool Converter::convertTitleInfo(const QDomElement &element)
while (!child.isNull()) {
if (child.tagName() == QLatin1String("genre")) {
QString genre;
if (!convertTextNode(child, genre))
if (!convertTextNode(child, genre)) {
return false;
}
if (!genre.isEmpty())
if (!genre.isEmpty()) {
mTitleInfo->mGenres.append(genre);
}
} else if (child.tagName() == QLatin1String("author")) {
QString firstName, middleName, lastName, dummy;
if (!convertAuthor(child, firstName, middleName, lastName, dummy, dummy))
if (!convertAuthor(child, firstName, middleName, lastName, dummy, dummy)) {
return false;
}
if (mTitleInfo->mAuthor.isEmpty())
if (mTitleInfo->mAuthor.isEmpty()) {
mTitleInfo->mAuthor = QStringLiteral("%1 %2 %3").arg(firstName, middleName, lastName).simplified();
else
} else {
mTitleInfo->mAuthor += QStringLiteral(", %1 %2 %3").arg(firstName, middleName, lastName).simplified();
}
} else if (child.tagName() == QLatin1String("book-title")) {
if (!convertTextNode(child, mTitleInfo->mTitle))
if (!convertTextNode(child, mTitleInfo->mTitle)) {
return false;
}
} else if (child.tagName() == QLatin1String("keywords")) {
QString keywords;
if (!convertTextNode(child, keywords))
if (!convertTextNode(child, keywords)) {
return false;
}
mTitleInfo->mKeywords = keywords;
} else if (child.tagName() == QLatin1String("annotation")) {
if (!convertAnnotation(child, mTitleInfo->mAnnotation))
if (!convertAnnotation(child, mTitleInfo->mAnnotation)) {
return false;
}
} else if (child.tagName() == QLatin1String("date")) {
if (!convertDate(child, mTitleInfo->mDate))
if (!convertDate(child, mTitleInfo->mDate)) {
return false;
}
} else if (child.tagName() == QLatin1String("coverpage")) {
mTitleInfo->mCoverPage = child;
} else if (child.tagName() == QLatin1String("lang")) {
if (!convertTextNode(child, mTitleInfo->mLanguage))
if (!convertTextNode(child, mTitleInfo->mLanguage)) {
return false;
}
}
child = child.nextSiblingElement();
}
@ -332,22 +353,27 @@ bool Converter::convertDocumentInfo(const QDomElement &element)
if (child.tagName() == QLatin1String("author")) {
QString firstName, middleName, lastName, email, nickname;
if (!convertAuthor(child, firstName, middleName, lastName, email, nickname))
if (!convertAuthor(child, firstName, middleName, lastName, email, nickname)) {
return false;
}
mDocumentInfo->mAuthor = QStringLiteral("%1 %2 %3 <%4> (%5)").arg(firstName, middleName, lastName, email, nickname);
} else if (child.tagName() == QLatin1String("program-used")) {
if (!convertTextNode(child, mDocumentInfo->mProducer))
if (!convertTextNode(child, mDocumentInfo->mProducer)) {
return false;
}
} else if (child.tagName() == QLatin1String("date")) {
if (!convertDate(child, mDocumentInfo->mDate))
if (!convertDate(child, mDocumentInfo->mDate)) {
return false;
}
} else if (child.tagName() == QLatin1String("id")) {
if (!convertTextNode(child, mDocumentInfo->mId))
if (!convertTextNode(child, mDocumentInfo->mId)) {
return false;
}
} else if (child.tagName() == QLatin1String("version")) {
if (!convertTextNode(child, mDocumentInfo->mVersion))
if (!convertTextNode(child, mDocumentInfo->mVersion)) {
return false;
}
}
child = child.nextSiblingElement();
@ -360,20 +386,25 @@ bool Converter::convertAuthor(const QDomElement &element, QString &firstName, QS
QDomElement child = element.firstChildElement();
while (!child.isNull()) {
if (child.tagName() == QLatin1String("first-name")) {
if (!convertTextNode(child, firstName))
if (!convertTextNode(child, firstName)) {
return false;
}
} else if (child.tagName() == QLatin1String("middle-name")) {
if (!convertTextNode(child, middleName))
if (!convertTextNode(child, middleName)) {
return false;
}
} else if (child.tagName() == QLatin1String("last-name")) {
if (!convertTextNode(child, lastName))
if (!convertTextNode(child, lastName)) {
return false;
}
} else if (child.tagName() == QLatin1String("email")) {
if (!convertTextNode(child, email))
if (!convertTextNode(child, email)) {
return false;
}
} else if (child.tagName() == QLatin1String("nickname")) {
if (!convertTextNode(child, nickname))
if (!convertTextNode(child, nickname)) {
return false;
}
}
child = child.nextSiblingElement();
@ -387,8 +418,9 @@ bool Converter::convertTextNode(const QDomElement &element, QString &data)
QDomNode child = element.firstChild();
while (!child.isNull()) {
QDomText text = child.toText();
if (!text.isNull())
if (!text.isNull()) {
data = text.data();
}
child = child.nextSibling();
}
@ -398,8 +430,9 @@ bool Converter::convertTextNode(const QDomElement &element, QString &data)
bool Converter::convertDate(const QDomElement &element, QDate &date)
{
if (element.hasAttribute(QStringLiteral("value")))
if (element.hasAttribute(QStringLiteral("value"))) {
date = QDate::fromString(element.attribute(QStringLiteral("value")), Qt::ISODate);
}
return true;
}
@ -409,8 +442,9 @@ bool Converter::convertAnnotation(const QDomElement &element, QString &data)
QDomElement child = element.firstChildElement();
while (!child.isNull()) {
QString text = child.text();
if (!text.isNull())
if (!text.isNull()) {
data = child.text();
}
child = child.nextSiblingElement();
}
@ -420,49 +454,61 @@ bool Converter::convertAnnotation(const QDomElement &element, QString &data)
bool Converter::convertSection(const QDomElement &element)
{
if (element.hasAttribute(QStringLiteral("id")))
if (element.hasAttribute(QStringLiteral("id"))) {
mSectionMap.insert(element.attribute(QStringLiteral("id")), mCursor->block());
}
mSectionCounter++;
QDomElement child = element.firstChildElement();
while (!child.isNull()) {
if (child.tagName() == QLatin1String("title")) {
if (!convertTitle(child))
if (!convertTitle(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("epigraph")) {
if (!convertEpigraph(child))
if (!convertEpigraph(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("image")) {
if (!convertImage(child))
if (!convertImage(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("section")) {
if (!convertSection(child))
if (!convertSection(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("p")) {
QTextBlockFormat format;
format.setTextIndent(10);
mCursor->insertBlock(format);
if (!convertParagraph(child))
if (!convertParagraph(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("poem")) {
if (!convertPoem(child))
if (!convertPoem(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("subtitle")) {
if (!convertSubTitle(child))
if (!convertSubTitle(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("cite")) {
if (!convertCite(child))
if (!convertCite(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("empty-line")) {
if (!convertEmptyLine(child))
if (!convertEmptyLine(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("code")) {
if (!convertCode(child))
if (!convertCode(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("table")) {
if (!convertTable(child))
if (!convertTable(child)) {
return false;
}
}
child = child.nextSiblingElement();
@ -489,10 +535,11 @@ bool Converter::convertTitle(const QDomElement &element)
bool firstParagraph = true;
while (!child.isNull()) {
if (child.tagName() == QLatin1String("p")) {
if (firstParagraph)
if (firstParagraph) {
firstParagraph = false;
else
} else {
mCursor->insertBlock();
}
QTextCharFormat origFormat = mCursor->charFormat();
@ -501,16 +548,18 @@ bool Converter::convertTitle(const QDomElement &element)
titleFormat.setFontWeight(QFont::Bold);
mCursor->setCharFormat(titleFormat);
if (!convertParagraph(child))
if (!convertParagraph(child)) {
return false;
}
mCursor->setCharFormat(origFormat);
emit addTitle(mSectionCounter, child.text(), mCursor->block());
} else if (child.tagName() == QLatin1String("empty-line")) {
if (!convertEmptyLine(child))
if (!convertEmptyLine(child)) {
return false;
}
}
child = child.nextSiblingElement();
@ -528,32 +577,41 @@ bool Converter::convertParagraph(const QDomElement &element)
if (child.isElement()) {
const QDomElement childElement = child.toElement();
if (childElement.tagName() == QLatin1String("emphasis")) {
if (!convertEmphasis(childElement))
if (!convertEmphasis(childElement)) {
return false;
}
} else if (childElement.tagName() == QLatin1String("strong")) {
if (!convertStrong(childElement))
if (!convertStrong(childElement)) {
return false;
}
} else if (childElement.tagName() == QLatin1String("style")) {
if (!convertStyle(childElement))
if (!convertStyle(childElement)) {
return false;
}
} else if (childElement.tagName() == QLatin1String("a")) {
if (!convertLink(childElement))
if (!convertLink(childElement)) {
return false;
}
} else if (childElement.tagName() == QLatin1String("image")) {
if (!convertImage(childElement))
if (!convertImage(childElement)) {
return false;
}
} else if (childElement.tagName() == QLatin1String("strikethrough")) {
if (!convertStrikethrough(childElement))
if (!convertStrikethrough(childElement)) {
return false;
}
} else if (childElement.tagName() == QLatin1String("code")) {
if (!convertCode(childElement))
if (!convertCode(childElement)) {
return false;
}
} else if (childElement.tagName() == QLatin1String("sup")) {
if (!convertSuperScript(childElement))
if (!convertSuperScript(childElement)) {
return false;
}
} else if (childElement.tagName() == QLatin1String("sub")) {
if (!convertSubScript(childElement))
if (!convertSubScript(childElement)) {
return false;
}
}
} else if (child.isText()) {
const QDomText childText = child.toText();
@ -574,8 +632,9 @@ bool Converter::convertEmphasis(const QDomElement &element)
italicFormat.setFontItalic(true);
mCursor->setCharFormat(italicFormat);
if (!convertParagraph(element))
if (!convertParagraph(element)) {
return false;
}
mCursor->setCharFormat(origFormat);
@ -590,8 +649,9 @@ bool Converter::convertStrikethrough(const QDomElement &element)
strikeoutFormat.setFontStrikeOut(true);
mCursor->setCharFormat(strikeoutFormat);
if (!convertParagraph(element))
if (!convertParagraph(element)) {
return false;
}
mCursor->setCharFormat(origFormat);
@ -606,8 +666,9 @@ bool Converter::convertStrong(const QDomElement &element)
boldFormat.setFontWeight(QFont::Bold);
mCursor->setCharFormat(boldFormat);
if (!convertParagraph(element))
if (!convertParagraph(element)) {
return false;
}
mCursor->setCharFormat(origFormat);
@ -616,8 +677,9 @@ bool Converter::convertStrong(const QDomElement &element)
bool Converter::convertStyle(const QDomElement &element)
{
if (!convertParagraph(element))
if (!convertParagraph(element)) {
return false;
}
return true;
}
@ -640,8 +702,9 @@ bool Converter::convertCover(const QDomElement &element)
QDomElement child = element.firstChildElement();
while (!child.isNull()) {
if (child.tagName() == QLatin1String("image")) {
if (!convertImage(child))
if (!convertImage(child)) {
return false;
}
}
child = child.nextSiblingElement();
@ -654,16 +717,18 @@ bool Converter::convertImage(const QDomElement &element)
{
QString href = element.attributeNS(QStringLiteral("http://www.w3.org/1999/xlink"), QStringLiteral("href"));
if (href.startsWith(QLatin1Char('#')))
if (href.startsWith(QLatin1Char('#'))) {
href = href.mid(1);
}
const QImage img = qvariant_cast<QImage>(mTextDocument->resource(QTextDocument::ImageResource, QUrl(href)));
QTextImageFormat format;
format.setName(href);
if (img.width() > 560)
if (img.width() > 560) {
format.setWidth(560);
}
format.setHeight(img.height());
@ -680,23 +745,28 @@ bool Converter::convertEpigraph(const QDomElement &element)
QTextBlockFormat format;
format.setTextIndent(10);
mCursor->insertBlock(format);
if (!convertParagraph(child))
if (!convertParagraph(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("poem")) {
if (!convertPoem(child))
if (!convertPoem(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("cite")) {
if (!convertCite(child))
if (!convertCite(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("empty-line")) {
if (!convertEmptyLine(child))
if (!convertEmptyLine(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("text-author")) {
QTextBlockFormat format;
format.setTextIndent(10);
mCursor->insertBlock(format);
if (!convertParagraph(child))
if (!convertParagraph(child)) {
return false;
}
}
child = child.nextSiblingElement();
@ -710,23 +780,28 @@ bool Converter::convertPoem(const QDomElement &element)
QDomElement child = element.firstChildElement();
while (!child.isNull()) {
if (child.tagName() == QLatin1String("title")) {
if (!convertTitle(child))
if (!convertTitle(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("epigraph")) {
if (!convertEpigraph(child))
if (!convertEpigraph(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("empty-line")) {
if (!convertEmptyLine(child))
if (!convertEmptyLine(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("stanza")) {
if (!convertStanza(child))
if (!convertStanza(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("text-author")) {
QTextBlockFormat format;
format.setTextIndent(10);
mCursor->insertBlock(format);
if (!convertParagraph(child))
if (!convertParagraph(child)) {
return false;
}
}
child = child.nextSiblingElement();
@ -764,26 +839,32 @@ bool Converter::convertCite(const QDomElement &element)
QTextBlockFormat format;
format.setTextIndent(10);
mCursor->insertBlock(format);
if (!convertParagraph(child))
if (!convertParagraph(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("poem")) {
if (!convertParagraph(child))
if (!convertParagraph(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("text-author")) {
QTextBlockFormat format;
format.setTextIndent(10);
mCursor->insertBlock(format);
if (!convertParagraph(child))
if (!convertParagraph(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("empty-line")) {
if (!convertEmptyLine(child))
if (!convertEmptyLine(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("subtitle")) {
if (!convertSubTitle(child))
if (!convertSubTitle(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("table")) {
if (!convertTable(child))
if (!convertTable(child)) {
return false;
}
}
child = child.nextSiblingElement();
@ -803,8 +884,9 @@ bool Converter::convertLink(const QDomElement &element)
QString href = element.attributeNS(QStringLiteral("http://www.w3.org/1999/xlink"), QStringLiteral("href"));
QString type = element.attributeNS(QStringLiteral("http://www.w3.org/1999/xlink"), QStringLiteral("type"));
if (type == QLatin1String("note"))
if (type == QLatin1String("note")) {
mCursor->insertText(QStringLiteral("["));
}
int startPosition = mCursor->position();
@ -820,14 +902,17 @@ bool Converter::convertLink(const QDomElement &element)
if (child.isElement()) {
const QDomElement childElement = child.toElement();
if (childElement.tagName() == QLatin1String("emphasis")) {
if (!convertEmphasis(childElement))
if (!convertEmphasis(childElement)) {
return false;
}
} else if (childElement.tagName() == QLatin1String("strong")) {
if (!convertStrong(childElement))
if (!convertStrong(childElement)) {
return false;
}
} else if (childElement.tagName() == QLatin1String("style")) {
if (!convertStyle(childElement))
if (!convertStyle(childElement)) {
return false;
}
}
} else if (child.isText()) {
const QDomText text = child.toText();
@ -842,8 +927,9 @@ bool Converter::convertLink(const QDomElement &element)
int endPosition = mCursor->position();
if (type == QLatin1String("note"))
if (type == QLatin1String("note")) {
mCursor->insertText(QStringLiteral("]"));
}
if (href.startsWith(QLatin1Char('#'))) { // local link
mLocalLinks.insert(href.mid(1), QPair<int, int>(startPosition, endPosition));
@ -861,17 +947,20 @@ bool Converter::convertStanza(const QDomElement &element)
QDomElement child = element.firstChildElement();
while (!child.isNull()) {
if (child.tagName() == QLatin1String("title")) {
if (!convertTitle(child))
if (!convertTitle(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("subtitle")) {
if (!convertSubTitle(child))
if (!convertSubTitle(child)) {
return false;
}
} else if (child.tagName() == QLatin1String("v")) {
QTextBlockFormat format;
format.setTextIndent(50);
mCursor->insertBlock(format);
if (!convertParagraph(child))
if (!convertParagraph(child)) {
return false;
}
}
child = child.nextSiblingElement();
@ -888,8 +977,9 @@ bool Converter::convertCode(const QDomElement &element)
codeFormat.setFontFamily(QStringLiteral("monospace"));
mCursor->setCharFormat(codeFormat);
if (!convertParagraph(element))
if (!convertParagraph(element)) {
return false;
}
mCursor->setCharFormat(origFormat);
@ -904,8 +994,9 @@ bool Converter::convertSuperScript(const QDomElement &element)
superScriptFormat.setVerticalAlignment(QTextCharFormat::AlignSuperScript);
mCursor->setCharFormat(superScriptFormat);
if (!convertParagraph(element))
if (!convertParagraph(element)) {
return false;
}
mCursor->setCharFormat(origFormat);
@ -920,8 +1011,9 @@ bool Converter::convertSubScript(const QDomElement &element)
subScriptFormat.setVerticalAlignment(QTextCharFormat::AlignSubScript);
mCursor->setCharFormat(subScriptFormat);
if (!convertParagraph(element))
if (!convertParagraph(element)) {
return false;
}
mCursor->setCharFormat(origFormat);
@ -945,8 +1037,9 @@ bool Converter::convertTable(const QDomElement &element)
table = mCursor->insertTable(1, 1, tableFormat);
}
if (!convertTableRow(child, *table))
if (!convertTableRow(child, *table)) {
return false;
}
}
child = child.nextSiblingElement();
@ -963,11 +1056,13 @@ bool Converter::convertTableRow(const QDomElement &element, QTextTable &table)
int column = 0;
while (!child.isNull()) {
if (child.tagName() == QLatin1String("th")) {
if (!convertTableHeaderCell(child, table, column))
if (!convertTableHeaderCell(child, table, column)) {
return false;
}
} else if (child.tagName() == QLatin1String("td")) {
if (!convertTableCell(child, table, column))
if (!convertTableCell(child, table, column)) {
return false;
}
}
child = child.nextSiblingElement();
@ -1031,8 +1126,9 @@ bool Converter::convertTableCellHelper(const QDomElement &element, QTextTable &t
format.setAlignment(alignment);
mCursor->insertBlock(format, charFormat);
if (!convertParagraph(element))
if (!convertParagraph(element)) {
return false;
}
column += colspan;
return true;

View File

@ -131,8 +131,9 @@ QImage KIMGIOGenerator::image(Okular::PixmapRequest *request)
} else {
int width = request->width();
int height = request->height();
if (request->page()->rotation() % 2 == 1)
if (request->page()->rotation() % 2 == 1) {
qSwap(width, height);
}
return m_img.scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
}
@ -144,9 +145,9 @@ Okular::Document::PrintError KIMGIOGenerator::print(QPrinter &printer)
QImage image(m_img);
if ((image.width() > printer.width()) || (image.height() > printer.height()))
if ((image.width() > printer.width()) || (image.height() > printer.height())) {
image = image.scaled(printer.width(), printer.height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
}
p.drawImage(0, 0, image);

View File

@ -96,8 +96,9 @@ QTextDocument *Converter::convertOpenFile()
MMIOT *markdownHandle = mkd_in(m_markdownFile, 0);
int flags = MKD_FENCEDCODE | MKD_GITHUBTAGS | MKD_AUTOLINK | MKD_TOC | MKD_IDANCHOR;
if (!m_isFancyPantsEnabled)
if (!m_isFancyPantsEnabled) {
flags |= MKD_NOPANTS;
}
if (!mkd_compile(markdownHandle, flags)) {
emit error(i18n("Failed to compile the Markdown document."), -1);
return nullptr;
@ -111,8 +112,9 @@ QTextDocument *Converter::convertOpenFile()
QTextDocument *textDocument = new QTextDocument;
textDocument->setPageSize(QSizeF(PAGE_WIDTH, PAGE_HEIGHT));
textDocument->setHtml(html);
if (generator())
if (generator()) {
textDocument->setDefaultFont(generator()->generalSettings()->font());
}
mkd_cleanup(markdownHandle);

View File

@ -77,22 +77,26 @@ QTextDocument *Converter::convert(const QString &fileName)
QMap<QString, QTextBlock> targets;
// go over whole document and add all <a> tags to links or targets map
for (QTextBlock it = newDocument->begin(); it != newDocument->end(); it = it.next())
for (QTextBlock it = newDocument->begin(); it != newDocument->end(); it = it.next()) {
for (QTextBlock::iterator fit = it.begin(); !fit.atEnd(); ++fit) {
QTextFragment frag = fit.fragment();
QTextCharFormat format = frag.charFormat();
if (!format.isAnchor())
if (!format.isAnchor()) {
continue;
}
// link
if (!format.anchorHref().isEmpty())
if (!format.anchorHref().isEmpty()) {
links[format.anchorHref()] = QPair<int, int>(frag.position(), frag.position() + frag.length());
}
const QStringList anchors = format.anchorNames();
if (!anchors.isEmpty()) {
// link targets
for (const QString &name : anchors)
for (const QString &name : anchors) {
targets[QLatin1Char('#') + name] = it;
}
}
}
}
// create link actions
QMapIterator<QString, QPair<int, int>> it(links);
@ -100,12 +104,13 @@ QTextDocument *Converter::convert(const QString &fileName)
it.next();
QUrl u(it.key());
// external or internal link
if (!u.isRelative())
if (!u.isRelative()) {
emit addAction(new Okular::BrowseAction(QUrl(it.key())), it.value().first, it.value().second);
else {
} else {
// is there valid target?
if (!targets.contains(it.key()) || !targets[it.key()].isValid())
if (!targets.contains(it.key()) || !targets[it.key()].isValid()) {
continue;
}
emit addAction(new Okular::GotoAction(QString(), calculateViewport(newDocument, targets[it.key()])), it.value().first, it.value().second);
}
}

View File

@ -51,12 +51,14 @@ MobiDocument::~MobiDocument()
QVariant MobiDocument::loadResource(int type, const QUrl &name)
{
if (type != QTextDocument::ImageResource || name.scheme() != QString(QStringLiteral("pdbrec")))
if (type != QTextDocument::ImageResource || name.scheme() != QString(QStringLiteral("pdbrec"))) {
return QVariant();
}
bool ok;
quint16 recnum = name.path().midRef(1).toUShort(&ok);
if (!ok || recnum >= doc->imageCount())
if (!ok || recnum >= doc->imageCount()) {
return QVariant();
}
QVariant resource;
resource.setValue(doc->getImage(recnum - 1));
@ -69,10 +71,12 @@ QVariant MobiDocument::loadResource(int type, const QUrl &name)
int outsideTag(const QString &data, int pos)
{
for (int i = pos - 1; i >= 0; i--) {
if (data[i] == QLatin1Char('>'))
if (data[i] == QLatin1Char('>')) {
return pos;
if (data[i] == QLatin1Char('<'))
}
if (data[i] == QLatin1Char('<')) {
return i;
}
}
return pos;
}
@ -87,8 +91,9 @@ QString MobiDocument::fixMobiMarkup(const QString &data)
// find all link destinations
while ((pos = anchors.indexIn(data, pos)) != -1) {
int filepos = anchors.cap(1).toUInt();
if (filepos)
if (filepos) {
anchorPositions[filepos] = anchors.cap(1);
}
pos += anchors.matchedLength();
}
@ -98,8 +103,9 @@ QString MobiDocument::fixMobiMarkup(const QString &data)
while (it.hasNext()) {
it.next();
// link pointing outside the document, ignore
if ((it.key() + offset) >= ret.size())
if ((it.key() + offset) >= ret.size()) {
continue;
}
int fixedpos = outsideTag(ret, it.key() + offset);
ret.insert(fixedpos, QStringLiteral("<a name=\"") + it.value() + QStringLiteral("\">&nbsp;</a>"));
// inserting anchor shifts all offsets after the anchor

View File

@ -57,8 +57,9 @@ bool PluckerGenerator::loadDocument(const QString &fileName, QVector<Okular::Pag
{
QUnpluck unpluck;
if (!unpluck.open(fileName))
if (!unpluck.open(fileName)) {
return false;
}
mPages = unpluck.pages();
mLinks = unpluck.links();
@ -68,14 +69,15 @@ bool PluckerGenerator::loadDocument(const QString &fileName, QVector<Okular::Pag
while (it.hasNext()) {
it.next();
if (!it.value().isEmpty()) {
if (it.key() == QLatin1String("name"))
if (it.key() == QLatin1String("name")) {
mDocumentInfo.set(QStringLiteral("name"), it.value(), i18n("Name"));
else if (it.key() == QLatin1String("title"))
} else if (it.key() == QLatin1String("title")) {
mDocumentInfo.set(Okular::DocumentInfo::Title, it.value());
else if (it.key() == QLatin1String("author"))
} else if (it.key() == QLatin1String("author")) {
mDocumentInfo.set(Okular::DocumentInfo::Author, it.value());
else if (it.key() == QLatin1String("time"))
} else if (it.key() == QLatin1String("time")) {
mDocumentInfo.set(Okular::DocumentInfo::CreationDate, it.value());
}
}
}
@ -139,8 +141,9 @@ QImage PluckerGenerator::image(Okular::PixmapRequest *request)
}
}
if (!objects.isEmpty())
if (!objects.isEmpty()) {
request->page()->setObjectRects(objects);
}
mLinkAdded.insert(request->pageNumber());
}
@ -151,8 +154,9 @@ QImage PluckerGenerator::image(Okular::PixmapRequest *request)
Okular::ExportFormat::List PluckerGenerator::exportFormats() const
{
static Okular::ExportFormat::List formats;
if (formats.isEmpty())
if (formats.isEmpty()) {
formats.append(Okular::ExportFormat::standardFormat(Okular::ExportFormat::PlainText));
}
return formats;
}
@ -161,8 +165,9 @@ bool PluckerGenerator::exportTo(const QString &fileName, const Okular::ExportFor
{
if (format.mimeType().name() == QLatin1String("text/plain")) {
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly))
if (!file.open(QIODevice::WriteOnly)) {
return false;
}
QTextStream out(&file);
for (int i = 0; i < mPages.count(); ++i) {

View File

@ -43,8 +43,9 @@ static HashTable *GetOrCreateSegment(const char *name)
{
HashTable *target;
if (SectionsTable == nullptr)
if (SectionsTable == nullptr) {
SectionsTable = _plkr_NewHashTable(23);
}
if ((target = (HashTable *)_plkr_FindInTable(SectionsTable, name)) == nullptr) {
target = _plkr_NewHashTable(53);
@ -84,28 +85,34 @@ static int ReadConfigFile(const char *filename)
while (true) {
ptr = fgets(linebuf, sizeof(linebuf) - 1, fp);
if (ptr == nullptr)
if (ptr == nullptr) {
break;
}
line_number += 1;
linebuf[strlen(linebuf) - 1] = 0; /* strip newline */
if (linebuf[strlen(linebuf) - 1] == '\r')
if (linebuf[strlen(linebuf) - 1] == '\r') {
linebuf[strlen(linebuf) - 1] = 0; /* strip carriage return */
}
/* fprintf (stderr, "%s:%d: line is '%s'\n", filename, line_number, linebuf); */
linelen = strlen(linebuf);
for (buf_index = 0; linebuf[buf_index] != 0; buf_index++)
if (!isspace(linebuf[buf_index]))
for (buf_index = 0; linebuf[buf_index] != 0; buf_index++) {
if (!isspace(linebuf[buf_index])) {
break;
}
}
if (linebuf[buf_index] == 0)
if (linebuf[buf_index] == 0) {
/* blank line */
continue;
}
if ((strchr(COMMENT_CHARS, linebuf[0]) != nullptr) || (strncmp(linebuf, "rem", 3) == 0) || (strncmp(linebuf, "REM", 3) == 0))
if ((strchr(COMMENT_CHARS, linebuf[0]) != nullptr) || (strncmp(linebuf, "rem", 3) == 0) || (strncmp(linebuf, "REM", 3) == 0)) {
/* comment */
continue;
}
/* At this point we have a valid thing */
@ -116,20 +123,23 @@ static int ReadConfigFile(const char *filename)
goto error_exit;
}
str_begin = linebuf + buf_index + 1;
for (charptr = str_begin; charptr < str_end; charptr++)
for (charptr = str_begin; charptr < str_end; charptr++) {
*charptr = tolower(*charptr);
}
*str_end = 0;
current_segment = GetOrCreateSegment(str_begin);
/* fprintf (stderr, "Current segment is now %p (%s)\n", current_segment, str_begin); */
if (current_option)
if (current_option) {
free(current_option);
}
current_option = nullptr;
} else if ((linebuf[0] == ' ' || linebuf[0] == '\t') && current_option != nullptr) {
/* continuation line */
str_begin = (char *)_plkr_RemoveFromTable(current_segment, current_option);
for (str_end = linebuf + strlen(linebuf) - 1; str_end > linebuf && isspace(*str_end); str_end--)
for (str_end = linebuf + strlen(linebuf) - 1; str_end > linebuf && isspace(*str_end); str_end--) {
;
}
charptr = (char *)malloc(strlen(str_begin) + (str_end - (linebuf + buf_index)) + 2);
strcpy(charptr, str_begin);
len2 = strlen(charptr);
@ -142,44 +152,50 @@ static int ReadConfigFile(const char *filename)
} else if ((int)strcspn(linebuf, OPTION_SEPARATOR_CHARS) < linelen) {
/* possible option line */
for (str_begin = linebuf + buf_index, ptr = str_begin; isalnum(*ptr) || (*ptr == '.') || (*ptr == '_') || (*ptr == '-'); ptr++)
for (str_begin = linebuf + buf_index, ptr = str_begin; isalnum(*ptr) || (*ptr == '.') || (*ptr == '_') || (*ptr == '-'); ptr++) {
;
}
if (ptr == str_begin) {
_plkr_message("%s:%d: Invalid option line '%s'", filename, line_number, linebuf);
goto error_exit;
}
for (charptr = str_begin; charptr < ptr; charptr++)
for (charptr = str_begin; charptr < ptr; charptr++) {
*charptr = tolower(*charptr);
}
str_end = ptr;
while (isspace(*ptr) && (*ptr != '\0'))
while (isspace(*ptr) && (*ptr != '\0')) {
ptr++;
}
if (strchr(OPTION_SEPARATOR_CHARS, *ptr) != nullptr)
if (strchr(OPTION_SEPARATOR_CHARS, *ptr) != nullptr) {
ptr++;
else {
} else {
_plkr_message("%s:%d: Invalid option line '%s'", filename, line_number, linebuf);
goto error_exit;
}
while (isspace(*ptr) && (*ptr != '\0'))
while (isspace(*ptr) && (*ptr != '\0')) {
ptr++;
}
if (*ptr == 0) {
_plkr_message("%s:%d: Invalid option line '%s'", filename, line_number, linebuf);
goto error_exit;
}
if (current_option)
if (current_option) {
free(current_option);
}
current_option = _plkr_strndup(str_begin, str_end - str_begin);
option_value = _plkr_strndup(ptr, strlen(ptr));
ptr = (char *)_plkr_RemoveFromTable(current_segment, current_option);
if (ptr)
if (ptr) {
free(ptr);
}
_plkr_AddToTable(current_segment, current_option, option_value);
/* fprintf (stderr, "Added value '%s' for option '%p:%s'\n", option_value, current_segment, current_option); */
@ -191,8 +207,9 @@ static int ReadConfigFile(const char *filename)
good_exit:
if (current_option)
if (current_option) {
free(current_option);
}
fclose(fp);
return status;
@ -205,15 +222,17 @@ static void TryReadConfigFile(const char *dir, const char *name)
{
char *filename;
if (dir == nullptr || name == nullptr)
if (dir == nullptr || name == nullptr) {
return;
}
filename = (char *)malloc(strlen(dir) + strlen(name) + 2);
strcpy(filename, dir);
strcpy(filename + strlen(filename), STRINGIFY(FILE_SEPARATOR_CHAR_S));
strcpy(filename + strlen(filename), name);
if (!ReadConfigFile(filename))
if (!ReadConfigFile(filename)) {
_plkr_message("Error reading config file %s", filename);
}
free(filename);
}
@ -225,8 +244,9 @@ static void InitializeConfigInfo()
char *home = getenv("HOME"); // clazy:exclude=raw-environment-function
TryReadConfigFile(config_dir, system_config_file_name);
if (home != nullptr)
if (home != nullptr) {
TryReadConfigFile(home, user_config_filename);
}
}
char *plkr_GetConfigString(const char *section_name, const char *option_name, char *default_value)
@ -234,23 +254,28 @@ char *plkr_GetConfigString(const char *section_name, const char *option_name, ch
char *value = nullptr;
HashTable *section;
if (SectionsTable == nullptr)
if (SectionsTable == nullptr) {
InitializeConfigInfo();
}
if (SectionsTable == nullptr)
if (SectionsTable == nullptr) {
return default_value;
}
if (section_name != nullptr) {
if ((section = (HashTable *)_plkr_FindInTable(SectionsTable, section_name)) != nullptr)
if ((section = (HashTable *)_plkr_FindInTable(SectionsTable, section_name)) != nullptr) {
value = (char *)_plkr_FindInTable(section, option_name);
}
}
if (value == nullptr && ((section_name == nullptr) || (strcmp(section_name, "default") != 0))) {
if ((section = (HashTable *)_plkr_FindInTable(SectionsTable, STRINGIFY(OS_SECTION_NAME))) != nullptr)
if ((section = (HashTable *)_plkr_FindInTable(SectionsTable, STRINGIFY(OS_SECTION_NAME))) != nullptr) {
value = (char *)_plkr_FindInTable(section, option_name);
}
}
if (value == nullptr && ((section_name == nullptr) || (strcmp(section_name, "default") != 0))) {
if ((section = (HashTable *)_plkr_FindInTable(SectionsTable, "default")) != nullptr)
if ((section = (HashTable *)_plkr_FindInTable(SectionsTable, "default")) != nullptr) {
value = (char *)_plkr_FindInTable(section, option_name);
}
}
return ((value == nullptr) ? default_value : value);
@ -262,8 +287,9 @@ long int plkr_GetConfigInt(const char *section_name, const char *option_name, lo
char *endptr;
long int value;
if (svalue == nullptr)
if (svalue == nullptr) {
return default_value;
}
value = strtol(svalue, &endptr, 0);
if (*endptr != 0) {
@ -280,8 +306,9 @@ double plkr_GetConfigFloat(const char *section_name, const char *option_name, do
char *endptr;
double value;
if (svalue == nullptr)
if (svalue == nullptr) {
return default_value;
}
value = strtod(svalue, &endptr);
if (*endptr != 0) {
@ -296,18 +323,19 @@ int plkr_GetConfigBoolean(const char *section_name, const char *option_name, int
{
char *svalue = plkr_GetConfigString(section_name, option_name, nullptr);
if (svalue == nullptr)
if (svalue == nullptr) {
return default_value;
}
if ((strcmp(svalue, "1") == 0) || (strcmp(svalue, "true") == 0) || (strcmp(svalue, "TRUE") == 0) || (strcmp(svalue, "on") == 0) || (strcmp(svalue, "ON") == 0) || (strcmp(svalue, "t") == 0) || (strcmp(svalue, "T") == 0) ||
(strcmp(svalue, "True") == 0))
(strcmp(svalue, "True") == 0)) {
return 1;
else if ((strcmp(svalue, "0") == 0) || (strcmp(svalue, "false") == 0) || (strcmp(svalue, "FALSE") == 0) || (strcmp(svalue, "off") == 0) || (strcmp(svalue, "OFF") == 0) || (strcmp(svalue, "F") == 0) || (strcmp(svalue, "f") == 0) ||
(strcmp(svalue, "False") == 0))
} else if ((strcmp(svalue, "0") == 0) || (strcmp(svalue, "false") == 0) || (strcmp(svalue, "FALSE") == 0) || (strcmp(svalue, "off") == 0) || (strcmp(svalue, "OFF") == 0) || (strcmp(svalue, "F") == 0) || (strcmp(svalue, "f") == 0) ||
(strcmp(svalue, "False") == 0)) {
return 0;
else {
} else {
_plkr_message("Bad boolean value string '%s' for option %s:%s", svalue, (section_name ? section_name : "default"), option_name);
return default_value;
}

View File

@ -196,8 +196,9 @@ bool TranscribePalmImageToJPEG(unsigned char *image_bytes_in, QImage &image)
QTemporaryFile tempFile;
tempFile.open();
FILE *outfile = fopen(QFile::encodeName(tempFile.fileName()).constData(), "w");
if (!outfile)
if (!outfile) {
return false;
}
/* now create the JPEG image row buffer */
jpeg_row = (JSAMPLE *)malloc(sizeof(JSAMPLE) * (width * 3));
@ -250,10 +251,11 @@ bool TranscribePalmImageToJPEG(unsigned char *image_bytes_in, QImage &image)
incount = *palm_ptr++;
inval = ((bytes_per_row - j) < 8) ? (bytes_per_row - j) : 8;
for (inbit = 0; inbit < inval; inbit += 1) {
if (incount & (1 << (7 - inbit)))
if (incount & (1 << (7 - inbit))) {
rowbuf[j + inbit] = *palm_ptr++;
else
} else {
rowbuf[j + inbit] = lastrow[j + inbit];
}
}
}
memcpy(lastrow, rowbuf, bytes_per_row);
@ -268,8 +270,9 @@ bool TranscribePalmImageToJPEG(unsigned char *image_bytes_in, QImage &image)
for (inbit = 8 - bits_per_pixel, inbyte = rowbuf, j = 0; j < width; ++j) {
inval = ((*inbyte) & (mask << inbit)) >> inbit;
/* correct for oddity of the 8-bit color Palm pixmap... */
if ((bits_per_pixel == 8) && (inval == 0xFF))
if ((bits_per_pixel == 8) && (inval == 0xFF)) {
inval = 231;
}
/* now lookup the correct color and set the pixel in the GTK bitmap */
jpeg_row[(j * 3) + 0] = colormap[inval].red;
jpeg_row[(j * 3) + 1] = colormap[inval].green;

View File

@ -84,8 +84,9 @@ public:
static Okular::DocumentViewport calculateViewport(QTextDocument *document, const QTextBlock &block)
{
if (!block.isValid())
if (!block.isValid()) {
return Okular::DocumentViewport();
}
const QRectF rect = document->documentLayout()->blockBoundingRect(block);
const QSizeF size = document->size();
@ -141,8 +142,9 @@ bool QUnpluck::open(const QString &fileName)
}
// Iterate over all records again to add those which aren't linked directly
for (int i = 1; i < plkr_GetRecordCount(mDocument); ++i)
for (int i = 1; i < plkr_GetRecordCount(mDocument); ++i) {
AddRecord(plkr_GetUidForIndex(mDocument, i));
}
number = GetNextRecordNumber();
while (number > 0) {
@ -150,8 +152,9 @@ bool QUnpluck::open(const QString &fileName)
number = GetNextRecordNumber();
}
for (int i = 0; i < mRecords.count(); ++i)
for (int i = 0; i < mRecords.count(); ++i) {
delete mRecords[i];
}
mRecords.clear();
@ -161,8 +164,9 @@ bool QUnpluck::open(const QString &fileName)
* Calculate hash map
*/
QHash<int, int> pageHash;
for (int i = 0; i < mContext.count(); ++i)
for (int i = 0; i < mContext.count(); ++i) {
pageHash.insert(mContext[i]->recordId, i);
}
/**
* Convert ids
@ -283,20 +287,25 @@ QString QUnpluck::MailtoURLFromBytes(unsigned char *record_data)
int body_offset = (bytes[6] << 8) + bytes[7];
QString url(QStringLiteral("mailto:"));
if (to_offset != 0)
if (to_offset != 0) {
url += QString::fromLatin1((char *)(bytes + to_offset));
}
if ((cc_offset != 0) || (subject_offset != 0) || (body_offset != 0))
if ((cc_offset != 0) || (subject_offset != 0) || (body_offset != 0)) {
url += QLatin1String("?");
}
if (cc_offset != 0)
if (cc_offset != 0) {
url += QLatin1String("cc=") + QString::fromLatin1((char *)(bytes + cc_offset));
}
if (subject_offset != 0)
if (subject_offset != 0) {
url += QLatin1String("subject=") + QString::fromLatin1((char *)(bytes + subject_offset));
}
if (body_offset != 0)
if (body_offset != 0) {
url += QLatin1String("body=") + QString::fromLatin1((char *)(bytes + body_offset));
}
return url;
}
@ -351,8 +360,9 @@ void QUnpluck::DoStyle(Context *context, int style, bool start)
format.setFontPointSize(qMax(pointSize, 1));
context->cursor->setCharFormat(format);
} else {
if (!context->stack.isEmpty())
if (!context->stack.isEmpty()) {
context->cursor->setCharFormat(context->stack.pop());
}
}
}
@ -427,8 +437,9 @@ void QUnpluck::ParseText(plkr_Document *doc, unsigned char *ptr, int text_len, i
case PLKR_TFC_COLOR:
if (*font) {
(*font)--;
if (!context->stack.isEmpty())
if (!context->stack.isEmpty()) {
context->cursor->setCharFormat(context->stack.pop());
}
}
{
@ -716,8 +727,9 @@ bool QUnpluck::TranscribeTextRecord(plkr_Document *doc, int id, Context *context
if (fclen == 0) {
if (current_link) {
if (!context->stack.isEmpty())
if (!context->stack.isEmpty()) {
context->cursor->setCharFormat(context->stack.pop());
}
if (!context->linkUrl.isEmpty()) {
Link link;
@ -790,8 +802,9 @@ bool QUnpluck::TranscribeTextRecord(plkr_Document *doc, int id, Context *context
} else if (fctype == PLKR_TFC_FONT) {
if (current_font != *ptr) {
if (!context->stack.isEmpty())
if (!context->stack.isEmpty()) {
context->cursor->setCharFormat(context->stack.pop());
}
QTextCharFormat format(context->cursor->charFormat());
context->stack.push(format);
@ -885,14 +898,15 @@ bool QUnpluck::TranscribeTextRecord(plkr_Document *doc, int id, Context *context
if (*ptr < 4) {
QTextBlockFormat format(context->cursor->blockFormat());
if (*ptr == 0)
if (*ptr == 0) {
format.setAlignment(Qt::AlignLeft);
else if (*ptr == 1)
} else if (*ptr == 1) {
format.setAlignment(Qt::AlignRight);
else if (*ptr == 2)
} else if (*ptr == 2) {
format.setAlignment(Qt::AlignCenter);
else if (*ptr == 3)
} else if (*ptr == 3) {
format.setAlignment(Qt::AlignJustify);
}
QTextCharFormat charFormat(context->cursor->charFormat());
context->cursor->insertBlock(format);
@ -927,10 +941,11 @@ bool QUnpluck::TranscribeTextRecord(plkr_Document *doc, int id, Context *context
TranscribeTableRecord(doc, context, bytes);
} else if (fctype == PLKR_TFC_UCHAR) {
if (fclen == 3)
if (fclen == 3) {
context->cursor->insertText(QChar((ptr[1] << 8) + ptr[2]));
else if (fclen == 5)
} else if (fclen == 5) {
context->cursor->insertText(QChar((ptr[3] << 8) + ptr[4]));
}
/* skip over alternate text */
ptr += ptr[0];
}
@ -952,8 +967,9 @@ bool QUnpluck::TranscribeTextRecord(plkr_Document *doc, int id, Context *context
/* clear the graphics state again */
if (current_font > 0 && current_font < 9) {
if (!context->stack.isEmpty())
if (!context->stack.isEmpty()) {
context->cursor->setCharFormat(context->stack.pop());
}
}
if (current_italic) {
@ -1015,8 +1031,9 @@ bool QUnpluck::TranscribeRecord(int index)
mImages.insert(index, image);
} else if (type == PLKR_DRTYPE_MULTIIMAGE) {
QImage image;
if (TranscribeMultiImageRecord(mDocument, image, data))
if (TranscribeMultiImageRecord(mDocument, image, data)) {
mImages.insert(index, image);
}
} else {
status = false;
}

Some files were not shown because too many files have changed in this diff Show More