Skip to content
This repository was archived by the owner on May 6, 2025. It is now read-only.

Fix page breaks in reflowable Epub books #229

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Platform/Apple/ePub3.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
588D24201A02EF8F006A92BB /* PassThroughFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 588D241E1A02EF8F006A92BB /* PassThroughFilter.cpp */; };
588D24211A02EF8F006A92BB /* PassThroughFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 588D241E1A02EF8F006A92BB /* PassThroughFilter.cpp */; };
588D24221A02EF8F006A92BB /* PassThroughFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 588D241F1A02EF8F006A92BB /* PassThroughFilter.h */; };
59753FDB1C88972600EE7908 /* css_preprocessor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 59753FD91C88972600EE7908 /* css_preprocessor.cpp */; };
59753FDC1C88972600EE7908 /* css_preprocessor.h in Headers */ = {isa = PBXBuildFile; fileRef = 59753FDA1C88972600EE7908 /* css_preprocessor.h */; };
59D714EA1C8E1FCD00F6CBDA /* css_preprocessor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 59753FD91C88972600EE7908 /* css_preprocessor.cpp */; };
834B09011A0BD015006AEB12 /* filter_chain_byte_stream_range.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A250D33BAFB8E8EAEF5FE5B5 /* filter_chain_byte_stream_range.cpp */; };
834B09021A0BD018006AEB12 /* filter_chain_byte_stream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A250DFDBD90C7E9C632B1E00 /* filter_chain_byte_stream.cpp */; };
850B1AE916A75AC600619C3C /* TestData in CopyFiles */ = {isa = PBXBuildFile; fileRef = 850B1AE816A75AB000619C3C /* TestData */; };
Expand Down Expand Up @@ -447,6 +450,8 @@
1EFA3ACA17AB0BEF003A4BC2 /* filter_manager_impl.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = filter_manager_impl.cpp; sourceTree = "<group>"; };
588D241E1A02EF8F006A92BB /* PassThroughFilter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PassThroughFilter.cpp; sourceTree = "<group>"; };
588D241F1A02EF8F006A92BB /* PassThroughFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PassThroughFilter.h; sourceTree = "<group>"; };
59753FD91C88972600EE7908 /* css_preprocessor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = css_preprocessor.cpp; sourceTree = "<group>"; };
59753FDA1C88972600EE7908 /* css_preprocessor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = css_preprocessor.h; sourceTree = "<group>"; };
850B1AE816A75AB000619C3C /* TestData */ = {isa = PBXFileReference; lastKnownFileType = folder; name = TestData; path = ../../TestData; sourceTree = "<group>"; };
A250D0D74FF2AD1AB643D2FA /* media-overlays_smil_data.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "media-overlays_smil_data.h"; sourceTree = "<group>"; };
A250D119DCB804938466E3D6 /* media-overlays_smil_model.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "media-overlays_smil_model.cpp"; sourceTree = "<group>"; };
Expand Down Expand Up @@ -1131,6 +1136,8 @@
AB95448216BAD32000EFD2FD /* switch_preprocessor.h */,
AB95448616BAF11000EFD2FD /* object_preprocessor.cpp */,
AB95448716BAF11000EFD2FD /* object_preprocessor.h */,
59753FD91C88972600EE7908 /* css_preprocessor.cpp */,
59753FDA1C88972600EE7908 /* css_preprocessor.h */,
);
name = "Content Preprocessing";
sourceTree = "<group>";
Expand Down Expand Up @@ -1837,6 +1844,7 @@
ABA4BA5D16A7414000161B77 /* logging.h in Headers */,
ABA4BA5F16A7414000161B77 /* scoped_ptr.h in Headers */,
ABA4BA6316A7414000161B77 /* string16.h in Headers */,
59753FDC1C88972600EE7908 /* css_preprocessor.h in Headers */,
ABA4BA6716A7414000161B77 /* gurl.h in Headers */,
ABA4BA6D16A7414000161B77 /* url_canon.h in Headers */,
ABA4BA7916A7414000161B77 /* url_canon_icu.h in Headers */,
Expand Down Expand Up @@ -2029,6 +2037,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
59D714EA1C8E1FCD00F6CBDA /* css_preprocessor.cpp in Sources */,
ABA4BAEF16ADF64400161B77 /* string16.cc in Sources */,
ABA4BAF016ADF64400161B77 /* gurl.cc in Sources */,
AB5284D417CBC395003D7BBF /* CPUCacheUtils.c in Sources */,
Expand Down Expand Up @@ -2305,6 +2314,7 @@
1ED0083B17A9B7F800819EBD /* byte_buffer.cpp in Sources */,
1ED0084417A9D6E800819EBD /* filter_manager.cpp in Sources */,
A250D0731D530005B0FFF5D5 /* media-overlays_smil_model.cpp in Sources */,
59753FDB1C88972600EE7908 /* css_preprocessor.cpp in Sources */,
A250DCD0523C05493141CE3B /* media-overlays_smil_data.cpp in Sources */,
1ED0084817A9DC6F00819EBD /* initialization.cpp in Sources */,
1EFA3ACB17AB0BEF003A4BC2 /* filter_manager_impl.cpp in Sources */,
Expand Down
157 changes: 157 additions & 0 deletions ePub3/ePub/css_preprocessor.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
//
// css_preprocessor.cpp
// ePub3
//
// Created by Olivier Körner on 2016-03-08.
// Copyright (c) 2016 Readium Foundation and/or its licensees. All rights reserved.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// Licensed under Gnu Affero General Public License Version 3 (provided, notwithstanding this notice,
// Readium Foundation reserves the right to license this material under a different separate license,
// and if you have done so, the terms of that separate license control and the following references
// to GPL do not apply).
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU
// Affero General Public License as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version. You should have received a copy of the GNU
// Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.

