Skip to content
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ CrossInk 2.x bridge and the later stable BookSync releases become available (`xt

## Screen and widget performance budgets

Local optional widgets inherit one-row/16 KiB budgets too: companion-owned vocabulary selection
and reading messages; native frontlight scalars only in Library. Paint never scans local history.

Nested group covers and Series next-book previews count as rows in the caller budget;
never hide multiple display records behind a single summary row. Companion materialization
owns their ordering, counts and status labels.
Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ Generated support counts (settings included): ✅ supported, 🟡 partial, ❌ m

| Platform | ✅ | 🟡 | ❌ | ➖ |
|---|---:|---:|---:|---:|
| Android (M8C / Boox) | 76 | 13 | 1 | 3 |
| X4 Pro | 55 | 12 | 14 | 12 |
| X4 classic | 54 | 12 | 14 | 13 |
| X3 | 20 | 16 | 44 | 13 |
| Android (M8C / Boox) | 76 | 14 | 1 | 3 |
| X4 Pro | 55 | 12 | 15 | 12 |
| X4 classic | 54 | 12 | 15 | 13 |
| X3 | 20 | 16 | 45 | 13 |
<!-- feature-counts:end -->

## Releases
Expand Down
1 change: 1 addition & 0 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ CrossInk 2.x only; 1.6 is retired).

| Outcome | Platforms | Status |
|---|---|---|
| Word of the day, local Reading buddy and hardware Light picker widgets; Highlight and A year ago await authorized server snapshots. | Android; X4 Pro/X4/X3 deferred to firmware | building (device acceptance pending) |
| Server-free Android catalog operations: companion-owned covers, refresh, copies, recommendations and end-of-book snapshots and commands. | Android; X4 Pro, X4, X3 later under Android-first ruling | building: covers, mirror planning and query/store reads migrated; copies, grouping, recommendations and finish pending |
| Independent optional account, sync and OPDS logins, encrypted credentials, origin-aware sign-out and account-wide reading statistics through the library interface. | Android; X4 Pro, X4, X3 later | building (Android F12-K foundation and F12-N plugin screens implemented; device acceptance and firmware follow) |
| Configure one Book list widget with presets, paged counted sources and local Custom filters in the Home editor. | Android building; X4 Pro, X4, X3 follow Android | building (approved design rev 16; device acceptance pending) |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class LibraryReadModel(
private val fallbackReadingStats: ((String) -> RemoteReadingStats?)? = null,
private val accountState: () -> Map<String, Any?> = { mapOf("signedIn" to false) },
private val accountStats: (String) -> Map<*, *>? = { null },
private val vocabulary: () -> java.io.File = { java.io.File(SleepScreen.dir().parentFile, "vocabulary_builder.sqlite3") },
private val adapter: ServerAdapter? = null,
) {
companion object {
Expand All @@ -32,10 +33,11 @@ class LibraryReadModel(
java.io.File(store.root.parentFile?.parentFile?.parentFile ?: store.root,it)
} + DeviceStorage.downloadRoot(store.root)) else adapter ?: ServerAdapters.forStore(store, clock = clock,
fallbackReadingStats = fallbackReadingStats, accountState = accountState, accountStats = accountStats)
val localStats by lazy { readingStats() }
val storage by lazy { DeviceStorage(store, projection) }
val power by lazy { battery() }
val account by lazy { if (local) null else accountStats(owner) }
val stats by lazy { ReadingStats.display(AccountStats.combine(readingStats(), if (local) null else projection.cachedReadingStats(owner), account, clock()), clock(), AccountStats.zone(account)) }
val stats by lazy { ReadingStats.display(AccountStats.combine(localStats, if (local) null else projection.cachedReadingStats(owner), account, clock()), clock(), AccountStats.zone(account)) }
for (encoded in requests) {
val start = System.nanoTime()
val request = encoded as? String ?: continue
Expand All @@ -48,6 +50,9 @@ class LibraryReadModel(
"reader.controls" -> ReaderControls.project(args["native"] as? Map<*, *> ?: emptyMap<Any, Any>())

"reading.stats" -> stats
"local.word" -> LocalWidgets.word(vocabulary(), clock())
"local.buddy" -> LocalWidgets.buddy(localStats)
"local.light" -> LocalWidgets.light(args["native"] as? Map<*, *> ?: emptyMap<Any, Any>())
"device.clock" -> ClockWidget.snapshot(clock(), power, twelve = args["twelve_hour"] == true)
"mode-estimates" -> BatteryEstimate.modeRows(power, (args["limit"] as? Number)?.toInt() ?: 3)
"battery" -> power
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: MIT
package net.fledgewing.orbitcompanion

import java.io.File
import java.time.Instant
import java.time.ZoneId

/** Local projections only. Borrowed vocabulary is read-only, on the existing worker. */
object LocalWidgets {
private fun row(state: String, message: String) = mapOf<String, Any?>(
"state" to state, "message" to LuaValue.str(message), "row_count" to 1,
"freshness" to mapOf("saved" to true, "origin" to "local-reader"))

fun word(file: File, now: Long): Map<String, Any?> {
if (!file.isFile) return row("empty", "Look up a word while reading.")
return try { AndroidSql(file, readOnly = true).use { word(it, now) } }
catch (e: Exception) { if (e is InterruptedException) throw e; row("error", "Vocabulary unavailable") }
}
fun word(db: Sql, now: Long, zone: ZoneId = ZoneId.systemDefault()): Map<String, Any?> {
val day = Instant.ofEpochSecond(now).atZone(zone).toLocalDate().toEpochDay()
// One SELECT uses one read snapshot, with at most one decoded record.
return db.query("SELECT substr(v.word,1,96),substr(v.prev_context,1,120),substr(v.next_context,1,120),substr(t.name,1,100) FROM vocabulary v LEFT JOIN title t ON t.id=v.title_id ORDER BY v.word LIMIT 1 OFFSET (SELECT ((? % max(count(*),1)) + max(count(*),1)) % max(count(*),1) FROM vocabulary)", day) {
row("ready", "On this reader") + mapOf(
"word" to LuaValue.str(it.text(0).orEmpty()),
"context" to LuaValue.str(listOfNotNull(it.text(1),it.text(0),it.text(2)).joinToString(" ").replace('\n',' ')),
"source" to LuaValue.str(it.text(3) ?: "Source unavailable"))
}.firstOrNull() ?: row("empty", "Look up a word while reading.")
}

fun buddy(stats: Map<String, Any?>): Map<String, Any?> {
val records = stats["records"] as? Map<*, *>
val streak = (records?.get("streak") as? Number)?.toLong()
val pages = (records?.get("recorded_pages") as? Number)?.toLong()
return when {
stats["state"] == "error" -> row("error", "Reading activity unavailable")
pages == null || pages == 0L -> row("empty", "Your next chapter is waiting.")
streak != null && streak > 0 -> row("ready", "$streak day reading streak · On this reader")
else -> row("ready", "Welcome back. Your next chapter is waiting.")
}
}
fun light(native: Map<*, *>): Map<String, Any?> {
val level = (native["level"] as? Number)?.toInt()?.takeIf { it in 0..100 }
return if (native["supported"] != true || level == null) row("unavailable", "Frontlight unavailable on this reader")
else row("ready", "Light · $level%") + mapOf("level" to level)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// SPDX-License-Identifier: MIT
package net.fledgewing.orbitcompanion

import org.junit.Assert.*
import org.junit.Test
import java.nio.file.Files
import java.time.ZoneOffset

class LocalWidgetsTest {
@Test fun oneBatchPublishesOnlyLocalRowsWithoutServerProjection() {
val dir=Files.createTempDirectory("local-widget-batch").toFile()
try { JdbcSql(java.io.File(dir,"views.sqlite3")).use { sql ->
LibraryReadModel.initialize(sql)
val store=object: ProjectionStore {
override fun db()=sql
override val root=dir
override fun meta(k:String)=if(k=="owner") "fixture" else null
override fun <T> transaction(block:()->T):T=sql.transaction(block)
override fun close()=Unit
}
val adapter=object:ServerAdapter {
override val id="fixture"
override fun project(owner:String,request:Map<*,*>):Map<String,Any?> = error("no server projection")
}
var reads=0
val model=LibraryReadModel(store,{86400},{},readingStats={reads++; mapOf("state" to "empty")},
vocabulary={java.io.File(dir,"missing.sqlite3")},adapter=adapter)
val requests=listOf("local.word","local.buddy","local.light").map { op ->
String(LuaValue.encode(mapOf("op" to op,"limit" to 1,"bytes" to 16384)),Charsets.ISO_8859_1)
}
assertTrue(model.publish("fixture",requests)); assertEquals(1,reads)
val rows=sql.query("SELECT body FROM library_views") { it.bytes(0)!! }
assertEquals(3,rows.size)
for(body in rows) {
assertTrue(body.size<=16384)
val result=LuaValue.parse(body) as Map<*,*>
assertEquals(1L,result["row_count"])
}
assertFalse(model.publish("another-owner",requests))
assertTrue(model.publish(DeviceLibrary.OWNER,requests))
assertEquals(2,reads)
assertEquals(3,sql.query("SELECT body FROM library_views WHERE owner=?",DeviceLibrary.OWNER) { it.bytes(0)!! }.size)
} } finally { dir.deleteRecursively() }
}
@Test fun vocabularyIsOneBoundedDailyRecordWithContextAndSource() {
val dir=Files.createTempDirectory("local-widget").toFile()
try { JdbcSql(java.io.File(dir,"vocabulary.sqlite3")).use { db ->
db.exec("CREATE TABLE title(id INTEGER PRIMARY KEY,name TEXT)")
db.exec("CREATE TABLE vocabulary(word TEXT PRIMARY KEY,title_id INTEGER,prev_context TEXT,next_context TEXT)")
assertEquals("empty",LocalWidgets.word(db,86400,ZoneOffset.UTC)["state"])
db.exec("INSERT INTO title VALUES(1,'The Moon')")
db.exec("INSERT INTO vocabulary VALUES('lantern',1,'the','room')")
val a=LocalWidgets.word(db,86400,ZoneOffset.UTC)
assertEquals("lantern",a["word"]); assertEquals("the lantern room",a["context"]); assertEquals("The Moon",a["source"])
assertEquals(a,LocalWidgets.word(db,86401,ZoneOffset.UTC))
db.exec("INSERT INTO vocabulary VALUES('anchor',NULL,?,?)","x".repeat(10000),"y".repeat(10000))
val b=LocalWidgets.word(db,2*86400,ZoneOffset.UTC)
assertEquals("anchor",b["word"]); assertEquals("Source unavailable",b["source"])
assertTrue(LuaValue.encode(b).size<16384); assertEquals(1,b["row_count"])
assertEquals(2L,db.query("SELECT count(*) FROM vocabulary") { it.long(0) }.first())
} } finally { dir.deleteRecursively() }
}
@Test fun missingVocabularyLightCapabilityAndLocalBuddyStates() {
assertEquals("empty",LocalWidgets.word(java.io.File("missing-widget-vocabulary"),1)["state"])
assertEquals("unavailable",LocalWidgets.light(emptyMap<Any,Any>())["state"])
assertEquals("unavailable",LocalWidgets.light(mapOf("supported" to true,"level" to 101))["state"])
assertEquals(LuaValue.str("Light · 40%"),LocalWidgets.light(mapOf("supported" to true,"level" to 40))["message"])
assertEquals("empty",LocalWidgets.buddy(emptyMap())["state"])
assertEquals("error",LocalWidgets.buddy(mapOf("state" to "error"))["state"])
val buddy=LocalWidgets.buddy(mapOf("records" to mapOf("streak" to 3,"recorded_pages" to 20)))
assertEquals(LuaValue.str("3 day reading streak · On this reader"),buddy["message"])
assertEquals("ready",buddy["state"])
}
}
7 changes: 6 additions & 1 deletion android/koreader/orbit.koplugin/ko/home_host.lua
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,9 @@ function HomeHost.create()
self.signatures[p.instance]=signature
if previous[p.instance] ~= signature then self.changed_rects[#self.changed_rects+1]=rect end
if self.list_layout then self.list_result=result end
local snapshot=HomeHostPlan.snapshot(result,caps.account)
local snapshotAccount=caps.account
if WidgetRegistry[p.widget].localOnly then snapshotAccount=nil end
local snapshot=HomeHostPlan.snapshot(result,snapshotAccount)
local interval=WidgetRegistry[p.widget].refreshSeconds
if interval then refreshDelay=math.min(refreshDelay or interval,interval) end
local dispatch=function(action,row) self:dispatch(action,row,p) end
Expand Down Expand Up @@ -207,6 +209,9 @@ function HomeHost.create()
function Host:dispatch(action,row,p)
if action == "setup" then AccountView.open()
elseif action == "retry" then Library.retry(); self:rebuild(); UIManager:setDirty(self,"ui")
elseif action == "word-lookup" or action == "light-down" or action == "light-up" then
Library.localWidgetAction(action,row)
if action~="word-lookup" then self:rebuild(); UIManager:setDirty(self,"ui") end
elseif action == "battery" then BatteryUI.show()
elseif action == "storage" then StorageUI.show()
elseif action == "collections" then StorageUI.show("collections",function(row)
Expand Down
66 changes: 66 additions & 0 deletions android/koreader/orbit.koplugin/ko/local_widgets.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
-- SPDX-License-Identifier: AGPL-3.0-or-later
-- Local native access stays behind Library; the host alone requests projections.
function Library.localWidgetNeed(id)
local need={op="local."..id,limit=1}
if id=="light" then
local device=require("device")
local supported=device.hasFrontlight and device:hasFrontlight() or false
local power=supported and device:getPowerDevice()
need.native={supported=supported,level=power and power:frontlightIntensity()}
end
return need
end
function Library.localWidgetAction(action,value)
if action=="word-lookup" then
if type(value)~="string" or #value>384 or value=="" then return false end
local ui=liveUI() or require("apps/filemanager/filemanager").instance
if ui and ui.dictionary then ui.dictionary:onLookupWord(value,true); return true end
return false
end
if action=="light-down" or action=="light-up" then
local need=Library.localWidgetNeed("light")
if not need.native.supported or not need.native.level then return false end
return Library.readerControl({},"light",math.max(0,math.min(100,need.native.level+(action=="light-up" and 10 or -10))))
end
return false
end
LocalWidgets = {}
function LocalWidgets.render(p,snapshot,dispatch,rect)
local finish=Budgets.span("local-widget."..p.widget,now_s,log)
assert(Budgets.check(Budgets.get("widgets",p.widget),{rows=1,bytes=snapshot.bytes,snapshotBytes=snapshot.bytes,spawns=0,network=0,roundTrips=0}))
local plan=LocalWidgetPlan.build(p.widget,snapshot)
local scale=function(n) return Device.screen:scaleBySize(n) end
local w,h=rect.w-2,rect.h-2
local pad=scale(10)
local c=HomeWidgets.canvas(w,h)
HomeWidgets.text(c,p.widget=="light" and plan.ready and plan.message or _(plan.title),pad,pad,w-2*pad,18,false,true)
if p.widget=="word" and plan.word then
if p.h==1 then
HomeWidgets.button(c,plan.word.." ›",pad,h-pad-scale(50),w-2*pad,scale(50),function() dispatch("word-lookup",plan.word) end)
else
HomeWidgets.text(c,plan.word,pad,pad+scale(30),w-2*pad,22,false,true)
HomeWidgets.text(c,plan.context or "",pad,pad+scale(60),w-2*pad,14)
HomeWidgets.text(c,plan.source or "Source unavailable",pad,pad+scale(83),w-2*pad,13)
HomeWidgets.button(c,_("Look up ›"),pad,h-pad-scale(50),w-2*pad,scale(50),function() dispatch("word-lookup",plan.word) end)
end
elseif p.widget=="light" and plan.ready then
local bw=math.floor((w-3*pad)/2)
if p.h>1 then HomeWidgets.text(c,plan.message,pad,pad+scale(36),w-2*pad,22,false,true) end
HomeWidgets.button(c,"−",pad,h-pad-scale(50),bw,scale(50),function() dispatch("light-down") end)
HomeWidgets.button(c,"+",2*pad+bw,h-pad-scale(50),bw,scale(50),function() dispatch("light-up") end)
else
-- A single bounded line in compact cards; no hidden history or render reads.
HomeWidgets.text(c,_(plan.message),pad,pad+scale(32),w-2*pad,14)
if plan.retry then
if p.h==1 then table.remove(c) end -- compact message is itself the retry target
HomeWidgets.button(c,_(p.h==1 and plan.message or "Retry"),pad,h-pad-scale(50),w-2*pad,scale(50),function() dispatch("retry") end)
end
end
finish()
return HomeWidgets.ui().Frame:new{padding=0,margin=0,bordersize=1,c}
end
for _,id in ipairs({"word","light","buddy"}) do
local name=id
HomeWidgets.register(name,LocalWidgets.render,function() return Library.localWidgetNeed(name) end)
WidgetRegistry[name].renderers={['android-tablet']=LocalWidgets.render}
end
2 changes: 1 addition & 1 deletion android/koreader/orbit.koplugin/logic/budgets.lua
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Budgets.screens["editor-picker"].drawNodes = 24
Budgets.screens["filter-picker"] = budget(24, 16384, 50)
Budgets.libraryWindow = budget(32, 32768, 30)
for _, id in ipairs({"continue-reading", "booklist", "lists", "library", "battery", "this-week",
"year-in-reading", "when-you-read", "reading-records", "clock"}) do
"year-in-reading", "when-you-read", "reading-records", "clock", "word", "light", "buddy"}) do
Budgets.widgets[id] = budget(id == "booklist" and 12 or id == "lists" and 8 or 1, 16384, 50)
end
-- Library summary + local storage summary are two materialized rows in one batch.
Expand Down
14 changes: 14 additions & 0 deletions android/koreader/orbit.koplugin/logic/local_widgets.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
-- SPDX-License-Identifier: AGPL-3.0-or-later
-- Bounded presentation only; selection and reading messages belong to the companion.
LocalWidgetPlan = {}
function LocalWidgetPlan.build(id,snapshot)
local d=snapshot.data or {}
local state=d.state or snapshot.state
local ready=state=="ready" or state=="offline-with-data"
local fallback={loading="Loading…",error="Couldn't load this widget",empty=id=="word" and "Look up a word while reading." or id=="light" and "Frontlight unavailable on this reader" or "Your next chapter is waiting.",
["offline-without-data"]="Not saved yet",["not-saved"]="Not saved yet",unavailable="Frontlight unavailable on this reader"}
return {title=WidgetRegistry[id].name,state=state,ready=ready,
message=ready and (d.message or "On this reader") or (fallback[state] or "Unavailable"),
word=ready and d.word,context=ready and d.context,source=ready and d.source,
retry=state=="error" or state=="loading" or state=="offline-without-data" or state=="not-saved"}
end
8 changes: 8 additions & 0 deletions android/koreader/orbit.koplugin/logic/widget_registry.lua
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ widget("year-in-reading", "reading.stats", {{4,3},{4,2}}, {{2,4},{2,3}})
widget("when-you-read", "reading.stats", {{2,2},{2,3},{2,1},{4,1}}, {{2,1},{2,2},{1,2}})
widget("reading-records", "reading.stats", {{3,2},{2,3},{2,2},{4,1}}, {{2,2},{2,3}})
widget("clock", "device.clock", {{1,2},{2,1},{2,2}}, {{2,2},{1,1},{2,1}})
for _,id in ipairs({"word","light","buddy"}) do
widget(id, "local."..id, {{2,1},{2,2}}, {{2,1}})
WidgetRegistry[id].localOnly=true
end
WidgetRegistry.word.refreshSeconds = 60 -- daily selection is companion-owned
WidgetRegistry.clock.refreshSeconds = 60 -- host-owned refresh, only while visible
-- The Library tile also displays local storage; both small needs share its budget and
-- are part of the host's single batched snapshot, never separate render-time round trips.
Expand All @@ -36,6 +41,9 @@ local descriptions={
["year-in-reading"]={"Year in reading","A calendar of your reading days."},
["when-you-read"]={"When you read","Your reading by hour of day."},
["reading-records"]={"Reading records","Your reading streaks and records."},
word={"Word of the day","A daily word from your KOReader vocabulary."},
light={"Light","Control this reader's frontlight."},
buddy={"Reading buddy","A reading message from activity on this reader."},
clock={"Clock","The time on your Home page."},
}
for id,copy in pairs(descriptions) do WidgetRegistry[id].name=copy[1]; WidgetRegistry[id].description=copy[2] end
Loading
Loading