### Usage Example: Measuring Code Execution Time Source: https://koreader.rocks/doc/modules/time A practical example demonstrating how to use the `time` module to measure the execution duration of a block of code. It records the start time, performs an operation, and then calculates and prints the elapsed time in milliseconds. ```lua local time = require("ui/time") local start_time = time.now() -- Simulate some work for i = 1, 1000000 do -- Do some computation local x = i * 2 end local duration = time.now() - start_time print(string.format("The loop took %.3fms", time.to_ms(duration))) ``` -------------------------------- ### Touch Event Parsing Example (Linux Kernel MT Protocol B) Source: https://koreader.rocks/doc/modules/device.input Illustrates the format of touch events received from the Linux kernel using the MT protocol B. This example shows how tracking IDs, coordinates, and synchronization reports are structured. ```text MT_TRACK_ID: 0 MT_X: 222 MT_Y: 207 SYN REPORT MT_TRACK_ID: -1 SYN REPORT ``` -------------------------------- ### Hello World Debug Plugin Source: https://koreader.rocks/doc/index A simple debug plugin designed to test the plugin functionality within KOReader. It serves as a basic example for plugin development. ```lua -- koplugin.HelloWorld: This is a debug plugin to test Plugin functionality. ``` -------------------------------- ### Dependency Graph Construction with DepGraph Source: https://koreader.rocks/doc/modules/depgraph Demonstrates how to use the DepGraph module to create and manage dependency graphs. It shows adding nodes with their dependencies and serializing the graph to get a valid execution order. Duplicates are automatically handled. ```lua local dg = DepGraph:new{} dg:addNode('a1', {'a2', 'b1'}) dg:addNode('b1', {'a2', 'c1'}) dg:addNode('c1') -- The return value of dg:serialize() will be: -- {'a2', 'c1', 'b1', 'a1'} ``` -------------------------------- ### NickelConf Frontlight Level API Source: https://koreader.rocks/doc/modules/device.kobo.nickel_conf Provides functions to get and set the frontlight level on Kobo devices. ```APIDOC ## NickelConf.frontLightLevel.get() ### Description Get the current frontlight level. ### Method GET ### Endpoint /device/kobo/nickel_conf ### Parameters None ### Request Example None ### Response #### Success Response (200) - **level** (integer) - The current frontlight level. #### Response Example ```json { "level": 50 } ``` ## NickelConf.frontLightLevel.set(new_intensity) ### Description Set the frontlight level. ### Method POST ### Endpoint /device/kobo/nickel_conf/frontlightlevel ### Parameters #### Query Parameters - **new_intensity** (integer) - Required - The desired frontlight level (e.g., 0-100). ### Request Example ```json { "new_intensity": 75 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success or failure of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### NickelConf Frontlight State API Source: https://koreader.rocks/doc/modules/device.kobo.nickel_conf Provides functions to get the frontlight state on Kobo devices. Note that this may be nil if the device lacks a hardware toggle. ```APIDOC ## NickelConf.frontLightState.get() ### Description Get the current frontlight state. ### Method GET ### Endpoint /device/kobo/nickel_conf ### Parameters None ### Request Example None ### Response #### Success Response (200) - **state** (integer | nil) - The current frontlight state (1 for on, 0 for off), or nil if not applicable. #### Response Example ```json { "state": 1 } ``` ## NickelConf.frontLightState.set(new_state) ### Description Set the frontlight state. ### Method POST ### Endpoint /device/kobo/nickel_conf/frontlightstate ### Parameters #### Query Parameters - **new_state** (integer) - Required - The desired frontlight state (1 for on, 0 for off). ### Request Example ```json { "new_state": 0 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success or failure of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### AlphaContainer Widget Example (Lua) Source: https://koreader.rocks/doc/modules/ui.widget.container.alphacontainer Demonstrates how to create and configure an AlphaContainer widget in Lua. This widget allows for setting an opacity level for its child widget. It requires the `AlphaContainer` and `FrameContainer` classes, along with `Blitbuffer` and `Size` constants. ```lua local alpha alpha = AlphaContainer:new{ alpha = 0.7, FrameContainer:new{ background = Blitbuffer.COLOR_WHITE, bordersize = Size.border.default, margin = 0, padding = Size.padding.default } } ``` -------------------------------- ### Logging with KOReader's logger module Source: https://koreader.rocks/doc/modules/logger Demonstrates how to use the logger module to output messages at different severity levels. It requires the 'logger' module to be required. The example shows how to log informational messages and errors. ```lua local logger = require("logger") logger.info("Something happened.") logger.err("House is on fire!") ``` -------------------------------- ### SQLite3 Database Operations with lua-ljsqlite3 in Lua Source: https://koreader.rocks/doc/topics/DataStore.md Demonstrates how to connect to an SQLite3 database, execute SQL commands, use prepared statements with binding, retrieve data, and perform aggregate functions using the lua-ljsqlite3 library. This example covers table creation, data insertion, and querying. ```lua local SQ3 = require("lua-ljsqlite3/init") local conn = SQ3.open("/path/to/database.sqlite3") -- Execute SQL commands separated by the ';' character: conn:exec([[ -- time is in unit of seconds CREATE TABLE IF NOT EXISTS page_read_time(page INTEGER, time INTEGER); CREATE TABLE IF NOT EXISTS book_property(title TEXT, author TEXT, language TEXT); ]]) -- Prepared statements are supported, with this you can bind different values -- to the same statement. Let's set the read time for the first 10 pages in the -- book to 5 seconds local stmt = conn:prepare("INSERT INTO page_read_time VALUES(?, ?)") for i=1,10 do stmt:reset():bind(i, 5):step() end -- Now we can retrieve all read time stats for the first 10 pages: local results = conn:exec("SELECT * FROM page_read_time") -- Records are by column. -- Access to results via column numbers or names: assert(results[1] == results.page) assert(results[2] == results.time) -- Nested indexing corresponds to the record(row) number, access value for 4th page: assert(results[1][4] == 4) assert(results[2][4] == 5) -- access value for 2nd page: assert(results.page[2] == 2) assert(results.time[2] == 5) -- Convenience function returns multiple values for one record: local page, time = conn:rowexec("SELECT * FROM page_read_time WHERE page==3") print(page, time) --> 3 5 -- We can also use builtin aggregate functions to do simple analytic task local total_time = conn:rowexec("SELECT SUM(time) FROM page_read_time") print(total_time) --> 50 conn:close() -- Do not forget to close stmt after you are done ``` -------------------------------- ### Initialize and Use Preset Object in a Module Source: https://koreader.rocks/doc/modules/ui.presets Demonstrates how to initialize a preset object within a module's init method, defining storage, dispatcher integration, and callback functions for building and loading presets. This setup is crucial for enabling the preset system for a specific module. ```lua local Presets = require("ui/presets") -- 1. In your module's init() method, set up a preset object: self.preset_obj = { presets = G_reader_settings:readSetting("my_module_presets", {}), -- or custom storage cycle_index = G_reader_settings:readSetting("my_module_presets_cycle_index"), -- optional, only needed if cycling through presets dispatcher_name = "load_my_module_preset", -- must match dispatcher.lua entry saveCycleIndex = function(this) -- Save cycle index to persistent storage G_reader_settings:saveSetting("my_module_presets_cycle_index", this.cycle_index) end, buildPreset = function() return self:buildPreset() end, -- Closure to build a preset from current state loadPreset = function(preset) self:loadPreset(preset) end, -- Closure to apply a preset to the module } ``` -------------------------------- ### CheckMark Widget Example (Lua) Source: https://koreader.rocks/doc/modules/ui.widget.checkmark Demonstrates how to create and display a CheckMark widget in KOReader. This widget can show a checkmark, an empty box, or nothing. It requires the 'ui/widget/CheckMark' module and can be added to a parent widget like FrameContainer. The 'checkable' property controls visibility, and 'checked' is a callback function. ```lua local CheckMark = require("ui/widget/CheckMark") local parent_widget = FrameContainer:new{} table.insert(parent_widget, CheckMark:new{ checkable = false, -- shows nothing when false, defaults to true checked = function() end, -- whether the box has a checkmark in it }) UIManager:show(parent_widget) ``` -------------------------------- ### Create a new Geometry object in Lua Source: https://koreader.rocks/doc/modules/ui.geometry Demonstrates how to create a new geometry object using the `ui/geometry` module in Lua. It shows examples of initializing with full rectangle properties, point properties, and dimension properties. This module can be used with simple tables or custom types. ```lua local Geom = require("ui/geometry") Geom:new{ x = 1, y = 0, w = Screen:scaleBySize(100), h = Screen:scaleBySize(200), } ``` ```lua Geom:new{ x = 0, y = 0, } ``` ```lua Geom:new{ w = Screen:scaleBySize(600), h = Screen:scaleBySize(800), } ``` -------------------------------- ### Create and Display RadioButtonWidget in Lua Source: https://koreader.rocks/doc/modules/ui.widget.radiobuttonwidget This snippet demonstrates how to create and display a RadioButtonWidget in KOReader using Lua. It shows how to define the radio button options, including text, provider identifiers, and initial checked states. The example also includes a callback function to handle user selections and perform actions based on the selected radio button's provider. ```lua local RadioButtonWidget = require("ui/widget/radiobuttonwidget") local radio_buttons = { { {text = _("Radio 1"), provider = 1} }, { {text = _("Radio 2"), provider = 2, checked = true} }, { {text = _("Radio 3"), provider = "identifier"} }, } UIManager:show(RadioButtonWidget:new{ title_text = _("Example Title"), info_text = _("Some more information"), cancel_text = _("Close"), ok_text = _("Apply"), width_factor = 0.9, radio_buttons = radio_buttons, callback = function(radio) if radio.provider == 1 then -- do something here elseif radio.provider == 2 then -- do some other things here elseif radio.provider == "identifier" then -- or do a third thing here end end, }) ``` -------------------------------- ### Register Touch Zones with InputContainer in Lua Source: https://koreader.rocks/doc/modules/ui.widget.container.inputcontainer This Lua example demonstrates how to create an InputContainer instance and register touch zones for handling user interactions like taps and swipes. It shows how to define zones using screen ratios and attach handler functions that execute when a gesture is detected. The `registerTouchZones` function is key to setting up interactive areas within the UI. ```lua local InputContainer = require("ui/widget/container/inputcontainer") local test_widget = InputContainer:new{} test_widget:registerTouchZones({ { id = "foo_tap", ges = "tap", -- This binds the handler to the full screen screen_zone = { ratio_x = 0, ratio_y = 0, ratio_w = 1, ratio_h = 1, }, handler = function(ges) print('User tapped on screen!') return true end }, { id = "foo_swipe", ges = "swipe", -- This binds the handler to bottom half of the screen screen_zone = { ratio_x = 0, ratio_y = 0.5, ratio_w = 1, ratio_h = 0.5, }, handler = function(ges) print("User swiped at the bottom with direction:", ges.direction) return true end }, }) require("ui/uimanager"):show(test_widget) ``` -------------------------------- ### Device-Specific Configurations and Mocking Source: https://koreader.rocks/doc/index Contains modules for device-specific configurations, such as accessing and modifying Kobo eReader.conf for Nickel, and a mock RTC module for checking alarm functionality. ```lua -- device.kindle.mockrtc: Checks if the alarm we set matches the current time. -- device.kobo.nickel_conf: Access and modify values in `Kobo eReader.conf` used by Nickel. ``` -------------------------------- ### Create and Configure a Button Widget in Lua Source: https://koreader.rocks/doc/modules/ui.widget.button Demonstrates how to create a new button widget using the `ui/widget/button` module. It shows how to set properties like text, enabled state, callback function, dimensions, and spacing. The `Screen:scaleBySize` function is used for responsive sizing. ```lua local Button = require("ui/widget/button") local button = Button:new{ text = _("Press me!"), enabled = false, -- defaults to true callback = some_callback_function, width = Screen:scaleBySize(50), bordersize = Screen:scaleBySize(3), margin = 0, padding = Screen:scaleBySize(2), } ``` -------------------------------- ### KoptInterface:getPageDimensions Source: https://koreader.rocks/doc/modules/document.koptinterface Gets the dimensions of a page with specified zoom and rotation. ```APIDOC ## POST /koptinterface/getPageDimensions ### Description Get page dimensions. ### Method POST ### Endpoint /koptinterface/getPageDimensions ### Parameters #### Request Body - **doc** (string) - Required - The document identifier. - **pageno** (integer) - Required - The page number. - **zoom** (float) - Required - The zoom level. - **rotation** (integer) - Required - The rotation angle (e.g., 0, 90, 180, 270). ``` -------------------------------- ### Load SDL2 Library (Lua) Source: https://koreader.rocks/doc/modules/ffi.util Loads and returns the SDL2 library, making its functionalities available for use. ```lua loadSDL2 () ``` -------------------------------- ### KoptInterface:getRFPageDimensions Source: https://koreader.rocks/doc/modules/document.koptinterface Gets the dimensions of a reflowed page with specified zoom and rotation. ```APIDOC ## POST /koptinterface/getRFPageDimensions ### Description Get reflowed page dimensions. ### Method POST ### Endpoint /koptinterface/getRFPageDimensions ### Parameters #### Request Body - **doc** (string) - Required - The document identifier. - **pageno** (integer) - Required - The page number. - **zoom** (float) - Required - The zoom level. - **rotation** (integer) - Required - The rotation angle (e.g., 0, 90, 180, 270). ``` -------------------------------- ### Widget:new Source: https://koreader.rocks/doc/modules/ui.widget.widget Initializes a new instance of the Widget class. This method should be used for instantiation and also calls the init() method. ```APIDOC ## Widget:new ### Description Use this method to initiate an instance of a class. Do NOT use it for class definitions because it also calls self:init(). ### Method `new` ### Parameters #### Path Parameters - **o** (table) - Required - The table containing initialization parameters. ### Request Example ```lua local myWidget = Widget:new({ /* initialization options */ }) ``` ### Response #### Success Response (200) - **Widget** (Widget) - A new instance of the Widget class. ``` -------------------------------- ### NickelConf Color Setting API Source: https://koreader.rocks/doc/modules/device.kobo.nickel_conf Provides functions to get and set the color setting on Kobo devices. ```APIDOC ## NickelConf.colorSetting.get() ### Description Get the current color setting. ### Method GET ### Endpoint /device/kobo/nickel_conf ### Parameters None ### Request Example None ### Response #### Success Response (200) - **setting** (string) - The current color setting (e.g., "color", "bw"). #### Response Example ```json { "setting": "color" } ``` ## NickelConf.colorSetting.set(new_color) ### Description Set the color setting. ### Method POST ### Endpoint /device/kobo/nickel_conf/colorsetting ### Parameters #### Query Parameters - **new_color** (string) - Required - The desired color setting (e.g., "color", "bw"). ### Request Example ```json { "new_color": "bw" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success or failure of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Get Topmost Visible Widget - UIManager Source: https://koreader.rocks/doc/modules/ui.uimanager Returns the widget that is currently at the very top of the visible widget stack. ```lua UIManager:getTopmostVisibleWidget() ``` -------------------------------- ### Create and Register Image Widget in Lua Source: https://koreader.rocks/doc/modules/apps.reader.modules.readerview Demonstrates how to create a new ImageWidget instance with a specified file and register it with the reader UI. This widget is intended to be displayed on all book pages. ```lua local ImageWidget = require("ui/widget/imagewidget") local dummy_image = ImageWidget:new{ file = "resources/koreader.png", } -- the image will be painted on all book pages readerui.view:registerViewModule('dummy_image', dummy_image) ``` -------------------------------- ### NumberPickerWidget Initialization in Lua Source: https://koreader.rocks/doc/modules/ui.widget.numberpickerwidget Demonstrates how to initialize and configure a NumberPickerWidget in Lua. It shows setting precision, initial value, min/max range, step increments, and wrap-around behavior. ```lua local NumberPickerWidget = require("ui/widget/numberpickerwidget") local numberpicker = NumberPickerWidget:new{ -- for floating point (decimals), use something like "%.2f" precision = "%02d", value = 0, value_min = 0, value_max = 23, value_step = 1, value_hold_step = 4, wrap = true, } ``` -------------------------------- ### UIManager:run Source: https://koreader.rocks/doc/modules/ui.uimanager Starts the main loop of the UI controller, responsible for managing and delegating input events to dialogs. ```APIDOC ## UIManager:run ### Description This is the main loop of the UI controller. It is intended to manage input events and delegate them to dialogs. ### Method GET ### Endpoint /UIManager/run ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **status** (string) - Indicates the UI loop has started or is running. #### Response Example ```json { "status": "running" } ``` ``` -------------------------------- ### Get UTF-8 Charcode (Lua) Source: https://koreader.rocks/doc/modules/ffi.util Retrieves the UTF-8 charcode for a given character string. An encoder for converting Unicode codepoints to UTF-8 can be found in frontend/util. ```lua utf8charcode (charstring) ``` -------------------------------- ### Create and Show Input Dialog (Lua) Source: https://koreader.rocks/doc/modules/ui.widget.inputdialog Demonstrates how to create and display a basic input dialog with a title, default input, hint text, description, and custom 'Cancel' and 'Save' buttons. The 'Save' button is configured as the default action triggered by the Enter key. It also shows how to retrieve the user's input. ```lua local InputDialog = require("ui/widget/inputdialog") local UIManager = require("ui/uimanager") local logger = require("logger") local _ = require("gettext") local sample_input sample_input = InputDialog:new{ title = _("Dialog title"), input = "default value", -- A placeholder text shown in the text box. input_hint = _("Hint text"), -- input_type = nil, -- default for text -- A description shown above the input. description = _("Some more description."), -- text_type = "password", buttons = { { { text = _("Cancel"), id = "close", callback = function() UIManager:close(sample_input) end, }, { text = _("Save"), -- button with is_enter_default set to true will be -- triggered after user press the enter key from keyboard is_enter_default = true, callback = function() logger.dbg("Got user input as raw text:", sample_input:getInputText()) logger.dbg("Got user input as value:", sample_input:getInputValue()) end, }, } }, } UIManager:show(sample_input) sample_input:onShowKeyboard() ``` -------------------------------- ### ImageWidget Usage Source: https://koreader.rocks/doc/modules/apps.reader.modules.readerview Demonstrates how to create and register an ImageWidget in Koreader. ```APIDOC ## ImageWidget Usage ### Description This section shows how to instantiate and utilize the `ImageWidget` to display images within the Koreader UI. ### Method ```lua local ImageWidget = require("ui/widget/imagewidget") local dummy_image = ImageWidget:new{ file = "resources/koreader.png", } -- the image will be painted on all book pages readerui.view:registerViewModule('dummy_image', dummy_image) ``` ### Parameters * **file** (string) - Required - The path to the image file to be displayed. ``` -------------------------------- ### Get Text Translation (Lua) Source: https://koreader.rocks/doc/modules/gettext Retrieves a translated string based on a given message ID. This is the most basic translation function. It requires the 'gettext' module to be loaded. ```lua local _ = require("gettext") local translation = _("A meaningful message.") ``` -------------------------------- ### Initialize Dispatcher Settings Source: https://koreader.rocks/doc/modules/dispatcher Initializes the dispatcher by adding settings from CreOptions or KoptOptions. This function is typically called once during the application's setup. ```lua Dispatcher:init () ``` -------------------------------- ### Wallabag:setDownloadDirectory Source: https://koreader.rocks/doc/modules/koplugin.wallabag Opens a dialog for setting the download folder for articles. ```APIDOC ## POST /websites/koreader_rocks_doc/Wallabag:setDownloadDirectory ### Description Opens a dialog for setting the download folder for articles. ### Method POST ### Endpoint /websites/koreader_rocks_doc/Wallabag:setDownloadDirectory ### Parameters #### Request Body - **touchmenu_instance** (object) - Required - The instance of the touch menu. ### Request Example ```json { "touchmenu_instance": {} } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "download directory dialog opened" } ``` ``` -------------------------------- ### Get Nth Top Widget - UIManager Source: https://koreader.rocks/doc/modules/ui.uimanager Retrieves the Nth topmost widget from the window stack. This is useful for accessing specific widgets based on their stacking order. ```lua UIManager:getNthTopWidget(n) ``` -------------------------------- ### Module koplugin.coverimage Source: https://koreader.rocks/doc/modules/koplugin.coverimage Documentation for the koplugin.coverimage module, including its functions for cache handling and file migration. ```APIDOC ## Module `koplugin.coverimage` ### Description This module provides functions for handling cover images, including cache management and file migration. ### Functions #### `CoverImage:getCacheFile(custom_cover)` ##### Description Handles cache operations for cover images. ##### Parameters - **custom_cover** (any) - Description of the custom cover parameter. #### `migrate(key)` ##### Description Chooses a path or an existing file for migration. ##### Parameters - **key** (string) - The G _reader_ setting key that is used and changed. #### `callback(setting, title, min, max, default)` ##### Description Updates a specific G _reader_ setting's value via a Spinner. ##### Parameters - **setting** (any) - The setting to be updated. - **title** (string) - The title for the setting. - **min** (number) - The minimum value for the setting. - **max** (number) - The maximum value for the setting. - **default** (any) - The default value for the setting. #### `migrate(key, title, help, info, the, folder_only, new_file)` ##### Description Provides a menu entry for setting a specific G _reader_ setting key for a path or file. ##### Parameters - **key** (string) - The G _reader_ setting key. - **title** (string) - The title displayed in the menu. - **help** (string) - Help text for the setting. - **info** (string) - Additional information about the setting. - **the** (any) - Unknown parameter. - **folder_only** (boolean) - If true, only folders can be selected. - **new_file** (boolean) - If true, allows creating a new file. ``` -------------------------------- ### Get Refresh Rate - UIManager Source: https://koreader.rocks/doc/modules/ui.uimanager Retrieves the current full refresh rate for e-ink screens. This value indicates the number of partial refreshes before a full refresh is triggered. ```lua UIManager:getRefreshRate() ``` -------------------------------- ### FFI Bindings for Multimedia and System Libraries Source: https://koreader.rocks/doc/index Provides FFI interfaces for multimedia libraries such as SDL 2.0 for video and input, and MuPDF for document rendering. It also includes modules for framebuffer operations and interfacing with the Real-Time Clock (RTC). ```lua -- ffi.framebuffer: Framebuffer API. -- ffi.mupdf: MuPDF API This is a FFI wrapper for what was a Lua-based API in the past Some kind of C wrapper is needed for muPDF since muPDF uses a setjmp/longjmp based approach to error/exception handling. -- ffi.rtc: Module for interfacing with the RTC (real time clock). -- ffi.sdl2_0: Module for SDL 2.0 video/input facilities ``` -------------------------------- ### Deflector Initialization and Creation Source: https://koreader.rocks/doc/modules/koplugin.japanese.deinflector Functions for initializing a Deflector instance with predefined rules or creating a new instance with custom options. ```APIDOC ## Deflector Instance Management ### Description Provides methods to initialize a Deflector instance, either with a default set of rules loaded from `yomichan-deflect.json` or by creating a new instance with custom options. ### Methods #### `init()` Initializes a Deflector instance with the set of rules defined in `yomichan-deflect.json`. #### `new(o)` Creates a new Deflector instance. The parameter `o` is used for configuration options, but its specific structure is not detailed here. ### Parameters #### `init()` *None* #### `new(o)` * **o** (object) - Configuration options for the new Deflector instance. ### Request Example ```javascript // Initialize with default rules Deflector.init(); // Create a new instance with custom options (example) const customDeflector = Deflector.new({ /* options */ }); ``` ### Response *These functions typically return the Deflector instance or modify its state. Specific return values are not detailed in the provided documentation.* ``` -------------------------------- ### Word Selection Handler Callback Source: https://koreader.rocks/doc/modules/languagesupport Callback for WordSelection handler used in `registerPlugin`. It receives XPointer objects and callbacks to get text and navigate characters. It should return new XPointers for the expanded word. ```lua -- Equivalent to document:getPrevVisibleChar(pos). get_prev_char_pos(pos: XPointer) -> XPointer, -- Equivalent to document:getNextVisibleChar(pos). get_next_char_pos(pos: XPointer) -> XPointer, -- Equivalent to document:getTextFromXPointers(pos0, pos1). get_text_in_range(pos0: XPointer, pos1: XPointer) -> string ``` -------------------------------- ### DocSettings.openSettingsFile Source: https://koreader.rocks/doc/modules/docsettings A lightweight version of `DocSettings:open()`. It opens a sidecar file or a custom metadata file. The returned object can be used to save changes to custom metadata files but not directly to the sidecar file. ```APIDOC ## DocSettings.openSettingsFile ### Description Light version of open(). Opens a sidecar file or a custom metadata file. Returned object cannot be used to save changes to the sidecar file (flush()). Must be used to save changes to the custom metadata file (flushCustomMetadata()). ### Method GET (assumed, as it retrieves settings) ### Endpoint `/websites/koreader_rocks_doc/DocSettings.openSettingsFile` ### Parameters #### Path Parameters - **sidecar_file** (string) - Required - Path to the sidecar or custom metadata file. ### Response #### Success Response (200) - **settings_object** (object) - An object representing the settings from the specified file. #### Response Example { "settings_object": { "custom_field": "value" } } ``` -------------------------------- ### Get Extra Dictionary Candidates Source: https://koreader.rocks/doc/modules/languagesupport Provides extra dictionary form candidates for a given text, typically used after OCR and cleaning for dictionary lookups. It returns a list of candidate strings or nil. ```lua LanguageSupport:extraDictionaryFormCandidates (text) -- Called from ReaderHighlight:startSdcv after the selected has text has been OCR'd, cleaned, and otherwise made ready for sdcv. -- Parameters: text string Original text being searched by the user. -- Returns: {string,...} Extra dictionary form candidates to search (or nil). ``` -------------------------------- ### Get Context-Disambiguated Translation (Lua) Source: https://koreader.rocks/doc/modules/gettext Retrieves a translation for a string that might appear multiple times with different meanings. It uses a context string to differentiate between them. Requires the 'gettext' module. ```lua local _ = require("gettext") local C_ = _.pgettext local copy_file = C_("File", "Copy") local copy_text = C_("Text", "Copy") ``` -------------------------------- ### Set Suntime Position and Calculate Times (Lua) Source: https://koreader.rocks/doc/modules/suntime This snippet demonstrates how to initialize the Suntime library by setting the geographical position (name, latitude, longitude, timezone, altitude, degree) and then calculating sunrise, sunset, and twilight times. It shows how to use both simple and advanced equation of time methods and access the calculated times. ```lua local SunTime = require("suntime") time_zone = 0 altitude = 50 degree = true SunTime:setPosition("Reykjavik", 64.14381, -21.92626, timezone, altitude, degree) SunTime:setAdvanced() -- or SunTime:setSimple() SunTime:setDate() SunTime:calculateTimes(true) -- Set to true for exact twilight times print(SunTime.rise, SunTime.set, SunTime.set_civil) -- Accessing specific times -- Accessing all times in a table: for i, time in ipairs(SunTime.times) do print(string.format("Time[%d]: %s", i, tostring(time))) end ``` -------------------------------- ### Load Native Library with ffi.loadlib (Lua) Source: https://koreader.rocks/doc/modules/ffi.loadlib Demonstrates how to load a native library using the `ffi.loadlib` function in Lua. This function searches specified paths for library candidates and loads the first one found. It's crucial for integrating native code into Lua applications, ensuring ABI compatibility through versioned library names. ```lua local sdl = ffi.loadlib("SDL2-2.0", 0, "SDL2-2.0", nil, "SDL2", nil) ``` -------------------------------- ### Search String in Text (Lua) Source: https://koreader.rocks/doc/modules/util Searches for a substring within a larger text, starting from a specified position. It returns the position of the found substring or 0 if not found, along with the original text and the search string. ```lua --- Search a string in a text. -- @param or string table txt Text (char list) to search in -- @param str string String to search for -- @param start_pos number Position number in text to start search from -- @return number Position number or 0 if not found -- @return table Text char list -- @return table Search string char list function stringSearch (or, str, start_pos) -- Implementation details omitted end ``` -------------------------------- ### String Templating for Translations (Lua) Source: https://koreader.rocks/doc/modules/ffi.util Provides a utility for creating translatable strings with dynamic placeholders. Placeholders are denoted by %1 to %99, and the function allows for easy substitution of these markers with provided arguments. Inspired by Qt's internationalization features. ```lua output = util.template( _("Hello %1, welcome to %2."), name, company ) ``` -------------------------------- ### Display ConfirmBox and Get User Choice Source: https://koreader.rocks/doc/modules/ui.trapper Presents a confirmation dialog to the user with custom text and button labels. It blocks execution until the user makes a choice (OK or Cancel) and returns a boolean indicating the selection. ```lua local user_choice = Trapper:confirm("Are you sure you want to proceed?", "No", "Yes") if user_choice then print("User chose Yes") else print("User chose No or cancelled") end ``` -------------------------------- ### FFI Library Loading Utility Source: https://koreader.rocks/doc/index A helper module for loading native libraries using LuaJIT's FFI. This is essential for integrating external C libraries into KOReader. ```lua -- ffi.loadlib: Helper for loading native libraries. ``` -------------------------------- ### Add Official KOReader Repository Source: https://koreader.rocks/doc/topics/Collaborating_with_Git.md Adds the official KOReader repository as a remote named 'upstream'. This is the first step to pulling the latest code. It requires Git to be installed and configured. ```git git remote add upstream git@github.com:koreader/koreader.git ``` -------------------------------- ### Implement Module Methods for Preset Management Source: https://koreader.rocks/doc/modules/ui.presets Defines the essential `buildPreset` and `loadPreset` methods required by the `ui.presets` module. `buildPreset` captures the current module's state for saving, while `loadPreset` applies a saved configuration back to the module. ```lua -- 2. Implement required methods in your module: function MyModule:buildPreset() return { -- Return a table with the settings you want to save in the preset setting1 = self.setting1, setting2 = self.setting2, enabled_features = self.enabled_features, } end function MyModule:loadPreset(preset) -- Apply the preset settings to your module self.setting1 = preset.setting1 self.setting2 = preset.setting2 self.enabled_features = preset.enabled_features -- Update UI or perform other necessary changes self:refresh() end ``` -------------------------------- ### Get Context-Disambiguated Plural Form (Lua) Source: https://koreader.rocks/doc/modules/gettext Combines context disambiguation and plural form handling. Useful when the same pluralizable string needs different translations based on its context. Requires 'gettext' and 'ffi/util' modules. ```lua local _ = require("gettext") local NC_ = _.npgettext local T = require("ffi/util").template local statistics_items_string = T(NC_("Statistics", "1 item", "%1 items", num_items), num_items) local books_items_string = T(NC_("Books", "1 item", "%1 items", num_items), num_items) ``` -------------------------------- ### Get Plural Form Translation (Lua) Source: https://koreader.rocks/doc/modules/gettext Returns the appropriate plural form of a string based on a given number. It handles complex pluralization rules for different languages. Requires 'gettext' and 'ffi/util' modules. ```lua local _ = require("gettext") local N_ = _.ngettext local T = require("ffi/util").template local items_string = T(N_("1 item", "%1 items", num_items), num_items) ``` -------------------------------- ### FFI Bindings for Image and Graphics Libraries Source: https://koreader.rocks/doc/index Offers LuaJIT FFI wrappers for image processing and graphics manipulation libraries, including JPEG, PNG, WebP, and general blitbuffer/GFX operations. Also includes an interface for the FreeType library for text rendering. ```lua -- ffi.blitbuffer: Generic blitbuffer/GFX stuff that works on memory buffers -- ffi.freetype: Freetype library interface (text rendering) -- ffi.jpeg: Module for JPEG decoding/encoding. -- ffi.png: Module for PNG decoding/encoding. -- ffi.webp: Module for WebP decoding. ``` -------------------------------- ### BaseExporter:getMenuTable Source: https://koreader.rocks/doc/modules/baseexporter Retrieves the configuration menu table for the exporter. ```APIDOC ## BaseExporter:getMenuTable ### Description Retrieves the configuration menu table for the exporter. ### Method GET ### Endpoint /websites/koreader_rocks_doc/exporter/menu ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **menu** (table) - A table containing the exporter's configuration menu settings. #### Response Example ```json { "menu": { "setting1": "value1", "setting2": "value2" } } ``` ``` -------------------------------- ### Require ToggleSwitch Module in Lua Source: https://koreader.rocks/doc/modules/ui.widget.toggleswitch This snippet demonstrates how to load and use the ToggleSwitch module in Lua. It assumes the module is available in the project's path. No specific inputs or outputs are defined for this basic usage example. ```lua local ToggleSwitch = require("ui/widget/toggleswitch") ``` -------------------------------- ### Create and Show ProgressWidget in Lua Source: https://koreader.rocks/doc/modules/ui.widget.progresswidget This snippet demonstrates how to create an instance of the ProgressWidget and display it using the UIManager. It configures the widget's size and percentage, requiring the Screen and UIManager modules. ```lua local foo_bar = ProgressWidget:new{ width = Screen:scaleBySize(400), height = Screen:scaleBySize(10), percentage = 50/100, } UIManager:show(foo_bar) ``` -------------------------------- ### Register a Dispatcher Action Source: https://koreader.rocks/doc/modules/dispatcher Dynamically adds a new action to the dispatcher at runtime. This is useful for features that need to be registered after the initial setup. It takes the action name and its configuration table as arguments. ```lua Dispatcher:registerAction (name, value) ``` ```lua function Hello:onDispatcherRegisterActions() Dispatcher:registerAction("helloworld_action", {category="none", event="HelloWorld", title=_("Hello World"), general=true}) end function Hello:init() self:onDispatcherRegisterActions() end ``` -------------------------------- ### BaseExporter:loadSettings Source: https://koreader.rocks/doc/modules/baseexporter Loads the settings for the exporter. ```APIDOC ## BaseExporter:loadSettings ### Description Loads the settings for the exporter. ### Method POST ### Endpoint /websites/koreader_rocks_doc/exporter/settings/load ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **status** (string) - Indicates if settings were loaded successfully. #### Response Example ```json { "status": "Settings loaded successfully." } ``` ``` -------------------------------- ### Get Current Wall Clock Time (Lua) Source: https://koreader.rocks/doc/modules/time Returns an fts time based on the current wall clock time (similar to `gettimeofday` or `clock_gettime(CLOCK_REALTIME)`). This is a fancier POSIX Epoch with sub-second precision. ```lua local time = require("ui/time") local fts_start = time.realtime() -- Do some stuff. local fts_duration = time.realtime() - fts_start print("Realtime duration: " .. fts_duration .. " sec.usecs") ``` -------------------------------- ### Create and Display KeyValuePage Widget in Lua Source: https://koreader.rocks/doc/modules/ui.widget.keyvaluepage Demonstrates how to create an instance of the KeyValuePage widget, populate it with key-value pairs (including a separator and a callback function), and display it using the UIManager. This widget is useful for presenting structured information in a multi-page format. ```lua local Foo = KeyValuePage:new{ title = "Statistics", kv_pairs = { {"Current period", "00:00:00"}, -- single or more "-" will generate a solid line "----------------------------", {"Page to read", "5"}, {"Time to read", "00:01:00"}, {"Press me", "will invoke the callback", callback = function() print("hello") end }, }, } UIManager:show(Foo) ``` -------------------------------- ### Stage Changes for Commit Source: https://koreader.rocks/doc/topics/Collaborating_with_Git.md Interactively stages specific changes within a file for the next commit. This allows for fine-grained control over what gets included in a commit, excluding whitespace changes if desired. Requires Git. ```git git add -p unireader.lua ``` -------------------------------- ### File System Utilities Source: https://koreader.rocks/doc/modules/util Functions for interacting with the file system, including checking path existence, creating/removing directories, and file operations. ```APIDOC ## getFilesystemType (path) ### Description Gets the filesystem type of a given path by checking `/proc/mounts`. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua local fs_type = getFilesystemType("/mnt/sdcard") ``` ### Response #### Success Response (200) - **string** (string) - The filesystem type (e.g., "ext4", "vfat"). #### Response Example ```json { "example": "ext4" } ``` ## isEmptyDir (path) ### Description Checks if a given directory is empty. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua local is_empty = isEmptyDir("/tmp/empty_folder") ``` ### Response #### Success Response (200) - **bool** (boolean) - `true` if the directory is empty, `false` otherwise. #### Response Example ```json { "example": true } ``` ## fileExists (path) ### Description Checks if a given path points to an existing file. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua local exists = fileExists("/etc/config.lua") ``` ### Response #### Success Response (200) - **bool** (boolean) - `true` if the file exists, `false` otherwise. #### Response Example ```json { "example": true } ``` ## pathExists (path) ### Description Checks if a given path exists, regardless of whether it is a file or a directory. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua local exists = pathExists("/usr/bin") ``` ### Response #### Success Response (200) - **bool** (boolean) - `true` if the path exists, `false` otherwise. #### Response Example ```json { "example": true } ``` ## directoryExists (path) ### Description Checks if a given path points to an existing directory. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua local exists = directoryExists("/home/user") ``` ### Response #### Success Response (200) - **bool** (boolean) - `true` if the directory exists, `false` otherwise. #### Response Example ```json { "example": true } ``` ## makePath (path) ### Description Creates a directory path, similar to `mkdir -p`. It does not error if the directory already exists and creates intermediate directories as needed. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua local success, err = makePath("/tmp/new/nested/directory") ``` ### Response #### Success Response (200) - **bool** (boolean) - `true` on success. - **err_message** (string) - Error message if an error occurred. #### Response Example ```json { "example": true } ``` ## removePath (path) ### Description Removes a directory tree, pruning children first. It does not fail if the directory is already gone. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua local success, err = removePath("/tmp/old_directory") ``` ### Response #### Success Response (200) - **bool** (boolean) - `true` on success. - **err_message** (string) - Error message if an error occurred. #### Response Example ```json { "example": true } ``` ## removeFile (path) ### Description Removes a file, similar to `rm`. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua local success, err = removeFile("/tmp/file_to_delete.txt") ``` ### Response #### Success Response (200) - **bool** (boolean) - `true` on success. - **err_message** (string) - Error message if an error occurred. #### Response Example ```json { "example": true } ``` ``` -------------------------------- ### Show Network Settings Widget in Lua Source: https://koreader.rocks/doc/modules/ui.widget.networksetting Demonstrates how to display the network setting widget using Lua. It takes a list of available networks and callback functions for connection and disconnection events. The widget is part of the UI module and requires the UIManager to be shown. ```lua local network_list = { { ssid = "foo", signal_level = -58, flags = "[WPA2-PSK-CCMP][ESS]", signal_quality = 84, password = "123abc", connected = true, }, { ssid = "bar", signal_level = -258, signal_quality = 44, flags = "[WEP][ESS]", }, } UIManager:show(require("ui/widget/networksetting"):new{ network_list = network_list, connect_callback = function() -- connect_callback will be called when a *connect* (NOT disconnect) -- attempt has been successful. -- You can update UI widgets in the callback. end, disconnect_callback = function() -- This one will fire unconditionally after a disconnect attempt. end, }) ```