#include "css_preprocessor.h"
#include "package.h"
#include "filter_manager.h"

static const REGEX_NS::regex::flag_type regexFlags(REGEX_NS::regex::ECMAScript|REGEX_NS::regex::optimize|REGEX_NS::regex::icase);

EPUB3_BEGIN_NAMESPACE

static REGEX_NS::regex CSSMatcher("page\\-break\\-(after|before|inside) *\\: *(always|avoid|left|right)", regexFlags);
static REGEX_NS::regex StyleAttributeMatcher("<[^>]+style=\\\"([^\\\"]*)\"", regexFlags);
static REGEX_NS::regex StyleTagMatcher("<style[^>]*>((.|\n|\r)*?)<\\/style>", regexFlags);

static const std::string PageBreakReplacement = "-webkit-column-break-$1: $2; column-break-$&: $2";


bool CSSPreprocessor::ShouldApply(ConstManifestItemPtr item)
{
auto mediaType = item->MediaType();
bool itemPrepaginated = false;
auto iprop = item->PropertyMatching("layout", "rendition");
if (iprop != nullptr) {
auto ilayout = iprop->Value();
itemPrepaginated = (ilayout == "pre-paginated");
}
bool pkgPrepaginated = false;
auto prop = item->GetPackage()->PropertyMatching("layout", "rendition");
if (prop != nullptr) {
auto layout = prop->Value();
pkgPrepaginated = (layout == "pre-paginated");
}

if (itemPrepaginated || pkgPrepaginated)
return false;

return (mediaType == "application/xhtml+xml" || mediaType == "text/html" || mediaType == "text/css");
}

ContentFilterPtr CSSPreprocessor::CSSFilterFactory(ConstPackagePtr package)
{
CSSSubstitution pageBreakSub(CSSMatcher, PageBreakReplacement);
std::vector<CSSSubstitution> substitutions { pageBreakSub };
return New(package, substitutions);
}

