mirror of https://github.com/koreader/koreader
Compare commits
No commits in common. 'master' and 'v2022.08' have entirely different histories.
@ -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 0.25.0-1
|
||||
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.8.0"
|
||||
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,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 a6e112a5ee06e6939203accbd0736134af8939cd
|
||||
Subproject commit 7fb47e46054ebf0499131db8f6fc006729795f3e
|
@ -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,340 +1,274 @@
|
||||
local ButtonDialog = require("ui/widget/buttondialog")
|
||||
local ButtonDialogTitle = require("ui/widget/buttondialogtitle")
|
||||
local CheckButton = require("ui/widget/checkbutton")
|
||||
local ConfirmBox = require("ui/widget/confirmbox")
|
||||
local DocSettings = require("docsettings")
|
||||
local CenterContainer = require("ui/widget/container/centercontainer")
|
||||
local DocumentRegistry = require("document/documentregistry")
|
||||
local FileChooser = require("ui/widget/filechooser")
|
||||
local InfoMessage = require("ui/widget/infomessage")
|
||||
local InputContainer = require("ui/widget/container/inputcontainer")
|
||||
local InputDialog = require("ui/widget/inputdialog")
|
||||
local Menu = require("ui/widget/menu")
|
||||
local Size = require("ui/size")
|
||||
local UIManager = require("ui/uimanager")
|
||||
local WidgetContainer = require("ui/widget/container/widgetcontainer")
|
||||
local Utf8Proc = require("ffi/utf8proc")
|
||||
local filemanagerutil = require("apps/filemanager/filemanagerutil")
|
||||
local lfs = require("libs/libkoreader-lfs")
|
||||
local BaseUtil = require("ffi/util")
|
||||
local util = require("util")
|
||||
local _ = require("gettext")
|
||||
local N_ = _.ngettext
|
||||
local Screen = require("device").screen
|
||||
local T = require("ffi/util").template
|
||||
|
||||
local FileSearcher = WidgetContainer:extend{
|
||||
local FileSearcher = InputContainer:new{
|
||||
dirs = {},
|
||||
files = {},
|
||||
results = {},
|
||||
|
||||
case_sensitive = false,
|
||||
include_subfolders = true,
|
||||
include_metadata = false,
|
||||
}
|
||||
|
||||
local sys_folders = { -- do not search in sys_folders
|
||||
["/dev"] = true,
|
||||
["/proc"] = true,
|
||||
["/sys"] = true,
|
||||
}
|
||||
|
||||
function FileSearcher:readDir()
|
||||
local ReaderUI = require("apps/reader/readerui")
|
||||
local show_unsupported = G_reader_settings:isTrue("show_unsupported")
|
||||
self.dirs = {self.path}
|
||||
self.files = {}
|
||||
while #self.dirs ~= 0 do
|
||||
local new_dirs = {}
|
||||
-- handle each dir
|
||||
for __, d in pairs(self.dirs) do
|
||||
-- handle files in d
|
||||
local ok, iter, dir_obj = pcall(lfs.dir, d)
|
||||
if ok then
|
||||
for f in iter, dir_obj do
|
||||
local fullpath = "/" .. f
|
||||
if d ~= "/" then
|
||||
fullpath = d .. fullpath
|
||||
end
|
||||
local attributes = lfs.attributes(fullpath) or {}
|
||||
-- Don't traverse hidden folders if we're not showing them
|
||||
if attributes.mode == "directory" and f ~= "." and f ~= ".."
|
||||
and (G_reader_settings:isTrue("show_hidden") or not util.stringStartsWith(f, "."))
|
||||
and FileChooser:show_dir(f)
|
||||
then
|
||||
if self.include_subfolders and not sys_folders[fullpath] then
|
||||
table.insert(new_dirs, fullpath)
|
||||
end
|
||||
table.insert(self.files, {
|
||||
dir = d,
|
||||
name = f,
|
||||
text = f.."/",
|
||||
attr = attributes,
|
||||
callback = function()
|
||||
self:showFolder(fullpath .. "/")
|
||||
end,
|
||||
})
|
||||
-- Always ignore macOS resource forks, too.
|
||||
elseif attributes.mode == "file" and not util.stringStartsWith(f, "._")
|
||||
and (show_unsupported or DocumentRegistry:hasProvider(fullpath))
|
||||
and FileChooser:show_file(f)
|
||||
then
|
||||
table.insert(self.files, {
|
||||
dir = d,
|
||||
name = f,
|
||||
text = f,
|
||||
mandatory = util.getFriendlySize(attributes.size or 0),
|
||||
attr = attributes,
|
||||
callback = function()
|
||||
ReaderUI:showReader(fullpath)
|
||||
end,
|
||||
})
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
self.dirs = new_dirs
|
||||
end
|
||||
end
|
||||
|
||||
function FileSearcher:setSearchResults()
|
||||
local keywords = self.search_value
|
||||
self.results = {}
|
||||
if keywords == "*" then -- one * to show all files
|
||||
self.results = self.files
|
||||
else
|
||||
if not self.case_sensitive then
|
||||
keywords = Utf8Proc.lowercase(util.fixUtf8(keywords, "?"))
|
||||
end
|
||||
-- replace '.' with '%.'
|
||||
keywords = keywords:gsub("%.","%%%.")
|
||||
-- replace '*' with '.*'
|
||||
keywords = keywords:gsub("%*","%.%*")
|
||||
-- replace '?' with '.'
|
||||
keywords = keywords:gsub("%?","%.")
|
||||
for __,f in pairs(self.files) do
|
||||
if self.case_sensitive then
|
||||
if string.find(f.name, keywords) then
|
||||
table.insert(self.results, f)
|
||||
end
|
||||
else
|
||||
if string.find(Utf8Proc.lowercase(util.fixUtf8(f.name, "?")), keywords) then
|
||||
table.insert(self.results, f)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function FileSearcher:close()
|
||||
UIManager:close(self.search_dialog)
|
||||
self:readDir() --- @todo this probably doesn't need to be repeated once it's been done
|
||||
self:setSearchResults() --- @todo doesn't have to be repeated if the search term is the same
|
||||
if #self.results > 0 then
|
||||
self:showSearchResults()
|
||||
else
|
||||
UIManager:show(
|
||||
InfoMessage:new{
|
||||
text = BaseUtil.template(_("No results for '%1'."),
|
||||
self.search_value)
|
||||
}
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
function FileSearcher:onShowFileSearch(search_string)
|
||||
local search_dialog
|
||||
local check_button_case, check_button_subfolders, check_button_metadata
|
||||
search_dialog = InputDialog:new{
|
||||
title = _("Enter text to search for in filename"),
|
||||
input = search_string or self.search_string,
|
||||
self.search_dialog = InputDialog:new{
|
||||
title = _("Enter filename to search for"),
|
||||
input = search_string or self.search_value,
|
||||
buttons = {
|
||||
{
|
||||
{
|
||||
text = _("Cancel"),
|
||||
id = "close",
|
||||
callback = function()
|
||||
UIManager:close(search_dialog)
|
||||
UIManager:close(self.search_dialog)
|
||||
end,
|
||||
},
|
||||
{
|
||||
text = _("Home folder"),
|
||||
enabled = G_reader_settings:has("home_dir"),
|
||||
callback = function()
|
||||
self.search_string = search_dialog:getInputText()
|
||||
if self.search_string == "" then return end
|
||||
UIManager:close(search_dialog)
|
||||
self.search_value = self.search_dialog:getInputText()
|
||||
if self.search_value == "" then return end
|
||||
self.path = G_reader_settings:readSetting("home_dir")
|
||||
self:doSearch()
|
||||
self:close()
|
||||
end,
|
||||
},
|
||||
{
|
||||
text = self.ui.file_chooser and _("Current folder") or _("Book folder"),
|
||||
text = _("Current folder"),
|
||||
is_enter_default = true,
|
||||
callback = function()
|
||||
self.search_string = search_dialog:getInputText()
|
||||
if self.search_string == "" then return end
|
||||
UIManager:close(search_dialog)
|
||||
self.search_value = self.search_dialog:getInputText()
|
||||
if self.search_value == "" then return end
|
||||
self.path = self.ui.file_chooser and self.ui.file_chooser.path or self.ui:getLastDirFile()
|
||||
self:doSearch()
|
||||
self:close()
|
||||
end,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
check_button_case = CheckButton:new{
|
||||
|
||||
self.check_button_case = CheckButton:new{
|
||||
text = _("Case sensitive"),
|
||||
checked = self.case_sensitive,
|
||||
parent = search_dialog,
|
||||
parent = self.search_dialog,
|
||||
callback = function()
|
||||
self.case_sensitive = check_button_case.checked
|
||||
self.case_sensitive = self.check_button_case.checked
|
||||
end,
|
||||
}
|
||||
search_dialog:addWidget(check_button_case)
|
||||
check_button_subfolders = CheckButton:new{
|
||||
self.search_dialog:addWidget(self.check_button_case)
|
||||
self.check_button_subfolders = CheckButton:new{
|
||||
text = _("Include subfolders"),
|
||||
checked = self.include_subfolders,
|
||||
parent = search_dialog,
|
||||
parent = self.search_dialog,
|
||||
callback = function()
|
||||
self.include_subfolders = check_button_subfolders.checked
|
||||
self.include_subfolders = self.check_button_subfolders.checked
|
||||
end,
|
||||
}
|
||||
search_dialog:addWidget(check_button_subfolders)
|
||||
if self.ui.coverbrowser then
|
||||
check_button_metadata = CheckButton:new{
|
||||
text = _("Also search in book metadata"),
|
||||
checked = self.include_metadata,
|
||||
parent = search_dialog,
|
||||
callback = function()
|
||||
self.include_metadata = check_button_metadata.checked
|
||||
end,
|
||||
}
|
||||
search_dialog:addWidget(check_button_metadata)
|
||||
end
|
||||
UIManager:show(search_dialog)
|
||||
search_dialog:onShowKeyboard()
|
||||
end
|
||||
self.search_dialog:addWidget(self.check_button_subfolders)
|
||||
|
||||
function FileSearcher:doSearch()
|
||||
local results
|
||||
local dirs, files = self:getList()
|
||||
-- If we have a FileChooser instance, use it, to be able to make use of its natsort cache
|
||||
if self.ui.file_chooser then
|
||||
results = self.ui.file_chooser:genItemTable(dirs, files)
|
||||
else
|
||||
results = FileChooser:genItemTable(dirs, files)
|
||||
end
|
||||
if #results > 0 then
|
||||
self:showSearchResults(results)
|
||||
else
|
||||
self:showSearchResultsMessage(true)
|
||||
end
|
||||
UIManager:show(self.search_dialog)
|
||||
self.search_dialog:onShowKeyboard()
|
||||
end
|
||||
|
||||
function FileSearcher:getList()
|
||||
self.no_metadata_count = 0
|
||||
local sys_folders = { -- do not search in sys_folders
|
||||
["/dev"] = true,
|
||||
["/proc"] = true,
|
||||
["/sys"] = true,
|
||||
function FileSearcher:showSearchResults()
|
||||
local menu_container = CenterContainer:new{
|
||||
dimen = Screen:getSize(),
|
||||
}
|
||||
local collate = FileChooser:getCollate()
|
||||
local search_string = self.search_string
|
||||
if search_string ~= "*" then -- one * to show all files
|
||||
if not self.case_sensitive then
|
||||
search_string = Utf8Proc.lowercase(util.fixUtf8(search_string, "?"))
|
||||
end
|
||||
-- replace '.' with '%.'
|
||||
search_string = search_string:gsub("%.","%%%.")
|
||||
-- replace '*' with '.*'
|
||||
search_string = search_string:gsub("%*","%.%*")
|
||||
-- replace '?' with '.'
|
||||
search_string = search_string:gsub("%?","%.")
|
||||
end
|
||||
|
||||
local dirs, files = {}, {}
|
||||
local scan_dirs = {self.path}
|
||||
while #scan_dirs ~= 0 do
|
||||
local new_dirs = {}
|
||||
-- handle each dir
|
||||
for _, d in ipairs(scan_dirs) do
|
||||
-- handle files in d
|
||||
local ok, iter, dir_obj = pcall(lfs.dir, d)
|
||||
if ok then
|
||||
for f in iter, dir_obj do
|
||||
local fullpath = "/" .. f
|
||||
if d ~= "/" then
|
||||
fullpath = d .. fullpath
|
||||
end
|
||||
local attributes = lfs.attributes(fullpath) or {}
|
||||
-- Don't traverse hidden folders if we're not showing them
|
||||
if attributes.mode == "directory" and f ~= "." and f ~= ".."
|
||||
and (FileChooser.show_hidden or not util.stringStartsWith(f, "."))
|
||||
and FileChooser:show_dir(f) then
|
||||
if self.include_subfolders and not sys_folders[fullpath] then
|
||||
table.insert(new_dirs, fullpath)
|
||||
end
|
||||
if self:isFileMatch(f, fullpath, search_string) then
|
||||
table.insert(dirs, FileChooser:getListItem(nil, f, fullpath, attributes, collate))
|
||||
end
|
||||
-- Always ignore macOS resource forks, too.
|
||||
elseif attributes.mode == "file" and not util.stringStartsWith(f, "._")
|
||||
and (FileChooser.show_unsupported or DocumentRegistry:hasProvider(fullpath))
|
||||
and FileChooser:show_file(f) then
|
||||
if self:isFileMatch(f, fullpath, search_string, true) then
|
||||
table.insert(files, FileChooser:getListItem(nil, f, fullpath, attributes, collate))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
scan_dirs = new_dirs
|
||||
end
|
||||
return dirs, files
|
||||
end
|
||||
|
||||
function FileSearcher:isFileMatch(filename, fullpath, search_string, is_file)
|
||||
if search_string == "*" then
|
||||
return true
|
||||
end
|
||||
if not self.case_sensitive then
|
||||
filename = Utf8Proc.lowercase(util.fixUtf8(filename, "?"))
|
||||
end
|
||||
if string.find(filename, search_string) then
|
||||
return true
|
||||
end
|
||||
if self.include_metadata and is_file and DocumentRegistry:hasProvider(fullpath) then
|
||||
local book_props = self.ui.coverbrowser:getBookInfo(fullpath) or
|
||||
self.ui.bookinfo.getDocProps(fullpath, nil, true) -- do not open the document
|
||||
if next(book_props) ~= nil then
|
||||
if self.ui.bookinfo:findInProps(book_props, search_string, self.case_sensitive) then
|
||||
return true
|
||||
end
|
||||
else
|
||||
self.no_metadata_count = self.no_metadata_count + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function FileSearcher:showSearchResultsMessage(no_results)
|
||||
local text = no_results and T(_("No results for '%1'."), self.search_string)
|
||||
if self.no_metadata_count == 0 then
|
||||
UIManager:show(InfoMessage:new{ text = text })
|
||||
else
|
||||
local txt = T(N_("1 book has been skipped.", "%1 books have been skipped.",
|
||||
self.no_metadata_count), self.no_metadata_count) .. "\n" ..
|
||||
_("Not all books metadata extracted yet.\nExtract metadata now?")
|
||||
text = no_results and text .. "\n\n" .. txt or txt
|
||||
UIManager:show(ConfirmBox:new{
|
||||
text = text,
|
||||
ok_text = _("Extract"),
|
||||
ok_callback = function()
|
||||
if not no_results then
|
||||
self.search_menu.close_callback()
|
||||
end
|
||||
self.ui.coverbrowser:extractBooksInDirectory(self.path)
|
||||
end
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
function FileSearcher:showSearchResults(results)
|
||||
self.search_menu = Menu:new{
|
||||
title = T(_("Search results (%1)"), #results),
|
||||
subtitle = T(_("Query: %1"), self.search_string),
|
||||
item_table = results,
|
||||
ui = self.ui,
|
||||
covers_fullscreen = true, -- hint for UIManager:_repaint()
|
||||
is_borderless = true,
|
||||
is_popout = false,
|
||||
title_bar_fm_style = true,
|
||||
onMenuSelect = self.onMenuSelect,
|
||||
width = Screen:getWidth() - (Size.margin.fullscreen_popout * 2),
|
||||
height = Screen:getHeight() - (Size.margin.fullscreen_popout * 2),
|
||||
show_parent = menu_container,
|
||||
onMenuHold = self.onMenuHold,
|
||||
handle_hold_on_hold_release = true,
|
||||
_manager = self,
|
||||
}
|
||||
table.insert(menu_container, self.search_menu)
|
||||
self.search_menu.close_callback = function()
|
||||
UIManager:close(self.search_menu)
|
||||
if self.ui.file_chooser then
|
||||
self.ui.file_chooser:refreshPath()
|
||||
end
|
||||
end
|
||||
UIManager:show(self.search_menu)
|
||||
if self.no_metadata_count ~= 0 then
|
||||
self:showSearchResultsMessage()
|
||||
UIManager:close(menu_container)
|
||||
end
|
||||
|
||||
local collate = G_reader_settings:readSetting("collate") or "strcoll"
|
||||
local reverse_collate = G_reader_settings:isTrue("reverse_collate")
|
||||
local sorting = FileChooser:getSortingFunction(collate, reverse_collate)
|
||||
|
||||
table.sort(self.results, sorting)
|
||||
self.search_menu:switchItemTable(T(_("Search results (%1)"), #self.results), self.results)
|
||||
UIManager:show(menu_container)
|
||||
end
|
||||
|
||||
function FileSearcher:onMenuSelect(item)
|
||||
local file = item.path
|
||||
local bookinfo, dialog
|
||||
local function close_dialog_callback()
|
||||
UIManager:close(dialog)
|
||||
end
|
||||
local function close_dialog_menu_callback()
|
||||
UIManager:close(dialog)
|
||||
self.close_callback()
|
||||
end
|
||||
local buttons = {}
|
||||
if item.is_file then
|
||||
local is_currently_opened = self.ui.document and self.ui.document.file == file
|
||||
if DocumentRegistry:hasProvider(file) or DocSettings:hasSidecarFile(file) then
|
||||
bookinfo = self.ui.coverbrowser and self.ui.coverbrowser:getBookInfo(file)
|
||||
local doc_settings_or_file = is_currently_opened and self.ui.doc_settings or file
|
||||
table.insert(buttons, filemanagerutil.genStatusButtonsRow(doc_settings_or_file, close_dialog_callback))
|
||||
table.insert(buttons, {}) -- separator
|
||||
table.insert(buttons, {
|
||||
filemanagerutil.genResetSettingsButton(file, close_dialog_callback, is_currently_opened),
|
||||
self.ui.collections:genAddToCollectionButton(file, close_dialog_callback),
|
||||
})
|
||||
end
|
||||
table.insert(buttons, {
|
||||
function FileSearcher:onMenuHold(item)
|
||||
local ReaderUI = require("apps/reader/readerui")
|
||||
local is_file = item.attr.mode == "file"
|
||||
local fullpath = item.dir .. "/" .. item.name .. (is_file and "" or "/")
|
||||
local buttons = {
|
||||
{
|
||||
{
|
||||
text = _("Delete"),
|
||||
enabled = not is_currently_opened,
|
||||
text = _("Cancel"),
|
||||
callback = function()
|
||||
local function post_delete_callback()
|
||||
UIManager:close(dialog)
|
||||
for i, menu_item in ipairs(self.item_table) do
|
||||
if menu_item.path == file then
|
||||
table.remove(self.item_table, i)
|
||||
break
|
||||
end
|
||||
self:switchItemTable(T(_("Search results (%1)"), #self.item_table), self.item_table)
|
||||
end
|
||||
end
|
||||
local FileManager = require("apps/filemanager/filemanager")
|
||||
FileManager:showDeleteFileDialog(file, post_delete_callback)
|
||||
UIManager:close(self.results_dialog)
|
||||
end,
|
||||
},
|
||||
filemanagerutil.genBookInformationButton(file, bookinfo, close_dialog_callback),
|
||||
})
|
||||
end
|
||||
table.insert(buttons, {
|
||||
filemanagerutil.genShowFolderButton(file, close_dialog_menu_callback),
|
||||
{
|
||||
{
|
||||
text = _("Show folder"),
|
||||
callback = function()
|
||||
UIManager:close(self.results_dialog)
|
||||
self.close_callback()
|
||||
self._manager:showFolder(fullpath)
|
||||
end,
|
||||
},
|
||||
},
|
||||
}
|
||||
if is_file then
|
||||
table.insert(buttons[1], {
|
||||
text = _("Open"),
|
||||
enabled = DocumentRegistry:hasProvider(file, nil, true), -- allow auxiliary providers
|
||||
callback = function()
|
||||
close_dialog_callback()
|
||||
local FileManager = require("apps/filemanager/filemanager")
|
||||
FileManager.openFile(self.ui, file, nil, self.close_callback)
|
||||
UIManager:close(self.results_dialog)
|
||||
self.close_callback()
|
||||
ReaderUI:showReader(fullpath)
|
||||
end,
|
||||
},
|
||||
})
|
||||
local title = file
|
||||
if bookinfo then
|
||||
if bookinfo.title then
|
||||
title = title .. "\n\n" .. T(_("Title: %1"), bookinfo.title)
|
||||
end
|
||||
if bookinfo.authors then
|
||||
title = title .. "\n" .. T(_("Authors: %1"), bookinfo.authors:gsub("[\n\t]", "|"))
|
||||
end
|
||||
})
|
||||
end
|
||||
dialog = ButtonDialog:new{
|
||||
title = title .. "\n",
|
||||
|
||||
self.results_dialog = ButtonDialogTitle:new{
|
||||
title = fullpath,
|
||||
buttons = buttons,
|
||||
}
|
||||
UIManager:show(dialog)
|
||||
UIManager:show(self.results_dialog)
|
||||
return true
|
||||
end
|
||||
|
||||
function FileSearcher:onMenuHold(item)
|
||||
if item.is_file then
|
||||
if DocumentRegistry:hasProvider(item.path, nil, true) then
|
||||
local FileManager = require("apps/filemanager/filemanager")
|
||||
FileManager.openFile(self.ui, item.path, nil, self.close_callback)
|
||||
end
|
||||
else
|
||||
self.close_callback()
|
||||
if self.ui.file_chooser then
|
||||
local pathname = util.splitFilePathName(item.path)
|
||||
self.ui.file_chooser:changeToPath(pathname, item.path)
|
||||
else -- called from Reader
|
||||
self.ui:onClose()
|
||||
self.ui:showFileManager(item.path)
|
||||
end
|
||||
function FileSearcher:showFolder(path)
|
||||
if self.ui.file_chooser then
|
||||
local pathname = util.splitFilePathName(path)
|
||||
self.ui.file_chooser:changeToPath(pathname, path)
|
||||
else -- called from Reader
|
||||
self.ui:onClose()
|
||||
self.ui:showFileManager(path)
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
return FileSearcher
|
||||
|
@ -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
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