mirror of https://github.com/koreader/koreader
Compare commits
No commits in common. 'master' and 'v2021.10.1' have entirely different histories.
master
...
v2021.10.1
@ -1,42 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
CI_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
# shellcheck source=/dev/null
|
||||
source "${CI_DIR}/common.sh"
|
||||
|
||||
set +e
|
||||
|
||||
echo -e "\\n${ANSI_GREEN}Updating translation source file."
|
||||
make pot
|
||||
pushd l10n && {
|
||||
git checkout master
|
||||
# If only one line was added and removed, it was just the timestamp.
|
||||
git diff --numstat | grep "1[[:space:]]1[[:space:]]templates/koreader.pot" && echo -e "\\n${ANSI_GREEN}No updated translations found." || {
|
||||
git -c user.name="KOReader build bot" -c user.email="non-reply@koreader.rocks" \
|
||||
commit templates/koreader.pot -m "Updated translation source file"
|
||||
git push --quiet "https://${TRANSLATIONS_GITHUB_TOKEN}@github.com/koreader/koreader-translations.git" master
|
||||
echo -e "\\n${ANSI_GREEN}Translation update pushed."
|
||||
}
|
||||
} && popd || exit
|
||||
|
||||
echo -e "\\n${ANSI_GREEN}Checking out koreader/doc for update."
|
||||
git clone git@github.com:koreader/doc.git koreader_doc
|
||||
|
||||
# push doc update
|
||||
pushd doc && {
|
||||
luajit "$(command -v ldoc)" .
|
||||
if [ ! -d html ]; then
|
||||
echo "Failed to generate documents..."
|
||||
exit 1
|
||||
fi
|
||||
} && popd || exit
|
||||
|
||||
cp -r doc/html/* koreader_doc/
|
||||
pushd koreader_doc && {
|
||||
git add -A
|
||||
echo -e "\\n${ANSI_GREEN}Pushing document update..."
|
||||
git -c user.name="KOReader build bot" -c user.email="non-reply@koreader.rocks" \
|
||||
commit -a --amend -m 'Automated documentation build from travis-ci.'
|
||||
git push -f --quiet "https://${DOCS_GITHUB_TOKEN}@github.com/koreader/doc.git" gh-pages >/dev/null
|
||||
echo -e "\\n${ANSI_GREEN}Documentation update pushed."
|
||||
} && popd || exit
|
@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# don't do this for clang
|
||||
if [ "${CXX}" = "g++" ]; then
|
||||
export CXX="g++-5" CC="gcc-5"
|
||||
fi
|
||||
# in case anything ignores the environment variables, override through PATH
|
||||
mkdir bin
|
||||
ln -s "$(command -v gcc-5)" bin/cc
|
||||
ln -s "$(command -v gcc-5)" bin/gcc
|
||||
ln -s "$(command -v c++)" bin/c++
|
||||
ln -s "$(command -v g++-5)" bin/g++
|
||||
|
||||
# Travis only makes a shallow clone of --depth=50. KOReader is small enough that
|
||||
# we can just grab it all. This is necessary to generate the version number,
|
||||
# without which some tests will fail.
|
||||
# git fetch --unshallow
|
@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
CI_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
# shellcheck source=/dev/null
|
||||
source "${CI_DIR}/common.sh"
|
||||
|
||||
rm -rf "${HOME}/.luarocks"
|
||||
mkdir "${HOME}/.luarocks"
|
||||
cp "${CI_BUILD_DIR}/install/etc/luarocks/config.lua" "${HOME}/.luarocks/config.lua"
|
||||
echo "wrap_bin_scripts = false" >>"${HOME}/.luarocks/config.lua"
|
||||
travis_retry luarocks --local install luafilesystem
|
||||
# for verbose_print module
|
||||
travis_retry luarocks --local install ansicolors
|
||||
travis_retry luarocks --local install busted 2.0.0-1
|
||||
#- mv -f $HOME/.luarocks/bin/busted_bootstrap $HOME/.luarocks/bin/busted
|
||||
|
||||
travis_retry luarocks --local install luacheck
|
||||
travis_retry luarocks --local install lanes # for parallel luacheck
|
||||
|
||||
# used only on master branch but added to cache for better speed
|
||||
travis_retry luarocks --local install ldoc
|
||||
travis_retry luarocks --local install luacov
|
@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
CI_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
# shellcheck source=/dev/null
|
||||
source "${CI_DIR}/common.sh"
|
||||
|
||||
# print some useful info
|
||||
echo "BUILD_DIR: ${CI_BUILD_DIR}"
|
||||
echo "pwd: $(pwd)"
|
||||
ls
|
||||
|
||||
# toss submodules if there are any changes
|
||||
# if [ "$(git status --ignore-submodules=dirty --porcelain)" ]; then
|
||||
# "--ignore-submodules=dirty", removed temporarily, as it did not notice as
|
||||
# expected that base was updated and kept using old cached base
|
||||
if [ "$(git status --ignore-submodules=dirty --porcelain)" ]; then
|
||||
# what changed?
|
||||
git status
|
||||
# purge and reinit submodules
|
||||
git submodule deinit -f .
|
||||
git submodule update --init
|
||||
else
|
||||
echo -e "${ANSI_GREEN}Using cached submodules."
|
||||
fi
|
||||
|
||||
# install our own updated luarocks
|
||||
echo "luarocks installation path: ${CI_BUILD_DIR}"
|
||||
if [ ! -f "${CI_BUILD_DIR}/install/bin/luarocks" ]; then
|
||||
git clone https://github.com/torch/luajit-rocks.git
|
||||
pushd luajit-rocks && {
|
||||
git checkout 6529891
|
||||
cmake . -DWITH_LUAJIT21=ON -DCMAKE_INSTALL_PREFIX="${CI_BUILD_DIR}/install"
|
||||
make install
|
||||
} && popd || exit
|
||||
else
|
||||
echo -e "${ANSI_GREEN}Using cached luarocks."
|
||||
fi
|
||||
|
||||
if [ ! -d "${HOME}/.luarocks" ] || [ ! -f "${HOME}/.luarocks/$(md5sum <"${CI_DIR}/helper_luarocks.sh")" ]; then
|
||||
echo -e "${ANSI_GREEN}Grabbing new .luarocks."
|
||||
sudo apt-get update
|
||||
# install openssl devel for luasec
|
||||
sudo apt-get -y install libssl-dev
|
||||
|
||||
"${CI_DIR}/helper_luarocks.sh"
|
||||
touch "${HOME}/.luarocks/$(md5sum <"${CI_DIR}/helper_luarocks.sh")"
|
||||
else
|
||||
echo -e "${ANSI_GREEN}Using cached .luarocks."
|
||||
fi
|
||||
|
||||
#install our own updated shellcheck
|
||||
SHELLCHECK_VERSION="v0.7.1"
|
||||
SHELLCHECK_URL="https://github.com/koalaman/shellcheck/releases/download/${SHELLCHECK_VERSION?}/shellcheck-${SHELLCHECK_VERSION?}.linux.x86_64.tar.xz"
|
||||
if ! command -v shellcheck; then
|
||||
curl -sSL "${SHELLCHECK_URL}" | tar --exclude 'SHA256SUMS' --strip-components=1 -C "${HOME}/bin" -xJf -
|
||||
chmod +x "${HOME}/bin/shellcheck"
|
||||
shellcheck --version
|
||||
else
|
||||
echo -e "${ANSI_GREEN}Using cached shellcheck."
|
||||
fi
|
||||
|
||||
# install shfmt
|
||||
SHFMT_URL="https://github.com/mvdan/sh/releases/download/v3.2.0/shfmt_v3.2.0_linux_amd64"
|
||||
if [ "$(shfmt --version)" != "v3.2.0" ]; then
|
||||
curl -sSL "${SHFMT_URL}" -o "${HOME}/bin/shfmt"
|
||||
chmod +x "${HOME}/bin/shfmt"
|
||||
else
|
||||
echo -e "${ANSI_GREEN}Using cached shfmt."
|
||||
fi
|
@ -1,6 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
@ -1,5 +0,0 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/sumneko/vscode-lua/master/setting/schema.json",
|
||||
"runtime.version": "LuaJIT",
|
||||
}
|
||||
|
@ -0,0 +1,48 @@
|
||||
language: c
|
||||
|
||||
# sudo: false
|
||||
sudo: true
|
||||
dist: trusty
|
||||
|
||||
compiler:
|
||||
- gcc
|
||||
|
||||
env:
|
||||
global:
|
||||
- "PATH=${HOME}/bin:${PATH}"
|
||||
matrix:
|
||||
- EMULATE_READER=1
|
||||
|
||||
cache:
|
||||
apt: true
|
||||
directories:
|
||||
- "${HOME}/bin"
|
||||
# compiled luarocks binaries
|
||||
- "${TRAVIS_BUILD_DIR}/install"
|
||||
# base build
|
||||
- "${TRAVIS_BUILD_DIR}/base"
|
||||
- "${HOME}/.ccache"
|
||||
- "${HOME}/.luarocks"
|
||||
before_cache:
|
||||
# don't quote like you normally would or it won't expand
|
||||
- rm -frv ${TRAVIS_BUILD_DIR}/base/build/*/cache/*
|
||||
# don't cache unit tests
|
||||
- rm -frv ${TRAVIS_BUILD_DIR}/base/build/*/spec
|
||||
|
||||
addons:
|
||||
apt:
|
||||
sources:
|
||||
- ubuntu-toolchain-r-test
|
||||
packages:
|
||||
- g++-4.8
|
||||
- libsdl1.2-dev
|
||||
# luasec dependencies
|
||||
- libssl1.0.0
|
||||
- nasm
|
||||
# OpenSSL likes this (package contains makedepend)
|
||||
- xutils-dev
|
||||
|
||||
before_install: .ci/before_install.sh
|
||||
install: .ci/install.sh
|
||||
script: .ci/script.sh
|
||||
after_success: .ci/after_success.sh
|
@ -1 +1 @@
|
||||
Subproject commit 67474697169dd88800bc37af5b7fb87ce0596ee8
|
||||
Subproject commit 9a3f61cdb2e0ff5da339ebd8460ca460efc2e21f
|
@ -1,191 +0,0 @@
|
||||
local DataStorage = require("datastorage")
|
||||
local Font = require("ui/font")
|
||||
local InfoMessage = require("ui/widget/infomessage")
|
||||
local LuaSettings = require("luasettings")
|
||||
local Menu = require("ui/widget/menu")
|
||||
local NetworkMgr = require("ui/network/manager")
|
||||
local Notification = require("ui/widget/notification")
|
||||
local Screen = require("device").screen
|
||||
local UIManager = require("ui/uimanager")
|
||||
local ffiutil = require("ffi/util")
|
||||
local util = require("util")
|
||||
|
||||
local _ = require("gettext")
|
||||
|
||||
local server_types = {
|
||||
dropbox = _("Dropbox"),
|
||||
webdav = _("WebDAV"),
|
||||
}
|
||||
local indent = ""
|
||||
|
||||
local SyncService = Menu:extend{
|
||||
no_title = false,
|
||||
show_parent = nil,
|
||||
is_popout = false,
|
||||
is_borderless = true,
|
||||
title = _("Cloud sync settings"),
|
||||
title_face = Font:getFace("smallinfofontbold"),
|
||||
}
|
||||
|
||||
function SyncService:init()
|
||||
self.item_table = self:generateItemTable()
|
||||
self.width = Screen:getWidth()
|
||||
self.height = Screen:getHeight()
|
||||
Menu.init(self)
|
||||
end
|
||||
|
||||
function SyncService:generateItemTable()
|
||||
local item_table = {}
|
||||
-- select and/or add server
|
||||
local added_servers = LuaSettings:open(DataStorage:getSettingsDir().."/cloudstorage.lua"):readSetting("cs_servers") or {}
|
||||
for _, server in ipairs(added_servers) do
|
||||
if server.type == "dropbox" or server.type == "webdav" then
|
||||
local item = {
|
||||
text = indent .. server.name,
|
||||
address = server.address,
|
||||
username = server.username,
|
||||
password = server.password,
|
||||
type = server.type,
|
||||
url = server.url,
|
||||
mandatory = server_types[server.type],
|
||||
}
|
||||
item.callback = function()
|
||||
require("ui/downloadmgr"):new{
|
||||
item = item,
|
||||
onConfirm = function(path)
|
||||
server.url = path
|
||||
self.onConfirm(server)
|
||||
self:onClose()
|
||||
end,
|
||||
}:chooseCloudDir()
|
||||
end
|
||||
table.insert(item_table, item)
|
||||
end
|
||||
end
|
||||
if #item_table > 0 then
|
||||
table.insert(item_table, 1, {
|
||||
text = _("Choose cloud service:"),
|
||||
bold = true,
|
||||
})
|
||||
end
|
||||
table.insert(item_table, {
|
||||
text = _("Add service"),
|
||||
bold = true,
|
||||
callback = function()
|
||||
local cloud_storage = require("apps/cloudstorage/cloudstorage"):new{}
|
||||
local onClose = cloud_storage.onClose
|
||||
cloud_storage.onClose = function(this)
|
||||
onClose(this)
|
||||
self:switchItemTable(nil, self:generateItemTable())
|
||||
end
|
||||
UIManager:show(cloud_storage)
|
||||
end
|
||||
})
|
||||
return item_table
|
||||
end
|
||||
|
||||
function SyncService.getReadablePath(server)
|
||||
local url = util.stringStartsWith(server.url, "/") and server.url:sub(2) or server.url
|
||||
url = util.urlDecode(url) or url
|
||||
url = util.stringEndsWith(url, "/") and url or url .. "/"
|
||||
if server.type == "dropbox" then
|
||||
url = "/" .. url
|
||||
elseif server.type == "webdav" then
|
||||
url = (server.address:sub(-1) == "/" and server.address or server.address .. "/") .. url
|
||||
end
|
||||
if url:sub(-2) == "//" then url = url:sub(1, -2) end
|
||||
return url
|
||||
end
|
||||
|
||||
-- Prepares three files for sync_cb to call to do the actual syncing:
|
||||
-- * local_file (one that is being used)
|
||||
-- * income_file (one that has just been downloaded from Cloud to be merged, then to be deleted)
|
||||
-- * cached_file (the one that was uploaded in the previous round of syncing)
|
||||
--
|
||||
-- How it works:
|
||||
--
|
||||
-- If we simply merge the local file with the income file (ignore duplicates), then items that have been deleted locally
|
||||
-- but not remotely (on other devices) will re-emerge in the result file. The same goes for items deleted remotely but
|
||||
-- not locally. To avoid this, we first need to delete them from both the income file and local file.
|
||||
--
|
||||
-- The problem is how to identify them, and that is when the cached file comes into play.
|
||||
-- The cached file represents what local and remote agreed on previously (was identical to local and remote after being uploaded
|
||||
-- the previous round), by comparing it with local file, items no longer in local file are ones being recently deleted.
|
||||
-- The same applies to income file. Then we can delete them from both local and income files to be ready for merging. (The actual
|
||||
-- deletion and merging procedures happen in sync_cb as users of this service will have different file specifications)
|
||||
--
|
||||
-- After merging, the income file is no longer needed and is deleted. The local file is uploaded and then a copy of it is saved
|
||||
-- and renamed to replace the old cached file (thus the naming). The cached file stays (in the same folder) till being replaced
|
||||
-- in the next round.
|
||||
function SyncService.sync(server, file_path, sync_cb, is_silent)
|
||||
if NetworkMgr:willRerunWhenOnline(function() SyncService.sync(server, file_path, sync_cb, is_silent) end) then
|
||||
return
|
||||
end
|
||||
local file_name = ffiutil.basename(file_path)
|
||||
local income_file_path = file_path .. ".temp" -- file downloaded from server
|
||||
local cached_file_path = file_path .. ".sync" -- file uploaded to server last time
|
||||
|
||||
local fail_msg = _("Something went wrong when syncing, please check your network connection and try again later.")
|
||||
local show_msg = function(msg)
|
||||
if is_silent then return end
|
||||
UIManager:show(InfoMessage:new{
|
||||
text = msg or fail_msg,
|
||||
timeout = 3,
|
||||
})
|
||||
end
|
||||
if server.type ~= "dropbox" and server.type ~= "webdav" then
|
||||
show_msg(_("Wrong server type."))
|
||||
return
|
||||
end
|
||||
local code_response = 412 -- If-Match header failed
|
||||
local etag
|
||||
local api = server.type == "dropbox" and require("apps/cloudstorage/dropboxapi") or require("apps/cloudstorage/webdavapi")
|
||||
local token = server.password
|
||||
if server.type == "dropbox" and not (server.address == nil or server.address == "") then
|
||||
token = api:getAccessToken(server.password, server.address)
|
||||
end
|
||||
while code_response == 412 do
|
||||
os.remove(income_file_path)
|
||||
if server.type == "dropbox" then
|
||||
local url_base = server.url:sub(-1) == "/" and server.url or server.url.."/"
|
||||
code_response, etag = api:downloadFile(url_base..file_name, token, income_file_path)
|
||||
elseif server.type == "webdav" then
|
||||
local path = api:getJoinedPath(server.address, server.url)
|
||||
path = api:getJoinedPath(path, file_name)
|
||||
code_response, etag = api:downloadFile(path, server.username, server.password, income_file_path)
|
||||
end
|
||||
if code_response ~= 200 and code_response ~= 404
|
||||
and not (server.type == "dropbox" and code_response == 409) then
|
||||
show_msg()
|
||||
return
|
||||
end
|
||||
local ok, cb_return = pcall(sync_cb, file_path, cached_file_path, income_file_path)
|
||||
if not ok or not cb_return then
|
||||
show_msg()
|
||||
if not ok then require("logger").err("sync service callback failed:", cb_return) end
|
||||
return
|
||||
end
|
||||
if server.type == "dropbox" then
|
||||
local url_base = server.url == "/" and "" or server.url
|
||||
code_response = api:uploadFile(url_base, token, file_path, etag, true)
|
||||
elseif server.type == "webdav" then
|
||||
local path = api:getJoinedPath(server.address, server.url)
|
||||
path = api:getJoinedPath(path, file_name)
|
||||
code_response = api:uploadFile(path, server.username, server.password, file_path, etag)
|
||||
end
|
||||
end
|
||||
os.remove(income_file_path)
|
||||
if type(code_response) == "number" and code_response >= 200 and code_response < 300 then
|
||||
os.remove(cached_file_path)
|
||||
ffiutil.copyFile(file_path, cached_file_path)
|
||||
UIManager:show(Notification:new{
|
||||
text = _("Successfully synchronized."),
|
||||
timeout = 2,
|
||||
})
|
||||
else
|
||||
show_msg()
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
return SyncService
|
File diff suppressed because it is too large
Load Diff
@ -1,423 +0,0 @@
|
||||
local WidgetContainer = require("ui/widget/container/widgetcontainer")
|
||||
local logger = require("logger")
|
||||
local _ = require("gettext")
|
||||
local T = require("ffi/util").template
|
||||
|
||||
local ReaderAnnotation = WidgetContainer:extend{
|
||||
annotations = nil, -- array sorted by annotation position order, ascending
|
||||
}
|
||||
|
||||
-- build, read, save
|
||||
|
||||
function ReaderAnnotation:buildAnnotation(bm, highlights, init)
|
||||
-- bm: associated single bookmark ; highlights: tables with all highlights
|
||||
local note = bm.text
|
||||
if note == "" then
|
||||
note = nil
|
||||
end
|
||||
local chapter = bm.chapter
|
||||
local hl, pageno = self:getHighlightByDatetime(highlights, bm.datetime)
|
||||
if init then
|
||||
if note and self.ui.bookmark:isBookmarkAutoText(bm) then
|
||||
note = nil
|
||||
end
|
||||
if chapter == nil then
|
||||
chapter = self.ui.toc:getTocTitleByPage(bm.page)
|
||||
end
|
||||
pageno = self.ui.paging and bm.page or self.document:getPageFromXPointer(bm.page)
|
||||
end
|
||||
if self.ui.paging and bm.pos0 and not bm.pos0.page then
|
||||
-- old single-page reflow highlights do not have page in position
|
||||
bm.pos0.page = bm.page
|
||||
bm.pos1.page = bm.page
|
||||
end
|
||||
if not hl then -- page bookmark or orphaned bookmark
|
||||
hl = {}
|
||||
if bm.highlighted then -- orphaned bookmark
|
||||
hl.drawer = self.view.highlight.saved_drawer
|
||||
hl.color = self.view.highlight.saved_color
|
||||
if self.ui.paging then
|
||||
if bm.pos0.page == bm.pos1.page then
|
||||
hl.pboxes = self.document:getPageBoxesFromPositions(bm.page, bm.pos0, bm.pos1)
|
||||
else -- multi-page highlight, restore the first box only
|
||||
hl.pboxes = self.document:getPageBoxesFromPositions(bm.page, bm.pos0, bm.pos0)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return { -- annotation
|
||||
datetime = bm.datetime, -- creation time, not changeable
|
||||
drawer = hl.drawer, -- highlight drawer
|
||||
color = hl.color, -- highlight color
|
||||
text = bm.notes, -- highlighted text, editable
|
||||
text_edited = hl.edited, -- true if highlighted text has been edited
|
||||
note = note, -- user's note, editable
|
||||
chapter = chapter, -- book chapter title
|
||||
pageno = pageno, -- book page number
|
||||
page = bm.page, -- highlight location, xPointer or number (pdf)
|
||||
pos0 = bm.pos0, -- highlight start position, xPointer (== page) or table (pdf)
|
||||
pos1 = bm.pos1, -- highlight end position, xPointer or table (pdf)
|
||||
pboxes = hl.pboxes, -- pdf pboxes, used only and changeable by addMarkupAnnotation
|
||||
ext = hl.ext, -- pdf multi-page highlight
|
||||
}
|
||||
end
|
||||
|
||||
function ReaderAnnotation:getHighlightByDatetime(highlights, datetime)
|
||||
for pageno, page_highlights in pairs(highlights) do
|
||||
for _, highlight in ipairs(page_highlights) do
|
||||
if highlight.datetime == datetime then
|
||||
return highlight, pageno
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderAnnotation:getAnnotationsFromBookmarksHighlights(bookmarks, highlights, init)
|
||||
local annotations = {}
|
||||
for i = #bookmarks, 1, -1 do
|
||||
table.insert(annotations, self:buildAnnotation(bookmarks[i], highlights, init))
|
||||
end
|
||||
if init then
|
||||
self:sortItems(annotations)
|
||||
end
|
||||
return annotations
|
||||
end
|
||||
|
||||
function ReaderAnnotation:onReadSettings(config)
|
||||
local annotations = config:readSetting("annotations")
|
||||
if annotations then
|
||||
-- KOHighlights may set this key when it has merged annotations from different sources:
|
||||
-- we want to make sure they are updated and sorted
|
||||
local needs_update = config:isTrue("annotations_externally_modified")
|
||||
local needs_sort -- if incompatible annotations were built of old highlights/bookmarks
|
||||
-- Annotation formats in crengine and mupdf are incompatible.
|
||||
local has_annotations = #annotations > 0
|
||||
local annotations_type = has_annotations and type(annotations[1].page)
|
||||
if self.ui.rolling and annotations_type ~= "string" then -- incompatible format loaded, or empty
|
||||
if has_annotations then -- backup incompatible format if not empty
|
||||
config:saveSetting("annotations_paging", annotations)
|
||||
end
|
||||
-- load compatible format
|
||||
annotations = config:readSetting("annotations_rolling") or {}
|
||||
config:delSetting("annotations_rolling")
|
||||
needs_sort = true
|
||||
elseif self.ui.paging and annotations_type ~= "number" then
|
||||
if has_annotations then
|
||||
config:saveSetting("annotations_rolling", annotations)
|
||||
end
|
||||
annotations = config:readSetting("annotations_paging") or {}
|
||||
config:delSetting("annotations_paging")
|
||||
needs_sort = true
|
||||
end
|
||||
self.annotations = annotations
|
||||
if needs_update or needs_sort then
|
||||
if self.ui.rolling then
|
||||
self.ui:registerPostInitCallback(function()
|
||||
self:updatedAnnotations(needs_update, needs_sort)
|
||||
end)
|
||||
else
|
||||
self:updatedAnnotations(needs_update, needs_sort)
|
||||
end
|
||||
config:delSetting("annotations_externally_modified")
|
||||
end
|
||||
else -- first run
|
||||
if self.ui.rolling then
|
||||
self.ui:registerPostInitCallback(function()
|
||||
self:migrateToAnnotations(config)
|
||||
end)
|
||||
else
|
||||
self:migrateToAnnotations(config)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderAnnotation:migrateToAnnotations(config)
|
||||
local bookmarks = config:readSetting("bookmarks") or {}
|
||||
local highlights = config:readSetting("highlight") or {}
|
||||
|
||||
if config:hasNot("highlights_imported") then
|
||||
-- before 2014, saved highlights were not added to bookmarks when they were created.
|
||||
for page, hls in pairs(highlights) do
|
||||
for _, hl in ipairs(hls) do
|
||||
local hl_page = self.ui.paging and page or hl.pos0
|
||||
-- highlights saved by some old versions don't have pos0 field
|
||||
-- we just ignore those highlights
|
||||
if hl_page then
|
||||
local item = {
|
||||
datetime = hl.datetime,
|
||||
highlighted = true,
|
||||
notes = hl.text,
|
||||
page = hl_page,
|
||||
pos0 = hl.pos0,
|
||||
pos1 = hl.pos1,
|
||||
}
|
||||
if self.ui.paging then
|
||||
item.pos0.page = page
|
||||
item.pos1.page = page
|
||||
end
|
||||
table.insert(bookmarks, item)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Bookmarks/highlights formats in crengine and mupdf are incompatible.
|
||||
local has_bookmarks = #bookmarks > 0
|
||||
local bookmarks_type = has_bookmarks and type(bookmarks[1].page)
|
||||
if self.ui.rolling then
|
||||
if bookmarks_type == "string" then -- compatible format loaded, check for incompatible old backup
|
||||
if config:has("bookmarks_paging") then -- save incompatible old backup
|
||||
local bookmarks_paging = config:readSetting("bookmarks_paging")
|
||||
local highlights_paging = config:readSetting("highlight_paging")
|
||||
local annotations = self:getAnnotationsFromBookmarksHighlights(bookmarks_paging, highlights_paging)
|
||||
config:saveSetting("annotations_paging", annotations)
|
||||
config:delSetting("bookmarks_paging")
|
||||
config:delSetting("highlight_paging")
|
||||
end
|
||||
else -- incompatible format loaded, or empty
|
||||
if has_bookmarks then -- save incompatible format if not empty
|
||||
local annotations = self:getAnnotationsFromBookmarksHighlights(bookmarks, highlights)
|
||||
config:saveSetting("annotations_paging", annotations)
|
||||
end
|
||||
-- load compatible format
|
||||
bookmarks = config:readSetting("bookmarks_rolling") or {}
|
||||
highlights = config:readSetting("highlight_rolling") or {}
|
||||
config:delSetting("bookmarks_rolling")
|
||||
config:delSetting("highlight_rolling")
|
||||
end
|
||||
else -- self.ui.paging
|
||||
if bookmarks_type == "number" then
|
||||
if config:has("bookmarks_rolling") then
|
||||
local bookmarks_rolling = config:readSetting("bookmarks_rolling")
|
||||
local highlights_rolling = config:readSetting("highlight_rolling")
|
||||
local annotations = self:getAnnotationsFromBookmarksHighlights(bookmarks_rolling, highlights_rolling)
|
||||
config:saveSetting("annotations_rolling", annotations)
|
||||
config:delSetting("bookmarks_rolling")
|
||||
config:delSetting("highlight_rolling")
|
||||
end
|
||||
else
|
||||
if has_bookmarks then
|
||||
local annotations = self:getAnnotationsFromBookmarksHighlights(bookmarks, highlights)
|
||||
config:saveSetting("annotations_rolling", annotations)
|
||||
end
|
||||
bookmarks = config:readSetting("bookmarks_paging") or {}
|
||||
highlights = config:readSetting("highlight_paging") or {}
|
||||
config:delSetting("bookmarks_paging")
|
||||
config:delSetting("highlight_paging")
|
||||
end
|
||||
end
|
||||
|
||||
self.annotations = self:getAnnotationsFromBookmarksHighlights(bookmarks, highlights, true)
|
||||
end
|
||||
|
||||
function ReaderAnnotation:onDocumentRerendered()
|
||||
self.needs_update = true
|
||||
end
|
||||
|
||||
function ReaderAnnotation:onCloseDocument()
|
||||
self:updatePageNumbers()
|
||||
end
|
||||
|
||||
function ReaderAnnotation:onSaveSettings()
|
||||
self:updatePageNumbers()
|
||||
self.ui.doc_settings:saveSetting("annotations", self.annotations)
|
||||
end
|
||||
|
||||
-- items handling
|
||||
|
||||
function ReaderAnnotation:updatePageNumbers()
|
||||
if self.needs_update and self.ui.rolling then -- triggered by ReaderRolling on document layout change
|
||||
for _, item in ipairs(self.annotations) do
|
||||
item.pageno = self.document:getPageFromXPointer(item.page)
|
||||
end
|
||||
end
|
||||
self.needs_update = nil
|
||||
end
|
||||
|
||||
function ReaderAnnotation:sortItems(items)
|
||||
if #items > 1 then
|
||||
local sort_func = self.ui.rolling and function(a, b) return self:isItemInPositionOrderRolling(a, b) end
|
||||
or function(a, b) return self:isItemInPositionOrderPaging(a, b) end
|
||||
table.sort(items, sort_func)
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderAnnotation:updatedAnnotations(needs_update, needs_sort)
|
||||
if needs_update then
|
||||
self.needs_update = true
|
||||
self:updatePageNumbers()
|
||||
needs_sort = true
|
||||
end
|
||||
if needs_sort then
|
||||
self:sortItems(self.annotations)
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderAnnotation:updateItemByXPointer(item)
|
||||
-- called by ReaderRolling:checkXPointersAndProposeDOMVersionUpgrade()
|
||||
local chapter = self.ui.toc:getTocTitleByPage(item.page)
|
||||
if chapter == "" then
|
||||
chapter = nil
|
||||
end
|
||||
if not item.drawer then -- page bookmark
|
||||
item.text = chapter and T(_("in %1"), chapter) or nil
|
||||
end
|
||||
item.chapter = chapter
|
||||
item.pageno = self.document:getPageFromXPointer(item.page)
|
||||
end
|
||||
|
||||
function ReaderAnnotation:isItemInPositionOrderRolling(a, b)
|
||||
local a_page = self.document:getPageFromXPointer(a.page)
|
||||
local b_page = self.document:getPageFromXPointer(b.page)
|
||||
if a_page == b_page then -- both items in the same page
|
||||
if a.drawer and b.drawer then -- both items are highlights, compare positions
|
||||
local compare_xp = self.document:compareXPointers(a.page, b.page)
|
||||
if compare_xp then
|
||||
if compare_xp == 0 then -- both highlights with the same start, compare ends
|
||||
compare_xp = self.document:compareXPointers(a.pos1, b.pos1)
|
||||
if compare_xp then
|
||||
return compare_xp > 0
|
||||
end
|
||||
logger.warn("Invalid xpointer in highlight:", a.pos1, b.pos1)
|
||||
return true
|
||||
end
|
||||
return compare_xp > 0
|
||||
end
|
||||
-- if compare_xp is nil, some xpointer is invalid and "a" will be sorted first to page 1
|
||||
logger.warn("Invalid xpointer in highlight:", a.page, b.page)
|
||||
return true
|
||||
end
|
||||
return not a.drawer -- have page bookmarks before highlights
|
||||
end
|
||||
return a_page < b_page
|
||||
end
|
||||
|
||||
function ReaderAnnotation:isItemInPositionOrderPaging(a, b)
|
||||
if a.page == b.page then -- both items in the same page
|
||||
if a.drawer and b.drawer then -- both items are highlights, compare positions
|
||||
local is_reflow = self.document.configurable.text_wrap -- save reflow mode
|
||||
self.document.configurable.text_wrap = 0 -- native positions
|
||||
-- sort start and end positions of each highlight
|
||||
local a_start, a_end, b_start, b_end, result
|
||||
if self.document:comparePositions(a.pos0, a.pos1) > 0 then
|
||||
a_start, a_end = a.pos0, a.pos1
|
||||
else
|
||||
a_start, a_end = a.pos1, a.pos0
|
||||
end
|
||||
if self.document:comparePositions(b.pos0, b.pos1) > 0 then
|
||||
b_start, b_end = b.pos0, b.pos1
|
||||
else
|
||||
b_start, b_end = b.pos1, b.pos0
|
||||
end
|
||||
-- compare start positions
|
||||
local compare_pos = self.document:comparePositions(a_start, b_start)
|
||||
if compare_pos == 0 then -- both highlights with the same start, compare ends
|
||||
result = self.document:comparePositions(a_end, b_end) > 0
|
||||
else
|
||||
result = compare_pos > 0
|
||||
end
|
||||
self.document.configurable.text_wrap = is_reflow -- restore reflow mode
|
||||
return result
|
||||
end
|
||||
return not a.drawer -- have page bookmarks before highlights
|
||||
end
|
||||
return a.page < b.page
|
||||
end
|
||||
|
||||
function ReaderAnnotation:getItemIndex(item, no_binary)
|
||||
local doesMatch
|
||||
if item.datetime then
|
||||
doesMatch = function(a, b)
|
||||
return a.datetime == b.datetime
|
||||
end
|
||||
else
|
||||
if self.ui.rolling then
|
||||
doesMatch = function(a, b)
|
||||
if a.text ~= b.text or a.pos0 ~= b.pos0 or a.pos1 ~= b.pos1 then
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
else
|
||||
doesMatch = function(a, b)
|
||||
if a.text ~= b.text or a.pos0.page ~= b.pos0.page
|
||||
or a.pos0.x ~= b.pos0.x or a.pos1.x ~= b.pos1.x
|
||||
or a.pos0.y ~= b.pos0.y or a.pos1.y ~= b.pos1.y then
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if not no_binary then
|
||||
local isInOrder = self.ui.rolling and self.isItemInPositionOrderRolling or self.isItemInPositionOrderPaging
|
||||
local _start, _end, _middle = 1, #self.annotations
|
||||
while _start <= _end do
|
||||
_middle = bit.rshift(_start + _end, 1)
|
||||
local v = self.annotations[_middle]
|
||||
if doesMatch(item, v) then
|
||||
return _middle
|
||||
elseif isInOrder(self, item, v) then
|
||||
_end = _middle - 1
|
||||
else
|
||||
_start = _middle + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
for i, v in ipairs(self.annotations) do
|
||||
if doesMatch(item, v) then
|
||||
return i
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderAnnotation:getInsertionIndex(item)
|
||||
local isInOrder = self.ui.rolling and self.isItemInPositionOrderRolling or self.isItemInPositionOrderPaging
|
||||
local _start, _end, _middle, direction = 1, #self.annotations, 1, 0
|
||||
while _start <= _end do
|
||||
_middle = bit.rshift(_start + _end, 1)
|
||||
if isInOrder(self, item, self.annotations[_middle]) then
|
||||
_end, direction = _middle - 1, 0
|
||||
else
|
||||
_start, direction = _middle + 1, 1
|
||||
end
|
||||
end
|
||||
return _middle + direction
|
||||
end
|
||||
|
||||
function ReaderAnnotation:addItem(item)
|
||||
item.datetime = os.date("%Y-%m-%d %H:%M:%S")
|
||||
item.pageno = self.ui.paging and item.page or self.document:getPageFromXPointer(item.page)
|
||||
local index = self:getInsertionIndex(item)
|
||||
table.insert(self.annotations, index, item)
|
||||
return index
|
||||
end
|
||||
|
||||
-- info
|
||||
|
||||
function ReaderAnnotation:hasAnnotations()
|
||||
return #self.annotations > 0
|
||||
end
|
||||
|
||||
function ReaderAnnotation:getNumberOfAnnotations()
|
||||
return #self.annotations
|
||||
end
|
||||
|
||||
function ReaderAnnotation:getNumberOfHighlightsAndNotes() -- for Statistics plugin
|
||||
local highlights = 0
|
||||
local notes = 0
|
||||
for _, item in ipairs(self.annotations) do
|
||||
if item.drawer then
|
||||
if item.note then
|
||||
notes = notes + 1
|
||||
else
|
||||
highlights = highlights + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
return highlights, notes
|
||||
end
|
||||
|
||||
return ReaderAnnotation
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,719 +0,0 @@
|
||||
local ConfirmBox = require("ui/widget/confirmbox")
|
||||
local Device = require("device")
|
||||
local Event = require("ui/event")
|
||||
local InfoMessage = require("ui/widget/infomessage")
|
||||
local InputDialog = require("ui/widget/inputdialog")
|
||||
local UIManager = require("ui/uimanager")
|
||||
local WidgetContainer = require("ui/widget/container/widgetcontainer")
|
||||
local util = require("util")
|
||||
local T = require("ffi/util").template
|
||||
local _ = require("gettext")
|
||||
|
||||
local ReaderHandMade = WidgetContainer:extend{
|
||||
custom_toc_symbol = "\u{EAEC}", -- used in a few places
|
||||
}
|
||||
|
||||
function ReaderHandMade:init()
|
||||
self.ui.menu:registerToMainMenu(self)
|
||||
end
|
||||
|
||||
function ReaderHandMade:onReadSettings(config)
|
||||
self.toc_enabled = config:isTrue("handmade_toc_enabled")
|
||||
self.toc_edit_enabled = config:nilOrTrue("handmade_toc_edit_enabled")
|
||||
self.toc = config:readSetting("handmade_toc") or {}
|
||||
self.flows_enabled = config:isTrue("handmade_flows_enabled")
|
||||
self.flows_edit_enabled = config:nilOrTrue("handmade_flows_edit_enabled")
|
||||
self.flow_points = config:readSetting("handmade_flow_points") or {}
|
||||
self.inactive_flow_points = {}
|
||||
|
||||
-- Don't mess toc and flow_points made on that document if saved when
|
||||
-- we were using a different engine - backup them if that's the case.
|
||||
if #self.toc > 0 then
|
||||
local has_xpointers = self.toc[1].xpointer ~= nil
|
||||
if self.ui.rolling and not has_xpointers then
|
||||
config:saveSetting("handmade_toc_paging", self.toc)
|
||||
self.toc = config:readSetting("handmade_toc_rolling") or {}
|
||||
config:delSetting("handmade_toc_rolling")
|
||||
elseif self.ui.paging and has_xpointers then
|
||||
config:saveSetting("handmade_toc_rolling", self.toc)
|
||||
self.toc = config:readSetting("handmade_toc_paging") or {}
|
||||
config:delSetting("handmade_toc_paging")
|
||||
end
|
||||
else
|
||||
if self.ui.rolling and config:has("handmade_toc_rolling") then
|
||||
self.toc = config:readSetting("handmade_toc_rolling")
|
||||
config:delSetting("handmade_toc_rolling")
|
||||
elseif self.ui.paging and config:has("handmade_toc_paging") then
|
||||
self.toc = config:readSetting("handmade_toc_paging")
|
||||
config:delSetting("handmade_toc_paging")
|
||||
end
|
||||
end
|
||||
if #self.flow_points > 0 then
|
||||
local has_xpointers = self.flow_points[1].xpointer ~= nil
|
||||
if self.ui.rolling and not has_xpointers then
|
||||
config:saveSetting("handmade_flow_points_paging", self.flow_points)
|
||||
self.flow_points = config:readSetting("handmade_flow_points_rolling") or {}
|
||||
config:delSetting("handmade_flow_points_rolling")
|
||||
elseif self.ui.paging and has_xpointers then
|
||||
config:saveSetting("handmade_flow_points_rolling", self.flow_points)
|
||||
self.flow_points = config:readSetting("handmade_flow_points_paging") or {}
|
||||
config:delSetting("handmade_flow_points_paging")
|
||||
end
|
||||
else
|
||||
if self.ui.rolling and config:has("handmade_flow_points_rolling") then
|
||||
self.flow_points = config:readSetting("handmade_flow_points_rolling")
|
||||
config:delSetting("handmade_flow_points_rolling")
|
||||
elseif self.ui.paging and config:has("handmade_flow_points_paging") then
|
||||
self.flow_points = config:readSetting("handmade_flow_points_paging")
|
||||
config:delSetting("handmade_flow_points_paging")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderHandMade:onSaveSettings()
|
||||
self.ui.doc_settings:saveSetting("handmade_toc_enabled", self.toc_enabled)
|
||||
self.ui.doc_settings:saveSetting("handmade_toc_edit_enabled", self.toc_edit_enabled)
|
||||
if #self.toc > 0 then
|
||||
self.ui.doc_settings:saveSetting("handmade_toc", self.toc)
|
||||
else
|
||||
self.ui.doc_settings:delSetting("handmade_toc")
|
||||
end
|
||||
self.ui.doc_settings:saveSetting("handmade_flows_enabled", self.flows_enabled)
|
||||
self.ui.doc_settings:saveSetting("handmade_flows_edit_enabled", self.flows_edit_enabled)
|
||||
if #self.flow_points > 0 then
|
||||
self.ui.doc_settings:saveSetting("handmade_flow_points", self.flow_points)
|
||||
else
|
||||
self.ui.doc_settings:delSetting("handmade_flow_points")
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderHandMade:isHandmadeTocEnabled()
|
||||
return self.toc_enabled
|
||||
end
|
||||
|
||||
function ReaderHandMade:isHandmadeTocEditEnabled()
|
||||
return self.toc_edit_enabled
|
||||
end
|
||||
|
||||
function ReaderHandMade:isHandmadeHiddenFlowsEnabled()
|
||||
-- Even if currently empty, we return true, which allows showing '//' in
|
||||
-- the footer and let know hidden flows are enabled.
|
||||
return self.flows_enabled
|
||||
end
|
||||
|
||||
function ReaderHandMade:isHandmadeHiddenFlowsEditEnabled()
|
||||
return self.flows_edit_enabled
|
||||
end
|
||||
|
||||
function ReaderHandMade:onToggleHandmadeToc()
|
||||
self.toc_enabled = not self.toc_enabled
|
||||
self:setupToc()
|
||||
-- Have footer updated, so we may see this took effect
|
||||
self.view.footer:onUpdateFooter(self.view.footer_visible)
|
||||
end
|
||||
|
||||
function ReaderHandMade:onToggleHandmadeFlows()
|
||||
self.flows_enabled = not self.flows_enabled
|
||||
self:setupFlows()
|
||||
-- Have footer updated, so we may see this took effect
|
||||
self.view.footer:onUpdateFooter(self.view.footer_visible)
|
||||
end
|
||||
|
||||
function ReaderHandMade:addToMainMenu(menu_items)
|
||||
-- As it's currently impossible to create custom hidden flows on non-touch, and really impractical to create a custom toc, it's better hide these features completely for now.
|
||||
if not Device:isTouchDevice() then
|
||||
return
|
||||
end
|
||||
menu_items.handmade_toc = {
|
||||
text = _("Custom table of contents") .. " " .. self.custom_toc_symbol,
|
||||
checked_func = function() return self.toc_enabled end,
|
||||
callback = function()
|
||||
self:onToggleHandmadeToc()
|
||||
end,
|
||||
}
|
||||
menu_items.handmade_hidden_flows = {
|
||||
text = _("Custom hidden flows"),
|
||||
checked_func = function() return self.flows_enabled end,
|
||||
callback = function()
|
||||
self:onToggleHandmadeFlows()
|
||||
end,
|
||||
}
|
||||
--[[ Not yet implemented
|
||||
menu_items.handmade_page_numbers = {
|
||||
text = _("Custom page numbers"),
|
||||
checked_func = function() return false end,
|
||||
callback = function()
|
||||
end,
|
||||
}
|
||||
]]--
|
||||
menu_items.handmade_settings = {
|
||||
text = _("Custom layout features"),
|
||||
sub_item_table_func = function()
|
||||
return {
|
||||
{
|
||||
text = _("About custom table of contents") .. " " .. self.custom_toc_symbol,
|
||||
callback = function()
|
||||
UIManager:show(InfoMessage:new{
|
||||
text = _([[
|
||||
If the book has no table of contents or you would like to substitute it with your own, you can create a custom TOC. The original TOC (if available) will not be altered.
|
||||
|
||||
You can create, edit and remove chapters:
|
||||
- in Page browser, by long-pressing on a thumbnail;
|
||||
- on a book page, by selecting some text to be used as the chapter title.
|
||||
(Once you're done building it and don't want to see the buttons anymore, you can disable Edit mode.)
|
||||
|
||||
This custom table of contents is currently limited to a single level and can't have sub-chapters.]])
|
||||
})
|
||||
end,
|
||||
keep_menu_open = true,
|
||||
},
|
||||
{
|
||||
text = _("Edit mode"),
|
||||
enabled_func = function()
|
||||
return self:isHandmadeTocEnabled()
|
||||
end,
|
||||
checked_func = function()
|
||||
return self:isHandmadeTocEditEnabled()
|
||||
end,
|
||||
callback = function()
|
||||
self.toc_edit_enabled = not self.toc_edit_enabled
|
||||
self:updateHighlightDialog()
|
||||
end,
|
||||
},
|
||||
--[[ Not yet implemented
|
||||
{
|
||||
text = _("Add multiple chapter start page numbers"),
|
||||
},
|
||||
]]--
|
||||
{
|
||||
text = _("Clear custom table of contents"),
|
||||
enabled_func = function()
|
||||
return #self.toc > 0
|
||||
end,
|
||||
callback = function(touchmenu_instance)
|
||||
UIManager:show(ConfirmBox:new{
|
||||
text = _("Are you sure you want to clear your custom table of contents?"),
|
||||
ok_callback = function()
|
||||
self.toc = {}
|
||||
self.ui:handleEvent(Event:new("UpdateToc"))
|
||||
-- The footer may be visible, so have it update its chapter related items
|
||||
self.view.footer:onUpdateFooter(self.view.footer_visible)
|
||||
if touchmenu_instance then
|
||||
touchmenu_instance:updateItems()
|
||||
end
|
||||
end,
|
||||
})
|
||||
end,
|
||||
keep_menu_open = true,
|
||||
separator = true,
|
||||
},
|
||||
{
|
||||
text = _("About custom hidden flows"),
|
||||
callback = function()
|
||||
UIManager:show(InfoMessage:new{
|
||||
text = _([[
|
||||
Custom hidden flows can be created to exclude sections of the book from your normal reading flow:
|
||||
- hidden flows will automatically be skipped when turning pages within the regular flow;
|
||||
- pages part of hidden flows are assigned distinct page numbers and won't be considered in the various book & chapter progress and time to read features;
|
||||
- following direct links to pages in hidden flows will still work, including from the TOC or Book map.
|
||||
|
||||
This can be useful to exclude long footnotes or bibliography sections.
|
||||
It can also be handy when interested in reading only a subset of a book.
|
||||
|
||||
In Page browser, you can long-press on a thumbnail to start a hidden flow or restart the regular flow on this page.
|
||||
(Once you're done building it and don't want to see the button anymore, you can disable Edit mode.)
|
||||
|
||||
Hidden flows are shown with gray or hatched background in Book map and Page browser.]])
|
||||
})
|
||||
end,
|
||||
keep_menu_open = true,
|
||||
},
|
||||
{
|
||||
text = _("Edit mode"),
|
||||
enabled_func = function()
|
||||
return self:isHandmadeHiddenFlowsEnabled()
|
||||
end,
|
||||
checked_func = function()
|
||||
return self:isHandmadeHiddenFlowsEditEnabled()
|
||||
end,
|
||||
callback = function()
|
||||
self.flows_edit_enabled = not self.flows_edit_enabled
|
||||
end,
|
||||
},
|
||||
{
|
||||
text_func = function()
|
||||
return T(_("Clear inactive marked pages (%1)"), #self.inactive_flow_points)
|
||||
end,
|
||||
enabled_func = function()
|
||||
return #self.inactive_flow_points > 0
|
||||
end,
|
||||
callback = function(touchmenu_instance)
|
||||
UIManager:show(ConfirmBox:new{
|
||||
text = _("Inactive marked pages are pages that you tagged as start hidden flow or restart regular flow, but that other marked pages made them have no effect.\nAre you sure you want to clear them?"),
|
||||
ok_callback = function()
|
||||
for i=#self.inactive_flow_points, 1, -1 do
|
||||
table.remove(self.flow_points, self.inactive_flow_points[i])
|
||||
end
|
||||
self:updateDocFlows()
|
||||
self.ui:handleEvent(Event:new("UpdateToc"))
|
||||
self.ui:handleEvent(Event:new("InitScrollPageStates"))
|
||||
-- The footer may be visible, so have it update its dependant items
|
||||
self.view.footer:onUpdateFooter(self.view.footer_visible)
|
||||
if touchmenu_instance then
|
||||
touchmenu_instance:updateItems()
|
||||
end
|
||||
end,
|
||||
})
|
||||
end,
|
||||
keep_menu_open = true,
|
||||
},
|
||||
{
|
||||
text = _("Clear all marked pages"),
|
||||
enabled_func = function()
|
||||
return #self.flow_points > 0
|
||||
end,
|
||||
callback = function(touchmenu_instance)
|
||||
UIManager:show(ConfirmBox:new{
|
||||
text = _("Are you sure you want to clear all your custom hidden flows?"),
|
||||
ok_callback = function()
|
||||
self.flow_points = {}
|
||||
self:updateDocFlows()
|
||||
self.ui:handleEvent(Event:new("UpdateToc"))
|
||||
self.ui:handleEvent(Event:new("InitScrollPageStates"))
|
||||
-- The footer may be visible, so have it update its dependant items
|
||||
self.view.footer:onUpdateFooter(self.view.footer_visible)
|
||||
if touchmenu_instance then
|
||||
touchmenu_instance:updateItems()
|
||||
end
|
||||
end,
|
||||
})
|
||||
end,
|
||||
keep_menu_open = true,
|
||||
separator = true,
|
||||
},
|
||||
--[[ Not yet implemented
|
||||
{
|
||||
text = _("About custom page numbers"),
|
||||
},
|
||||
{
|
||||
text = _("Clear custom page numbers"),
|
||||
},
|
||||
]]--
|
||||
}
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
function ReaderHandMade:updateHandmagePages()
|
||||
if not self.ui.rolling then
|
||||
return
|
||||
end
|
||||
for _, item in ipairs(self.toc) do
|
||||
item.page = self.document:getPageFromXPointer(item.xpointer)
|
||||
end
|
||||
for _, item in ipairs(self.flow_points) do
|
||||
item.page = self.document:getPageFromXPointer(item.xpointer)
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderHandMade:onReaderReady()
|
||||
-- Called on load, and with a CRE document when reloading after partial rerendering.
|
||||
-- Notes:
|
||||
-- - ReaderFooter (from ReaderView) will have its onReaderReady() called before ours,
|
||||
-- and it may fillToc(). So, it may happen that the expensive validateAndFixToc()
|
||||
-- is called twice (first with the original ToC, then with ours).
|
||||
-- - ReaderRolling will have its onReaderReady() called after ours, and if we
|
||||
-- have set up hidden flows, we'll have overriden some documents methods so
|
||||
-- its cacheFlows() is a no-op.
|
||||
self:updateHandmagePages()
|
||||
-- Don't have each of these send their own events: we'll send them once afterwards
|
||||
self:setupFlows(true)
|
||||
self:setupToc(true)
|
||||
-- Now send the events
|
||||
if self.toc_enabled or self.flows_enabled then
|
||||
self.ui:handleEvent(Event:new("UpdateToc"))
|
||||
end
|
||||
if self.flows_enabled then
|
||||
-- Needed to skip hidden flows if PDF in scroll mode
|
||||
self.ui:handleEvent(Event:new("InitScrollPageStates"))
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderHandMade:onDocumentRerendered()
|
||||
-- Called with CRE document when partial rerendering not enabled
|
||||
self:updateHandmagePages()
|
||||
-- Don't have these send events their own events
|
||||
self:setupFlows(true)
|
||||
self:setupToc(true)
|
||||
-- ReaderToc will process this event just after us, and will
|
||||
-- call its onUpdateToc: we don't need to send it.
|
||||
-- (Also, no need for InitScrollPageStates with CRE.)
|
||||
end
|
||||
|
||||
function ReaderHandMade:setupToc(no_event)
|
||||
if self.toc_enabled then
|
||||
-- If enabled, plug one method into the document object,
|
||||
-- so it is used instead of the method from its class.
|
||||
self.document.getToc = function(this)
|
||||
-- ReaderToc may add fieds to ToC items: return a copy,
|
||||
-- so the one we will save doesn't get polluted.
|
||||
return util.tableDeepCopy(self.toc)
|
||||
end
|
||||
else
|
||||
-- If disabled, remove our plug so the method from the
|
||||
-- class gets used again.
|
||||
self.document.getToc = nil
|
||||
end
|
||||
self:updateHighlightDialog()
|
||||
if not no_event then
|
||||
self.ui:handleEvent(Event:new("UpdateToc"))
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderHandMade:updateHighlightDialog()
|
||||
if self.toc_enabled and self.toc_edit_enabled then
|
||||
-- We don't want this button to be the last wide one, and rather
|
||||
-- keep having the Search button being that one: so plug this one
|
||||
-- just before 12_search.
|
||||
self.ui.highlight:addToHighlightDialog("12_0_make_handmade_toc_item", function(this)
|
||||
return {
|
||||
text_func = function()
|
||||
local selected_text = this.selected_text
|
||||
local pageno, xpointer
|
||||
if self.ui.rolling then
|
||||
xpointer = selected_text.pos0
|
||||
else
|
||||
pageno = selected_text.pos0.page
|
||||
end
|
||||
local text
|
||||
if self:hasPageTocItem(pageno, xpointer) then
|
||||
text = _("Edit TOC chapter")
|
||||
else
|
||||
text = _("Start TOC chapter")
|
||||
end
|
||||
text = text .. " " .. self.custom_toc_symbol
|
||||
return text
|
||||
end,
|
||||
callback = function()
|
||||
local selected_text = this.selected_text
|
||||
this:onClose()
|
||||
self:addOrEditPageTocItem(nil, nil, selected_text)
|
||||
end,
|
||||
}
|
||||
end)
|
||||
else
|
||||
self.ui.highlight:removeFromHighlightDialog("12_0_make_handmade_toc_item")
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderHandMade:_getItemIndex(tab, pageno, xpointer)
|
||||
if not pageno and xpointer then
|
||||
pageno = self.document:getPageFromXPointer(xpointer)
|
||||
end
|
||||
-- (No need to use a binary search, our user made tables should
|
||||
-- not be too large)
|
||||
local matching_idx
|
||||
local insertion_idx = #tab + 1
|
||||
for i, item in ipairs(tab) do
|
||||
if item.page >= pageno then
|
||||
if item.page > pageno then
|
||||
insertion_idx = i
|
||||
break
|
||||
end
|
||||
-- Same page numbers.
|
||||
-- (We can trust page numbers, and only compare xpointers when both
|
||||
-- resolve to the same page.)
|
||||
if xpointer and item.xpointer then
|
||||
local order = self.document:compareXPointers(xpointer, item.xpointer)
|
||||
if order > 0 then -- item.xpointer after xpointer
|
||||
insertion_idx = i
|
||||
break
|
||||
elseif order == 0 then
|
||||
matching_idx = i
|
||||
break
|
||||
end
|
||||
else
|
||||
matching_idx = i
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
-- We always return an index, and a boolean stating if this index is a match or not
|
||||
-- (if not, the index is the insertion index if we ever want to insert an item with
|
||||
-- the asked pageno/xpointer)
|
||||
return matching_idx or insertion_idx, matching_idx and true or false
|
||||
end
|
||||
|
||||
function ReaderHandMade:hasPageTocItem(pageno, xpointer)
|
||||
local _, is_match = self:_getItemIndex(self.toc, pageno, xpointer)
|
||||
return is_match
|
||||
end
|
||||
|
||||
function ReaderHandMade:addOrEditPageTocItem(pageno, when_updated_callback, selected_text)
|
||||
local xpointer, title
|
||||
if selected_text then
|
||||
-- If we get selected_text, it's from the highlight dialog after text selection
|
||||
title = selected_text.text
|
||||
if self.ui.rolling then
|
||||
xpointer = selected_text.pos0
|
||||
pageno = self.document:getPageFromXPointer(xpointer)
|
||||
else
|
||||
pageno = selected_text.pos0.page
|
||||
end
|
||||
end
|
||||
local idx, item_found = self:_getItemIndex(self.toc, pageno, xpointer)
|
||||
local item
|
||||
if item_found then
|
||||
-- Chapter found: it's an update (edit text or remove item)
|
||||
item = self.toc[idx]
|
||||
else
|
||||
-- No chapter starting on this page or at this xpointer:
|
||||
-- we'll add a new item
|
||||
if not xpointer and self.ui.rolling and type(pageno) == "number" then
|
||||
xpointer = self.document:getPageXPointer(pageno)
|
||||
end
|
||||
item = {
|
||||
title = title or "",
|
||||
page = pageno,
|
||||
xpointer = xpointer,
|
||||
depth = 1, -- we only support 1-level chapters to keep the UX simple
|
||||
}
|
||||
end
|
||||
local dialog
|
||||
dialog = InputDialog:new{
|
||||
title = item_found and _("Edit custom TOC chapter") or _("Create new custom ToC chapter"),
|
||||
input = item.title,
|
||||
input_hint = _("TOC chapter title"),
|
||||
description = T(_([[On page %1.]]), pageno),
|
||||
buttons = {
|
||||
{
|
||||
{
|
||||
text = _("Cancel"),
|
||||
id = "close",
|
||||
callback = function()
|
||||
UIManager:close(dialog)
|
||||
end,
|
||||
},
|
||||
{
|
||||
text = item_found and _("Save") or _("Create"),
|
||||
is_enter_default = true,
|
||||
callback = function()
|
||||
item.title = dialog:getInputText()
|
||||
UIManager:close(dialog)
|
||||
if not item_found then
|
||||
table.insert(self.toc, idx, item)
|
||||
end
|
||||
self.ui:handleEvent(Event:new("UpdateToc"))
|
||||
if when_updated_callback then
|
||||
when_updated_callback()
|
||||
end
|
||||
end,
|
||||
},
|
||||
},
|
||||
item_found and {
|
||||
{
|
||||
text = _("Remove"),
|
||||
callback = function()
|
||||
UIManager:close(dialog)
|
||||
table.remove(self.toc, idx)
|
||||
self.ui:handleEvent(Event:new("UpdateToc"))
|
||||
if when_updated_callback then
|
||||
when_updated_callback()
|
||||
end
|
||||
end,
|
||||
},
|
||||
selected_text and
|
||||
{
|
||||
text = _("Use selected text"),
|
||||
callback = function()
|
||||
-- Just replace the text without saving, to allow editing/fixing it
|
||||
dialog:setInputText(selected_text.text, nil, false)
|
||||
end,
|
||||
} or nil,
|
||||
} or nil,
|
||||
},
|
||||
}
|
||||
UIManager:show(dialog)
|
||||
dialog:onShowKeyboard()
|
||||
return true
|
||||
end
|
||||
|
||||
function ReaderHandMade:isInHiddenFlow(pageno)
|
||||
local idx, is_match = self:_getItemIndex(self.flow_points, pageno)
|
||||
if is_match then
|
||||
return self.flow_points[idx].hidden
|
||||
else
|
||||
if idx > 1 then
|
||||
return self.flow_points[idx-1].hidden
|
||||
end
|
||||
end
|
||||
-- Before any first flow_point: not hidden
|
||||
return false
|
||||
end
|
||||
|
||||
function ReaderHandMade:toggleHiddenFlow(pageno)
|
||||
local idx, is_match = self:_getItemIndex(self.flow_points, pageno)
|
||||
if is_match then
|
||||
-- Just remove the item (it feels we can, and that we don't
|
||||
-- have to just toggle its hidden value)
|
||||
table.remove(self.flow_points, idx)
|
||||
self:updateDocFlows()
|
||||
return
|
||||
end
|
||||
local hidden
|
||||
if idx > 1 then
|
||||
local previous_item = self.flow_points[idx-1]
|
||||
hidden = not previous_item.hidden
|
||||
else
|
||||
-- First item, can only start an hidden flow
|
||||
hidden = true
|
||||
end
|
||||
local xpointer
|
||||
if self.ui.rolling and type(pageno) == "number" then
|
||||
xpointer = self.document:getPageXPointer(pageno)
|
||||
end
|
||||
local item = {
|
||||
hidden = hidden,
|
||||
page = pageno,
|
||||
xpointer = xpointer,
|
||||
}
|
||||
table.insert(self.flow_points, idx, item)
|
||||
-- We could remove any followup item(s) with the same hidden state, but by keeping them,
|
||||
-- we allow users to adjust the start of a flow without killing its end. One can clean
|
||||
-- all the unnefective ones via the "Clear inactive marked pages" menu item.
|
||||
self:updateDocFlows()
|
||||
end
|
||||
|
||||
function ReaderHandMade:updateDocFlows()
|
||||
local flows = {}
|
||||
local inactive_flow_points = {}
|
||||
-- (getPageCount(), needing the document to be fully loaded, is not available
|
||||
-- until ReaderReady, so be sure this is called only after ReaderReady.)
|
||||
local nb_pages = self.document:getPageCount()
|
||||
local nb_hidden_pages = 0
|
||||
local cur_hidden_flow
|
||||
for i, point in ipairs(self.flow_points) do
|
||||
if point.hidden and not cur_hidden_flow then
|
||||
cur_hidden_flow = {point.page, 0}
|
||||
elseif not point.hidden and cur_hidden_flow then
|
||||
local cur_hidden_pages = point.page - cur_hidden_flow[1]
|
||||
if cur_hidden_pages > 0 then
|
||||
cur_hidden_flow[2] = cur_hidden_pages
|
||||
nb_hidden_pages = nb_hidden_pages + cur_hidden_pages
|
||||
table.insert(flows, cur_hidden_flow)
|
||||
end
|
||||
cur_hidden_flow = nil
|
||||
else
|
||||
table.insert(inactive_flow_points, i)
|
||||
end
|
||||
end
|
||||
if cur_hidden_flow then
|
||||
local cur_hidden_pages = nb_pages + 1 - cur_hidden_flow[1]
|
||||
if cur_hidden_pages > 0 then
|
||||
cur_hidden_flow[2] = cur_hidden_pages
|
||||
nb_hidden_pages = nb_hidden_pages + cur_hidden_pages
|
||||
table.insert(flows, cur_hidden_flow)
|
||||
end
|
||||
end
|
||||
local first_linear_page
|
||||
local last_linear_page
|
||||
local prev_flow
|
||||
for i, flow in ipairs(flows) do
|
||||
if not prev_flow or prev_flow[1] + prev_flow[2] < flow[1] then
|
||||
if not first_linear_page and flow[1] > 1 then
|
||||
first_linear_page = prev_flow and prev_flow[1] + prev_flow[2] or 1
|
||||
end
|
||||
last_linear_page = flow[1] - 1
|
||||
end
|
||||
prev_flow = flow
|
||||
end
|
||||
if not prev_flow or prev_flow[1] + prev_flow[2] < nb_pages then
|
||||
last_linear_page = nb_pages
|
||||
end
|
||||
if not first_linear_page then -- no flow met
|
||||
first_linear_page = 1
|
||||
end
|
||||
-- CreDocument adds and item with key [0] with info about the main flow
|
||||
flows[0] = {first_linear_page, nb_pages - nb_hidden_pages}
|
||||
self.last_linear_page = last_linear_page
|
||||
self.flows = flows
|
||||
self.inactive_flow_points = inactive_flow_points
|
||||
-- We plug our flows table into the document, as some code peeks into it
|
||||
self.document.flows = self.flows
|
||||
end
|
||||
|
||||
function ReaderHandMade:setupFlows(no_event)
|
||||
if self.flows_enabled then
|
||||
self:updateDocFlows()
|
||||
-- If enabled, plug some methods into the document object,
|
||||
-- so they are used instead of the methods from its class.
|
||||
self.document.hasHiddenFlows = function(this)
|
||||
return true
|
||||
end
|
||||
self.document.cacheFlows = function(this)
|
||||
return
|
||||
end
|
||||
self.document.getPageFlow = function(this, page)
|
||||
for i, flow in ipairs(self.flows) do
|
||||
if page < flow[1] then
|
||||
return 0 -- page is not in a hidden flow
|
||||
end
|
||||
if page < flow[1] + flow[2] then
|
||||
return i
|
||||
end
|
||||
end
|
||||
return 0
|
||||
end
|
||||
self.document.getFirstPageInFlow = function(this, flow)
|
||||
return self.flows[flow][1]
|
||||
end
|
||||
self.document.getTotalPagesInFlow = function(this, flow)
|
||||
return self.flows[flow][2]
|
||||
end
|
||||
self.document.getPageNumberInFlow = function(this, page)
|
||||
local nb_hidden_pages = 0
|
||||
for i, flow in ipairs(self.flows) do
|
||||
if page < flow[1] then
|
||||
break -- page is not in a hidden flow
|
||||
end
|
||||
if page < flow[1] + flow[2] then
|
||||
return page - flow[1] + 1
|
||||
end
|
||||
nb_hidden_pages = nb_hidden_pages + flow[2]
|
||||
end
|
||||
return page - nb_hidden_pages
|
||||
end
|
||||
self.document.getLastLinearPage = function(this)
|
||||
return self.last_linear_page
|
||||
end
|
||||
-- We can reuse as-is these ones from CreDocument, which uses the ones defined above.
|
||||
-- Note: these could probably be rewritten and simplified.
|
||||
local CreDocument = require("document/credocument")
|
||||
self.document.getTotalPagesLeft = CreDocument.getTotalPagesLeft
|
||||
self.document.getNextPage = CreDocument.getNextPage
|
||||
self.document.getPrevPage = CreDocument.getPrevPage
|
||||
else
|
||||
-- Remove all our overrides, so the class methods can be used again
|
||||
self.document.hasHiddenFlows = nil
|
||||
self.document.cacheFlows = nil
|
||||
self.document.getPageFlow = nil
|
||||
self.document.getFirstPageInFlow = nil
|
||||
self.document.getTotalPagesInFlow = nil
|
||||
self.document.getPageNumberInFlow = nil
|
||||
self.document.getLastLinearPage = nil
|
||||
self.document.getTotalPagesLeft = nil
|
||||
self.document.getNextPage = nil
|
||||
self.document.getPrevPage = nil
|
||||
self.document.flows = nil
|
||||
if self.document.cacheFlows then
|
||||
self.document:cacheFlows()
|
||||
end
|
||||
end
|
||||
if not no_event then
|
||||
self.ui:handleEvent(Event:new("UpdateToc"))
|
||||
-- Needed to skip hidden flows if PDF in scroll mode
|
||||
self.ui:handleEvent(Event:new("InitScrollPageStates"))
|
||||
end
|
||||
end
|
||||
|
||||
return ReaderHandMade
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,542 +0,0 @@
|
||||
local Blitbuffer = require("ffi/blitbuffer")
|
||||
local Cache = require("cache")
|
||||
local Device = require("device")
|
||||
local Geom = require("ui/geometry")
|
||||
local Persist = require("persist")
|
||||
local RenderImage = require("ui/renderimage")
|
||||
local TileCacheItem = require("document/tilecacheitem")
|
||||
local UIManager = require("ui/uimanager")
|
||||
local WidgetContainer = require("ui/widget/container/widgetcontainer")
|
||||
local Screen = Device.screen
|
||||
local ffiutil = require("ffi/util")
|
||||
local logger = require("logger")
|
||||
local util = require("util")
|
||||
local _ = require("gettext")
|
||||
|
||||
-- This ReaderThumbnail module provides a service for generating thumbnails
|
||||
-- of book pages.
|
||||
-- It handles launching via the menu or Dispatcher/Gestures two fullscreen
|
||||
-- widgets related to showing pages and thumbnails that will make use of
|
||||
-- its services: BookMap and PageBrowser.
|
||||
local ReaderThumbnail = WidgetContainer:extend{}
|
||||
|
||||
function ReaderThumbnail:init()
|
||||
if not Device:isTouchDevice() then
|
||||
-- The BookMap and PageBrowser widgets depend too much on gestures,
|
||||
-- making them work with keys would be hard and very limited, so
|
||||
-- just don't make them available.
|
||||
return
|
||||
end
|
||||
|
||||
self.ui.menu:registerToMainMenu(self)
|
||||
|
||||
-- Use LuaJIT fast buffer.encode()/decode() when serializing BlitBuffer
|
||||
-- for exchange between subprocess and parent.
|
||||
self.codec = Persist.getCodec("luajit")
|
||||
|
||||
self:setupColor()
|
||||
self.thumbnails_requests = {}
|
||||
self.current_target_size_tag = nil
|
||||
|
||||
-- Ensure no multiple executions, and nextTick() the scheduleIn()
|
||||
-- so we get a chance to process events in-between refreshes and
|
||||
-- this can be interrupted (otherwise, something scheduleIn(0.1),
|
||||
-- if a screen refresh is then done and taking longer than 0.1s,
|
||||
-- would be executed immediately, without emptying any input event).
|
||||
local schedule_step = 0
|
||||
self._ensureTileGeneration_action = function(restart)
|
||||
if restart then
|
||||
UIManager:unschedule(self._ensureTileGeneration_action)
|
||||
schedule_step = 0
|
||||
end
|
||||
if schedule_step == 0 then
|
||||
schedule_step = 1
|
||||
UIManager:nextTick(self._ensureTileGeneration_action)
|
||||
elseif schedule_step == 1 then
|
||||
schedule_step = 2
|
||||
UIManager:scheduleIn(0.1, self._ensureTileGeneration_action)
|
||||
else
|
||||
schedule_step = 0
|
||||
self:ensureTileGeneration()
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderThumbnail:addToMainMenu(menu_items)
|
||||
menu_items.book_map = {
|
||||
text = _("Book map"),
|
||||
callback = function()
|
||||
self:onShowBookMap()
|
||||
end,
|
||||
-- Show the alternative overview mode (which is just a restricted
|
||||
-- variation of the main book map) with long-press (let's avoid
|
||||
-- adding another item in the crowded first menu).
|
||||
hold_callback = function()
|
||||
self:onShowBookMap(true)
|
||||
end,
|
||||
}
|
||||
menu_items.page_browser = {
|
||||
text = _("Page browser"),
|
||||
callback = function()
|
||||
self:onShowPageBrowser()
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
function ReaderThumbnail:onShowBookMap(overview_mode)
|
||||
local BookMapWidget = require("ui/widget/bookmapwidget")
|
||||
UIManager:show(BookMapWidget:new{
|
||||
ui = self.ui,
|
||||
overview_mode = overview_mode,
|
||||
})
|
||||
return true
|
||||
end
|
||||
|
||||
function ReaderThumbnail:onShowPageBrowser()
|
||||
local PageBrowserWidget = require("ui/widget/pagebrowserwidget")
|
||||
UIManager:show(PageBrowserWidget:new{
|
||||
ui = self.ui,
|
||||
})
|
||||
return true
|
||||
end
|
||||
|
||||
-- This is made a module local so we can keep track of pids
|
||||
-- to collect across multiple Reader instantiations
|
||||
local pids_to_collect = {}
|
||||
|
||||
function ReaderThumbnail:collectPids()
|
||||
if #pids_to_collect == 0 then
|
||||
return false
|
||||
end
|
||||
for i=#pids_to_collect, 1, -1 do
|
||||
if ffiutil.isSubProcessDone(pids_to_collect[i]) then
|
||||
table.remove(pids_to_collect, i)
|
||||
end
|
||||
end
|
||||
return #pids_to_collect > 0
|
||||
end
|
||||
|
||||
function ReaderThumbnail:setupColor()
|
||||
self.bb_type = self.ui.document.render_color and self.ui.document.color_bb_type or Blitbuffer.TYPE_BB8
|
||||
end
|
||||
|
||||
function ReaderThumbnail:setupCache()
|
||||
if not self.tile_cache then
|
||||
-- We want to allow browsing at least N pages worth of thumbnails
|
||||
-- without cache trashing. A little more than N pages (because inter
|
||||
-- thumbnail margins) will fit in N * screen size.
|
||||
-- With N=5, this should use from 5 to 15 Mb on a classic eInk device.
|
||||
local N = 5
|
||||
local max_bytes = math.ceil(N * Screen:getWidth() * Screen:getHeight() * Blitbuffer.TYPE_TO_BPP[self.bb_type] / 8)
|
||||
-- We don't really care about limiting any number of slots, so allow
|
||||
-- for at least 5 pages of 10x10 tiles
|
||||
local avg_itemsize = math.ceil(max_bytes * (1/500))
|
||||
self.tile_cache = Cache:new{
|
||||
size = max_bytes,
|
||||
avg_itemsize = avg_itemsize, -- will make slots=500
|
||||
enable_eviction_cb = true,
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderThumbnail:logCacheSize()
|
||||
logger.info(string.format("Thumbnails cache: %d/%d (%s/%s)",
|
||||
self.tile_cache.cache.used_slots(),
|
||||
self.tile_cache.slots,
|
||||
util.getFriendlySize(self.tile_cache.cache.used_size()),
|
||||
util.getFriendlySize(self.tile_cache.size)))
|
||||
end
|
||||
|
||||
function ReaderThumbnail:resetCache()
|
||||
if self.tile_cache then
|
||||
self.tile_cache:clear()
|
||||
self.tile_cache = nil
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderThumbnail:removeFromCache(hash_subs, remove_only_non_matching)
|
||||
-- Remove from cache all tiles matching any hash from hash_subs.
|
||||
-- IF only_non_matching=true, keep those matching and remove all others.
|
||||
if not self.tile_cache then
|
||||
return
|
||||
end
|
||||
if type(hash_subs) ~= "table" then
|
||||
hash_subs = { hash_subs }
|
||||
end
|
||||
local nb_removed, size_removed = 0, 0
|
||||
local to_remove = {}
|
||||
for thash, tile in self.tile_cache.cache:pairs() do
|
||||
local remove = remove_only_non_matching
|
||||
for _, h in ipairs(hash_subs) do
|
||||
if thash:find(h, 1, true) then -- plain text match (no pattern needed)
|
||||
remove = not remove
|
||||
break
|
||||
end
|
||||
end
|
||||
if remove then
|
||||
to_remove[thash] = true
|
||||
nb_removed = nb_removed + 1
|
||||
size_removed = size_removed + tile.size
|
||||
end
|
||||
end
|
||||
for thash, _ in pairs(to_remove) do
|
||||
self.tile_cache.cache:delete(thash)
|
||||
logger.dbg("removed cached thumbnail", thash)
|
||||
end
|
||||
return nb_removed, size_removed
|
||||
end
|
||||
|
||||
function ReaderThumbnail:resetCachedPagesForBookmarks(annotations)
|
||||
-- Multiple bookmarks may be provided
|
||||
local start_page, end_page
|
||||
for i = 1, #annotations do
|
||||
local bm = annotations[i]
|
||||
if self.ui.rolling then
|
||||
-- Look at all properties that may be xpointers
|
||||
for _, k in ipairs({"page", "pos0", "pos1"}) do
|
||||
if bm[k] and type(bm[k]) == "string" then
|
||||
local p = self.ui.document:getPageFromXPointer(bm[k])
|
||||
if not start_page or p < start_page then
|
||||
start_page = p
|
||||
end
|
||||
if not end_page or p > end_page then
|
||||
end_page = p
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
if bm.page and type(bm.page) == "number" then
|
||||
local bm_page0 = (bm.pos0 and bm.pos0.page) or bm.page
|
||||
local bm_page1 = (bm.pos1 and bm.pos1.page) or bm.page
|
||||
for p = bm_page0, bm_page1 do
|
||||
if not start_page or p < start_page then
|
||||
start_page = p
|
||||
end
|
||||
if not end_page or p > end_page then
|
||||
end_page = p
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if start_page and end_page then
|
||||
local hash_subs_to_remove = {}
|
||||
for p=start_page, end_page do
|
||||
table.insert(hash_subs_to_remove, string.format("p%d-", p))
|
||||
end
|
||||
self:removeFromCache(hash_subs_to_remove)
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderThumbnail:tidyCache()
|
||||
if self.current_target_size_tag then
|
||||
-- Remove all thumbnails generated for an older target size
|
||||
self:removeFromCache("-"..self.current_target_size_tag, true)
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderThumbnail:cancelPageThumbnailRequests(batch_id)
|
||||
if batch_id then
|
||||
self.thumbnails_requests[batch_id] = nil
|
||||
else
|
||||
self.thumbnails_requests = {}
|
||||
end
|
||||
if self.req_in_progress and (not batch_id or self.req_in_progress.batch_id == batch_id) then
|
||||
-- Kill any reference to the module cancelling it
|
||||
self.req_in_progress.when_generated_callback = nil
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderThumbnail:getPageThumbnail(page, width, height, batch_id, when_generated_callback)
|
||||
self:setupCache()
|
||||
self.current_target_size_tag = string.format("w%d_h%d", width, height)
|
||||
if self.ui.rolling and Screen.night_mode and self.ui.document.configurable.nightmode_images == 1 then
|
||||
-- We'll get a different bb in this case: it needs its own cache hash
|
||||
self.current_target_size_tag = self.current_target_size_tag .. "_nm"
|
||||
end
|
||||
local hash = string.format("p%d-%s", page, self.current_target_size_tag)
|
||||
local tile = self.tile_cache and self.tile_cache:check(hash)
|
||||
if tile then
|
||||
-- Cached: call callback and we're done.
|
||||
when_generated_callback(tile, batch_id, false)
|
||||
return false -- not delayed
|
||||
end
|
||||
if not self.thumbnails_requests[batch_id] then
|
||||
self.thumbnails_requests[batch_id] = {}
|
||||
end
|
||||
table.insert(self.thumbnails_requests[batch_id], {
|
||||
batch_id = batch_id,
|
||||
hash = hash,
|
||||
page = page,
|
||||
width = width,
|
||||
height = height,
|
||||
when_generated_callback = when_generated_callback,
|
||||
})
|
||||
-- Start tile generation, avoid multiple ones
|
||||
self._ensureTileGeneration_action(true)
|
||||
return true -- delayed
|
||||
end
|
||||
|
||||
function ReaderThumbnail:ensureTileGeneration()
|
||||
if not self._standby_prevented then
|
||||
self._standby_prevented = true
|
||||
UIManager:preventStandby()
|
||||
end
|
||||
local has_pids_still_to_collect = self:collectPids()
|
||||
|
||||
local still_in_progress = false
|
||||
if self.req_in_progress then
|
||||
local pid_still_to_collect
|
||||
still_in_progress, pid_still_to_collect = self:checkTileGeneration(self.req_in_progress)
|
||||
if pid_still_to_collect then
|
||||
has_pids_still_to_collect = true
|
||||
end
|
||||
end
|
||||
if not still_in_progress then
|
||||
self.req_in_progress = nil
|
||||
while true do
|
||||
local req_id, requests = next(self.thumbnails_requests)
|
||||
if not req_id then -- no more requests
|
||||
break
|
||||
end
|
||||
local req = table.remove(requests, 1)
|
||||
if #requests == 0 then
|
||||
self.thumbnails_requests[req_id] = nil
|
||||
end
|
||||
if req.when_generated_callback then -- not cancelled since queued
|
||||
-- It might have been generated and cached by a previous batch
|
||||
local tile = self.tile_cache and self.tile_cache:check(req.hash)
|
||||
if tile then
|
||||
req.when_generated_callback(tile, req.batch_id, true)
|
||||
else
|
||||
if self:startTileGeneration(req) then
|
||||
self.req_in_progress = req
|
||||
break
|
||||
else
|
||||
-- Failure starting it: let requester know in case it cares, and forget it
|
||||
req.when_generated_callback(nil, req.batch_id, true)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if self.req_in_progress or has_pids_still_to_collect or next(self.thumbnails_requests) then
|
||||
self._ensureTileGeneration_action()
|
||||
else
|
||||
if self._standby_prevented then
|
||||
self._standby_prevented = false
|
||||
UIManager:allowStandby()
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderThumbnail:startTileGeneration(request)
|
||||
local pid, parent_read_fd = ffiutil.runInSubProcess(function(pid, child_write_fd)
|
||||
-- Get page image as if drawn on the screen
|
||||
local bb = self:_getPageImage(request.page)
|
||||
-- Scale it to fit in the requested size
|
||||
local scale_factor = math.min(request.width / bb:getWidth(), request.height / bb:getHeight())
|
||||
local target_w = math.floor(bb:getWidth() * scale_factor)
|
||||
local target_h = math.floor(bb:getHeight() * scale_factor)
|
||||
-- local time = require("ui/time")
|
||||
-- local start_time = time.now()
|
||||
local tile = TileCacheItem:new{
|
||||
bb = RenderImage:scaleBlitBuffer(bb, target_w, target_h, true),
|
||||
pageno = request.page,
|
||||
}
|
||||
tile.size = tonumber(tile.bb.stride) * tile.bb.h
|
||||
-- logger.info("tile size", tile.bb.w, tile.bb.h, "=>", tile.size)
|
||||
-- logger.info(string.format(" scaling took %.3f seconds, %d bpp", time.to_s(time.since(start_time)), tile.bb:getBpp()))
|
||||
-- bb:free() -- no need to spend time freeing, we're dying soon anyway!
|
||||
|
||||
ffiutil.writeToFD(child_write_fd, self.codec.serialize(tile:totable()), true)
|
||||
end, true) -- with_pipe = true
|
||||
if pid then
|
||||
-- Store these in the request object itself
|
||||
request.pid = pid
|
||||
request.parent_read_fd = parent_read_fd
|
||||
return true
|
||||
end
|
||||
logger.warn("PageBrowserWidget thumbnail start failure:", parent_read_fd)
|
||||
return false
|
||||
end
|
||||
|
||||
function ReaderThumbnail:checkTileGeneration(request)
|
||||
local pid, parent_read_fd = request.pid, request.parent_read_fd
|
||||
local stuff_to_read = ffiutil.getNonBlockingReadSize(parent_read_fd) ~= 0
|
||||
local subprocess_done = ffiutil.isSubProcessDone(pid)
|
||||
logger.dbg("subprocess_done:", subprocess_done, " stuff_to_read:", stuff_to_read)
|
||||
if stuff_to_read then
|
||||
-- local time = require("ui/time")
|
||||
-- local start_time = time.now()
|
||||
local result, err = self.codec.deserialize(ffiutil.readAllFromFD(parent_read_fd))
|
||||
if result then
|
||||
local tile = TileCacheItem:new{}
|
||||
tile:fromtable(result)
|
||||
if self.tile_cache then
|
||||
self.tile_cache:insert(request.hash, tile)
|
||||
end
|
||||
if request.when_generated_callback then -- not cancelled
|
||||
request.when_generated_callback(tile, request.batch_id, true)
|
||||
end
|
||||
else
|
||||
logger.warn("PageBrowserWidget thumbnail deserialize() failed:", err)
|
||||
if request.when_generated_callback then -- not cancelled
|
||||
request.when_generated_callback(nil, request.batch_id, true)
|
||||
end
|
||||
end
|
||||
-- logger.info(string.format(" parsing result from subprocess took %.3f seconds", time.to_s(time.since(start_time))))
|
||||
if not subprocess_done then
|
||||
table.insert(pids_to_collect, pid)
|
||||
return false, true
|
||||
end
|
||||
return false
|
||||
elseif subprocess_done then
|
||||
-- subprocess_done: process exited with no output
|
||||
ffiutil.readAllFromFD(parent_read_fd) -- close our fd
|
||||
return false
|
||||
end
|
||||
logger.dbg("process not yet done, will check again soon")
|
||||
return true
|
||||
end
|
||||
|
||||
function ReaderThumbnail:_getPageImage(page)
|
||||
-- This is run in a subprocess: we can tweak all document settings
|
||||
-- to get an adequate image of the page.
|
||||
-- No need to worry about the final state of things: this subprocess
|
||||
-- will die just after drawing the page, and all will be forgotten,
|
||||
-- without impact on the parent process.
|
||||
|
||||
-- Be sure to limit our impact on the disk-saved book state
|
||||
self.ui.saveSettings = function() end -- Be sure nothing is flushed
|
||||
self.ui.statistics = nil -- Don't update statistics for pages we visit
|
||||
|
||||
-- By default, our target page size is the current screen size
|
||||
local target_w, target_h = Screen:getWidth(), Screen:getHeight()
|
||||
|
||||
-- This was all mostly chosen by experimenting.
|
||||
-- Be sure to call the innermost methods enough to get what we want, and
|
||||
-- not upper event handlers that may trigger other unneeded events and stuff.
|
||||
-- Especially, be sure to not trigger any paint on the screen buffer, or
|
||||
-- any processing of input events.
|
||||
-- No need to worry about UIManager:scheduleIn() or :nextTick(), as
|
||||
-- we will die before the callback gets a chance to be run.
|
||||
|
||||
-- Common to ReaderRolling and ReaderPaging
|
||||
self.ui.view.footer_visible = false -- We want no footer on page image
|
||||
if self.ui.view.highlight.lighten_factor < 0.3 then
|
||||
self.ui.view.highlight.lighten_factor = 0.3 -- make lighten highlight a bit darker
|
||||
end
|
||||
self.ui.highlight.select_mode = false -- Remove any select mode icon
|
||||
|
||||
if self.ui.rolling then
|
||||
-- CRE documents: pages all have the aspect ratio of our screen (alt top status bar
|
||||
-- will be croped out after drawing), we will show them just as rendered.
|
||||
self.ui.rolling.rendering_state = nil -- Remove any partial rerendering icon
|
||||
if self.ui.view.view_mode == "scroll" then
|
||||
-- Get out of scroll mode, and be sure we'll be in one-page mode as that
|
||||
-- is what is shown in scroll mode (needs to do the following in that
|
||||
-- order to avoid rendering hash change)
|
||||
self.ui.rolling:onSetVisiblePages(1)
|
||||
self.ui.view:onSetViewMode("page")
|
||||
end
|
||||
if self.ui.document.configurable.font_gamma < 30 then -- Increase font gamma (if not already increased),
|
||||
self.ui.document:setGammaIndex(30) -- as downscaling will make text grayer
|
||||
end
|
||||
self.ui.document:setImageScaling(false) -- No need for smooth scaling as all will be downscaled
|
||||
-- (We keep "nighmode_images" as it was set: we may get and cache a different bb whether nightmode is on or off)
|
||||
self.ui.view.state.page = page -- Be on requested page
|
||||
self.ui.document:gotoPage(page) -- Current xpointer needs to be updated for some of what follows
|
||||
self.ui.bookmark:onPageUpdate(page) -- Update dogear state for this page
|
||||
self.ui.pagemap:onPageUpdate(page) -- Update pagemap labels for this page
|
||||
end
|
||||
|
||||
if self.ui.paging then
|
||||
-- With PDF/DJVU/Pics, we will show the native page (no reflow, no crop, no zoom
|
||||
-- to columns...). This makes thumbnail generation faster, and will allow the user
|
||||
-- to get an overview of the book native pages to better decide which option will
|
||||
-- be best to use for the book.
|
||||
-- We also want to get a thumbnail with the aspect ratio of the native page
|
||||
-- (so we don't get a native landscape page smallish and centered with blank above
|
||||
-- and below in a portrait thumbnail, if the screen is in portrait mode).
|
||||
|
||||
self.ui.view.hinting = false -- Disable hinting
|
||||
self.ui.view.page_scroll = false -- Get out of scroll mode
|
||||
self.ui.view.flipping_visible = false -- No page flipping icon
|
||||
self.ui.document.configurable.text_wrap = false -- Get out of reflow mode
|
||||
self.ui.document.configurable.trim_page = 3 -- Page crop: none
|
||||
-- self.ui.document.configurable.trim_page = 1 -- Page crop: auto (very slower)
|
||||
self.ui.document.configurable.auto_straighten = 0 -- No auto straighten
|
||||
-- We can let dewatermark if the user has enabled it, it helps
|
||||
-- limiting annoying eInk refreshes of light gray areas
|
||||
-- self.ui.document.configurable.page_opt = 0 -- No dewatermark
|
||||
-- We won't touch the contrast (to try making text less gray), as it applies on
|
||||
-- images that could get too dark.
|
||||
|
||||
-- Get native page dimensions, and update our target bb dimensions so it gets the
|
||||
-- same aspect ratio (we don't use native dimensions as is, as they may get huge)
|
||||
local dimen = self.ui.document:getPageDimensions(page, 1, 0)
|
||||
local scale_factor = math.min(target_w / dimen.w, target_h / dimen.h)
|
||||
target_w = math.floor(dimen.w * scale_factor)
|
||||
target_h = math.floor(dimen.h * scale_factor)
|
||||
dimen = Geom:new{ w=target_w, h=target_h }
|
||||
-- logger.info("getPageImage", page, dimen, "=>", target_w, target_h, scale_factor)
|
||||
|
||||
-- This seems to do it all well:
|
||||
-- local Event = require("ui/event")
|
||||
-- self.ui:handleEvent(Event:new("SetDimensions", dimen))
|
||||
-- self.ui.view.dogear[1].dimen.w = dimen.w -- (hack... its code uses the Screen width)
|
||||
-- self.ui:handleEvent(Event:new("PageUpdate", page))
|
||||
-- self.ui:handleEvent(Event:new("SetZoomMode", "page"))
|
||||
|
||||
-- Trying to do as little as needed, knowing the internals:
|
||||
self.ui.view:onSetDimensions(dimen)
|
||||
self.ui.view:onBBoxUpdate(nil) -- drop any bbox, draw native page
|
||||
self.ui.view.state.page = page
|
||||
self.ui.view.state.zoom = scale_factor
|
||||
self.ui.view.state.rotation = 0
|
||||
self.ui.view:recalculate()
|
||||
self.ui.view.dogear[1].dimen.w = dimen.w -- (hack... its code uses the Screen width)
|
||||
self.ui.bookmark:onPageUpdate(page) -- Update dogear state for this page
|
||||
end
|
||||
|
||||
-- Draw the page on a new BB with the targetted size
|
||||
local bb = Blitbuffer.new(target_w, target_h, self.bb_type)
|
||||
self.ui.view:paintTo(bb, 0, 0)
|
||||
|
||||
if self.ui.rolling then
|
||||
-- Crop out the top alt status bar if enabled
|
||||
local header_height = self.ui.document:getHeaderHeight()
|
||||
if header_height > 0 then
|
||||
bb = bb:viewport(0, header_height, bb.w, bb.h - header_height)
|
||||
end
|
||||
end
|
||||
|
||||
return bb
|
||||
end
|
||||
|
||||
function ReaderThumbnail:onCloseDocument()
|
||||
self:cancelPageThumbnailRequests()
|
||||
if self.tile_cache then
|
||||
self:logCacheSize()
|
||||
self.tile_cache:clear()
|
||||
self.tile_cache = nil
|
||||
end
|
||||
if self._standby_prevented then
|
||||
self._standby_prevented = false
|
||||
UIManager:allowStandby()
|
||||
end
|
||||
end
|
||||
|
||||
function ReaderThumbnail:onColorRenderingUpdate()
|
||||
self:setupColor()
|
||||
self:resetCache()
|
||||
end
|
||||
|
||||
-- CRE: emitted after a re-rendering
|
||||
ReaderThumbnail.onDocumentRerendered = ReaderThumbnail.resetCache
|
||||
ReaderThumbnail.onDocumentPartiallyRerendered = ReaderThumbnail.resetCache
|
||||
-- Emitted When adding/removing/updating bookmarks and highlights
|
||||
ReaderThumbnail.onAnnotationsModified = ReaderThumbnail.resetCachedPagesForBookmarks
|
||||
|
||||
return ReaderThumbnail
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue