You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
koreader/plugins/autoturn.koplugin/main.lua

215 lines
7.3 KiB
Lua

local Device = require("device")
local Event = require("ui/event")
local PluginShare = require("pluginshare")
local UIManager = require("ui/uimanager")
local WidgetContainer = require("ui/widget/container/widgetcontainer")
local logger = require("logger")
local time = require("ui/time")
local util = require("util")
local _ = require("gettext")
local T = require("ffi/util").template
local AutoTurn = WidgetContainer:new{
name = "autoturn",
is_doc_only = true,
The great Input/GestureDetector/TimeVal spring cleanup (a.k.a., a saner main loop) (#7415) * ReaderDictionary: Port delay computations to TimeVal * ReaderHighlight: Port delay computations to TimeVal * ReaderView: Port delay computations to TimeVal * Android: Reset gesture detection state on APP_CMD_TERM_WINDOW. This prevents potentially being stuck in bogus gesture states when switching apps. * GestureDetector: * Port delay computations to TimeVal * Fixed delay computations to handle time warps (large and negative deltas). * Simplified timed callback handling to invalidate timers much earlier, preventing accumulating useless timers that no longer have any chance of ever detecting a gesture. * Fixed state clearing to handle the actual effective slots, instead of hard-coding slot 0 & slot 1. * Simplified timed callback handling in general, and added support for a timerfd backend for better performance and accuracy. * The improved timed callback handling allows us to detect and honor (as much as possible) the three possible clock sources usable by Linux evdev events. The only case where synthetic timestamps are used (and that only to handle timed callbacks) is limited to non-timerfd platforms where input events use a clock source that is *NOT* MONOTONIC. AFAICT, that's pretty much... PocketBook, and that's it? * Input: * Use the <linux/input.h> FFI module instead of re-declaring every constant * Fixed (verbose) debug logging of input events to actually translate said constants properly. * Completely reset gesture detection state on suspend. This should prevent bogus gesture detection on resume. * Refactored the waitEvent loop to make it easier to comprehend (hopefully) and much more efficient. Of specific note, it no longer does a crazy select spam every 100µs, instead computing and relying on sane timeouts, as afforded by switching the UI event/input loop to the MONOTONIC time base, and the refactored timed callbacks in GestureDetector. * reMarkable: Stopped enforcing synthetic timestamps on input events, as it should no longer be necessary. * TimeVal: * Refactored and simplified, especially as far as metamethods are concerned (based on <bsd/sys/time.h>). * Added a host of new methods to query the various POSIX clock sources, and made :now default to MONOTONIC. * Removed the debug guard in __sub, as time going backwards can be a perfectly normal occurrence. * New methods: * Clock sources: :realtime, :monotonic, :monotonic_coarse, :realtime_coarse, :boottime * Utility: :tonumber, :tousecs, :tomsecs, :fromnumber, :isPositive, :isZero * UIManager: * Ported event loop & scheduling to TimeVal, and switched to the MONOTONIC time base. This ensures reliable and consistent scheduling, as time is ensured never to go backwards. * Added a :getTime() method, that returns a cached TimeVal:now(), updated at the top of every UI frame. It's used throughout the codebase to cadge a syscall in circumstances where we are guaranteed that a syscall would return a mostly identical value, because very few time has passed. The only code left that does live syscalls does it because it's actually necessary for accuracy, and the only code left that does that in a REALTIME time base is code that *actually* deals with calendar time (e.g., Statistics). * DictQuickLookup: Port delay computations to TimeVal * FootNoteWidget: Port delay computations to TimeVal * HTMLBoxWidget: Port delay computations to TimeVal * Notification: Port delay computations to TimeVal * TextBoxWidget: Port delay computations to TimeVal * AutoSuspend: Port to TimeVal * AutoTurn: * Fix it so that settings are actually honored. * Port to TimeVal * BackgroundRunner: Port to TimeVal * Calibre: Port benchmarking code to TimeVal * BookInfoManager: Removed unnecessary yield in the metadata extraction subprocess now that subprocesses get scheduled properly. * All in all, these changes reduced the CPU cost of a single tap by a factor of ten (!), and got rid of an insane amount of weird poll/wakeup cycles that must have been hell on CPU schedulers and batteries..
3 years ago
autoturn_sec = 0,
autoturn_distance = 1,
enabled = false,
last_action_time = 0,
task = nil,
}
function AutoTurn:_enabled()
return self.enabled and self.autoturn_sec > 0
end
function AutoTurn:_schedule()
if not self:_enabled() then
logger.dbg("AutoTurn:_schedule is disabled")
return
end
local delay = self.last_action_time + time.s(self.autoturn_sec) - UIManager:getTime()
if delay <= 0 then
if UIManager:getTopWidget() == "ReaderUI" then
logger.dbg("AutoTurn: go to next page")
self.ui:handleEvent(Event:new("GotoViewRel", self.autoturn_distance))
self.last_action_time = UIManager:getTime()
end
logger.dbg("AutoTurn: schedule in", self.autoturn_sec)
UIManager:scheduleIn(self.autoturn_sec, self.task)
self.scheduled = true
else
local delay_s = time.to_number(delay)
logger.dbg("AutoTurn: schedule in", delay_s, "s")
UIManager:scheduleIn(delay_s, self.task)
self.scheduled = true
end
end
function AutoTurn:_unschedule()
PluginShare.pause_auto_suspend = false
if self.scheduled then
logger.dbg("AutoTurn: unschedule")
UIManager:unschedule(self.task)
self.scheduled = false
end
end
function AutoTurn:_start()
if self:_enabled() then
local now = UIManager:getTime()
logger.dbg("AutoTurn: start at", time.format_time(now))
PluginShare.pause_auto_suspend = true
self.last_action_time = now
self:_schedule()
local text
if self.autoturn_distance == 1 then
local time_string = util.secondsToClockDuration("modern", self.autoturn_sec, false, true, true, true)
text = T(_("Autoturn is now active and will automatically turn the page every %1."), time_string)
else
text = T(_("Autoturn is now active and will automatically scroll %1 % of the page every %2 seconds."),
self.autoturn_distance * 100,
self.autoturn_sec)
end
local InfoMessage = require("ui/widget/infomessage")
UIManager:show(InfoMessage:new{
text = text,
timeout = 3,
})
end
end
function AutoTurn:init()
UIManager.event_hook:registerWidget("InputEvent", self)
self.autoturn_sec = G_reader_settings:readSetting("autoturn_timeout_seconds", 0)
self.autoturn_distance = G_reader_settings:readSetting("autoturn_distance", 1)
The great Input/GestureDetector/TimeVal spring cleanup (a.k.a., a saner main loop) (#7415) * ReaderDictionary: Port delay computations to TimeVal * ReaderHighlight: Port delay computations to TimeVal * ReaderView: Port delay computations to TimeVal * Android: Reset gesture detection state on APP_CMD_TERM_WINDOW. This prevents potentially being stuck in bogus gesture states when switching apps. * GestureDetector: * Port delay computations to TimeVal * Fixed delay computations to handle time warps (large and negative deltas). * Simplified timed callback handling to invalidate timers much earlier, preventing accumulating useless timers that no longer have any chance of ever detecting a gesture. * Fixed state clearing to handle the actual effective slots, instead of hard-coding slot 0 & slot 1. * Simplified timed callback handling in general, and added support for a timerfd backend for better performance and accuracy. * The improved timed callback handling allows us to detect and honor (as much as possible) the three possible clock sources usable by Linux evdev events. The only case where synthetic timestamps are used (and that only to handle timed callbacks) is limited to non-timerfd platforms where input events use a clock source that is *NOT* MONOTONIC. AFAICT, that's pretty much... PocketBook, and that's it? * Input: * Use the <linux/input.h> FFI module instead of re-declaring every constant * Fixed (verbose) debug logging of input events to actually translate said constants properly. * Completely reset gesture detection state on suspend. This should prevent bogus gesture detection on resume. * Refactored the waitEvent loop to make it easier to comprehend (hopefully) and much more efficient. Of specific note, it no longer does a crazy select spam every 100µs, instead computing and relying on sane timeouts, as afforded by switching the UI event/input loop to the MONOTONIC time base, and the refactored timed callbacks in GestureDetector. * reMarkable: Stopped enforcing synthetic timestamps on input events, as it should no longer be necessary. * TimeVal: * Refactored and simplified, especially as far as metamethods are concerned (based on <bsd/sys/time.h>). * Added a host of new methods to query the various POSIX clock sources, and made :now default to MONOTONIC. * Removed the debug guard in __sub, as time going backwards can be a perfectly normal occurrence. * New methods: * Clock sources: :realtime, :monotonic, :monotonic_coarse, :realtime_coarse, :boottime * Utility: :tonumber, :tousecs, :tomsecs, :fromnumber, :isPositive, :isZero * UIManager: * Ported event loop & scheduling to TimeVal, and switched to the MONOTONIC time base. This ensures reliable and consistent scheduling, as time is ensured never to go backwards. * Added a :getTime() method, that returns a cached TimeVal:now(), updated at the top of every UI frame. It's used throughout the codebase to cadge a syscall in circumstances where we are guaranteed that a syscall would return a mostly identical value, because very few time has passed. The only code left that does live syscalls does it because it's actually necessary for accuracy, and the only code left that does that in a REALTIME time base is code that *actually* deals with calendar time (e.g., Statistics). * DictQuickLookup: Port delay computations to TimeVal * FootNoteWidget: Port delay computations to TimeVal * HTMLBoxWidget: Port delay computations to TimeVal * Notification: Port delay computations to TimeVal * TextBoxWidget: Port delay computations to TimeVal * AutoSuspend: Port to TimeVal * AutoTurn: * Fix it so that settings are actually honored. * Port to TimeVal * BackgroundRunner: Port to TimeVal * Calibre: Port benchmarking code to TimeVal * BookInfoManager: Removed unnecessary yield in the metadata extraction subprocess now that subprocesses get scheduled properly. * All in all, these changes reduced the CPU cost of a single tap by a factor of ten (!), and got rid of an insane amount of weird poll/wakeup cycles that must have been hell on CPU schedulers and batteries..
3 years ago
self.enabled = G_reader_settings:isTrue("autoturn_enabled")
self.ui.menu:registerToMainMenu(self)
self.task = function()
self:_schedule()
end
self:_start()
end
function AutoTurn:onCloseWidget()
logger.dbg("AutoTurn: onCloseWidget")
self:_unschedule()
self.task = nil
end
function AutoTurn:onCloseDocument()
logger.dbg("AutoTurn: onCloseDocument")
self:_unschedule()
end
function AutoTurn:onInputEvent()
logger.dbg("AutoTurn: onInputEvent")
self.last_action_time = UIManager:getTime()
end
function AutoTurn:onEnterStandby()
self:_unschedule()
end
-- We do not want autoturn to turn pages during the suspend process.
-- Unschedule it and restart after resume.
function AutoTurn:onSuspend()
logger.dbg("AutoTurn: onSuspend")
self:_unschedule()
end
function AutoTurn:_onLeaveStandby()
self.last_action_time = self.last_action_time - Device.last_standby_time
-- We messed with last_action_time, so a complete reschedule has to be done.
if self:_enabled() then
self:_unschedule()
self:_schedule()
end
end
function AutoTurn:_onResume()
logger.dbg("AutoTurn: onResume")
self:_start()
end
function AutoTurn:addToMainMenu(menu_items)
menu_items.autoturn = {
sorting_hint = "navi",
text_func = function()
local time_string = util.secondsToClockDuration("modern", self.autoturn_sec, false, true, true, true)
return self:_enabled() and T(_("Autoturn: %1"), time_string) or _("Autoturn")
end,
checked_func = function() return self:_enabled() end,
callback = function(menu)
local DateTimeWidget = require("ui/widget/datetimewidget")
local autoturn_seconds = G_reader_settings:readSetting("autoturn_timeout_seconds", 30)
local autoturn_minutes = math.floor(autoturn_seconds / 60)
autoturn_seconds = autoturn_seconds % 60
local autoturn_spin = DateTimeWidget:new {
title_text = _("Autoturn time"),
info_text = _("Enter time in minutes and seconds."),
min = autoturn_minutes,
min_max = 60 * 24, -- maximum one day
min_default = 0,
sec = autoturn_seconds,
sec_default = 30,
keep_shown_on_apply = true,
ok_text = _("Set timeout"),
cancel_text = _("Disable"),
cancel_callback = function()
self.enabled = false
G_reader_settings:makeFalse("autoturn_enabled")
self:_unschedule()
menu:updateItems()
self.onResume = nil
self.onLeaveStandby = nil
end,
ok_always_enabled = true,
callback = function(t)
self.autoturn_sec = t.min * 60 + t.sec
G_reader_settings:saveSetting("autoturn_timeout_seconds", self.autoturn_sec)
self.enabled = true
G_reader_settings:makeTrue("autoturn_enabled")
self:_unschedule()
self:_start()
menu:updateItems()
self.onResume = self._onResume
self.onLeaveStandby = self._onLeaveStandby
end,
}
UIManager:show(autoturn_spin)
end,
hold_callback = function(menu)
local SpinWidget = require("ui/widget/spinwidget")
local curr_items = G_reader_settings:readSetting("autoturn_distance") or 1
local autoturn_spin = SpinWidget:new {
value = curr_items,
value_min = -20,
value_max = 20,
precision = "%.2f",
value_step = .1,
value_hold_step = .5,
ok_text = _("Set distance"),
title_text = _("Scrolling distance"),
callback = function(autoturn_spin)
self.autoturn_distance = autoturn_spin.value
G_reader_settings:saveSetting("autoturn_distance", autoturn_spin.value)
if self.enabled then
self:_unschedule()
self:_start()
end
menu:updateItems()
end,
}
UIManager:show(autoturn_spin)
end,
}
end
return AutoTurn