### QuickStart:isShown() Source: https://koreader.rocks/doc/modules/ui.quickstart.html Checks if the quickstart guide has been shown to the user. ```APIDOC ## QuickStart:isShown() ### Description Returns true if the quickstart guide has been shown, false if it hasn't been shown yet or if display is forced through a higher version number. ### Returns - **boolean** - true if shown, false otherwise. ``` -------------------------------- ### QuickStart:getQuickStart() Source: https://koreader.rocks/doc/modules/ui.quickstart.html Generates the quickstart guide in the user's language. ```APIDOC ## QuickStart:getQuickStart() ### Description Generates the quickstart guide in the user's language and returns its file system location. ### Returns - **string** - The path to the generated HTML quickstart guide. ``` -------------------------------- ### IconWidget Initialization Source: https://koreader.rocks/doc/modules/ui.widget.iconwidget.html Example of how to instantiate and display an IconWidget. ```APIDOC ## IconWidget:new ### Description Creates a new instance of an IconWidget to display an icon from the resources/icons directory. ### Parameters - **icon** (string) - Required - The name of the icon file (excluding extension) located in resources/icons. - **dim** (boolean) - Optional - Whether to dim the icon. - **alpha** (boolean) - Optional - Whether to enable transparency on the icon (defaults to false). ### Usage Example ```lua local IconWidget = require("ui/widget/iconwidget") local icon_widget = IconWidget:new{ icon = "check", dim = true, alpha = true } UIManager:show(icon_widget) ``` ``` -------------------------------- ### Initialize gettext and pluralization Source: https://koreader.rocks/doc/modules/gettext.html Standard setup for gettext and pluralization helpers using ffi/util template. ```lua local _ = require("gettext") -- gettext() local C_ = _.pgettext -- pgettext() local N_ = _.ngettext -- ngettext() local NC_ = _.npgettext -- npgettext() local T = require("ffi/util").template -- ffi.util.template() -- The most common use case with regular gettext(). local simple_string = _("item") -- A more complex example. The correct plural form will be automatically -- selected by ngettext() based on the number. local numbered_string = T(N_("1 item", "%1 items", num_items), num_items) ``` -------------------------------- ### Initialize and Calculate Sun Times Source: https://koreader.rocks/doc/modules/suntime.html Basic setup sequence for configuring a location and calculating solar events. ```lua local SunTime = require("suntime") time_zone = 0 altitude = 50 degree = true SunTime:setPosition("Reykjavik", 64.14381, -21.92626, timezone, altitude, degree) SunTime:setAdvanced() SunTime:setDate() SunTime:calculateTimes() print(SunTime.rise, SunTime.set, SunTime.set_civil) -- or similar see calculateTime() ``` -------------------------------- ### stringStartsWith(str, start) Source: https://koreader.rocks/doc/modules/util.html Checks if a string starts with a specific substring. ```APIDOC ## stringStartsWith(str, start) ### Description Checks if a string starts with the provided substring. ### Parameters - **str** (string) - Required - The source string. - **start** (string) - Required - The string to match. ### Returns - (bool) - Returns true on success. ``` -------------------------------- ### KoptInterface:getCoverPageImage Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get first page image. ```APIDOC ## KoptInterface:getCoverPageImage(doc) ### Description Get first page image. ### Parameters - **doc** - The document object. ``` -------------------------------- ### DepGraph Usage Source: https://koreader.rocks/doc/modules/depgraph.html Example of how to initialize a dependency graph, add nodes with dependencies, and serialize the result. ```APIDOC ## DepGraph ### Description Library for constructing dependency graphs. Insertion order is preserved, and duplicates are automatically prevented for both main nodes and dependencies. ### Usage Example ```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'} ``` ``` -------------------------------- ### Measuring duration with time module Source: https://koreader.rocks/doc/modules/time.html Demonstrates capturing a start time, calculating a duration, and converting the result to milliseconds. ```lua local time = require("ui/time") local start_time = time.now() -- Do some stuff. -- You can add and subtract `fts times` objects local duration = time.now() - start_time -- and convert that object to various more human-readable formats, e.g., print(string.format("Stuff took %.3fms", time.to_ms(duration))) local offset = time.s(100) print(string.format("Stuff plus 100s took %.3fms", time.to_ms(duration + offset))) ``` -------------------------------- ### Initialize Geom Objects Source: https://koreader.rocks/doc/modules/ui.geometry.html Examples of initializing Geom objects for full rectangles, points, and dimensions. ```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), } ``` -------------------------------- ### Measure elapsed time using realtime Source: https://koreader.rocks/doc/modules/time.html Demonstrates capturing a start time and calculating the duration using the realtime clock. ```lua local time = require("ui/time") local fts_start = time.realtime() -- Do some stuff. -- You can add and subtract fts times local fts_duration = time.realtime() - fts_start ``` -------------------------------- ### KoptInterface:getWordFromPosition Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get word and word box from document position. ```APIDOC ## KoptInterface:getWordFromPosition(doc, pos) ### Description Get word and word box from `doc` position. ### Parameters - **doc** - The document object. - **pos** - The position. ``` -------------------------------- ### CheckButton Usage Source: https://koreader.rocks/doc/modules/ui.widget.checkbutton.html Example of how to instantiate and display a CheckButton widget within a parent container. ```APIDOC ## CheckButton Widget ### Description The CheckButton widget is a UI component that displays a checkmark when active and an empty box when inactive. It is typically used for boolean settings or selection toggles. ### Usage Example ```lua local CheckButton = require("ui/widget/CheckButton") local parent_widget = OverlapGroup:new{} table.insert(parent_widget, CheckButton:new{ text = _("Show password"), callback = function() end, }) UIManager:show(parent_widget) ``` ``` -------------------------------- ### Registering Custom Dictionary Buttons Source: https://koreader.rocks/doc/modules/ui.widget.dictquicklookup.html Example of registering a custom dictionary button within a plugin, utilizing dynamic labels and callbacks. ```lua function MyPlugin:registerDictButtons() if self.ui and self.ui.dictionary then self.ui.dictionary:addToDictButtons({ id = "my_custom_action", menu_text = _("My custom action"), text_func = function(dict_popup) return dict_popup._my_custom_action_state and _("Disable action") or _("Enable action") end, insert_first = true, show_func = function(dict_popup) return true -- or some condition based on dict_popup end, callback = function(dict_popup) local current = dict_popup._my_custom_action_state == true dict_popup._my_custom_action_state = not current end, }) end end ``` -------------------------------- ### Adding a submenu Source: https://koreader.rocks/doc/modules/dispatcher.html Example usage of the addSubMenu function to integrate a submenu into the dispatcher. ```lua Dispatcher:addSubMenu(self, sub_items, self.data, "profile1") ``` -------------------------------- ### Example debug log output Source: https://koreader.rocks/doc/topics/Hacking.md.html The format of log entries generated by the logger module. ```text 04/06/17-21:44:53 DEBUG foo ``` -------------------------------- ### KoptInterface:getNativeTextBoxesFromScratch Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get text boxes in native page via optical method. ```APIDOC ## KoptInterface:getNativeTextBoxesFromScratch(doc, pageno) ### Description Get text boxes in native page via optical method. Done by OCR pre-processing in Tesseract and Leptonica. ### Parameters - **doc** - The document object. - **pageno** - The page number. ``` -------------------------------- ### Implement Preset Management in a Module Source: https://koreader.rocks/doc/modules/ui.presets.html Demonstrates the full lifecycle of integrating the preset system, including object initialization, method implementation, menu generation, and dispatcher integration. ```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 } -- 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() } -- 3. Create menu items for presets: (Alternatively, you could call Presets.genPresetMenuItemTable directly from touchmenu_instance) function MyModule:genPresetMenuItemTable(touchmenu_instance) return Presets.genPresetMenuItemTable( self.preset_obj, -- preset object _("Create new preset from current settings"), -- optional: custom text for UI menu function() return self:hasValidSettings() end, -- optional: function to enable/disable creating presets ) end -- 4. Load a preset by name (for dispatcher/event handling): function MyModule:onLoadMyModulePreset(preset_name) return Presets.onLoadPreset( self.preset_obj, preset_name, true -- show notification ) end -- 5. Cycle through presets (for dispatcher/event handling): function MyModule:onCycleMyModulePresets() return Presets.cycleThroughPresets( self.preset_obj, true -- show notification ) end -- 6. Get list of available presets (for dispatcher): function MyModule.getPresets() -- Note: This is a static method on MyModule local config = { presets = G_reader_settings:readSetting("my_module_presets", {}) } return Presets.getPresets(config) end -- 7. Add to dispatcher.lua: load_my_module_preset = { category = "string", event = "LoadMyModulePreset", title = _("Load my module preset"), args_func = MyModule.getPresets, reader = true }, cycle_my_module_preset = { category = "none", event = "CycleMyModulePresets", title = _("Cycle through my module presets"), reader = true }, ``` -------------------------------- ### Example Linux Kernel MT Protocol B Events Source: https://koreader.rocks/doc/modules/device.input.html Example of events for a single tap motion from the Linux kernel using MT protocol B. ```text MT_TRACK_ID: 0 MT_X: 222 MT_Y: 207 SYN REPORT MT_TRACK_ID: -1 SYN REPORT ``` -------------------------------- ### Button Initialization Source: https://koreader.rocks/doc/modules/ui.widget.button.html How to instantiate and configure a new button widget. ```APIDOC ## Button Initialization ### Description Creates a new instance of a button widget with specified text, state, and callback behavior. ### Usage ```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.html Get page dimensions. ```APIDOC ## KoptInterface:getPageDimensions(doc, pageno, zoom, rotation) ### Description Get page dimensions. ### Parameters - **doc** - The document object. - **pageno** - The page number. - **zoom** - Zoom level. - **rotation** - Rotation angle. ``` -------------------------------- ### getScreenHeight() Source: https://koreader.rocks/doc/modules/android.html Gets the current screen height. ```APIDOC ## getScreenHeight() ### Description Gets the screen height. ### Returns - **screen height** (int) - The height of the screen in pixels. ``` -------------------------------- ### Initialize and use CacheSQLite Source: https://koreader.rocks/doc/modules/cachesqlite.html Demonstrates creating a new cache instance with a specified size and file path, followed by basic insertion and retrieval operations. ```lua local CacheSQLite = require("cachesqlite") local cache = CacheSQLite:new{ size = 1024 * 1024 * 10, -- 10 MB -- Set to :memory: for an in-memory database. -- In that case, set auto_close to false. db_path = "/path/to/cache.db", } cache:insert("key", {value = "data"}) local data = cache:check("key") ``` -------------------------------- ### Run UI widget builder Source: https://koreader.rocks/doc/topics/Hacking.md.html Execute the wbuilder tool to bootstrap the UI framework for rapid widget development. ```bash ./kodev wbuilder ``` -------------------------------- ### getScreenWidth() Source: https://koreader.rocks/doc/modules/android.html Gets the current screen width. ```APIDOC ## getScreenWidth() ### Description Gets the screen width. ### Returns - **screen width** (int) - The width of the screen in pixels. ``` -------------------------------- ### Initialize and display a CheckMark widget Source: https://koreader.rocks/doc/modules/ui.widget.checkmark.html Demonstrates how to require the CheckMark module, instantiate it within a container, and display it using the UIManager. ```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) ``` -------------------------------- ### Initialize and display the network setting widget Source: https://koreader.rocks/doc/modules/ui.widget.networksetting.html This snippet demonstrates how to define a list of networks and initialize the network setting widget with connection and disconnection callbacks. ```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, }) ``` -------------------------------- ### KoptInterface:getRFPageDimensions Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get reflowed page dimensions. ```APIDOC ## KoptInterface:getRFPageDimensions(doc, pageno, zoom, rotation) ### Description Get reflowed page dimensions. ### Parameters - **doc** - The document object. - **pageno** - The page number. - **zoom** - Zoom level. - **rotation** - Rotation angle. ``` -------------------------------- ### Widget:new Source: https://koreader.rocks/doc/modules/ui.widget.widget.html Initiates an instance of a widget class and calls the init method. ```APIDOC ## Widget:new(o) ### Description Use this method to initiate an instance of a class. Do NOT use it for class definitions because it also calls self:init(). ### Parameters - **o** (table) - The table to be initialized as an instance. ### Returns - **Widget** - The initialized widget instance. ``` -------------------------------- ### getFilesystemType(path) Source: https://koreader.rocks/doc/modules/util.html Gets the filesystem type of a given path. ```APIDOC ## getFilesystemType(path) ### Description Gets the filesystem type of a path by checking `/proc/mounts`. ### Parameters - **path** (string) - Required - An absolute path. ### Returns - **string** - The filesystem type. ``` -------------------------------- ### KoptInterface:getLinkFromPosition Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get link from position in screen page. ```APIDOC ## KoptInterface:getLinkFromPosition(doc, pageno, pos) ### Description Get link from position in screen page. ### Parameters - **doc** - The document object. - **pageno** - The page number. - **pos** - The position. ``` -------------------------------- ### Initialize and display a TextViewer Source: https://koreader.rocks/doc/modules/ui.widget.textviewer.html Create a new TextViewer instance with a title and text, then register it with the UIManager to render it on screen. ```lua local textviewer = TextViewer:new{ title = _("I can scroll!"), text = _("I'll need to be longer than this example to scroll."), } UIManager:show(textviewer) ``` -------------------------------- ### KoptInterface:getNativeOCRWord Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get word from OCR in native page. ```APIDOC ## KoptInterface:getNativeOCRWord(doc, pageno, rect) ### Description Get word from OCR in native page. ### Parameters - **doc** - The document object. - **pageno** - The page number. - **rect** - The rectangle area. ``` -------------------------------- ### init() Source: https://koreader.rocks/doc/modules/koplugin.japanese.deinflector.html Initializes a Deflector instance with rules from yomichan-deflect.json. ```APIDOC ## init() ### Description Initializes a Deflector instance using the set of rules defined in the yomichan-deflect.json file. ``` -------------------------------- ### Initialize and display a RadioButtonWidget Source: https://koreader.rocks/doc/modules/ui.widget.radiobuttonwidget.html Demonstrates how to define a list of radio button options and display the widget using UIManager with a callback function. ```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, }) ``` -------------------------------- ### KoptInterface:getReflewOCRWord Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get word from OCR in reflowed page. ```APIDOC ## KoptInterface:getReflewOCRWord(doc, pageno, rect) ### Description Get word from OCR in reflowed page. ### Parameters - **doc** - The document object. - **pageno** - The page number. - **rect** - The rectangle area. ``` -------------------------------- ### KoptInterface:getCachedContext Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get cached koptcontext for a certain page. ```APIDOC ## KoptInterface:getCachedContext(doc, pageno) ### Description Get cached koptcontext for a certain page. If the context doesn't exist in cache, make a new context and reflow the src page immediately, or wait for the background thread with reflowed context. ### Parameters - **doc** - The document object. - **pageno** - The page number. ``` -------------------------------- ### ProgressbarDialog:new Source: https://koreader.rocks/doc/modules/ui.widget.progressbardialog.html Initializes a new ProgressbarDialog instance. ```APIDOC ## ProgressbarDialog:new ### Description Creates a new instance of the ProgressbarDialog. ### Parameters - **title** (string) - Optional - The title of the dialog. - **subtitle** (string) - Optional - The subtitle of the dialog. - **progress_max** (number) - Optional - The maximum value for the progress bar. - **refresh_time_seconds** (number) - Optional - The interval in seconds to refresh the UI. ``` -------------------------------- ### Initialize DataStorage module Source: https://koreader.rocks/doc/modules/datastorage.html Load the datastorage module to access directory path utility functions. ```lua local DataStorage = require("datastorage") ``` -------------------------------- ### KoptInterface:createContext Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get reflow context for a specific page. ```APIDOC ## KoptInterface:createContext(doc, pageno, bbox) ### Description Get reflow context. Koptcontext keeps track of its dst bitmap reflowed by libk2pdfopt. ### Parameters - **doc** - The document object. - **pageno** - The page number. - **bbox** - The bounding box. ``` -------------------------------- ### lastIndexOf(string, ch) Source: https://koreader.rocks/doc/modules/util.html Gets the last index of a character in a string. ```APIDOC ## lastIndexOf(string, ch) ### Description Gets the last index of a character in a string (similar to strrchr). To find a dot (.), it must be escaped. ### Parameters - **string** (string) - Required - The string to search. - **ch** (string) - Required - The character to find. ### Returns - **int** - The index of the last occurrence or -1 if not found. ``` -------------------------------- ### Using ui.size Constants Source: https://koreader.rocks/doc/modules/ui.size.html Demonstrates how to import the ui.size module and apply its predefined constants to widget properties like radius, bordersize, padding, and margin. ```APIDOC ## Using ui.size Constants ### Description Import the `ui.size` module to access standardized dimension constants for consistent UI layout. ### Usage Example ```lua local Size = require("ui/size") local frame -- example widget frame = FrameContainer:new{ radius = Size.radius.window, bordersize = Size.border.window, padding = Size.padding.default, margin = Size.margin.default, VerticalGroup:new{ -- widget content } } ``` ``` -------------------------------- ### Initialize and display a ProgressWidget Source: https://koreader.rocks/doc/modules/ui.widget.progresswidget.html Create a new progress bar instance with specific dimensions and an initial percentage, then display it using the UIManager. ```lua local foo_bar = ProgressWidget:new{ width = Screen:scaleBySize(400), height = Screen:scaleBySize(10), percentage = 50/100, } UIManager:show(foo_bar) ``` -------------------------------- ### migrate(key, title, help, info, the, folder_only, new_file) Source: https://koreader.rocks/doc/modules/koplugin.coverimage.html Creates a menu entry for setting a reader setting key for a path or file. ```APIDOC ## migrate(key, title, help, info, the, folder_only, new_file) ### Description Provides a menu entry to configure a specific G_reader setting key for a path or file selection. ### Parameters - **key** (string) - The G_reader setting key to be updated. - **title** (string) - The title shown in the menu. - **help** (string) - The help text shown in the menu. - **info** (string) - The info text shown in the menu (use %1 to display the current key value). - **the** (string) - The default value. - **folder_only** (boolean) - If true, only folders can be selected. - **new_file** (boolean) - If true, a new filename can be entered. ``` -------------------------------- ### KoptInterface:getTextFromBoxes Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get text and text boxes between two positions. ```APIDOC ## KoptInterface:getTextFromBoxes(boxes, pos0, pos1) ### Description Get text and text boxes between `pos0` and `pos1`. ### Parameters - **boxes** - The boxes collection. - **pos0** - The start position. - **pos1** - The end position. ``` -------------------------------- ### KoptInterface:getWordFromBoxes Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get word and word box around position. ```APIDOC ## KoptInterface:getWordFromBoxes(boxes, pos) ### Description Get word and word box around `pos`. ### Parameters - **boxes** - The boxes collection. - **pos** - The position. ``` -------------------------------- ### CacheSQLite:get Source: https://koreader.rocks/doc/modules/cachesqlite.html Retrieves an object without updating access time. ```APIDOC ## CacheSQLite:get(key) ### Description Retrieves an object if it is in the cache without updating its access time. ### Parameters - **key** (string) - Required ### Returns - **any** - The cached object ``` -------------------------------- ### LuaData:open Source: https://koreader.rocks/doc/modules/luadata.html Creates a new LuaData instance. ```APIDOC ## LuaData:open(file_path, name) ### Description Creates a new LuaData instance. ### Parameters - **file_path** - Required - The path to the data file. - **name** - Optional - Backwards compatibility parameter. ``` -------------------------------- ### Initialize and display an InputDialog Source: https://koreader.rocks/doc/modules/ui.widget.inputdialog.html Create a new InputDialog instance with custom title, input hint, and button callbacks, then display it using the UIManager. ```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() ``` -------------------------------- ### KoptInterface:getWordFromNativePosition Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get word and word box from position in native page. ```APIDOC ## KoptInterface:getWordFromNativePosition(doc, boxes, pos) ### Description Get word and word box from position in native page. ### Parameters - **doc** - The document object. - **boxes** - The boxes collection. - **pos** - The position. ``` -------------------------------- ### Initialize and display an IconWidget Source: https://koreader.rocks/doc/modules/ui.widget.iconwidget.html Create a new instance of IconWidget by specifying the icon name and optional rendering properties, then display it using the UIManager. ```lua local IconWidget = require("ui/widget/iconwidget") local icon_widget = IconWidget:new{ icon = "check", -- Which corresponds to resources/icons/mdlight/check.svg dim = true, alpha = true } UIManager:show(icon_widget) ``` -------------------------------- ### KoptInterface:getWordFromReflowPosition Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get word and word box from position in reflowed page. ```APIDOC ## KoptInterface:getWordFromReflowPosition(doc, boxes, pos) ### Description Get word and word box from position in reflowed page. ### Parameters - **doc** - The document object. - **boxes** - The boxes collection. - **pos** - The position. ``` -------------------------------- ### Initialize a ListView widget Source: https://koreader.rocks/doc/modules/ui.widget.listview.html Create a new ListView instance with defined dimensions, a page update callback, and a collection of child widgets. ```lua local list_view = ListView:new{ height = Screen:scaleBySize(400), width = Screen:scaleBySize(200), page_update_cb = function(curr_page_num, total_pages) -- This callback function will be called whenever a page -- turn event is triggered. You can use it to update -- information on the parent widget. end, items = { FrameContainer:new{ bordersize = 0, background = Blitbuffer.COLOR_WHITE, TextWidget:new{ text = "foo", face = Font:getFace("cfont"), } }, FrameContainer:new{ bordersize = 0, background = Blitbuffer.COLOR_LIGHT_GRAY, TextWidget:new{ text = "bar", face = Font:getFace("cfont"), } }, -- You can add as many widgets as you want here... } } ``` -------------------------------- ### Input:open Source: https://koreader.rocks/doc/modules/device.input.html Opens an input device by path. ```APIDOC ## Input:open(path, name) ### Description Wrapper for our Lua/C input module's open. ### Parameters - **path** (string) - Required - The path to the device. - **name** (string) - Optional - Used for logging purposes. ``` -------------------------------- ### KoptInterface:getOCRText Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get text from OCR providing selected text boxes. ```APIDOC ## KoptInterface:getOCRText(doc, pageno, tboxes) ### Description Get text from OCR providing selected text boxes. ### Parameters - **doc** - The document object. - **pageno** - The page number. - **tboxes** - The text boxes. ``` -------------------------------- ### KoptInterface:getOCRWord Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get word from OCR providing selected word box. ```APIDOC ## KoptInterface:getOCRWord(doc, pageno, wbox) ### Description Get word from OCR providing selected word box. ### Parameters - **doc** - The document object. - **pageno** - The page number. - **wbox** - The word box. ``` -------------------------------- ### LuaDefaults:open Source: https://koreader.rocks/doc/modules/luadefaults.html Opens a settings file at the specified path. ```APIDOC ## LuaDefaults:open(path) ### Description Opens a settings file. ### Parameters - **path** - The file path to open. ``` -------------------------------- ### KoptInterface:getNativeTextBoxes Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get text boxes in native page via rectmaps. ```APIDOC ## KoptInterface:getNativeTextBoxes(doc, pageno) ### Description Get text boxes in native page via rectmaps in koptcontext. ### Parameters - **doc** - The document object. - **pageno** - The page number. ``` -------------------------------- ### KeyValuePage Initialization Source: https://koreader.rocks/doc/modules/ui.widget.keyvaluepage.html How to instantiate and display a KeyValuePage widget with custom data and callbacks. ```APIDOC ## KeyValuePage:new ### Description Creates a new instance of the KeyValuePage widget to display a list of key-value pairs. ### Parameters - **title** (string) - The title displayed at the top of the page. - **kv_pairs** (table) - A list of items to display. Items can be a table of two strings for key-value pairs, a string containing dashes for a separator, or a table with a callback function for interactive elements. ### Example ```lua local Foo = KeyValuePage:new{ title = "Statistics", kv_pairs = { {"Current period", "00:00:00"}, "----------------------------", {"Page to read", "5"}, {"Time to read", "00:01:00"}, {"Press me", "will invoke the callback", callback = function() print("hello") end }, }, } UIManager:show(Foo) ``` ``` -------------------------------- ### KoptInterface:getReflowedTextBoxes Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get text boxes in reflowed page via rectmaps. ```APIDOC ## KoptInterface:getReflowedTextBoxes(doc, pageno) ### Description Get text boxes in reflowed page via rectmaps in koptcontext. ### Parameters - **doc** - The document object. - **pageno** - The page number. ``` -------------------------------- ### Input:open Source: https://koreader.rocks/doc/modules/device.input.html Opens an input device by path and name. ```APIDOC ## Input:open(path, name) ### Description Wrapper for the Lua/C input module's open function to initialize an input device. ### Parameters - **path** (string) - The file system path to the input device. - **name** (string) - The name identifier for the input device. ``` -------------------------------- ### LuaData:append Source: https://koreader.rocks/doc/modules/luadata.html Appends settings to disk. ```APIDOC ## LuaData:append(data) ### Description Appends settings to disk. ### Parameters - **data** - Required - The data to append. ``` -------------------------------- ### Initialize and display a TextBoxWidget Source: https://koreader.rocks/doc/modules/ui.widget.textboxwidget.html Create a new instance of TextBoxWidget with a specified font and text content, then display it using the UIManager. ```lua local Foo = TextBoxWidget:new{ face = Font:getFace("cfont", 25), text = 'We can show multiple lines.\nFoo.\nBar.', -- width = math.floor(Screen:getWidth() * 2/3), } UIManager:show(Foo) ``` -------------------------------- ### KoptInterface:getPageBlock Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get page regions in native page via optical method. ```APIDOC ## KoptInterface:getPageBlock(doc, pageno, x, y) ### Description Get page regions in native page via optical method. ### Parameters - **doc** - The document object. - **pageno** - The page number. - **x** - X coordinate. - **y** - Y coordinate. ``` -------------------------------- ### Initialize and display a KeyValuePage Source: https://koreader.rocks/doc/modules/ui.widget.keyvaluepage.html Create a new KeyValuePage instance with a title and a list of key-value pairs, then display it using UIManager. ```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) ``` -------------------------------- ### Initialize a Button Widget Source: https://koreader.rocks/doc/modules/ui.widget.button.html Create a new button instance by requiring the module and passing configuration parameters to the new method. ```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:getReflowedTextBoxesFromScratch Source: https://koreader.rocks/doc/modules/document.koptinterface.html Get text boxes in reflowed page via optical method. ```APIDOC ## KoptInterface:getReflowedTextBoxesFromScratch(doc, pageno) ### Description Get text boxes in reflowed page via optical method. Done by OCR pre-processing in Tesseract and Leptonica. ### Parameters - **doc** - The document object. - **pageno** - The page number. ``` -------------------------------- ### Constructing and serializing a dependency graph Source: https://koreader.rocks/doc/modules/depgraph.html Demonstrates how to initialize a new DepGraph, add nodes with their dependencies, and serialize the resulting graph. ```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'} ``` -------------------------------- ### ui.widget.networksetting Source: https://koreader.rocks/doc/modules/ui.widget.networksetting.html Initializes and displays the network setting widget with a list of networks and associated callbacks. ```APIDOC ## ui.widget.networksetting ### Description Displays a network management widget that lists available networks and provides callbacks for connection and disconnection events. ### Usage ```lua UIManager:show(require("ui/widget/networksetting"):new{ network_list = network_list, connect_callback = function() -- Called on successful connection attempt end, disconnect_callback = function() -- Called after a disconnect attempt end, }) ``` ### Parameters - **network_list** (table) - Required - A list of network objects, each containing: - **ssid** (string) - The network name. - **signal_level** (number) - The signal strength in dBm. - **signal_quality** (number) - The signal quality percentage. - **flags** (string) - Security flags (e.g., [WPA2-PSK-CCMP]). - **password** (string) - Optional password for the network. - **connected** (boolean) - Optional connection status. - **connect_callback** (function) - Optional - Callback triggered upon a successful connection. - **disconnect_callback** (function) - Optional - Callback triggered after a disconnection attempt. ``` -------------------------------- ### InputDialog:new Source: https://koreader.rocks/doc/modules/ui.widget.inputdialog.html Creates a new instance of an InputDialog with specified configuration options. ```APIDOC ## InputDialog:new(options) ### Description Creates and configures a new InputDialog widget instance. ### Parameters - **options** (table) - Required - Configuration table containing: - **title** (string) - Dialog title - **input** (string) - Default input value - **input_hint** (string) - Placeholder text - **description** (string) - Description text shown above the input - **buttons** (table) - List of button configurations - **fullscreen** (boolean) - Enable full-screen mode - **allow_newline** (boolean) - Allow multi-line input - **save_callback** (function) - Callback for save action - **reset_callback** (function) - Callback for reset action ``` -------------------------------- ### Display a MultiConfirmBox Source: https://koreader.rocks/doc/modules/ui.widget.multiconfirmbox.html Shows how to instantiate and display a MultiConfirmBox with custom text and callback functions for two distinct choices. ```lua UIManager:show(MultiConfirmBox:new{ text = T( _("Set %1 as fallback font?"), face), choice1_text = _("Default"), choice1_callback = function() -- set as default font end, choice2_text = _("Fallback"), choice2_callback = function() -- set as fallback font end, }) ``` -------------------------------- ### Initialize WakeupMgr instance Source: https://koreader.rocks/doc/modules/device.wakeupmgr.html Create a new instance of the WakeupMgr, optionally specifying the RTC device path if the default /dev/rtc0 is not appropriate. ```lua local WakeupMgr = require("device/wakeupmgr") local wakeup_mgr = WakeupMgr:new{ -- The default is /dev/rtc0, but some devices have more than one RTC. -- You might therefore need to use /dev/rtc1, etc. dev_rtc = "/dev/rtc0", } ``` -------------------------------- ### Basic Logging Usage Source: https://koreader.rocks/doc/modules/logger.html Initialize the logger and record messages at different severity levels. ```lua local logger = require("logger") logger.info("Something happened.") logger.err("House is on fire!") ``` -------------------------------- ### Set Dirty Region for Repaint Source: https://koreader.rocks/doc/modules/ui.uimanager.html Examples of triggering a widget repaint with different refresh types and optional geometry regions. ```lua UIManager:setDirty(self.widget, "partial") UIManager:setDirty(self.widget, "partial", Geom:new{x=10,y=10,w=100,h=50}) UIManager:setDirty(self.widget, function() return "ui", self.someelement.dimen end) ``` -------------------------------- ### LuaSettings:open Source: https://koreader.rocks/doc/modules/luasettings.html Opens a settings file for reading and writing. ```APIDOC ## LuaSettings:open(file_path) ### Description Opens a settings file. ### Parameters - **file_path** (string) - Required - The path to the settings file. ``` -------------------------------- ### Initialize ProgressbarDialog Source: https://koreader.rocks/doc/modules/ui.widget.progressbardialog.html Create a new instance of the progress bar dialog. Ensure at least one of title, subtitle, or progress_max is provided. ```lua local progressbar_dialog = ProgressbarDialog:new { title = nil, subtitle = nil, progress_max = nil refresh_time_seconds = 3, } ``` -------------------------------- ### Initialize and display a CheckButton Source: https://koreader.rocks/doc/modules/ui.widget.checkbutton.html Demonstrates how to require the CheckButton module, instantiate it within a parent container, and display it using the UIManager. ```lua local CheckButton = require("ui/widget/CheckButton") local parent_widget = OverlapGroup:new{} table.insert(parent_widget, CheckButton:new{ text = _("Show password"), callback = function() end, }) UIManager:show(parent_widget) ``` -------------------------------- ### Using ui.size constants in a widget Source: https://koreader.rocks/doc/modules/ui.size.html Demonstrates how to import the ui.size module and apply its predefined constants to widget properties like radius, bordersize, padding, and margin. ```lua local Size = require("ui/size") local frame -- just an example widget frame = FrameContainer:new{ radius = Size.radius.window, bordersize = Size.border.window, padding = Size.padding.default, margin = Size.margin.default, VerticalGroup:new{ -- etc } } ``` -------------------------------- ### Registering an action at runtime Source: https://koreader.rocks/doc/modules/dispatcher.html Demonstrates how to register a new action with the dispatcher using the registerAction method. ```lua function Hello:onDispatcherRegisterActions() Dispatcher:registerAction("helloworld_action", {category="none", event="HelloWorld", title=_("Hello World"), general=true}) end function Hello:init() self:onDispatcherRegisterActions() end ``` -------------------------------- ### NumberPickerWidget:new Source: https://koreader.rocks/doc/modules/ui.widget.numberpickerwidget.html Initializes a new NumberPickerWidget instance with specific configuration options. ```APIDOC ## NumberPickerWidget:new ### Description Creates a new instance of the NumberPickerWidget. ### Parameters - **precision** (string) - Optional - Format string for the number (e.g., "%02d" for integers, "%.2f" for decimals). - **value** (number) - Optional - Initial value. - **value_min** (number) - Optional - Minimum allowed value. - **value_max** (number) - Optional - Maximum allowed value. - **value_step** (number) - Optional - Increment/decrement step size. - **value_hold_step** (number) - Optional - Step size when holding the button. - **wrap** (boolean) - Optional - Whether the value wraps around at min/max boundaries. ``` -------------------------------- ### Configure full screen text editor options Source: https://koreader.rocks/doc/modules/ui.widget.inputdialog.html Set these properties in the InputDialog configuration to enable full screen editing mode. ```lua fullscreen = true, -- No need to provide any height and width. condensed = true, allow_newline = true, cursor_at_end = false, -- and one of these: add_scroll_buttons = true, add_nav_bar = true, ``` -------------------------------- ### UIManager:run Source: https://koreader.rocks/doc/modules/ui.uimanager.html The main loop of the UI controller. ```APIDOC ## UIManager:run() ### Description This is the main loop of the UI controller, managing input events and delegating them to dialogs. ``` -------------------------------- ### SQLite3 Database Operations in Lua Source: https://koreader.rocks/doc/topics/DataStore.md.html Demonstrates opening a connection, executing SQL commands, using prepared statements, and querying data using the lua-ljsqlite3 library. ```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 a NumberPickerWidget Source: https://koreader.rocks/doc/modules/ui.widget.numberpickerwidget.html Create a new instance of the number picker with specific constraints such as range, step size, and display precision. ```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, } ``` -------------------------------- ### Verify Remote Configuration Source: https://koreader.rocks/doc/topics/Collaborating_with_Git.md.html Displays the currently configured remote repositories. ```bash git remote -v show ``` -------------------------------- ### VocabBuilder:init Source: https://koreader.rocks/doc/modules/koplugin.vocabbuilder.html Initializes the VocabBuilder plugin and adds the corresponding item to the main menu. ```APIDOC ## VocabBuilder:init() ### Description Initializes the VocabBuilder plugin. This function is responsible for adding the VocabBuilder item to the main menu of the application. ### Signature `VocabBuilder:init()` ``` -------------------------------- ### Accessing child settings Source: https://koreader.rocks/doc/modules/luasettings.html Demonstrates how to save a table of settings and access them as a child object. ```lua Settings:saveSetting("key", { a = "b", c = true, d = false, }) local child = Settings:child("key") child:readSetting("a") -- result "b" ``` -------------------------------- ### Iterate over widgets Source: https://koreader.rocks/doc/modules/ui.uimanager.html Note that VirtualKeyboard can be instantiated multiple times and is a modal, so multiple instances may appear at the top of the stack. ```lua so don't be surprised if you find a couple of instances of it at the top ;). ``` -------------------------------- ### Initialize AlphaContainer Source: https://koreader.rocks/doc/modules/ui.widget.container.alphacontainer.html Create an AlphaContainer instance with a defined opacity and a child widget. ```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 } } ```