void CSSPreprocessor::Register()
{
FilterManager::Instance()->RegisterFilter("CSSPreprocessor", ValidationComplete, CSSFilterFactory);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is ValidationComplete the most adequate Content Filter priority? I think so, but just double-checking (must be after decryption).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked: ValidationComplete is the lowest priority, the filter is applied last.

}

CSSPreprocessor::CSSPreprocessor(ConstPackagePtr pkg, CSSSubstitutionList substitutions) : ContentFilter(ShouldApply), m_substitutions(substitutions)
{
}


void* CSSPreprocessor::FilterData(FilterContext* context, void *data, size_t len, size_t *outputLen)
{
CSSFilterContext* p = dynamic_cast<CSSFilterContext*>(context);
bool isCSS = p->isCSS();
char* input = reinterpret_cast<char*>(data);

std::string output;
if (isCSS) {
// Data is pure CSS, proceed with substitutions
output.assign(input, len);
for (CSSSubstitution& substitution: m_substitutions) {
output = REGEX_NS::regex_replace(output, substitution.GetSearchRegex(), substitution.GetReplaceFormat());
}
}
else
{
// Data is HTML, look for <style> elements and style attributes

std::string toutput;
// find each `style` tags
REGEX_NS::cregex_iterator pos(input, input+len, StyleTagMatcher);
REGEX_NS::cregex_iterator end;
if ( pos == end )
{
toutput.assign(input, len); // no match
}
else
{
while (pos != end) {
toutput += pos->prefix();

std::string str = pos->str();
for (CSSSubstitution& substitution: m_substitutions) {
str = REGEX_NS::regex_replace(str, substitution.GetSearchRegex(), substitution.GetReplaceFormat());
}
toutput += str;

auto here = pos++;
if ( pos == end )
toutput += here->suffix();
}
}

// find each `style` attributes
REGEX_NS::sregex_iterator apos(toutput.begin(), toutput.end(), StyleAttributeMatcher);
REGEX_NS::sregex_iterator aend;
if ( apos == aend )
{
output = toutput; // no match
}
else {
while (apos != aend) {
output += apos->prefix();

std::string str = apos->str();
for (CSSSubstitution& substitution: m_substitutions) {
str = REGEX_NS::regex_replace(str, substitution.GetSearchRegex(), substitution.GetReplaceFormat());
}
output += str;

auto here = apos++;
if ( apos == aend )
output += here->suffix();
}
}

}

*outputLen = output.size();
if ( output.size() < len )
{
// use the incoming buffer
output.copy(input, output.size());
return input;
}

// allocate a new buffer and copy
char* result = new char[output.size()];
output.copy(result, output.size());
return result;
}

EPUB3_END_NAMESPACE
142 changes: 142 additions & 0 deletions ePub3/ePub/css_preprocessor.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
//
// css_preprocessor.hpp
// ePub3
//
// Created by Olivier Körner on 03/03/2016.
// Copyright (c) 2016 The Readium Foundation and contributors. All rights reserved.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// Licensed under Gnu Affero General Public License Version 3 (provided, notwithstanding this notice,
// Readium Foundation reserves the right to license this material under a different separate license,
// and if you have done so, the terms of that separate license control and the following references
// to GPL do not apply).
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU
// Affero General Public License as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version. You should have received a copy of the GNU
// Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.

#ifndef __ePub3__css_preprocessor_hpp
#define __ePub3__css_preprocessor_hpp

#include <ePub3/epub3.h>
#include <ePub3/filter.h>
#include <ePub3/utilities/iri.h>
#include <ePub3/content_handler.h>
#include REGEX_INCLUDE

EPUB3_BEGIN_NAMESPACE

class Package;

