diff --git a/frontend/apps/filemanager/filemanagerbookinfo.lua b/frontend/apps/filemanager/filemanagerbookinfo.lua index 732f42722..6fc7a8666 100644 --- a/frontend/apps/filemanager/filemanagerbookinfo.lua +++ b/frontend/apps/filemanager/filemanagerbookinfo.lua @@ -13,10 +13,12 @@ local DocumentRegistry = require("document/documentregistry") local Event = require("ui/event") local InfoMessage = require("ui/widget/infomessage") local InputDialog = require("ui/widget/inputdialog") +local Math = require("optmath") local Notification = require("ui/widget/notification") local TextViewer = require("ui/widget/textviewer") local UIManager = require("ui/uimanager") local WidgetContainer = require("ui/widget/container/widgetcontainer") +local datetime = require("datetime") local ffiUtil = require("ffi/util") local filemanagerutil = require("apps/filemanager/filemanagerutil") local lfs = require("libs/libkoreader-lfs") @@ -940,4 +942,138 @@ function BookInfo.showBooksWithHashBasedMetadata() }) end +function BookInfo:expandString(str, file, timestamp) + if self == nil then + UIManager:show(InfoMessage:new{ + text = _([[ +%T title +%A author +%S series +%t total pages +%c current page +%p book percentage read +%H time left in book +%C chapter title +%P chapter percentage read +%h time left in chapter +%F file path +%f file name +%b battery level +%B battery symbol +%D current date (yyyy-mm-dd) +%d current date (mm-dd) +%m current time (hh:mm) +%M current time (hh-mm-ss)]]), + monospace_font = true, + }) + return + end + + if not (str and str:find("%%")) then + return str + end + + local na = _("N/A") + local doc_patterns, is_doc_required = "%T%A%S%t%c%p%H%C%P%h" + local patterns = {} + for p in str:gmatch("%%%a") do + patterns[p] = na -- calculate only needed items + if not is_doc_required and doc_patterns:find(p, 1, true) then + is_doc_required = true + end + end + + file = file or G_reader_settings:readSetting("lastfile") + if file then + if is_doc_required then + local props + local doc = self.document and self.document.file == file and self.document + if doc then -- Reader, currently opened file + props = self.ui.doc_props + local pageno = self.ui.view.footer.pageno + if patterns["%t"] or patterns["%c"] then + if doc:hasHiddenFlows() then + patterns["%t"] = patterns["%t"] and doc:getTotalPagesInFlow(doc:getPageFlow(pageno)) + patterns["%c"] = patterns["%c"] and doc:getPageNumberInFlow(pageno) + else + patterns["%t"] = patterns["%t"] and self.ui.view.footer.pages + patterns["%c"] = patterns["%c"] and pageno + end + end + patterns["%p"] = patterns["%p"] and Math.round(self.ui.view.footer:getBookProgress() * 100) + if patterns["%C"] then + local title = self.ui.toc:getTocTitleByPage(pageno) + if title and title ~= "" then + patterns["%C"] = title + end + end + patterns["%P"] = patterns["%P"] and Math.round(self.ui.view.footer:getChapterProgress(true) * 100) + if (patterns["%H"] or patterns["%h"]) and self.ui.statistics then + local pages = doc:getTotalPagesLeft(pageno) + if patterns["%H"] then + local time_left = self.ui.statistics:getTimeForPages(pages) + if time_left then + patterns["%H"] = time_left + end + end + if patterns["%h"] then + pages = self.ui.toc:getChapterPagesLeft(pageno) or pages + local time_left = self.ui.statistics:getTimeForPages(pages) + if time_left then + patterns["%h"] = time_left + end + end + end + elseif BookList.hasBookBeenOpened(file) then -- do not open book, use sdr only + local doc_settings = BookList.getDocSettings(file) + props = BookInfo.extendProps(doc_settings:readSetting("doc_props"), file) + if patterns["%t"] or patterns["%c"] or patterns["%p"] then + local pages = doc_settings:readSetting("doc_pages") + if pages then + patterns["%t"] = patterns["%t"] and pages + local percent = doc_settings:readSetting("percent_finished") + if percent then + patterns["%c"] = patterns["%c"] and Math.round(percent * pages) + patterns["%p"] = patterns["%p"] and Math.round(percent * 100) + end + end + end + -- %H %C %P %h unavailable + end + if props then + patterns["%T"] = patterns["%T"] and props.display_title + if patterns["%A"] and props.authors then + patterns["%A"] = props.authors + end + if patterns["%S"] and props.series then + patterns["%S"] = props.series_index and props.series .. " #" .. props.series_index or props.series + end + end + end + + patterns["%F"] = patterns["%F"] and file + patterns["%f"] = patterns["%f"] and file:gsub(".*/", "") + end + + if (patterns["%b"] or patterns["%B"]) and Device:hasBattery() then + local powerd = Device:getPowerDevice() + local batt_lvl = powerd:getCapacity() + if Device:hasAuxBattery() and powerd:isAuxBatteryConnected() then + batt_lvl = batt_lvl + powerd:getAuxCapacity() + patterns["%B"] = patterns["%B"] and powerd:getBatterySymbol(powerd:isAuxCharged(), powerd:isAuxCharging(), batt_lvl / 2) + else + patterns["%B"] = patterns["%B"] and powerd:getBatterySymbol(powerd:isCharged(), powerd:isCharging(), batt_lvl) + end + patterns["%b"] = patterns["%b"] and batt_lvl + end + + timestamp = timestamp or os.time() + patterns["%D"] = patterns["%D"] and os.date("%Y-%m-%d", timestamp) + patterns["%d"] = patterns["%d"] and os.date("%m-%d", timestamp) + patterns["%m"] = patterns["%m"] and datetime.secondsToHour(timestamp, G_reader_settings:isTrue("twelve_hour_clock")) + patterns["%M"] = patterns["%M"] and os.date("%H-%M-%S", timestamp) + + return str:gsub("(%%%a)", patterns) +end + return BookInfo diff --git a/frontend/apps/reader/modules/readerfooter.lua b/frontend/apps/reader/modules/readerfooter.lua index a685672ce..a5a8cd47a 100644 --- a/frontend/apps/reader/modules/readerfooter.lua +++ b/frontend/apps/reader/modules/readerfooter.lua @@ -320,13 +320,15 @@ footerTextGeneratorMap = { local symbol_type = footer.settings.item_prefix local prefix = symbol_prefix[symbol_type].book_time_to_read local left = footer.ui.document:getTotalPagesLeft(footer.pageno) - return footer:getDataFromStatistics(prefix and (prefix .. " ") or "", left) + return (prefix and prefix .. " " or "") .. + (footer.ui.statistics and footer.ui.statistics:getTimeForPages(left) or _("N/A")) end, chapter_time_to_read = function(footer) local symbol_type = footer.settings.item_prefix local prefix = symbol_prefix[symbol_type].chapter_time_to_read local left = footer.ui.toc:getChapterPagesLeft(footer.pageno) or footer.ui.document:getTotalPagesLeft(footer.pageno) - return footer:getDataFromStatistics(prefix .. " ", left) + return prefix .. " " .. + (footer.ui.statistics and footer.ui.statistics:getTimeForPages(left) or _("N/A")) end, mem_usage = function(footer) local statm = io.open("/proc/self/statm", "r") @@ -403,8 +405,8 @@ footerTextGeneratorMap = { custom_text = function(footer) -- if custom_text contains only spaces, request to merge it with the text before and after, -- in other words, don't add a separator then. - local merge = footer.custom_text:gsub(" ", ""):len() == 0 - return footer.custom_text:rep(footer.custom_text_repetitions), merge + local merge = footer.custom_text:gsub(" ", "") == "" + return footer.ui.bookinfo:expandString(footer.custom_text):rep(footer.custom_text_repetitions), merge end, dynamic_filler = function(footer) local margin = footer.horizontal_margin @@ -684,6 +686,10 @@ function ReaderFooter:set_custom_text(touchmenu_instance) UIManager:close(text_dialog) end, }, + { + text = _("Info"), + callback = self.ui.bookinfo.expandString, + }, { text = _("Set"), callback = function() @@ -1396,21 +1402,21 @@ function ReaderFooter:addToMainMenu(menu_items) table.insert(footer_items, getMinibarOption("time")) table.insert(footer_items, getMinibarOption("chapter_progress")) table.insert(footer_items, getMinibarOption("pages_left")) - if Device:hasBattery() then + if MODE.battery then table.insert(footer_items, getMinibarOption("battery")) end table.insert(footer_items, getMinibarOption("bookmark_count")) table.insert(footer_items, getMinibarOption("percentage")) table.insert(footer_items, getMinibarOption("book_time_to_read")) table.insert(footer_items, getMinibarOption("chapter_time_to_read")) - if Device:hasFrontlight() then + if MODE.frontlight then table.insert(footer_items, getMinibarOption("frontlight")) end - if Device:hasNaturalLight() then + if MODE.frontlight_warmth then table.insert(footer_items, getMinibarOption("frontlight_warmth")) end table.insert(footer_items, getMinibarOption("mem_usage")) - if Device:hasFastWifiStatusQuery() then + if MODE.wifi_status then table.insert(footer_items, getMinibarOption("wifi_status")) end table.insert(footer_items, getMinibarOption("page_turning_inverted")) @@ -1655,7 +1661,7 @@ With this feature enabled, the current page is factored in, resulting in the cou } }) local configure_items_sub_table = sub_items[#sub_items].sub_item_table -- will pick the last item of sub_items - if Device:hasBattery() then + if MODE.battery then table.insert(configure_items_sub_table, 5, { text_func = function() if self.settings.battery_hide_threshold <= self.default_settings.battery_hide_threshold then @@ -2099,19 +2105,6 @@ function ReaderFooter:setTocMarkers(reset) return true end --- This is implemented by the Statistics plugin -function ReaderFooter:getAvgTimePerPage() end - -function ReaderFooter:getDataFromStatistics(title, pages) - local sec = _("N/A") - local average_time_per_page = self:getAvgTimePerPage() - local user_duration_format = G_reader_settings:readSetting("duration_format", "classic") - if average_time_per_page then - sec = datetime.secondsToClockDuration(user_duration_format, pages * average_time_per_page, true) - end - return title .. sec -end - function ReaderFooter:onUpdateFooter(force_repaint, full_repaint) if type(self.pageno) ~= "number" then return end if self.settings.chapter_progress_bar then @@ -2476,7 +2469,7 @@ end function ReaderFooter:onResume() -- Reset the initial marker, if any - if self.progress_bar.initial_pos_marker then + if self.progress_bar and self.progress_bar.initial_pos_marker then self.initial_pageno = self.pageno self.progress_bar.initial_percentage = self.progress_bar.percentage end diff --git a/frontend/apps/reader/modules/readermenu.lua b/frontend/apps/reader/modules/readermenu.lua index 6a6ae6711..f7de3a48c 100644 --- a/frontend/apps/reader/modules/readermenu.lua +++ b/frontend/apps/reader/modules/readermenu.lua @@ -253,30 +253,25 @@ function ReaderMenu:setUpdateItemTable() end if Device:supportsScreensaver() then - local ss_book_settings = { + local screensaver_sub_item_table = dofile("frontend/ui/elements/screensaver_menu.lua") + table.insert(screensaver_sub_item_table, { text = _("Do not show this book cover on sleep screen"), enabled_func = function() - if self.ui and self.ui.document then - local screensaverType = G_reader_settings:readSetting("screensaver_type") - return screensaverType == "cover" or screensaverType == "disable" - else - return false - end + local screensaver_type = G_reader_settings:readSetting("screensaver_type") + return screensaver_type == "cover" or screensaver_type == "disable" end, checked_func = function() - return self.ui and self.ui.doc_settings and self.ui.doc_settings:isTrue("exclude_screensaver") + return self.ui.doc_settings:isTrue("exclude_screensaver") end, callback = function() - if Screensaver:isExcluded() then + if Screensaver.isExcluded(self.ui) then self.ui.doc_settings:makeFalse("exclude_screensaver") else self.ui.doc_settings:makeTrue("exclude_screensaver") end self.ui:saveSettings() end, - } - local screensaver_sub_item_table = dofile("frontend/ui/elements/screensaver_menu.lua") - table.insert(screensaver_sub_item_table, ss_book_settings) + }) self.menu_items.screensaver = { text = _("Sleep screen"), sub_item_table = screensaver_sub_item_table, diff --git a/frontend/ui/elements/screensaver_menu.lua b/frontend/ui/elements/screensaver_menu.lua index 46f163825..6d5cb5698 100644 --- a/frontend/ui/elements/screensaver_menu.lua +++ b/frontend/ui/elements/screensaver_menu.lua @@ -4,20 +4,22 @@ local lfs = require("libs/libkoreader-lfs") local _ = require("gettext") local T = require("ffi/util").template +local ui = require("apps/reader/readerui").instance or require("apps/filemanager/filemanager").instance + local function hasLastFile() local last_file = G_reader_settings:readSetting("lastfile") return last_file and lfs.attributes(last_file, "mode") == "file" end local function isReaderProgressEnabled() - return Screensaver.getReaderProgress ~= nil and hasLastFile() + return ui.statistics ~= nil end local function allowRandomImageFolder() local may_ignore_book_cover = G_reader_settings:isTrue("screensaver_exclude_on_hold_books") or G_reader_settings:isTrue("screensaver_exclude_finished_books") or G_reader_settings:isTrue("screensaver_hide_cover_in_filemanager") - or Screensaver:isExcluded() + or Screensaver.isExcluded(ui) return G_reader_settings:readSetting("screensaver_type") == "random_image" or (G_reader_settings:readSetting("screensaver_type") == "cover" and may_ignore_book_cover) end @@ -47,6 +49,7 @@ return { genMenuItem(_("Show reading progress on sleep screen"), "screensaver_type", "readingprogress", isReaderProgressEnabled), genMenuItem(_("Show book status on sleep screen"), "screensaver_type", "bookstatus", hasLastFile), genMenuItem(_("Leave screen as-is"), "screensaver_type", "disable", nil, true), + -- separator { text = _("Ignore book cover"), help_text = _("Choose when to ignore showing book covers on the sleep screen."), @@ -154,17 +157,13 @@ return { return G_reader_settings:readSetting("screensaver_type") == "document_cover" end, keep_menu_open = true, - callback = function() - Screensaver:chooseFile() - end, + callback = Screensaver.chooseFile, }, { text = _("Choose random image folder"), enabled_func = allowRandomImageFolder, keep_menu_open = true, - callback = function() - Screensaver:chooseFolder() - end, + callback = Screensaver.chooseFolder, separator = true, }, { @@ -205,6 +204,17 @@ return { Screensaver:setMessage() end, }, + { + text = _("Message position"), + enabled_func = function() + return G_reader_settings:isTrue("screensaver_show_message") + end, + sub_item_table = { + genMenuItem(_("Top"), "screensaver_message_position", "top"), + genMenuItem(_("Middle"), "screensaver_message_position", "middle"), + genMenuItem(_("Bottom"), "screensaver_message_position", "bottom"), + }, + }, { text = _("Background fill"), help_text = _("This option will only become available, if you have selected 'Leave screen as-is' as wallpaper and have 'Sleep screen message' on."), @@ -214,18 +224,7 @@ return { sub_item_table = { genMenuItem(_("Black fill"), "screensaver_msg_background", "black"), genMenuItem(_("White fill"), "screensaver_msg_background", "white"), - genMenuItem(_("No fill"), "screensaver_msg_background", "none", nil, true), - }, - }, - { - text = _("Message position"), - enabled_func = function() - return G_reader_settings:isTrue("screensaver_show_message") - end, - sub_item_table = { - genMenuItem(_("Top"), "screensaver_message_position", "top"), - genMenuItem(_("Middle"), "screensaver_message_position", "middle"), - genMenuItem(_("Bottom"), "screensaver_message_position", "bottom", nil, true), + genMenuItem(_("No fill"), "screensaver_msg_background", "none"), }, }, (Device:canReboot() and Device:canPowerOff()) and { diff --git a/frontend/ui/screensaver.lua b/frontend/ui/screensaver.lua index 7c0b2bb2c..6083e409a 100644 --- a/frontend/ui/screensaver.lua +++ b/frontend/ui/screensaver.lua @@ -4,12 +4,10 @@ local BookStatusWidget = require("ui/widget/bookstatuswidget") local BottomContainer = require("ui/widget/container/bottomcontainer") local Device = require("device") local DocumentRegistry = require("document/documentregistry") -local FileManagerBookInfo = require("apps/filemanager/filemanagerbookinfo") local Font = require("ui/font") local Geom = require("ui/geometry") local InfoMessage = require("ui/widget/infomessage") local ImageWidget = require("ui/widget/imagewidget") -local Math = require("optmath") local OverlapGroup = require("ui/widget/overlapgroup") local RenderImage = require("ui/renderimage") local ScreenSaverWidget = require("ui/widget/screensaverwidget") @@ -20,7 +18,6 @@ local TopContainer = require("ui/widget/container/topcontainer") local UIManager = require("ui/uimanager") local VerticalGroup = require("ui/widget/verticalgroup") local VerticalSpan = require("ui/widget/verticalspan") -local datetime = require("datetime") local ffiUtil = require("ffi/util") local filemanagerutil = require("apps/filemanager/filemanagerutil") local lfs = require("libs/libkoreader-lfs") @@ -120,130 +117,6 @@ local function _getRandomImage(dir) end end --- This is implemented by the Statistics plugin -function Screensaver:getAvgTimePerPage() - return -end - -function Screensaver:_calcAverageTimeForPages(pages) - local sec = _("N/A") - local average_time_per_page = self:getAvgTimePerPage() - - -- Compare average_time_per_page against itself to make sure it's not nan - if average_time_per_page and average_time_per_page == average_time_per_page and pages then - local user_duration_format = G_reader_settings:readSetting("duration_format", "classic") - sec = datetime.secondsToClockDuration(user_duration_format, pages * average_time_per_page, true) - end - return sec -end - -function Screensaver:expandSpecial(message) - -- Expand special character sequences in given message. - -- %T document title - -- %A document authors - -- %S document series - -- %c current page (if there are hidden flows, current page in current flow) - -- %t total pages (if there are hidden flows, total pages in current flow) - -- %p percentage read (if there are hidden flows, percentage read of current flow) - -- %h time left in chapter - -- %H time left in document (if there are hidden flows, time left in current flow) - -- %b battery level - -- %B battery symbol - - local lastfile = G_reader_settings:readSetting("lastfile") - if lastfile == nil then return end - - local totalpages = 0 - local percent = 0 - local currentpage = 0 - local title = _("N/A") - local authors = _("N/A") - local series = _("N/A") - local time_left_chapter = _("N/A") - local time_left_document = _("N/A") - local batt_lvl = _("N/A") - local batt_symbol = _("N/A") - local props - - local ReaderUI = require("apps/reader/readerui") - local ui = ReaderUI.instance - if ui and ui.document then - -- If we have a ReaderUI instance, use it. - local doc = ui.document - if doc:hasHiddenFlows() then - local currentpageAll = ui.view.state.page or currentpage - currentpage = doc:getPageNumberInFlow(ui.view.state.page or currentpageAll) - totalpages = doc:getTotalPagesInFlow(doc:getPageFlow(currentpageAll)) - time_left_chapter = self:_calcAverageTimeForPages(ui.toc:getChapterPagesLeft(currentpageAll) or (totalpages - currentpage)) - time_left_document = self:_calcAverageTimeForPages(totalpages - currentpage) - else - currentpage = ui.view.state.page or currentpage - totalpages = doc:getPageCount() or totalpages - time_left_chapter = self:_calcAverageTimeForPages(ui.toc:getChapterPagesLeft(currentpage) or doc:getTotalPagesLeft(currentpage)) - time_left_document = self:_calcAverageTimeForPages(doc:getTotalPagesLeft(currentpage)) - end - if currentpage == 1 then - percent = 0 - elseif currentpage == totalpages then - percent = 100 - else - percent = Math.round(Math.clamp(((currentpage * 100) / totalpages), 1, 99)) - end - props = ui.doc_props - elseif BookList.hasBookBeenOpened(lastfile) then - -- If there's no ReaderUI instance, but the file has sidecar data, use that - local doc_settings = BookList.getDocSettings(lastfile) - totalpages = doc_settings:readSetting("doc_pages") or totalpages - percent = doc_settings:readSetting("percent_finished") or percent - currentpage = Math.round(percent * totalpages) - if currentpage == 1 then - percent = 0 - elseif currentpage == totalpages then - percent = 100 - else - percent = Math.round(Math.clamp(percent * 100, 1, 99)) - end - props = FileManagerBookInfo.extendProps(doc_settings:readSetting("doc_props"), lastfile) - -- Unable to set time_left_chapter and time_left_document without ReaderUI, so leave N/A - end - if props then - title = props.display_title - if props.authors then - authors = props.authors - end - if props.series then - series = props.series - if props.series_index then - series = series .. " #" .. props.series_index - end - end - end - if Device:hasBattery() then - local powerd = Device:getPowerDevice() - if Device:hasAuxBattery() and powerd:isAuxBatteryConnected() then - batt_lvl = powerd:getCapacity() + powerd:getAuxCapacity() - batt_symbol = powerd:getBatterySymbol(powerd:isAuxCharged(), powerd:isAuxCharging(), batt_lvl / 2) - else - batt_lvl = powerd:getCapacity() - batt_symbol = powerd:getBatterySymbol(powerd:isCharged(), powerd:isCharging(), batt_lvl) - end - end - - local replace = { - ["%T"] = title, - ["%A"] = authors, - ["%S"] = series, - ["%c"] = currentpage, - ["%t"] = totalpages, - ["%p"] = percent, - ["%h"] = time_left_chapter, - ["%H"] = time_left_document, - ["%b"] = batt_lvl, - ["%B"] = batt_symbol, - } - return message:gsub("(%%%a)", replace) -end - local function addOverlayMessage(widget, widget_height, text) local FrameContainer = require("ui/widget/container/framecontainer") local RightContainer = require("ui/widget/container/rightcontainer") @@ -299,7 +172,7 @@ local function addOverlayMessage(widget, widget_height, text) return widget end -function Screensaver:chooseFolder() +function Screensaver.chooseFolder() local title_header = _("Current random image folder:") local current_path = G_reader_settings:readSetting("screensaver_dir") local caller_callback = function(path) @@ -308,7 +181,7 @@ function Screensaver:chooseFolder() filemanagerutil.showChooseDialog(title_header, caller_callback, current_path) end -function Screensaver:chooseFile() +function Screensaver.chooseFile() local title_header, current_path, file_filter, caller_callback title_header = _("Current image or document cover:") current_path = G_reader_settings:readSetting("screensaver_document_cover") @@ -321,46 +194,23 @@ function Screensaver:chooseFile() filemanagerutil.showChooseDialog(title_header, caller_callback, current_path, nil, file_filter) end -function Screensaver:isExcluded() - local ReaderUI = require("apps/reader/readerui") - local ui = ReaderUI.instance - if ui and ui.doc_settings then - local doc_settings = ui.doc_settings - return doc_settings:isTrue("exclude_screensaver") +function Screensaver.isExcluded(ui) + if ui.document then + return ui.doc_settings:isTrue("exclude_screensaver") else - if G_reader_settings:hasNot("lastfile") then - return false - end - - local lastfile = G_reader_settings:readSetting("lastfile") - if BookList.hasBookBeenOpened(lastfile) then - return BookList.getDocSettings(lastfile):isTrue("exclude_screensaver") - else - -- No DocSetting, not excluded - return false - end + local lastfile = G_reader_settings:readSetting("lastfile") or false + return lastfile and BookList.hasBookBeenOpened(lastfile) + and BookList.getDocSettings(lastfile):isTrue("exclude_screensaver") end end function Screensaver:setMessage() + local FileManagerBookInfo = require("apps/filemanager/filemanagerbookinfo") local InputDialog = require("ui/widget/inputdialog") - local screensaver_message = G_reader_settings:readSetting("screensaver_message") - or self.default_screensaver_message - local info_text = _([[ -%T title -%A author(s) -%S series -%c current page number -%t total page number -%p percentage read -%h time left in chapter -%H time left in document -%b battery level -%B battery symbol]]) local input_dialog input_dialog = InputDialog:new{ title = _("Sleep screen message"), - input = screensaver_message, + input = G_reader_settings:readSetting("screensaver_message") or self.default_screensaver_message, allow_newline = true, buttons = { { @@ -373,12 +223,7 @@ function Screensaver:setMessage() }, { text = _("Info"), - callback = function() - UIManager:show(InfoMessage:new{ - text = info_text, - monospace_font = true, - }) - end, + callback = FileManagerBookInfo.expandString, }, { text = _("Set message"), @@ -465,8 +310,7 @@ function Screensaver:setup(event, event_message) end -- Check lastfile and setup the requested mode's resources, or a fallback mode if the required resources are unavailable. - local ReaderUI = require("apps/reader/readerui") - local ui = ReaderUI.instance + self.ui = require("apps/reader/readerui").instance or require("apps/filemanager/filemanager").instance local lastfile = G_reader_settings:readSetting("lastfile") local is_document_cover = false if self.screensaver_type == "document_cover" then @@ -480,16 +324,10 @@ function Screensaver:setup(event, event_message) if not is_document_cover and lastfile then local exclude_finished_book local exclude_on_hold_book - local exclude_book_in_fm = not ui and G_reader_settings:isTrue("screensaver_hide_cover_in_filemanager") + local exclude_book_in_fm = not self.ui.document and G_reader_settings:isTrue("screensaver_hide_cover_in_filemanager") if BookList.hasBookBeenOpened(lastfile) then - local doc_settings - if ui and ui.doc_settings then - doc_settings = ui.doc_settings - else - doc_settings = BookList.getDocSettings(lastfile) - end + local doc_settings = self.ui.doc_settings or BookList.getDocSettings(lastfile) excluded = doc_settings:isTrue("exclude_screensaver") - local book_summary = doc_settings:readSetting("summary") local book_finished = book_summary and book_summary.status == "complete" local book_on_hold = book_summary and book_summary.status == "abandoned" @@ -510,7 +348,7 @@ function Screensaver:setup(event, event_message) if DocumentRegistry:isImageFile(lastfile) then self.image_file = lastfile else - self.image = FileManagerBookInfo:getCoverImage(ui and ui.document, lastfile) + self.image = self.ui.bookinfo:getCoverImage(self.ui.document, lastfile) if self.image == nil then self.screensaver_type = "random_image" end @@ -524,18 +362,15 @@ function Screensaver:setup(event, event_message) end end if self.screensaver_type == "bookstatus" then - if not (ui and ui.doc_settings and ui.doc_settings:nilOrFalse("exclude_screensaver")) then + if not (self.ui.document and self.ui.doc_settings:nilOrFalse("exclude_screensaver")) then self.screensaver_type = "random_image" end end - if self.screensaver_type == "readingprogress" then - -- This is implemented by the Statistics plugin - if Screensaver.getReaderProgress == nil then - self.screensaver_type = "random_image" - end + if self.screensaver_type == "readingprogress" and self.ui.statistics == nil then + self.screensaver_type = "random_image" end if self.screensaver_type == "disable" then - if ui and ui.doc_settings and ui.doc_settings:isTrue("exclude_screensaver") then + if self.ui.document and self.ui.doc_settings:isTrue("exclude_screensaver") then self.screensaver_type = "random_image" end end @@ -554,6 +389,8 @@ function Screensaver:setup(event, event_message) end function Screensaver:show() + -- self.ui is set in Screensaver:setup() + -- Notify Device methods that we're in screen saver mode, so they know whether to suspend or resume on Power events. Device.screen_saver_mode = true @@ -565,6 +402,7 @@ function Screensaver:show() return end + local screen_w, screen_h = Screen:getWidth(), Screen:getHeight() local rotation_mode = Screen:getRotationMode() -- We mostly always suspend in Portrait/Inverted Portrait mode... @@ -588,7 +426,7 @@ function Screensaver:show() if self:withBackground() then Screen:clear() end - Screen:refreshFull(0, 0, Screen:getWidth(), Screen:getHeight()) + Screen:refreshFull(0, 0, screen_w, screen_h) -- On Kobo, on sunxi SoCs with a recent kernel, wait a tiny bit more to avoid weird refresh glitches... if Device:isKobo() and Device:isSunxi() then @@ -604,8 +442,8 @@ function Screensaver:show() local widget = nil if self.screensaver_type == "cover" or self.screensaver_type == "random_image" then local widget_settings = { - width = Screen:getWidth(), - height = Screen:getHeight(), + width = screen_w, + height = screen_h, scale_factor = G_reader_settings:isFalse("screensaver_stretch_images") and 0 or nil, stretch_limit_percentage = G_reader_settings:readSetting("screensaver_stretch_limit_percentage"), } @@ -621,7 +459,7 @@ function Screensaver:show() widget_settings.image = RenderImage:renderImageFile(self.image_file, false, nil, nil) end if not widget_settings.image then - widget_settings.image = RenderImage:renderCheckerboard(Screen:getWidth(), Screen:getHeight(), Screen.bb:getType()) + widget_settings.image = RenderImage:renderCheckerboard(screen_w, screen_h, Screen.bb:getType()) end widget_settings.image_disposable = true else @@ -639,13 +477,12 @@ function Screensaver:show() end widget = ImageWidget:new(widget_settings) elseif self.screensaver_type == "bookstatus" then - local ReaderUI = require("apps/reader/readerui") widget = BookStatusWidget:new{ - ui = ReaderUI.instance, + ui = self.ui, readonly = true, } elseif self.screensaver_type == "readingprogress" then - widget = Screensaver.getReaderProgress() + widget = self.ui.statistics:onShowReaderProgress(true) -- get widget end -- Assume that we'll be covering the full-screen by default (either because of a widget, or a background fill). @@ -678,10 +515,8 @@ function Screensaver:show() end end - -- NOTE: Only attempt to expand if there are special characters in the message. - if screensaver_message:find("%%") then - screensaver_message = self:expandSpecial(screensaver_message) or self.event_message or self.default_screensaver_message - end + screensaver_message = self.ui.bookinfo:expandString(screensaver_message) + or self.event_message or self.default_screensaver_message local message_pos if G_reader_settings:has(self.prefix .. "screensaver_message_position") then @@ -712,7 +547,6 @@ function Screensaver:show() container = TopContainer end - local screen_w, screen_h = Screen:getWidth(), Screen:getHeight() message_widget = container:new{ dimen = Geom:new{ w = screen_w, @@ -738,8 +572,8 @@ function Screensaver:show() -- Show message_widget on top of previously created widget widget = OverlapGroup:new{ dimen = { - w = Screen:getWidth(), - h = Screen:getHeight(), + w = screen_w, + h = screen_h, }, widget, message_widget, diff --git a/frontend/ui/widget/bookstatuswidget.lua b/frontend/ui/widget/bookstatuswidget.lua index 8daf09981..313bc3f11 100644 --- a/frontend/ui/widget/bookstatuswidget.lua +++ b/frontend/ui/widget/bookstatuswidget.lua @@ -3,7 +3,6 @@ local BookList = require("ui/widget/booklist") local Button = require("ui/widget/button") local CenterContainer = require("ui/widget/container/centercontainer") local Device = require("device") -local FileManagerBookInfo = require("apps/filemanager/filemanagerbookinfo") local Font = require("ui/font") local FocusManager = require("ui/widget/focusmanager") local FrameContainer = require("ui/widget/container/framecontainer") @@ -32,7 +31,7 @@ local _ = require("gettext") local Screen = Device.screen local T = require("ffi/util").template -local stats_book = {} +local stats_book --[[ -- Stored in the sidecar metadata, in a dedicated table: @@ -53,7 +52,7 @@ function BookStatusWidget:init() self.layout = {} self.summary = self.ui.doc_settings:readSetting("summary") self.total_pages = self.ui.document:getPageCount() - stats_book = self:getStats() + stats_book = self.ui.statistics and self.ui.statistics:getStatsBookStatus() or {} self.small_font_face = Font:getFace("smallffont") self.medium_font_face = Font:getFace("ffont") @@ -101,10 +100,6 @@ function BookStatusWidget:init() self.dithered = true end -function BookStatusWidget:getStats() - return {} -end - function BookStatusWidget:getStatDays() if stats_book.days then return tostring(stats_book.days) @@ -339,7 +334,7 @@ function BookStatusWidget:genBookInfoGroup() HorizontalSpan:new{ width = split_span_width } } -- thumbnail - local thumbnail = FileManagerBookInfo:getCoverImage(self.ui.document) + local thumbnail = self.ui.bookinfo:getCoverImage(self.ui.document) if thumbnail then -- Much like BookInfoManager, honor AR here local cbb_w, cbb_h = thumbnail:getWidth(), thumbnail:getHeight() diff --git a/plugins/statistics.koplugin/main.lua b/plugins/statistics.koplugin/main.lua index 1fbaa1313..99174561b 100644 --- a/plugins/statistics.koplugin/main.lua +++ b/plugins/statistics.koplugin/main.lua @@ -1,31 +1,28 @@ local BD = require("ui/bidi") -local BookStatusWidget = require("ui/widget/bookstatuswidget") local ButtonDialog = require("ui/widget/buttondialog") local ConfirmBox = require("ui/widget/confirmbox") local DataStorage = require("datastorage") local Device = require("device") local Dispatcher = require("dispatcher") local DocSettings = require("docsettings") -local FFIUtil = require("ffi/util") local InfoMessage = require("ui/widget/infomessage") local KeyValuePage = require("ui/widget/keyvaluepage") local Math = require("optmath") -local ReaderFooter = require("apps/reader/modules/readerfooter") local ReaderProgress = require("readerprogress") local ReadHistory = require("readhistory") -local Screensaver = require("ui/screensaver") local SQ3 = require("lua-ljsqlite3/init") local SyncService = require("frontend/apps/cloudstorage/syncservice") local UIManager = require("ui/uimanager") local Widget = require("ui/widget/widget") local datetime = require("datetime") +local ffiUtil = require("ffi/util") local lfs = require("libs/libkoreader-lfs") local logger = require("logger") local util = require("util") local _ = require("gettext") local C_ = _.pgettext local N_ = _.ngettext -local T = FFIUtil.template +local T = ffiUtil.template local statistics_dir = DataStorage:getDataDir() .. "/statistics/" local db_location = DataStorage:getSettingsDir() .. "/statistics.sqlite3" @@ -146,37 +143,6 @@ function ReaderStatistics:init() self.ui.menu:registerToMainMenu(self) self:onDispatcherRegisterActions() self:checkInitDatabase() - BookStatusWidget.getStats = function() - return self:getStatsBookStatus(self.id_curr_book, self.settings.is_enabled) - end - ReaderFooter.getAvgTimePerPage = function() - if self.settings.is_enabled then - return self.avg_time - end - end - Screensaver.getAvgTimePerPage = function() - if self.settings.is_enabled then - return self.avg_time - end - end - Screensaver.getReaderProgress = function() - self:insertDB() - local current_duration, current_pages = self:getCurrentBookStats() - local today_duration, today_pages = self:getTodayBookStats() - local dates_stats = self:getReadingProgressStats(7) - local readingprogress - if dates_stats then - readingprogress = ReaderProgress:new{ - dates = dates_stats, - current_duration = current_duration, - current_pages = current_pages, - today_duration = today_duration, - today_pages = today_pages, - readonly = true, - } - end - return readingprogress - end end function ReaderStatistics:initData() @@ -293,11 +259,8 @@ function ReaderStatistics:resetVolatileStats(now_ts) end end -function ReaderStatistics:getStatsBookStatus(id_curr_book, stat_enable) - if not stat_enable or id_curr_book == nil then - return {} - end - +function ReaderStatistics:getStatsBookStatus() + if not (self.settings.is_enabled and self.id_curr_book) then return end self:insertDB() local conn = SQ3.open(db_location) local sql_stmt = [[ @@ -309,20 +272,13 @@ function ReaderStatistics:getStatsBookStatus(id_curr_book, stat_enable) GROUP BY dates ); ]] - local total_days = conn:rowexec(string.format(sql_stmt, id_curr_book)) - local total_read_pages, total_time_book = conn:rowexec(string.format(STATISTICS_SQL_BOOK_TOTALS_QUERY, id_curr_book)) + local total_days = conn:rowexec(string.format(sql_stmt, self.id_curr_book)) + local total_read_pages, total_time_book = conn:rowexec(string.format(STATISTICS_SQL_BOOK_TOTALS_QUERY, self.id_curr_book)) conn:close() - - if total_time_book == nil then - total_time_book = 0 - end - if total_read_pages == nil then - total_read_pages = 0 - end - return { + return { days = tonumber(total_days), - time = tonumber(total_time_book), - pages = tonumber(total_read_pages), + time = tonumber(total_time_book) or 0, + pages = tonumber(total_read_pages) or 0, } end @@ -365,7 +321,7 @@ Do you want to create an empty database? if lfs.attributes(bkp_db_location, "mode") == "file" then logger.warn("ReaderStatistics: A DB backup from schema", db_version, "to schema", DB_SCHEMA_VERSION, "already exists!") else - FFIUtil.copyFile(db_location, bkp_db_location) + ffiUtil.copyFile(db_location, bkp_db_location) logger.info("ReaderStatistics: Old DB backed up as", bkp_db_location) end @@ -403,7 +359,7 @@ Do you want to create an empty database? if lfs.attributes(bkp_db_location, "mode") == "file" then logger.warn("ReaderStatistics: A DB backup from schema", db_version, "to schema", DB_SCHEMA_VERSION, "already exists!") else - FFIUtil.copyFile(db_location, bkp_db_location) + ffiUtil.copyFile(db_location, bkp_db_location) logger.info("ReaderStatistics: Old DB backed up as", bkp_db_location) end @@ -1366,31 +1322,15 @@ Time is in hours and minutes.]]), text = _("Reading progress"), keep_menu_open = true, callback = function() - self:insertDB() - local current_duration, current_pages = self:getCurrentBookStats() - local today_duration, today_pages = self:getTodayBookStats() - local dates_stats = self:getReadingProgressStats(7) - if dates_stats then - UIManager:show(ReaderProgress:new{ - dates = dates_stats, - current_duration = current_duration, - current_pages = current_pages, - today_duration = today_duration, - today_pages = today_pages, - }) - else - UIManager:show(InfoMessage:new{ - text = _("Reading progress is not available.\nThere is no data for the last week."), - }) - end - end + self:onShowReaderProgress() + end, }, { text = _("Time range"), keep_menu_open = true, callback = function() self:onShowTimeRange() - end + end, }, { text = _("Calendar view"), @@ -2767,7 +2707,7 @@ end function ReaderStatistics:importFromFile(base_path, item) item = util.trim(item) if item ~= ".stat" then - local statistic_file = FFIUtil.joinPath(base_path, item) + local statistic_file = ffiUtil.joinPath(base_path, item) if lfs.attributes(statistic_file, "mode") == "directory" then return end @@ -3056,23 +2996,29 @@ function ReaderStatistics:getReadingDurationBySecond(ts) return per_book end -function ReaderStatistics:onShowReaderProgress() +function ReaderStatistics:onShowReaderProgress(get_widget) self:insertDB() local current_duration, current_pages = self:getCurrentBookStats() local today_duration, today_pages = self:getTodayBookStats() local dates_stats = self:getReadingProgressStats(7) - local readingprogress - if dates_stats then - readingprogress = ReaderProgress:new{ - dates = dates_stats, - current_duration = current_duration, - current_pages = current_pages, - today_duration = today_duration, - today_pages = today_pages, - --readonly = true, - } + local readingprogress = dates_stats and ReaderProgress:new{ + dates = dates_stats, + current_duration = current_duration, + current_pages = current_pages, + today_duration = today_duration, + today_pages = today_pages, + readonly = get_widget, -- true for Screensaver + } + if get_widget then + return readingprogress + end + if readingprogress then + UIManager:show(readingprogress) + else + UIManager:show(InfoMessage:new{ + text = _("Reading progress is not available.\nThere is no data for the last week."), + }) end - UIManager:show(readingprogress) end function ReaderStatistics:onShowBookStats() @@ -3123,6 +3069,13 @@ function ReaderStatistics:getCurrentBookReadPages() return read_pages end +function ReaderStatistics:getTimeForPages(pages) + if self.settings.is_enabled and self.avg_time and self.avg_time == self.avg_time then -- not nan + local duration_format = G_reader_settings:readSetting("duration_format", "classic") + return datetime.secondsToClockDuration(duration_format, pages * self.avg_time, true) + end +end + function ReaderStatistics:canSync() return self.settings.sync_server ~= nil and self.settings.is_enabled end