/**
Implements a filter for reading content documents which statically replaces `object`
elements with `iframe` elements referencing the appropriate DHTML handler.
@ingroup filters
*/
class CSSPreprocessor : public ContentFilter, public PointerType<CSSPreprocessor>
{
protected:
///
/// Matches only mnifest items with a media-type of "application/xhtml+xml" or "text/html" or "text/css".
static bool ShouldApply(ConstManifestItemPtr item);

/// The factory routine
static ContentFilterPtr CSSFilterFactory(ConstPackagePtr package);

private:

///
/// No default constructor.
//CSSPreprocessor() : ContentFilter(ShouldApply) { }
CSSPreprocessor() _DELETED_;

// Filter context for CSS preprocessing: is the stream CSS or HTML?
class CSSFilterContext : public FilterContext
{
private:
bool _isCSS;

public:
CSSFilterContext() : FilterContext(), _isCSS(false) {}
CSSFilterContext(ConstManifestItemPtr item) { _isCSS = (item->MediaType().compare("text/css") == 0); }

bool isCSS() const { return _isCSS; }
void setCSS(bool val) { _isCSS = val; }

};

public:
class CSSSubstitution
{
public:
CSSSubstitution(const REGEX_NS::regex& search_re, const std::string& replace) : m_search_re(search_re), m_replace(replace) {}
CSSSubstitution(const CSSSubstitution &o) : m_search_re(o.m_search_re), m_replace(o.m_replace) {}
CSSSubstitution(CSSSubstitution &&o) : m_search_re(std::move(o.m_search_re)), m_replace(std::move(o.m_replace)) {}
virtual ~CSSSubstitution() {}

const REGEX_NS::regex& GetSearchRegex() const
{
return m_search_re;
}
const std::string& GetReplaceFormat() const
{
return m_replace;
}

private:

REGEX_NS::regex m_search_re;
std::string m_replace;

};

typedef std::vector<CSSSubstitution> CSSSubstitutionList;

/**
Initializes a preprocessor and associates it with a Package object, from which
it can obtain foreign media handler details.
@param pkg The package to which this filter will apply.
*/
EPUB3_EXPORT
CSSPreprocessor(ConstPackagePtr pkg, CSSSubstitutionList substitutions);
//CSSPreprocessor(ConstPackagePtr pkg) : ContentFilter(ShouldApply);

///
/// Standard copy constructor.
CSSPreprocessor(const CSSPreprocessor& o) : ContentFilter(o), m_substitutions(o.m_substitutions) {}

///
/// C++11 'move' constructor.
CSSPreprocessor(CSSPreprocessor&& o) : ContentFilter(std::move(o)), m_substitutions(std::move(o.m_substitutions)) {}

///
/// Destructor.

///
/// This preprocessor requires access to the entire content document at once.
virtual OperatingMode GetOperatingMode() const OVERRIDE { return OperatingMode::RequiresCompleteData; }

/**
Performs the static replacement of `object` tags whose `type` attribute
identifies a media-type for which the Publication provides a media handler.

*/
virtual void* FilterData(FilterContext* context, void* data, size_t len, size_t* outputLen) OVERRIDE;

// register with the filter manager
static void Register();

private:
CSSSubstitutionList m_substitutions;

protected:

virtual FilterContext *InnerMakeFilterContext(ConstManifestItemPtr item) const OVERRIDE { return new CSSFilterContext(item); }
};

EPUB3_END_NAMESPACE

#endif /* defined(__ePub3__css_preprocessor__) */
4 changes: 3 additions & 1 deletion ePub3/ePub/initialization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include <ePub3/font_obfuscation.h>
#include <ePub3/switch_preprocessor.h>
#include <ePub3/object_preprocessor.h>
#include <ePub3/css_preprocessor.h>
#include <ePub3/PassThroughFilter.h>

EPUB3_BEGIN_NAMESPACE
Expand All @@ -47,9 +48,10 @@ void PopulateFilterManager()
// simply uncomment the line below. Also take a look at the file PassThroughFilter.cpp
// to see if the class is enabling itself.
//
// PassThroughFilter::Register();
//PassThroughFilter::Register();
SwitchPreprocessor::Register();
ObjectPreprocessor::Register();
CSSPreprocessor::Register();
});
}

Expand Down