From bb81816b8334584d0ac0957fa96e37bd74672021 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 12:37:18 -0500 Subject: [PATCH 1/4] Drawing: a Stickers tool with the Memos fork's Kid Pix stickers The stickers come from the fork's /kidpix/sticker-png/ (PNG pictures of its Kid Pix stickers): the list and each category fetched once over Wi-Fi and kept. A tap puts the picked sticker down as a picture (undo, lasso). Pictures with a clear ground are now blended onto the page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HqNYrwobY8un97LQ2jriQC --- .../gzreader.koplugin/gzreader_changelog.lua | 1 + .../gzreader.koplugin/gzreader_drawscreen.lua | 99 ++++++- plugins/gzreader.koplugin/gzreader_sketch.lua | 7 + .../gzreader_stickergrid.lua | 245 ++++++++++++++++++ .../gzreader.koplugin/gzreader_stickers.lua | 199 ++++++++++++++ .../gzreader.koplugin/icons/draw/sticker.svg | 1 + tools/gzreader/emulator/demo/mock_memos.py | 48 +++- tools/gzreader/emulator/sticker_tour.lua | 85 ++++++ tools/gzreader/tests/run_tests.lua | 115 +++++++- tools/gzreader/tests/sketch_test.lua | 25 ++ wiki/Notes.md | 12 + 11 files changed, 828 insertions(+), 9 deletions(-) create mode 100644 plugins/gzreader.koplugin/gzreader_stickergrid.lua create mode 100644 plugins/gzreader.koplugin/gzreader_stickers.lua create mode 100644 plugins/gzreader.koplugin/icons/draw/sticker.svg create mode 100644 tools/gzreader/emulator/sticker_tour.lua diff --git a/plugins/gzreader.koplugin/gzreader_changelog.lua b/plugins/gzreader.koplugin/gzreader_changelog.lua index f74c0fa23..5c3c21efb 100644 --- a/plugins/gzreader.koplugin/gzreader_changelog.lua +++ b/plugins/gzreader.koplugin/gzreader_changelog.lua @@ -9,6 +9,7 @@ return { { version = "next", changes = { + { short = "Drawing: Kid Pix stickers", text = "The drawing screen has a Stickers tool, under Text: the 935 Kid Pix stickers of the Memos fork's drawing sheet (animals, food, flags, vehicles, praise and more, in 42 categories). The first tap opens them, a tap on one takes it, and then each tap on the page puts it down there; tap Stickers again for another sticker or its size (Small, Medium, Large). A sticker is a picture in the drawing, as in Memos' Kid Pix mode: Undo takes it off, the lasso moves and sizes it, and Memos shows it. They come from your Memos server (the fork, with its sticker pictures): a category is fetched over Wi-Fi the first time it's opened and then kept on the Kindle. On a colour Kindle they're in colour. Pictures with a clear ground (stickers, PNGs) now show the paper and the ink under them instead of a box." }, { short = "GZreader has a folder of its own, beside KOReader: GZreader/app, books, music, audiobooks, notes", text = "GZreader used to take KOReader's place on the drive (the koreader folder, or .adds/koreader on a Kobo), so you couldn't have both. Everything GZreader keeps is now in one GZreader folder: app (GZreader itself, its settings and logs), books (your books and their reading positions), music and audiobooks (what you downloaded, no longer in hidden folders) and notes (the notes kept on the device, drawings waiting to be sent, attachments). The koreader folder is left free, so KOReader can be installed beside GZreader. When you update, GZreader moves everything there itself at its first start: your books with their reading positions, highlights and history, your music, audiobooks and notes, and the program, then starts again (a few seconds longer than usual, once) and says what it did. The Kindle's KUAL menu and the Kobo's NickelMenu and KFMon entries are changed to start it from its new place. Sign-ins stay on the Kindle's own disk, as before. On the Nook, GZreader's programs and settings stay on its own disk (the card can't run programs), and everything else goes into GZreader on the card the same way: the hidden .gzreader-app becomes GZreader/app (still checked against its fingerprints at every start), and your books, music, audiobooks and notes are moved into their folders (the notes off the Nook's small internal disk), without a restart." }, { short = "Drawing: the Kindle no longer falls asleep, or stops answering, while you draw", text = "While you drew, the drawing screen took the pen's input before KOReader's sleep timer saw it, so KOReader thought the Kindle hadn't been touched since the drawing opened. It put the Kindle to sleep in the middle of a drawing, and after a long while drawing, its sleep timer's rounds took longer and longer until the screen stopped answering the pen and the power button, and GZreader restarted, losing the drawing. Now the drawing screen tells the sleep timer you're active as you draw (at most every 5 seconds), as any other tap does. The Kindle still sleeps when you put it down for as long as your sleep setting says." }, { short = "Drawing: what you draw is kept as you go, and comes back if GZreader stops before you save", text = "A drawing was only written to the Kindle when you saved it, so if GZreader stopped first (it hung, crashed or the battery ran out), everything drawn since was lost. Now every drawing is kept as you draw: a few seconds after you pause (at most every 30 seconds, and at least every minute and a half however long you write, between strokes), and right before the Kindle goes to sleep. It is never written while the pen is on the page or has just moved (hovering counts), and it is written by a separate background process, so writing is never held up by it. (In the first test build it was written on the screen's own thread: on a full page that froze the pen for a second or more, and a stroke begun then could break.) When you save or discard it, that copy is deleted. If GZreader stops before then, the next time it starts it asks about the drawing: Open it (a journal entry comes back with its mood, tags, words and drawing; a note's drawing opens as a new drawing note), Later (it asks again at the next start), or Delete it." }, diff --git a/plugins/gzreader.koplugin/gzreader_drawscreen.lua b/plugins/gzreader.koplugin/gzreader_drawscreen.lua index 5b4411f53..095012de4 100644 --- a/plugins/gzreader.koplugin/gzreader_drawscreen.lua +++ b/plugins/gzreader.koplugin/gzreader_drawscreen.lua @@ -108,6 +108,8 @@ DrawScreen.SIDE_TOOLS = { { id = "highlighter", icon = "highlighter", label = _("Highlighter") }, { id = "shape", icon = "shapes", label = _("Shapes") }, { id = "text", icon = "text", label = _("Text") }, + -- (Kid Pix's stickers, from the Memos server: gzreader_stickers.lua) + { id = "sticker", icon = "sticker", label = _("Stickers") }, { id = "eraser", icon = "eraser", label = _("Eraser") }, { id = "lasso", icon = "lasso", label = _("Lasso") }, { id = "hand", icon = "hand", label = _("Move the page") }, @@ -248,6 +250,16 @@ function DrawScreen:init() if self.writing == "highlighter" then self.tool, self.writing = "highlighter", "pen" end self.hl_width = oneOf("gzreader_drawing_hl_width", Sketch.WIDTHS, 2) self.eraser_width = oneOf("gzreader_drawing_eraser_width", Sketch.ERASER_WIDTHS, 4) + -- the sticker last put down, and its size (the Stickers tool stamps it) + do + local Stickers = require("gzreader_stickers") + local last, size = Stickers.last() + self.sticker_size = size + if last then + local item = Stickers.find(Stickers.index(), last.slug, last.n) + if item and Stickers.path(item) then self.sticker = item end + end + end local shape = G_reader_settings and G_reader_settings:readSetting("gzreader_drawing_shape") self.shape = Sketch.SHAPE_SET[shape or ""] and shape or "square" self.has_color = DrawScreen.hasColor() @@ -525,6 +537,11 @@ function DrawScreen:flyoutRows(which) rows[#rows + 1] = { id = "e" .. tostring(w), row = true, eraser_width = w, bar = k, hollow = true, label = DrawScreen.WIDTH_NAMES[k] } end rows[#rows + 1] = { id = "clear", row = true, label = _("Erase page") } + elseif which == "sticker" then + rows[#rows + 1] = { id = "sticker-pick", row = true, label = _("Choose a sticker…") } + for k, _f in ipairs(require("gzreader_stickers").SIZES) do + rows[#rows + 1] = { id = "ss" .. k, row = true, sticker_size = k, label = DrawScreen.STICKER_SIZE_NAMES[k] } + end elseif which == "more" then rows[#rows + 1] = { id = "side", row = true, label = self.toolbar_side == "left" and _("Move to right side") or _("Move to left side") } if self.has_pen then @@ -770,12 +787,13 @@ function DrawScreen:selected(t) if t.hl_width then return self.hl_width == t.hl_width end if t.shape then return self.tool == "shape" and self.shape == t.shape end if t.eraser_width then return self.eraser_width == t.eraser_width end + if t.sticker_size then return self.sticker_size == t.sticker_size end if t.color then return Sketch.inkColor(t.color) == self.color end if t.tagname then for _i, name in ipairs(self.meta and self.meta.tags or {}) do if name == t.tagname then return true end end return false end - if t.id == "pen" or t.id == "highlighter" or t.id == "shape" or t.id == "eraser" or t.id == "text" or t.id == "hand" or t.id == "lasso" then return self.tool == t.id end + if t.id == "pen" or t.id == "highlighter" or t.id == "shape" or t.id == "eraser" or t.id == "text" or t.id == "hand" or t.id == "lasso" or t.id == "sticker" then return self.tool == t.id end if t.id == "fingers" then return not self.pen_only end if t.id == "more" or t.id == "options" then return self.flyout == t.id end if t.id == "tag" then return self.flyout == "tags" end @@ -1144,6 +1162,26 @@ local function strokeSegments(sk, st) return out end +--- A picture onto the page: through its transparency when it has one (a +--- sticker, a PNG with a clear ground: the paper and the ink under it show), +--- else copied as it is (quicker). +function DrawScreen.blitPicture(dst, src, dx, dy, sx, sy, w, h) + local t = src.getType and src:getType() + if t ~= nil and (t == Blitbuffer.TYPE_BB8A or t == Blitbuffer.TYPE_BBRGB32) then + if dst.getType and dst:getType() == Blitbuffer.TYPE_BBRGB24 then + -- (KOReader's blitter can't blend into 24-bit colour, the PNG's page: through a 32-bit copy of that part) + local tmp = Blitbuffer.new(w, h, Blitbuffer.TYPE_BBRGB32) + tmp:blitFrom(dst, 0, 0, dx, dy, w, h) + tmp:alphablitFrom(src, 0, 0, sx, sy, w, h) + dst:blitFrom(tmp, dx, dy, 0, 0, w, h) + tmp:free() + return + end + return dst:alphablitFrom(src, dx, dy, sx, sy, w, h) + end + return dst:blitFrom(src, dx, dy, sx, sy, w, h) +end + --- Picture `el` of the page's scene, at w x h (cached for the page): a --- BlitBuffer, or nil when it can't be read. function DrawScreen:picture(el, w, h) @@ -1195,12 +1233,12 @@ function DrawScreen:paintPicture(el) local dx, dy = math.max(0, x1), math.max(0, y1) local bw, bh = math.min(w - sx, c.w - dx), math.min(h - sy, c.h - dy) if bw <= 0 or bh <= 0 then return true end - self.canvas_bb:blitFrom(bb, dx, dy, sx, sy, bw, bh) + DrawScreen.blitPicture(self.canvas_bb, bb, dx, dy, sx, sy, bw, bh) if not self.color_bb then self.color_bb = Blitbuffer.new(c.w, c.h, Blitbuffer.TYPE_BBRGB24) self.color_bb:fill(Blitbuffer.ColorRGB24(DrawScreen.hexRGB(Drawing.PAPER))) end - self.color_bb:blitFrom(bb, dx, dy, sx, sy, bw, bh) + DrawScreen.blitPicture(self.color_bb, bb, dx, dy, sx, sy, bw, bh) return true end @@ -1223,12 +1261,12 @@ function DrawScreen:paintPicturePart(el, x1, y1, w, h) return require("ui/renderimage"):scaleBlitBuffer(view, dx1 - dx0, dy1 - dy0, false) end) if not ok or not part then return false end - self.canvas_bb:blitFrom(part, dx0, dy0, 0, 0, dx1 - dx0, dy1 - dy0) + DrawScreen.blitPicture(self.canvas_bb, part, dx0, dy0, 0, 0, dx1 - dx0, dy1 - dy0) if not self.color_bb then self.color_bb = Blitbuffer.new(c.w, c.h, Blitbuffer.TYPE_BBRGB24) self.color_bb:fill(Blitbuffer.ColorRGB24(DrawScreen.hexRGB(Drawing.PAPER))) end - self.color_bb:blitFrom(part, dx0, dy0, 0, 0, dx1 - dx0, dy1 - dy0) + DrawScreen.blitPicture(self.color_bb, part, dx0, dy0, 0, 0, dx1 - dx0, dy1 - dy0) part:free() return true end @@ -1374,8 +1412,8 @@ function DrawScreen:repaintArea(area) local dx0, dy0 = math.max(x0, p.x), math.max(y0, p.y) local dx1, dy1 = math.min(x1, p.x + p.w), math.min(y1, p.y + p.h) if dx1 > dx0 and dy1 > dy0 then - self.canvas_bb:blitFrom(part.bb, dx0, dy0, dx0 - p.x, dy0 - p.y, dx1 - dx0, dy1 - dy0) - if self.color_bb then self.color_bb:blitFrom(part.bb, dx0, dy0, dx0 - p.x, dy0 - p.y, dx1 - dx0, dy1 - dy0) end + DrawScreen.blitPicture(self.canvas_bb, part.bb, dx0, dy0, dx0 - p.x, dy0 - p.y, dx1 - dx0, dy1 - dy0) + if self.color_bb then DrawScreen.blitPicture(self.color_bb, part.bb, dx0, dy0, dx0 - p.x, dy0 - p.y, dx1 - dx0, dy1 - dy0) end end end -- …and the bits of line that cross it (highlighters under the rest, as on the whole page; @@ -1779,6 +1817,7 @@ function DrawScreen:apply(out) self._stroke_area, self._stroke_grey = nil, nil end for _i, tap in ipairs(out.taps) do self:tapAt(tap.x, tap.y) end + if out.sticker_tap then self:stampSticker(out.sticker_tap.x, out.sticker_tap.y) end if out.text_tap then self:textTap(out.text_tap) end if out.pull then self:pullPanel() end end @@ -2424,6 +2463,16 @@ function DrawScreen:use(t) self.eraser_width = t.eraser_width keep("gzreader_drawing_eraser_width", t.eraser_width) self:setTool("eraser"); self:setFlyout(nil) + elseif t.sticker_size then + self.sticker_size = t.sticker_size + keep("gzreader_drawing_sticker_size", t.sticker_size) + self:setTool("sticker"); self:setFlyout(nil) + elseif t.id == "sticker" then + -- in hand already: its panel (another sticker, its size); none chosen yet: the stickers to choose from + if self.tool == "sticker" then self:setFlyout(self.flyout ~= "sticker" and "sticker" or nil) + elseif self.sticker then self:setTool("sticker"); self:setFlyout(nil) + else self:setFlyout(nil); self:pickSticker() end + elseif t.id == "sticker-pick" then self:setFlyout(nil); self:pickSticker() elseif t.color then self:setColor(t.color); self:setFlyout(nil) elseif t.tagname then self:toggleTag(t.tagname); self:setFlyout("tags") elseif t.id == "newtag" then self:newTag() @@ -2657,6 +2706,42 @@ end -- ------------------------------------------------------------ pictures +DrawScreen.STICKER_SIZE_NAMES = { _("Small"), _("Medium"), _("Large") } + +--- The Stickers tool's picker (gzreader_stickergrid.lua): the sticker picked is the one each tap puts down. +function DrawScreen:pickSticker() + return require("gzreader_stickergrid").show(self.plugin, { on_pick = function(item) + if self._closed then return end + self.sticker = item + if G_reader_settings then + G_reader_settings:saveSetting("gzreader_drawing_sticker", { slug = item.slug, n = require("gzreader_stickers").number(item) }) + end + self:setTool("sticker"); self:setFlyout(nil) + end }) +end + +--- A tap with the Stickers tool at canvas point (x, y): the sticker put down +--- there, centred on it (a picture in the drawing, as Memos' Kid Pix mode puts +--- its stickers in; Undo takes it off, the lasso moves and sizes it). +function DrawScreen:stampSticker(x, y) + local Stickers = require("gzreader_stickers") + local item = self.sticker + local url = item and Stickers.dataURL(item) + if not url then return self:pickSticker() end + local sk = self.sketch + local sx, sy = sk:toScene(x, y) + local w, h = Stickers.size(item, self.sticker_size) + local el = sk:addPicture(url, "image/png", w, h, sx, sy) + self:touched() + Log.info("drawing: a sticker,", item.file) + -- (only where it went) + local x0, y0 = sk:toCanvas(el.x, el.y) + local x1, y1 = sk:toCanvas(el.x + el.width, el.y + el.height) + local area = { x0 = math.floor(x0) - 1, y0 = math.floor(y0) - 1, x1 = math.ceil(x1) + 1, y1 = math.ceil(y1) + 1 } + if self:repaintArea(area) then self:refreshBar() else self:redrawAll() end + return el +end + --- Photos from Immich (gzreader_immichpick.lua), placed on the page as --- memos' drawing sheet places them: in the middle of what's shown. function DrawScreen:pickPictures() diff --git a/plugins/gzreader.koplugin/gzreader_sketch.lua b/plugins/gzreader.koplugin/gzreader_sketch.lua index 732bd76d0..927c58612 100644 --- a/plugins/gzreader.koplugin/gzreader_sketch.lua +++ b/plugins/gzreader.koplugin/gzreader_sketch.lua @@ -963,6 +963,9 @@ local function startContact(self, s, now, out) local el, part = self:textAt(s.x - self.canvas.x, s.y - self.canvas.y) c.kind, c.el, c.part, c.at = "text", el, part, now if el then c.orig = { x = el.x, y = el.y, width = el.width, height = el.height } end + elseif self.tool == "sticker" then + -- the Stickers tool: a tap puts the sticker down there (the pen or a finger); a drag does nothing + c.kind = "sticker" elseif self.pen_only and not pen and self.zoomed then -- A pen Kindle, zoomed in: a finger moves the page (a second, at once: a pinch). -- Whatever else rests on the screen: only "the first finger down, nothing else @@ -1188,6 +1191,10 @@ local function endContact(self, slot, out) if self.pan_slot == slot then self.pan_slot = nil end return end + if c.kind == "sticker" then + if c.moved <= self.tap_slop then out.sticker_tap = { x = c.x0 - self.canvas.x, y = c.y0 - self.canvas.y } end + return + end if c.kind == "text" then if c.moved <= self.tap_slop then out.text_tap = { el = c.el, x = c.x0 - self.canvas.x, y = c.y0 - self.canvas.y } diff --git a/plugins/gzreader.koplugin/gzreader_stickergrid.lua b/plugins/gzreader.koplugin/gzreader_stickergrid.lua new file mode 100644 index 000000000..00fbb2f40 --- /dev/null +++ b/plugins/gzreader.koplugin/gzreader_stickergrid.lua @@ -0,0 +1,245 @@ +--[[-- +The Stickers tool's picker (gzreader_stickers.lua): a category of Kid Pix +stickers as a grid, a tap picks one. The category's name at the top opens the +list of categories; ‹ › (or a swipe) turn the pages. A category's pictures +are fetched from the Memos server the first time it's opened, then kept. + + StickerGrid.show(plugin, { on_pick = function(item, cat) end }) +]] + +local Blitbuffer = require("ffi/blitbuffer") +local Button = require("ui/widget/button") +local CenterContainer = require("ui/widget/container/centercontainer") +local Device = require("device") +local Font = require("ui/font") +local FrameContainer = require("ui/widget/container/framecontainer") +local Geom = require("ui/geometry") +local GestureRange = require("ui/gesturerange") +local HorizontalGroup = require("ui/widget/horizontalgroup") +local HorizontalSpan = require("ui/widget/horizontalspan") +local ImageWidget = require("ui/widget/imagewidget") +local InfoMessage = require("ui/widget/infomessage") +local InputContainer = require("ui/widget/container/inputcontainer") +local TextWidget = require("ui/widget/textwidget") +local UIManager = require("ui/uimanager") +local VerticalGroup = require("ui/widget/verticalgroup") +local VerticalSpan = require("ui/widget/verticalspan") +local Log = require("gzreader_log") +local Stickers = require("gzreader_stickers") +local _ = require("gettext") +local T = require("ffi/util").template +local Screen = Device.screen + +local function S(n) return Screen:scaleBySize(n) end + +local Grid = InputContainer:extend{ + name = "gz_sticker_grid", + covers_fullscreen = true, + plugin = nil, index = nil, cat = nil, + on_pick = nil, +} + +--- How many stickers a screen shows: cols, rows, a cell's side. +function Grid.layout(w, h) + local cols = w >= 1000 and 5 or 4 + local cell = math.floor(w / cols) + return cols, math.max(1, math.floor(h / cell)), cell +end + +function Grid:init() + self.dimen = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight() } + self.page = 1 + self.ges_events = { + TapGrid = { GestureRange:new{ ges = "tap", range = function() return self.dimen end } }, + SwipeGrid = { GestureRange:new{ ges = "swipe", range = function() return self.dimen end } }, + } + self.key_events = Device:hasKeys() and { Close = { { "Back" } } } or {} + self.bar_h, self.foot_h = S(56), S(56) + self.cols, self.rows, self.cell = Grid.layout(self.dimen.w, self.dimen.h - self.bar_h - self.foot_h) + self[1] = VerticalGroup:new{} +end + +function Grid:perScreen() return self.cols * self.rows end + +function Grid:pages() return math.max(1, math.ceil(#self.cat.items / self:perScreen())) end + +--- A sticker's picture fitted into a square `side` wide (kept while the picker is open). +function Grid:thumb(item, side) + self.bbs = self.bbs or {} + local key = item.file .. ":" .. side + if self.bbs[key] == nil then + local bb + local path = Stickers.path(item) + if path then + local RenderImage = require("ui/renderimage") + local ok, img = pcall(RenderImage.renderImageFile, RenderImage, path, false) + if ok and img then + local iw, ih = img:getWidth(), img:getHeight() + local k = math.min(side / iw, side / ih, 3) -- (a small sticker shown bigger, to see what it is) + local nw, nh = math.max(1, math.floor(iw * k)), math.max(1, math.floor(ih * k)) + bb = (nw ~= iw or nh ~= ih) and RenderImage:scaleBlitBuffer(img, nw, nh, true) or img + end + end + self.bbs[key] = bb or false + end + return self.bbs[key] or nil +end + +function Grid:build() + local w = self.dimen.w + self.cells = {} + local cat = self.cat + local bar = HorizontalGroup:new{ align = "center", + Button:new{ text = "\u{2190}", bordersize = 0, width = S(56), callback = function() self:onClose() end, show_parent = self }, + Button:new{ text = cat.name .. " \u{25BE}", bordersize = 0, width = w - S(112), callback = function() self:chooseCategory() end, + show_parent = self }, + HorizontalSpan:new{ width = S(56) }, + } + local grid = VerticalGroup:new{} + local from = (self.page - 1) * self:perScreen() + local cell, pad = self.cell, S(6) + for r = 1, self.rows do + local row = HorizontalGroup:new{} + for c = 1, self.cols do + local item = cat.items[from + (r - 1) * self.cols + c] + if item then + local tb = self:thumb(item, cell - 2 * pad - S(8)) + local inside = tb and ImageWidget:new{ image = tb, image_disposable = false, alpha = true } + or TextWidget:new{ text = item.name ~= "" and item.name or "?", face = Font:getFace("cfont", 12), max_width = cell - S(16) } + local holder = FrameContainer:new{ padding = pad, margin = 0, bordersize = 0, + CenterContainer:new{ dimen = Geom:new{ w = cell - 2 * pad, h = cell - 2 * pad }, inside } } + self.cells[#self.cells + 1] = { w = holder, item = item } + row[#row + 1] = holder + else + row[#row + 1] = HorizontalSpan:new{ width = cell } + end + end + grid[#grid + 1] = row + end + local foot = HorizontalGroup:new{ align = "center", + Button:new{ text = "\u{2039}", width = S(90), enabled = self.page > 1, callback = function() self:turn(-1) end, show_parent = self }, + CenterContainer:new{ dimen = Geom:new{ w = w - S(200), h = self.foot_h }, + TextWidget:new{ text = T(_("Page %1 of %2"), self.page, self:pages()), face = Font:getFace("cfont", 16) } }, + Button:new{ text = "\u{203A}", width = S(90), enabled = self.page < self:pages(), callback = function() self:turn(1) end, show_parent = self }, + } + self[1] = FrameContainer:new{ width = self.dimen.w, height = self.dimen.h, padding = 0, margin = 0, bordersize = 0, + background = Blitbuffer.COLOR_WHITE, + VerticalGroup:new{ + CenterContainer:new{ dimen = Geom:new{ w = w, h = self.bar_h }, bar }, + -- (the stickers from the top down) + CenterContainer:new{ dimen = Geom:new{ w = w, h = self.rows * cell }, grid }, + VerticalSpan:new{ width = self.dimen.h - self.bar_h - self.foot_h - self.rows * cell }, + CenterContainer:new{ dimen = Geom:new{ w = w, h = self.foot_h }, foot }, + } } +end + +function Grid:turn(d) + local p = self.page + d + if p < 1 or p > self:pages() then return end + self.page = p + self:build() + UIManager:setDirty(self, "ui") +end + +--- Category `cat` shown (its pictures fetched first when they aren't all here). +function Grid:showCategory(cat) + local function show() + self.cat, self.page = cat, 1 + if G_reader_settings then G_reader_settings:saveSetting("gzreader_drawing_sticker_category", cat.slug) end + self:build() + UIManager:setDirty(self, "full") + end + if Stickers.have(cat) == #cat.items then return show() end + local server = Stickers.server(self.plugin) + if not server then + if Stickers.have(cat) > 0 then return show() end + return UIManager:show(InfoMessage:new{ text = Stickers.why("no_server"), timeout = 5 }) + end + require("gzreader_net").run(function() + local busy = InfoMessage:new{ text = T(_("Fetching %1 stickers…"), cat.name), timeout = 0 } + UIManager:show(busy) + UIManager:forceRePaint() + local n, err = Stickers.fetchCategory(server, cat) + UIManager:close(busy) + if n == 0 then return UIManager:show(InfoMessage:new{ text = Stickers.why(err), timeout = 5 }) end + show() + end, { reason = "stickers" }) +end + +--- The list of categories (each with how many stickers it has). +function Grid:chooseCategory() + local Menu = require("ui/widget/menu") + local menu + local items = {} + for _i, c in ipairs(self.index.categories) do + items[#items + 1] = { text = c.name, mandatory = tostring(#c.items), bold = c == self.cat, + callback = function() UIManager:close(menu); self:showCategory(c) end } + end + menu = Menu:new{ title = _("Stickers"), item_table = items, width = Screen:getWidth(), height = Screen:getHeight(), + is_borderless = true, covers_fullscreen = true } + UIManager:show(menu) + return menu +end + +function Grid:onTapGrid(_arg, ges) + for _i, c in ipairs(self.cells or {}) do + if c.w.dimen and ges.pos:intersectWith(c.w.dimen) then + if not Stickers.path(c.item) then return true end + Log.info("stickers: picked", c.item.file) + UIManager:close(self, "full") + if self.on_pick then self.on_pick(c.item, self.cat) end + return true + end + end + return false +end + +function Grid:onSwipeGrid(_arg, ges) + if ges.direction == "west" then self:turn(1); return true end + if ges.direction == "east" then self:turn(-1); return true end + return false +end + +function Grid:onClose() + UIManager:close(self, "full") + return true +end + +function Grid:onCloseWidget() + for _k, bb in pairs(self.bbs or {}) do if bb then bb:free() end end + self.bbs = nil +end + +--- The picker, at the category last opened (the first one the first time). +--- The list of stickers comes from the Memos server the first time (Wi-Fi). +function Grid.show(plugin, opts) + opts = opts or {} + local function open(index) + local last = G_reader_settings and G_reader_settings:readSetting("gzreader_drawing_sticker_category") + local cat = index.categories[1] + for _i, c in ipairs(index.categories) do if c.slug == last then cat = c end end + local grid = Grid:new{ plugin = plugin, index = index, on_pick = opts.on_pick } + grid.cat = cat + UIManager:show(grid) + grid:showCategory(cat) + return grid + end + local index = Stickers.index() + if index then return open(index) end + local server = Stickers.server(plugin) + if not server then return UIManager:show(InfoMessage:new{ text = Stickers.why("no_server"), timeout = 5 }) end + require("gzreader_net").run(function() + local busy = InfoMessage:new{ text = _("Fetching the stickers…"), timeout = 0 } + UIManager:show(busy) + UIManager:forceRePaint() + local got, err = Stickers.fetchIndex(server) + UIManager:close(busy) + if not got then + Log.warn("stickers: the list:", tostring(err)) + return UIManager:show(InfoMessage:new{ text = Stickers.why(err), timeout = 5 }) + end + open(got) + end, { reason = "stickers" }) +end + +return Grid diff --git a/plugins/gzreader.koplugin/gzreader_stickers.lua b/plugins/gzreader.koplugin/gzreader_stickers.lua new file mode 100644 index 000000000..0d0999ce4 --- /dev/null +++ b/plugins/gzreader.koplugin/gzreader_stickers.lua @@ -0,0 +1,199 @@ +--[[-- +Kid Pix stickers for the drawing screen's Stickers tool (gzreader_drawscreen.lua, +picked in gzreader_stickergrid.lua). + +The stickers are the Memos fork's: Kid Pix Deluxe 4's 935 stickers, which the +fork draws from their Flash movies in its own drawing sheet. A Kindle can't read +Flash, so the fork also serves them as PNG pictures (its +web/scripts/render-kidpix-stickers.mjs): + + /kidpix/sticker-png/index.json + { version = 1, scale = 2, categories = { { slug, name, items = { { name, file, width, height } } } } } + /kidpix/sticker-png//.png (twice the sticker's own size, 256 colours, a clear ground) + +They're public files of the web app (no sign-in). The list and a category's +pictures are fetched the first time they're opened (over Wi-Fi) and kept in +cache/gzreader-stickers/, so a category opened once works without Wi-Fi. + +A sticker goes on the page as a picture (Sketch:addPicture), as the fork's own +Kid Pix mode puts its stickers into the drawing: Memos shows it, the lasso +moves and sizes it, Undo takes it off. +]] + +local DataStorage = require("datastorage") +local JSON = require("gzreader_json") +local Log = require("gzreader_log") +local lfs = require("libs/libkoreader-lfs") +local ltn12 = require("ltn12") + +local Stickers = { + PATH = "/kidpix/sticker-png/", + MAX_BYTES = 512 * 1024, -- (a sticker picture; the biggest is about 60 kB) + -- the sizes offered: the sticker's own size (1x: as Kid Pix put it down) times these + SIZES = { 1, 1.6, 2.4 }, + DEFAULT_SIZE = 2, +} + +--- Where the list and the pictures are kept. +function Stickers.dir() + local dir = DataStorage:getDataDir() .. "/cache/gzreader-stickers" + if lfs.attributes(dir, "mode") ~= "directory" then + lfs.mkdir(DataStorage:getDataDir() .. "/cache") + lfs.mkdir(dir) + end + return dir +end + +--- The Memos server the stickers come from (GZreader's Memos sign-in), or nil. +function Stickers.server(plugin) + local m = plugin and plugin.store and plugin.store.memos + local s = type(m) == "table" and m.server + if type(s) ~= "string" or not s:match("^https?://") then return nil end + return (s:gsub("/+$", "")) +end + +local function safe(s) return type(s) == "string" and s:match("^[%w][%w%-_]*$") ~= nil end + +--- The fork's index.json, checked: { categories = { { slug, name, items = { { name, file, w, h } } } } } or nil. +--- (A file name must be "/.png": nothing else is fetched or written.) +function Stickers.parseIndex(data) + if type(data) ~= "table" or tonumber(data.version) ~= 1 or type(data.categories) ~= "table" then return nil end + local out = { scale = tonumber(data.scale) or 2, categories = {} } + for _i, c in ipairs(data.categories) do + if type(c) == "table" and safe(c.slug) and type(c.items) == "table" then + local cat = { slug = c.slug, name = type(c.name) == "string" and c.name or c.slug, items = {} } + for n, it in ipairs(c.items) do + local file = type(it) == "table" and it.file + local w, h = tonumber(type(it) == "table" and it.width), tonumber(type(it) == "table" and it.height) + if file == c.slug .. "/" .. (n - 1) .. ".png" and w and h and w > 0 and h > 0 then + cat.items[#cat.items + 1] = { name = type(it.name) == "string" and it.name or "", file = file, w = w, h = h, slug = c.slug } + end + end + if #cat.items > 0 then out.categories[#out.categories + 1] = cat end + end + end + return #out.categories > 0 and out or nil +end + +--- The list kept on the Kindle (from the last time it was fetched), or nil. +function Stickers.index() + local f = io.open(Stickers.dir() .. "/index.json", "rb") + if not f then return nil end + local text = f:read("*a") + f:close() + local ok, data = pcall(JSON.decode, text) + return ok and Stickers.parseIndex(data) or nil +end + +--- A sticker's picture on the Kindle (its path), or nil when it isn't there yet. +function Stickers.path(item) + local p = Stickers.dir() .. "/" .. item.file + return lfs.attributes(p, "mode") == "file" and p or nil +end + +--- How many of a category's pictures are on the Kindle. +function Stickers.have(cat) + local n = 0 + for _i, it in ipairs(cat.items) do if Stickers.path(it) then n = n + 1 end end + return n +end + +local function get(url, sink) + local Api = require("gzreader_api") + return Api.rawRequest("GET", url, { headers = { Accept = sink and "image/png" or "application/json" }, sink = sink, + want_raw = not sink or nil, timeouts = { 10, 30 } }) +end + +--- Fetches the list from `server` and keeps it: the list, or nil, err. +--- (In a background process or with Wi-Fi up: it waits for the answer.) +function Stickers.fetchIndex(server) + local code, text = get(server .. Stickers.PATH .. "index.json") + if type(code) ~= "number" then return nil, "unreachable" end + if code == 404 then return nil, "no_stickers" end -- (a Memos without the fork's sticker pictures) + if code ~= 200 then return nil, "http_" .. code end + local ok, data = pcall(JSON.decode, type(text) == "string" and text or "") + local index = ok and Stickers.parseIndex(data) or nil + if not index then return nil, "bad_index" end + local f = io.open(Stickers.dir() .. "/index.json", "wb") + if f then f:write(text); f:close() end + Log.info("stickers: the list,", #index.categories, "categories") + return index +end + +--- Fetches the pictures of category `cat` that aren't on the Kindle yet: +--- how many it has now, and an error when some couldn't be fetched. +function Stickers.fetchCategory(server, cat) + local dir = Stickers.dir() .. "/" .. cat.slug + if lfs.attributes(dir, "mode") ~= "directory" then lfs.mkdir(dir) end + local err + for _i, it in ipairs(cat.items) do + if not Stickers.path(it) then + local path = Stickers.dir() .. "/" .. it.file + local part = path .. ".part" + local fh = io.open(part, "wb") + if not fh then err = "write"; break end + local code = get(server .. Stickers.PATH .. it.file, ltn12.sink.file(fh)) + local size = lfs.attributes(part, "size") or 0 + local head + local rf = io.open(part, "rb") + if rf then head = rf:read(8); rf:close() end + if code == 200 and size > 0 and size <= Stickers.MAX_BYTES and head == "\137PNG\r\n\26\n" then + os.rename(part, path) + else + os.remove(part) + err = type(code) == "number" and ("http_" .. code) or "unreachable" + if err == "unreachable" then break end + end + end + end + local n = Stickers.have(cat) + Log.info("stickers:", cat.slug, n, "of", #cat.items, err and ("(" .. err .. ")") or "") + return n, err +end + +--- Sticker `item` at size `k` (Stickers.SIZES' index): its width and height in +--- the drawing's units (the drawing's units are Memos' pixels: a sticker at 1x +--- is as big as Kid Pix put it down). +function Stickers.size(item, k) + local f = Stickers.SIZES[k] or Stickers.SIZES[Stickers.DEFAULT_SIZE] + return item.w * f, item.h * f +end + +--- The sticker's picture as the drawing keeps it: a PNG data URL, or nil. +function Stickers.dataURL(item) + local p = Stickers.path(item) + local f = p and io.open(p, "rb") + if not f then return nil end + local data = f:read("*a") + f:close() + if not data or #data == 0 then return nil end + return "data:image/png;base64," .. require("ffi/sha2").bin_to_base64(data) +end + +--- The sticker and size last used (kept for next time): { slug, n }, size. +function Stickers.last() + local s = G_reader_settings and G_reader_settings:readSetting("gzreader_drawing_sticker") + local size = G_reader_settings and G_reader_settings:readSetting("gzreader_drawing_sticker_size") + return type(s) == "table" and safe(s.slug) and tonumber(s.n) and s or nil, Stickers.SIZES[tonumber(size)] and tonumber(size) or Stickers.DEFAULT_SIZE +end + +--- The sticker `slug`/`n` (0-based, as the fork's files) in `index`, or nil. +function Stickers.find(index, slug, n) + for _i, c in ipairs(index and index.categories or {}) do + if c.slug == slug then return c.items[(tonumber(n) or -1) + 1], c end + end +end + +--- The number of a sticker in its category (0-based, as its file). +function Stickers.number(item) return tonumber(item.file:match("/(%d+)%.png$")) end + +--- Why fetching failed, in words. +function Stickers.why(err) + local _ = require("gettext") + if err == "no_server" then return _("Stickers come from your Memos server: sign in to Memos first (Settings → Accounts and services → Memos).") end + if err == "no_stickers" then return _("Your Memos server has no stickers. They come with the Memos fork's Kid Pix stickers (sticker pictures from November 2026 on).") end + if err == "unreachable" then return _("Couldn't reach your Memos server for the stickers.") end + return _("Couldn't fetch the stickers.") .. " (" .. tostring(err) .. ")" +end + +return Stickers diff --git a/plugins/gzreader.koplugin/icons/draw/sticker.svg b/plugins/gzreader.koplugin/icons/draw/sticker.svg new file mode 100644 index 000000000..e2ae2aa79 --- /dev/null +++ b/plugins/gzreader.koplugin/icons/draw/sticker.svg @@ -0,0 +1 @@ + diff --git a/tools/gzreader/emulator/demo/mock_memos.py b/tools/gzreader/emulator/demo/mock_memos.py index b3be81611..5be49fa17 100644 --- a/tools/gzreader/emulator/demo/mock_memos.py +++ b/tools/gzreader/emulator/demo/mock_memos.py @@ -24,6 +24,9 @@ GET /api/immich/albums [{id, name, photoCount, thumbnailPhotoId}] GET /api/immich/photos ?album=&next= -> {photos: [{id, fileName, mimeType, takenAt, width, height}], next ("p:2")} GET /api/immich/photos//thumbnail | /preview (a small JPEG) +--stickers: the fork's Kid Pix stickers as PNG pictures (public files, no sign-in; without it: 404, as a stock Memos): + GET /kidpix/sticker-png/index.json two small categories (STICKER_INDEX) + GET /kidpix/sticker-png//.png a coloured disc on a clear ground, twice the listed size Sign-in: "Authorization: Bearer " (TOKEN below). python3 -I mock_memos.py PORT [--sample] [--prefix /api] [--memos26] [--spaces] [--journal] [--drawings] @@ -56,6 +59,7 @@ JOURNAL = "--journal" in sys.argv DAWARICH = "--dawarich" in sys.argv # (with --journal: Dawarich connected to the fork) IMMICH = "--immich" in sys.argv +STICKERS = "--stickers" in sys.argv # (the fork's Kid Pix stickers as PNGs: /kidpix/sticker-png/) # a small grey JPEG (96 x 64): what the Immich proxy sends as a thumbnail or a preview TEST_JPEG = base64.b64decode("/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA0JCgsKCA0LCgsODg0PEyAVExISEyccHhcgLikxMC4pLSwzOko+MzZGNywtQFdBRkxOUlNSMj5aYVpQYEpRUk//wAALCABAAGABAREA/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/9oACAEBAAA/AL/iTxC+hyWccVi1290WVVV9pyNuABg5zurO/wCEt1j/AKFK+/N//iKP+Et1j/oUr783/wDiKP8AhLdY/wChSvvzf/4ij/hLdY/6FK+/N/8A4ij/AIS3WP8AoUr783/+Io/4S3WP+hSvvzf/AOIo/wCEt1j/AKFK+/N//iKP+Et1j/oUr783/wDiKP8AhLdY/wChSvvzf/4ij/hLdY/6FK+/N/8A4itHw34hfXJLyOWxa0e1Kqys+45O7IIwMY21neMv+Rh8M/8AX3/7PHXXUUUVRutZ020fZPdxhskELliCOoOM4/GmQa9pU7lUvYwQM/OCg/NgK0aKKK5Hwb/yMPib/r7/APZ5KPGX/Iw+Gf8Ar7/9njrrqKK4/wAR+IPP32Vg/wC66SSg/f8AYe3v3+nXmaK3PD2utpzi3uSWtGP1MZ9R7eo/H69yjK6K6MGVhkEHII9aWiuR8G/8jD4m/wCvv/2eSjxl/wAjD4Z/6+//AGeOuuoqjrly1po11MmdwTaCGwQWOM59s5rzeiiiu98J3LXGior5zC5jyWzkcEfocfhWzRXI+Df+Rh8Tf9ff/s8lHjL/AJGHwz/19/8As8dddRWd4hhafQrtEIBCb+fRSGP6CvOqKKK7rwfC0Wi72IxLKzrjsOF5/FTW5RXI+Df+Rh8Tf9ff/s8lHjL/AJGHwz/19/8As8dddRRXC+IdCbTnNxbAtaMfqYz6H29D+H1w6K1ND0aXVZ8nKWyH55PX2Hv/AC/n6BFGkMKRRjakahVGc4A4FOorkfBv/Iw+Jv8Ar7/9nko8Zf8AIw+Gf+vv/wBnjrrqKKR1V0ZHUMrDBBGQR6Vj3XhjTLh9ypJAcknymwDn2OcfhimQeFNMics/nTDGNrvgD3+UCtqKKOGMRwxpGg6KowB+FOoorkfBv/Iw+Jv+vv8A9nkrR8SeHn1ySzkivmtHtSzKypuOTtwQcjGNtZ3/AAiWsf8AQ2335P8A/F0f8IlrH/Q2335P/wDF0f8ACJax/wBDbffk/wD8XR/wiWsf9Dbffk//AMXR/wAIlrH/AENt9+T/APxdH/CJax/0Nt9+T/8AxdH/AAiWsf8AQ2335P8A/F0f8IlrH/Q2335P/wDF0f8ACJax/wBDbffk/wD8XR/wiWsf9Dbffk//AMXWj4b8PPocl5JLfNdvdFWZmTacjdkk5Oc7q//Z") @@ -129,6 +133,35 @@ def chunk(t, d): + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")) +def sticker_png(w, h, rgb): + """A test sticker: a coloured disc on a clear ground (RGBA PNG).""" + rows = b"" + for y in range(h): + row = bytearray([0]) + for x in range(w): + inside = (x - w / 2) ** 2 + (y - h / 2) ** 2 <= (min(w, h) / 2 - 1) ** 2 + row += bytes(rgb) + bytes([255]) if inside else b"\0\0\0\0" + rows += bytes(row) + def chunk(t, d): + c = struct.pack(">I", len(d)) + t + d + return c + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")) + + +# the fork's index.json (two small categories); each picture twice its size +STICKER_INDEX = {"version": 1, "scale": 2, "categories": [ + {"slug": "animals", "name": "Animals", "items": [ + {"name": "Armadillo", "file": "animals/0.png", "width": 40, "height": 30}, + {"name": "Baby Zebra", "file": "animals/1.png", "width": 30, "height": 40}, + {"name": "Blue Bunny", "file": "animals/2.png", "width": 20, "height": 20}]}, + {"slug": "food", "name": "Food", "items": [ + {"name": "Apple", "file": "food/0.png", "width": 25, "height": 25}, + {"name": "Pie", "file": "food/1.png", "width": 35, "height": 20}]}, +]} +STICKER_COLOURS = {"animals": (200, 40, 40), "food": (40, 160, 60)} + + def pdf(): text = "BT /F1 24 Tf 72 720 Td (Trail map: Springer Mountain to Neels Gap) Tj ET" objs = [ @@ -349,7 +382,7 @@ def do_GET(self): u = urlparse(self.path) self.note(u) if u.path == "/__state": - return self.send(200, {"memos": STATE["memos"], "log": STATE["log"], "immich_fetched": STATE.get("immich_fetched", []), "meteo": STATE.get("meteo", []), + return self.send(200, {"memos": STATE["memos"], "log": STATE["log"], "immich_fetched": STATE.get("immich_fetched", []), "stickers_fetched": STATE.get("stickers_fetched", []), "meteo": STATE.get("meteo", []), "loose": sorted(STATE["loose"].keys())}) if STATE["offline"]: self.close_connection = True @@ -397,6 +430,19 @@ def do_GET(self): return self.send(200, [{"lat": "42.36", "lon": "-71.06", "name": "Example Deli", "display_name": "Example Deli, Exampleton"}]) if u.path == "/__osm/reverse": return self.send(200, {"name": "", "address": {"suburb": "Example Square", "city": "Exampleton"}}) + if u.path.startswith("/kidpix/sticker-png/"): + # (public files of the web app: no sign-in) + if not STICKERS: + return self.send(404, raw=b"404 page not found", ctype="text/plain") + rest = u.path[len("/kidpix/sticker-png/"):] + STATE.setdefault("stickers_fetched", []).append(rest) + if rest == "index.json": + return self.send(200, STICKER_INDEX) + for cat in STICKER_INDEX["categories"]: + for it in cat["items"]: + if it["file"] == rest: + return self.send(200, raw=sticker_png(it["width"] * 2, it["height"] * 2, STICKER_COLOURS[cat["slug"]]), ctype="image/png") + return self.send(404, raw=b"404 page not found", ctype="text/plain") if u.path.startswith("/api/immich/"): if not (IMMICH or JOURNAL): # (stock Memos: no such address) return self.send(404, raw=b"404 page not found", ctype="text/plain") diff --git a/tools/gzreader/emulator/sticker_tour.lua b/tools/gzreader/emulator/sticker_tour.lua new file mode 100644 index 000000000..94f1fd58e --- /dev/null +++ b/tools/gzreader/emulator/sticker_tour.lua @@ -0,0 +1,85 @@ +-- The drawing screen's Stickers tool, on a touch Kindle: the Kid Pix stickers +-- from the Memos fork (demo/mock_memos.py --stickers on 18090), the picker, +-- two stickers put down on ruled paper, Undo. +-- python3 -I demo/mock_memos.py 18090 --stickers & +-- GZ_EMU_MODEL=pw3 GZ_EMU_TREE=/koreader run.sh sticker_tour.lua +-- Checks go to /sticker-checks.txt. +local s = { start = 14 } +local function add(t) s[#s + 1] = t end +local lines = {} +local function check(ok, what) lines[#lines + 1] = (ok and "ok " or "FAIL ") .. what end +local function UIM() return require("ui/uimanager") end +local function find(name) for _i, w in ipairs(UIM()._window_stack) do if w.widget.name == name then return w.widget end end end +local function screen() return find("gz_drawscreen") end +local W, H +local function button(id) + local d = screen() + for _i, b in ipairs(d and d.buttons or {}) do + if b.tool.id == id then return { b.rect.x + math.floor(b.rect.w / 2), b.rect.y + math.floor(b.rect.h / 2) } end + end +end + +add({ fn = function(E) + W, H = require("device").screen:getWidth(), require("device").screen:getHeight() + for _i, w in ipairs(UIM()._window_stack) do + if w.widget.name == "setup guide" or w.widget.name == "QR code screen" then UIM():close(w.widget) end + end + local p = require("apps/filemanager/filemanager").instance.gzreader + p.store.memos = { server = os.getenv("GZ_STICKER_SERVER") or "http://127.0.0.1:18090", token = "memos-test-token", prefix = "/api/v1", user = "Will" } + G_reader_settings:delSetting("gzreader_drawing_sticker") + G_reader_settings:delSetting("gzreader_drawing_sticker_category") + os.execute("rm -rf '" .. require("gzreader_stickers").dir() .. "'") + require("gzreader_drawscreen").show{ title = "Stickers", plugin = p, on_done = function() end, on_cancel = function() end } +end, after = 4 }) +add({ fn = function(E) screen():setPaper("ruled-medium") end, after = 3 }) +add({ fn = function(E) + check(button("sticker") ~= nil, "the tools down the side have Stickers") + E.tap(button("sticker")) +end, after = 6 }) +add({ shot = "1-picker", after = 0.5 }) +add({ fn = function(E) + local g = find("gz_sticker_grid") + check(g and g.cat and g.cat.slug == "animals" and #g.cells == 3, "no sticker chosen yet: the picker, at the first category (its 3 stickers fetched)") + E.tap({ g.cells[2].w.dimen.x + 20, g.cells[2].w.dimen.y + 20 }) +end, after = 3 }) +add({ fn = function(E) + local d = screen() + check(not find("gz_sticker_grid") and d.tool == "sticker" and d.sticker and d.sticker.name == "Baby Zebra", + "a sticker tapped: the picker closes, the Stickers tool in hand with it") + E.tap({ math.floor(W * 0.4), math.floor(H * 0.35) }) +end, after = 3 }) +add({ fn = function(E) E.tap({ math.floor(W * 0.6), math.floor(H * 0.55) }) end, after = 3 }) +add({ shot = "2-stamped", after = 0.5 }) +add({ fn = function(E) + local d = screen() + local pics = d.sketch:movablePictures() + check(#pics == 2 and pics[1].width == 30 * require("gzreader_stickers").SIZES[2], "two taps: two stickers on the page (Medium)") + -- the clear ground: the paper's lines go on under the sticker, not a box + local el = pics[1] + local x0, y0 = d.sketch:toCanvas(el.x, el.y) + local px = d.canvas_bb:getPixel(math.floor(x0) + 2, math.floor(y0) + 2) + local v = px.a or (px.getColor8 and px:getColor8().a) + check(v and v > 200, "…around the sticker the page shows, not a dark box (corner pixel " .. tostring(v) .. ")") + E.tap(button("sticker")) +end, after = 3 }) +add({ shot = "3-panel", after = 0.5 }) +add({ fn = function(E) + local d = screen() + check(d.flyout == "sticker" and button("ss3") ~= nil and button("sticker-pick") ~= nil, "Stickers again: its panel (another sticker, Small / Medium / Large)") + E.tap(button("ss3")) +end, after = 2 }) +add({ fn = function(E) + check(screen().sticker_size == 3, "Large chosen") + E.tap({ math.floor(W * 0.45), math.floor(H * 0.78) }) +end, after = 3 }) +add({ shot = "4-large", after = 0.5 }) +add({ fn = function(E) + E.tap(button("undo")) +end, after = 3 }) +add({ fn = function(E) + check(#screen().sketch:movablePictures() == 2, "Undo takes the last sticker off") + local f = io.open(E.out .. "/sticker-checks.txt", "w") + f:write(table.concat(lines, "\n") .. "\n") + f:close() +end, after = 1 }) +return s diff --git a/tools/gzreader/tests/run_tests.lua b/tools/gzreader/tests/run_tests.lua index c143bd10e..5f0438a97 100644 --- a/tools/gzreader/tests/run_tests.lua +++ b/tools/gzreader/tests/run_tests.lua @@ -10583,7 +10583,7 @@ print("Notes (Memos v0.31)") "drawing: the page is the whole screen, the top bar and the tools fold away; a new drawing's name and tags come from the top bar and Done saves it") local ids = {} for _i, t in ipairs(require("gzreader_drawscreen").SIDE_TOOLS) do ids[#ids + 1] = t.id end - check(table.concat(ids, ",") == "pen,highlighter,shape,text,eraser,lasso,hand,fingers,sep,undo,redo,more", + check(table.concat(ids, ",") == "pen,highlighter,shape,text,sticker,eraser,lasso,hand,fingers,sep,undo,redo,more", "drawing: the tools down the side, as the Scribe's (pen / finger on pen Kindles): " .. table.concat(ids, ",")) -- drawing keeps the Kindle awake (AutoSuspend's idle timer: KOReader's InputEvent hook), at most every few seconds do @@ -15088,5 +15088,118 @@ print("Immich photos for notes and drawings (gzreader_immichpick.lua): the Memos plugin.store.memos, plugin.store.immich = saved.memos, saved.immich end)() +print("Stickers in drawings (gzreader_stickers.lua): the Memos fork's Kid Pix stickers, as PNG pictures") +;(function() + local Stickers = require("gzreader_stickers") + local DS = require("gzreader_drawscreen") + local Sketch = require("gzreader_sketch") + local lfs = require("libs/libkoreader-lfs") + local SP = PORT + 88 + local function start(flags) + os.execute("python3 -I " .. PLUGIN .. "/../../tools/gzreader/emulator/demo/mock_memos.py " .. SP .. " " .. flags + .. " > " .. WORK .. "/stk.log 2>&1 & echo $! > " .. WORK .. "/stk.pid") + for _try = 1, 50 do + local pp = io.popen("curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:" .. SP .. "/__state"); local cc = pp:read("*a"); pp:close() + if cc == "200" then break end + socket.sleep(0.2) + end + end + local function stop() os.execute("kill $(cat " .. WORK .. "/stk.pid) 2>/dev/null") end + local function fetched() + local st = json.decode(io.popen("curl -s http://127.0.0.1:" .. SP .. "/__state"):read("*a")) + return st.stickers_fetched or {} + end + os.execute("rm -rf '" .. Stickers.dir() .. "'") + + -- the fork's list, checked + local good = { version = 1, scale = 2, categories = { + { slug = "animals", name = "Animals", items = { { name = "Fox", file = "animals/0.png", width = 40, height = 30 }, + { name = "Bad", file = "../../etc/passwd", width = 1, height = 1 }, { name = "Owl", file = "animals/2.png", width = 20, height = 25 } } }, + { slug = "../x", name = "Nope", items = { { name = "a", file = "../x/0.png", width = 1, height = 1 } } }, + } } + local idx = Stickers.parseIndex(good) + check(idx and #idx.categories == 1 and #idx.categories[1].items == 2 and idx.categories[1].items[2].file == "animals/2.png" + and idx.categories[1].items[1].w == 40 and Stickers.parseIndex({ version = 2, categories = {} }) == nil and Stickers.parseIndex("x") == nil, + "stickers: the fork's list read; a file name that isn't /.png (or a strange category) left out") + local saved_memos = plugin.store.memos + plugin.store.memos = nil + check(Stickers.server(plugin) == nil, "stickers: no Memos sign-in: no server to fetch them from") + plugin.store.memos = { server = "http://127.0.0.1:" .. SP .. "/", token = "memos-test-token" } + local server = Stickers.server(plugin) + check(server == "http://127.0.0.1:" .. SP, "stickers: from GZreader's Memos server") + + -- a stock Memos (no sticker pictures) + start("") + local none, err = Stickers.fetchIndex(server) + check(none == nil and err == "no_stickers" and Stickers.why(err):find("Memos fork", 1, true) ~= nil and Stickers.index() == nil, + "stickers: a Memos without them: said so (they come with the Memos fork)") + stop() + + -- the fork's + start("--stickers") + local index = Stickers.fetchIndex(server) + check(index and #index.categories == 2 and index.categories[1].name == "Animals" and #index.categories[1].items == 3, + "stickers: the list fetched from the fork") + local kept = Stickers.index() + check(kept and #kept.categories == 2 and kept.categories[2].items[2].name == "Pie", "…and kept on the Kindle (opened again without Wi-Fi)") + local animals = index.categories[1] + check(Stickers.have(animals) == 0 and Stickers.path(animals.items[1]) == nil, "…the pictures aren't fetched until their category is opened") + local n, ferr = Stickers.fetchCategory(server, animals) + check(n == 3 and ferr == nil and Stickers.have(animals) == 3 and Stickers.have(index.categories[2]) == 0, + "stickers: a category opened: its pictures fetched (only its own)") + local before = #fetched() + Stickers.fetchCategory(server, animals) + check(#fetched() == before, "…and kept: opened again, nothing is fetched") + local f = io.open(Stickers.path(animals.items[2]), "rb"); local head = f:read(8); f:close() + check(head == "\137PNG\r\n\26\n", "…each a PNG") + stop() + + -- how one goes on the page + local w, h = Stickers.size(animals.items[1], 1) + local w3 = Stickers.size(animals.items[1], 3) + check(w == 40 and h == 30 and w3 == 40 * Stickers.SIZES[3] and Stickers.size(animals.items[1], 99) == 40 * Stickers.SIZES[Stickers.DEFAULT_SIZE], + "stickers: Small is the sticker's own size (as Kid Pix put it down), Medium and Large bigger") + check(Stickers.number(animals.items[3]) == 2 and Stickers.find(kept, "animals", 2).name == "Blue Bunny" and Stickers.find(kept, "nope", 0) == nil, + "stickers: one found again by its category and number (the one last used, kept)") + local url = Stickers.dataURL(animals.items[1]) + check(url and url:find("^data:image/png;base64,iVBORw0KGgo") ~= nil, "stickers: its picture as the drawing keeps a picture (a PNG data URL)") + + -- the drawing screen: a tap with the Stickers tool + local sk = Sketch.new{ canvas = { x = 0, y = 0, w = 1000, h = 1400 }, per_unit = 2 } + local painted = 0 + local fake = setmetatable({ sketch = sk, sticker = animals.items[1], sticker_size = 2, + touched = function(self) self.was_touched = true end, + repaintArea = function(_self, area) painted = area.x1 - area.x0; return true end, + refreshBar = function() end, redrawAll = function() end }, { __index = function(_t, k) return rawget(DS, k) end }) + local el = fake:stampSticker(300, 400) + local sx, sy = sk:toScene(300, 400) + check(el and el.type == "image" and el.width == 40 * Stickers.SIZES[2] and math.abs(el.x + el.width / 2 - sx) < 0.01 + and math.abs(el.y + el.height / 2 - sy) < 0.01 and sk.base.files[el.fileId].dataURL == url and fake.was_touched + and painted >= el.width * sk.per_unit, + "drawing: a tap with the Stickers tool puts the sticker down there (Medium), only that part of the page drawn again") + check(sk:undo() and #sk:movablePictures() == 0, "…Undo takes it off") + -- its panel + local rows = DS.flyoutRows(fake, "sticker") + local labels = {} + for _i, r in ipairs(rows) do labels[#labels + 1] = r.label end + check(table.concat(labels, "|") == "Choose a sticker…|Small|Medium|Large" and DS.selected(fake, rows[3]) and not DS.selected(fake, rows[2]), + "drawing: the Stickers tool's panel: choose another, its size (the one in use marked)") + -- pictures with a clear ground (stickers) go on through it; others are copied (quicker) + local Blitbuffer = require("ffi/blitbuffer") + local calls = {} + local dst = { blitFrom = function() calls[#calls + 1] = "copy" end, alphablitFrom = function() calls[#calls + 1] = "alpha" end } + local was_t = { rawget(Blitbuffer, "TYPE_BB8"), rawget(Blitbuffer, "TYPE_BB8A"), rawget(Blitbuffer, "TYPE_BBRGB32") } + rawset(Blitbuffer, "TYPE_BB8", 1); rawset(Blitbuffer, "TYPE_BB8A", 2); rawset(Blitbuffer, "TYPE_BBRGB32", 5) + DS.blitPicture(dst, { getType = function() return 5 end }, 0, 0, 0, 0, 1, 1) + DS.blitPicture(dst, { getType = function() return 2 end }, 0, 0, 0, 0, 1, 1) + DS.blitPicture(dst, { getType = function() return 1 end }, 0, 0, 0, 0, 1, 1) + rawset(Blitbuffer, "TYPE_BB8", was_t[1]); rawset(Blitbuffer, "TYPE_BB8A", was_t[2]); rawset(Blitbuffer, "TYPE_BBRGB32", was_t[3]) + check(calls[1] == "alpha" and calls[2] == "alpha" and calls[3] == "copy", "drawing: a sticker's clear ground shows the page under it (a grey picture: copied)") + local dsrc = io.open(PLUGIN .. "/gzreader_drawscreen.lua"):read("*a") + check(select(2, dsrc:gsub("DrawScreen%.blitPicture%(", "")) >= 6 and dsrc:find("if out.sticker_tap then self:stampSticker", 1, true) ~= nil, + "drawing: every picture of the page goes on that way; the tap reaches stampSticker") + plugin.store.memos = saved_memos +end)() + print(string.format("\n%d passed, %d failed", pass, fail)) os.exit(fail == 0 and 0 or 1) diff --git a/tools/gzreader/tests/sketch_test.lua b/tools/gzreader/tests/sketch_test.lua index 8e99794fb..cb039fafe 100644 --- a/tools/gzreader/tests/sketch_test.lua +++ b/tools/gzreader/tests/sketch_test.lua @@ -643,6 +643,31 @@ print("== text boxes: added, moved, resized, undone; in the memos scene") check(#sk.strokes == 1, "another tool: a stroke over the box draws as before") end)() +print("== the Stickers tool: a tap puts a sticker down; a picture in the scene, undone") +;(function() + local sk = Sketch.new{ canvas = { x = 0, y = 0, w = 1000, h = 1400 }, per_unit = 2 } + sk.tool = "sticker" + local function frames(list) + local last + for i, f in ipairs(list) do last = sk:frame(f, i * 0.4) end + return last + end + local out = frames({ { finger(0, 200, 300) }, { lift(0) } }) + check(out.sticker_tap and out.sticker_tap.x == 200 and out.sticker_tap.y == 300 and #sk.strokes == 0, + "the Stickers tool: a tap on the page is for a sticker there (no ink)") + out = frames({ { pen(400, 500) }, { lift(PEN_SLOT, PEN) } }) + check(out.sticker_tap and out.sticker_tap.x == 400, "…with the pen too") + out = frames({ { finger(0, 200, 300) }, { finger(0, 300, 400) }, { finger(0, 400, 500) }, { lift(0) } }) + check(not out.sticker_tap and #sk.strokes == 0, "a drag: nothing (no sticker, no ink)") + -- what the drawing screen does with the tap (DrawScreen:stampSticker): a picture, centred there + local sx, sy = sk:toScene(200, 300) + local el = sk:addPicture("data:image/png;base64,iVBORw0KGgo=", "image/png", 64, 48, sx, sy) + check(el.type == "image" and el.x == sx - 32 and el.y == sy - 24 and el.width == 64 + and sk.base.files[el.fileId].mimeType == "image/png" and #sk:movablePictures() == 1, + "a sticker: a picture in the scene, centred where tapped, a PNG; the lasso can take it") + check(sk:undo() and #sk:movablePictures() == 0, "Undo takes it off") +end)() + print("== the PNG's crop and the memos scene") ;(function() local sk = Sketch.new{ canvas = CANVAS, per_unit = 2 } diff --git a/wiki/Notes.md b/wiki/Notes.md index d84821d23..08efd8a26 100644 --- a/wiki/Notes.md +++ b/wiki/Notes.md @@ -367,6 +367,18 @@ API to `/api` are found too. and the words go into the same box. **Undo** brings the writing back as ink. How it's read is in the panel (**Read: …**) and in [Settings → Notes → Handwriting to text](#handwriting-to-text). + - **Stickers:** the 935 Kid Pix stickers of the Memos fork's drawing + sheet (animals, food, flags, vehicles, praise…). The first tap opens + them: the category's name at the top lists the 42 categories, ‹ › + turn the pages; tap one to take it. Then each tap on the page puts it + down there; tap **Stickers** again for another sticker and its size + (**Small** is the size Kid Pix put it down at, **Medium**, **Large**). + A sticker is a picture in the drawing, as in Memos' Kid Pix mode: + **Undo** takes it off, the **lasso** moves it and makes it bigger or + smaller, and Memos shows it. They come from your Memos server (the + fork's, with its sticker pictures): a category is fetched over Wi‑Fi + the first time it's opened, then kept on the Kindle. On a colour + Kindle (Colorsoft, Scribe Colorsoft) they're in colour. - **Eraser:** rubs out whole strokes, as in Memos; five sizes (how near a stroke it has to pass) and **Erase page**. It keeps up with the pen on a full page too. From 22b2836ee9e74cf5067d457c67afe06b0fc64a6a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 12:44:56 -0500 Subject: [PATCH 2/4] Drawing: the Stickers tool's lines away from the colour PR's (#321) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HqNYrwobY8un97LQ2jriQC --- plugins/gzreader.koplugin/gzreader_drawscreen.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/plugins/gzreader.koplugin/gzreader_drawscreen.lua b/plugins/gzreader.koplugin/gzreader_drawscreen.lua index 095012de4..09a1e8a19 100644 --- a/plugins/gzreader.koplugin/gzreader_drawscreen.lua +++ b/plugins/gzreader.koplugin/gzreader_drawscreen.lua @@ -782,12 +782,12 @@ DrawScreen.EDGE = function() return S(24) end DrawScreen.FLYOUT_ANCHOR = { tags = "tag" } function DrawScreen:selected(t) + if t.sticker_size then return self.sticker_size == t.sticker_size end if t.writing then return self.tool == "pen" and self.writing == t.writing end if t.width then return self.tool ~= "highlighter" and self.width == t.width end if t.hl_width then return self.hl_width == t.hl_width end if t.shape then return self.tool == "shape" and self.shape == t.shape end if t.eraser_width then return self.eraser_width == t.eraser_width end - if t.sticker_size then return self.sticker_size == t.sticker_size end if t.color then return Sketch.inkColor(t.color) == self.color end if t.tagname then for _i, name in ipairs(self.meta and self.meta.tags or {}) do if name == t.tagname then return true end end @@ -2463,6 +2463,9 @@ function DrawScreen:use(t) self.eraser_width = t.eraser_width keep("gzreader_drawing_eraser_width", t.eraser_width) self:setTool("eraser"); self:setFlyout(nil) + elseif t.color then self:setColor(t.color); self:setFlyout(nil) + elseif t.tagname then self:toggleTag(t.tagname); self:setFlyout("tags") + elseif t.id == "newtag" then self:newTag() elseif t.sticker_size then self.sticker_size = t.sticker_size keep("gzreader_drawing_sticker_size", t.sticker_size) @@ -2473,9 +2476,6 @@ function DrawScreen:use(t) elseif self.sticker then self:setTool("sticker"); self:setFlyout(nil) else self:setFlyout(nil); self:pickSticker() end elseif t.id == "sticker-pick" then self:setFlyout(nil); self:pickSticker() - elseif t.color then self:setColor(t.color); self:setFlyout(nil) - elseif t.tagname then self:toggleTag(t.tagname); self:setFlyout("tags") - elseif t.id == "newtag" then self:newTag() elseif t.id == "tag" then self:setFlyout(self.flyout ~= "tags" and "tags" or nil) elseif t.id == "title" then self:setFlyout(nil); self:rename() elseif t.id == "snap" then From fe6fb9a8de60584167d394554e43b8d9f53b38d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 13:15:32 -0500 Subject: [PATCH 3/4] Stickers: the list and pictures downloads capped; at most 100 categories, 500 stickers each A server sending more than it may (the list over 1 MB, a picture over 512 kB) has its download stopped and nothing of it kept. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HqNYrwobY8un97LQ2jriQC --- .../gzreader.koplugin/gzreader_stickers.lua | 32 +++++++++++++++---- tools/gzreader/tests/run_tests.lua | 16 ++++++++++ 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/plugins/gzreader.koplugin/gzreader_stickers.lua b/plugins/gzreader.koplugin/gzreader_stickers.lua index 0d0999ce4..4cb71587e 100644 --- a/plugins/gzreader.koplugin/gzreader_stickers.lua +++ b/plugins/gzreader.koplugin/gzreader_stickers.lua @@ -29,6 +29,9 @@ local ltn12 = require("ltn12") local Stickers = { PATH = "/kidpix/sticker-png/", MAX_BYTES = 512 * 1024, -- (a sticker picture; the biggest is about 60 kB) + MAX_INDEX_BYTES = 1024 * 1024, -- (the list; the fork's is about 100 kB) + MAX_CATEGORIES = 100, -- (the fork has 42) + MAX_ITEMS = 500, -- (in a category; the fork's biggest has about 60) -- the sizes offered: the sticker's own size (1x: as Kid Pix put it down) times these SIZES = { 1, 1.6, 2.4 }, DEFAULT_SIZE = 2, @@ -60,9 +63,11 @@ function Stickers.parseIndex(data) if type(data) ~= "table" or tonumber(data.version) ~= 1 or type(data.categories) ~= "table" then return nil end local out = { scale = tonumber(data.scale) or 2, categories = {} } for _i, c in ipairs(data.categories) do + if #out.categories >= Stickers.MAX_CATEGORIES then break end if type(c) == "table" and safe(c.slug) and type(c.items) == "table" then local cat = { slug = c.slug, name = type(c.name) == "string" and c.name or c.slug, items = {} } for n, it in ipairs(c.items) do + if n > Stickers.MAX_ITEMS then break end local file = type(it) == "table" and it.file local w, h = tonumber(type(it) == "table" and it.width), tonumber(type(it) == "table" and it.height) if file == c.slug .. "/" .. (n - 1) .. ".png" and w and h and w > 0 and h > 0 then @@ -98,16 +103,30 @@ function Stickers.have(cat) return n end -local function get(url, sink) +--- GET `url` into `sink`, at most `max` bytes (more: the download stops). +--- Returns the HTTP code (nil: no answer, or stopped) and whether it was too big. +local function get(url, sink, max) local Api = require("gzreader_api") - return Api.rawRequest("GET", url, { headers = { Accept = sink and "image/png" or "application/json" }, sink = sink, - want_raw = not sink or nil, timeouts = { 10, 30 } }) + local got, over = 0, false + local function capped(chunk, err) + if chunk then + got = got + #chunk + if got > max then over = true; return nil, "too big" end + end + return sink(chunk, err) + end + local code = Api.rawRequest("GET", url, { headers = { Accept = "image/png, application/json" }, sink = capped, + timeouts = { 10, 30 } }) + return code, over end --- Fetches the list from `server` and keeps it: the list, or nil, err. --- (In a background process or with Wi-Fi up: it waits for the answer.) function Stickers.fetchIndex(server) - local code, text = get(server .. Stickers.PATH .. "index.json") + local parts = {} + local code, over = get(server .. Stickers.PATH .. "index.json", ltn12.sink.table(parts), Stickers.MAX_INDEX_BYTES) + local text = table.concat(parts) + if over then return nil, "too_big" end if type(code) ~= "number" then return nil, "unreachable" end if code == 404 then return nil, "no_stickers" end -- (a Memos without the fork's sticker pictures) if code ~= 200 then return nil, "http_" .. code end @@ -132,7 +151,8 @@ function Stickers.fetchCategory(server, cat) local part = path .. ".part" local fh = io.open(part, "wb") if not fh then err = "write"; break end - local code = get(server .. Stickers.PATH .. it.file, ltn12.sink.file(fh)) + local code, over = get(server .. Stickers.PATH .. it.file, ltn12.sink.file(fh), Stickers.MAX_BYTES) + pcall(fh.close, fh) -- (stopped part way: the sink didn't close it) local size = lfs.attributes(part, "size") or 0 local head local rf = io.open(part, "rb") @@ -141,7 +161,7 @@ function Stickers.fetchCategory(server, cat) os.rename(part, path) else os.remove(part) - err = type(code) == "number" and ("http_" .. code) or "unreachable" + err = over and "too_big" or type(code) == "number" and ("http_" .. code) or "unreachable" if err == "unreachable" then break end end end diff --git a/tools/gzreader/tests/run_tests.lua b/tools/gzreader/tests/run_tests.lua index 5f0438a97..537296cb8 100644 --- a/tools/gzreader/tests/run_tests.lua +++ b/tools/gzreader/tests/run_tests.lua @@ -15118,6 +15118,9 @@ print("Stickers in drawings (gzreader_stickers.lua): the Memos fork's Kid Pix st { slug = "../x", name = "Nope", items = { { name = "a", file = "../x/0.png", width = 1, height = 1 } } }, } } local idx = Stickers.parseIndex(good) + local many = { version = 1, categories = { { slug = "lots", name = "Lots", items = {} } } } + for k = 1, 600 do many.categories[1].items[k] = { name = "x", file = "lots/" .. (k - 1) .. ".png", width = 1, height = 1 } end + check(#Stickers.parseIndex(many).categories[1].items == Stickers.MAX_ITEMS, "stickers: a list naming too many stickers: only the first " .. Stickers.MAX_ITEMS .. " of a category") check(idx and #idx.categories == 1 and #idx.categories[1].items == 2 and idx.categories[1].items[2].file == "animals/2.png" and idx.categories[1].items[1].w == 40 and Stickers.parseIndex({ version = 2, categories = {} }) == nil and Stickers.parseIndex("x") == nil, "stickers: the fork's list read; a file name that isn't /.png (or a strange category) left out") @@ -15152,6 +15155,19 @@ print("Stickers in drawings (gzreader_stickers.lua): the Memos fork's Kid Pix st check(#fetched() == before, "…and kept: opened again, nothing is fetched") local f = io.open(Stickers.path(animals.items[2]), "rb"); local head = f:read(8); f:close() check(head == "\137PNG\r\n\26\n", "…each a PNG") + -- a server that sends too much: the download stops, nothing kept + local max_i, max_b = Stickers.MAX_INDEX_BYTES, Stickers.MAX_BYTES + Stickers.MAX_INDEX_BYTES = 100 + local big, berr = Stickers.fetchIndex(server) + Stickers.MAX_INDEX_BYTES = max_i + Stickers.MAX_BYTES = 50 + local food = index.categories[2] + local fn, fe = Stickers.fetchCategory(server, food) + Stickers.MAX_BYTES = max_b + local leftovers = 0 + for name in lfs.dir(Stickers.dir() .. "/food") do if name:match("%.part$") or name:match("%.png$") then leftovers = leftovers + 1 end end + check(big == nil and berr == "too_big" and fn == 0 and fe == "too_big" and leftovers == 0 and Stickers.index() ~= nil, + "stickers: a list or picture bigger than it may be: stopped, nothing of it kept (the list kept from before stays)") stop() -- how one goes on the page From d2dbd5092924246b9a8bf0fc91c5912afdf3ab7c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 13:59:34 -0500 Subject: [PATCH 4/4] Stickers: from the fork's SVGs (gzipped), drawn at the size they're put down The fork now serves its Kid Pix stickers as gzipped SVG (/kidpix/sticker-svg//.svgz). GZreader unzips each (capped at 4 MB), keeps it as .svg and draws it with KOReader's SVG renderer: for the picker, and for a sticker put down at its size (2 px a unit, at most 1600 a side), kept in the drawing as a PNG. Gzip.inflate takes a limit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HqNYrwobY8un97LQ2jriQC --- .../gzreader.koplugin/gzreader_drawscreen.lua | 6 +- plugins/gzreader.koplugin/gzreader_gzip.lua | 10 +- .../gzreader_stickergrid.lua | 14 +-- .../gzreader.koplugin/gzreader_stickers.lua | 116 +++++++++++------- tools/gzreader/emulator/demo/mock_memos.py | 48 ++++---- tools/gzreader/tests/run_tests.lua | 36 ++++-- 6 files changed, 135 insertions(+), 95 deletions(-) diff --git a/plugins/gzreader.koplugin/gzreader_drawscreen.lua b/plugins/gzreader.koplugin/gzreader_drawscreen.lua index 09a1e8a19..5ecf6ca01 100644 --- a/plugins/gzreader.koplugin/gzreader_drawscreen.lua +++ b/plugins/gzreader.koplugin/gzreader_drawscreen.lua @@ -2726,11 +2726,13 @@ end function DrawScreen:stampSticker(x, y) local Stickers = require("gzreader_stickers") local item = self.sticker - local url = item and Stickers.dataURL(item) + if not item then return self:pickSticker() end + local w, h = Stickers.size(item, self.sticker_size) + -- (drawn from its SVG at the size it goes down: sharp at any size) + local url = Stickers.dataURL(item, w, h) if not url then return self:pickSticker() end local sk = self.sketch local sx, sy = sk:toScene(x, y) - local w, h = Stickers.size(item, self.sticker_size) local el = sk:addPicture(url, "image/png", w, h, sx, sy) self:touched() Log.info("drawing: a sticker,", item.file) diff --git a/plugins/gzreader.koplugin/gzreader_gzip.lua b/plugins/gzreader.koplugin/gzreader_gzip.lua index ca9cac986..6cd8b4fbc 100644 --- a/plugins/gzreader.koplugin/gzreader_gzip.lua +++ b/plugins/gzreader.koplugin/gzreader_gzip.lua @@ -46,8 +46,8 @@ end function Gzip.available() return lib() ~= nil end ---- Decompress gzip data; nil, err on failure. -function Gzip.inflate(data) +--- Decompress gzip data; nil, err on failure. `max`: give up past that many bytes ("too big"). +function Gzip.inflate(data, max) local z = lib() if not z then return nil, "no zlib" end local strm = ffi.new("gz_z_stream") @@ -59,6 +59,7 @@ function Gzip.inflate(data) local chunk = math.max(65536, #data * 4) local buf = ffi.new("unsigned char[?]", chunk) local parts = {} + local total = 0 local ret repeat strm.next_out = buf @@ -69,6 +70,11 @@ function Gzip.inflate(data) return nil, "inflate error " .. tostring(ret) end parts[#parts + 1] = ffi.string(buf, chunk - strm.avail_out) + total = total + chunk - strm.avail_out + if max and total > max then + z.inflateEnd(strm) + return nil, "too big" + end until ret == 1 or (strm.avail_in == 0 and strm.avail_out ~= 0) z.inflateEnd(strm) return table.concat(parts) diff --git a/plugins/gzreader.koplugin/gzreader_stickergrid.lua b/plugins/gzreader.koplugin/gzreader_stickergrid.lua index 00fbb2f40..959c749e5 100644 --- a/plugins/gzreader.koplugin/gzreader_stickergrid.lua +++ b/plugins/gzreader.koplugin/gzreader_stickergrid.lua @@ -68,18 +68,8 @@ function Grid:thumb(item, side) self.bbs = self.bbs or {} local key = item.file .. ":" .. side if self.bbs[key] == nil then - local bb - local path = Stickers.path(item) - if path then - local RenderImage = require("ui/renderimage") - local ok, img = pcall(RenderImage.renderImageFile, RenderImage, path, false) - if ok and img then - local iw, ih = img:getWidth(), img:getHeight() - local k = math.min(side / iw, side / ih, 3) -- (a small sticker shown bigger, to see what it is) - local nw, nh = math.max(1, math.floor(iw * k)), math.max(1, math.floor(ih * k)) - bb = (nw ~= iw or nh ~= ih) and RenderImage:scaleBlitBuffer(img, nw, nh, true) or img - end - end + -- (drawn from its SVG, fitted into the square) + local bb = Stickers.render(item, side, side) self.bbs[key] = bb or false end return self.bbs[key] or nil diff --git a/plugins/gzreader.koplugin/gzreader_stickers.lua b/plugins/gzreader.koplugin/gzreader_stickers.lua index 4cb71587e..527dc4c36 100644 --- a/plugins/gzreader.koplugin/gzreader_stickers.lua +++ b/plugins/gzreader.koplugin/gzreader_stickers.lua @@ -4,20 +4,22 @@ picked in gzreader_stickergrid.lua). The stickers are the Memos fork's: Kid Pix Deluxe 4's 935 stickers, which the fork draws from their Flash movies in its own drawing sheet. A Kindle can't read -Flash, so the fork also serves them as PNG pictures (its -web/scripts/render-kidpix-stickers.mjs): +Flash, so the fork also serves them as SVG pictures, gzipped (its +web/scripts/render-kidpix-stickers.mjs; swf.ts's svg()): - /kidpix/sticker-png/index.json - { version = 1, scale = 2, categories = { { slug, name, items = { { name, file, width, height } } } } } - /kidpix/sticker-png//.png (twice the sticker's own size, 256 colours, a clear ground) + /kidpix/sticker-svg/index.json + { version = 1, categories = { { slug, name, items = { { name, file, width, height } } } } } + /kidpix/sticker-svg//.svgz (the sticker's shapes, at its own size, a clear ground) They're public files of the web app (no sign-in). The list and a category's -pictures are fetched the first time they're opened (over Wi-Fi) and kept in -cache/gzreader-stickers/, so a category opened once works without Wi-Fi. +pictures are fetched the first time they're opened (over Wi-Fi), unzipped and +kept in cache/gzreader-stickers/ as /.svg, so a category opened once +works without Wi-Fi. A sticker goes on the page as a picture (Sketch:addPicture), as the fork's own -Kid Pix mode puts its stickers into the drawing: Memos shows it, the lasso -moves and sizes it, Undo takes it off. +Kid Pix mode puts its stickers into the drawing: drawn from its SVG at the size +it's put down (sharp at any size), kept in the drawing as a PNG. Memos shows it, +the lasso moves and sizes it, Undo takes it off. ]] local DataStorage = require("datastorage") @@ -27,8 +29,11 @@ local lfs = require("libs/libkoreader-lfs") local ltn12 = require("ltn12") local Stickers = { - PATH = "/kidpix/sticker-png/", - MAX_BYTES = 512 * 1024, -- (a sticker picture; the biggest is about 60 kB) + PATH = "/kidpix/sticker-svg/", + MAX_BYTES = 512 * 1024, -- (a sticker as fetched, gzipped; the biggest is about 60 kB) + MAX_SVG_BYTES = 4 * 1024 * 1024, -- (unzipped; the biggest is about 250 kB) + PX_PER_UNIT = 2, -- (a sticker put down: drawn at 2 pixels a drawing unit, as sharp as a Scribe shows it) + MAX_SIDE = 1600, -- (… and never more than this many pixels a side) MAX_INDEX_BYTES = 1024 * 1024, -- (the list; the fork's is about 100 kB) MAX_CATEGORIES = 100, -- (the fork has 42) MAX_ITEMS = 500, -- (in a category; the fork's biggest has about 60) @@ -58,7 +63,7 @@ end local function safe(s) return type(s) == "string" and s:match("^[%w][%w%-_]*$") ~= nil end --- The fork's index.json, checked: { categories = { { slug, name, items = { { name, file, w, h } } } } } or nil. ---- (A file name must be "/.png": nothing else is fetched or written.) +--- (A file name must be "/.svgz": nothing else is fetched or written.) function Stickers.parseIndex(data) if type(data) ~= "table" or tonumber(data.version) ~= 1 or type(data.categories) ~= "table" then return nil end local out = { scale = tonumber(data.scale) or 2, categories = {} } @@ -70,8 +75,9 @@ function Stickers.parseIndex(data) if n > Stickers.MAX_ITEMS then break end local file = type(it) == "table" and it.file local w, h = tonumber(type(it) == "table" and it.width), tonumber(type(it) == "table" and it.height) - if file == c.slug .. "/" .. (n - 1) .. ".png" and w and h and w > 0 and h > 0 then - cat.items[#cat.items + 1] = { name = type(it.name) == "string" and it.name or "", file = file, w = w, h = h, slug = c.slug } + if file == c.slug .. "/" .. (n - 1) .. ".svgz" and w and h and w > 0 and h > 0 then + cat.items[#cat.items + 1] = { name = type(it.name) == "string" and it.name or "", file = file, + here = c.slug .. "/" .. (n - 1) .. ".svg", w = w, h = h, slug = c.slug } end end if #cat.items > 0 then out.categories[#out.categories + 1] = cat end @@ -90,9 +96,9 @@ function Stickers.index() return ok and Stickers.parseIndex(data) or nil end ---- A sticker's picture on the Kindle (its path), or nil when it isn't there yet. +--- A sticker's picture on the Kindle (its SVG's path), or nil when it isn't there yet. function Stickers.path(item) - local p = Stickers.dir() .. "/" .. item.file + local p = Stickers.dir() .. "/" .. item.here return lfs.attributes(p, "mode") == "file" and p or nil end @@ -115,7 +121,7 @@ local function get(url, sink, max) end return sink(chunk, err) end - local code = Api.rawRequest("GET", url, { headers = { Accept = "image/png, application/json" }, sink = capped, + local code = Api.rawRequest("GET", url, { headers = { Accept = "image/svg+xml, application/gzip, application/json" }, sink = capped, timeouts = { 10, 30 } }) return code, over end @@ -139,29 +145,34 @@ function Stickers.fetchIndex(server) return index end ---- Fetches the pictures of category `cat` that aren't on the Kindle yet: ---- how many it has now, and an error when some couldn't be fetched. +--- Fetches the pictures of category `cat` that aren't on the Kindle yet +--- (each gzipped SVG, unzipped and checked): how many it has now, and an +--- error when some couldn't be fetched. function Stickers.fetchCategory(server, cat) + local Gzip = require("gzreader_gzip") + if not Gzip.available() then return Stickers.have(cat), "no_gzip" end local dir = Stickers.dir() .. "/" .. cat.slug if lfs.attributes(dir, "mode") ~= "directory" then lfs.mkdir(dir) end local err for _i, it in ipairs(cat.items) do if not Stickers.path(it) then - local path = Stickers.dir() .. "/" .. it.file - local part = path .. ".part" - local fh = io.open(part, "wb") - if not fh then err = "write"; break end - local code, over = get(server .. Stickers.PATH .. it.file, ltn12.sink.file(fh), Stickers.MAX_BYTES) - pcall(fh.close, fh) -- (stopped part way: the sink didn't close it) - local size = lfs.attributes(part, "size") or 0 - local head - local rf = io.open(part, "rb") - if rf then head = rf:read(8); rf:close() end - if code == 200 and size > 0 and size <= Stickers.MAX_BYTES and head == "\137PNG\r\n\26\n" then - os.rename(part, path) + local parts = {} + local code, over = get(server .. Stickers.PATH .. it.file, ltn12.sink.table(parts), Stickers.MAX_BYTES) + local data = table.concat(parts) + local svg, zerr + if code == 200 and not over and data:sub(1, 2) == "\31\139" then + svg, zerr = Gzip.inflate(data, Stickers.MAX_SVG_BYTES) + end + if svg and svg:match("^%s*]") then + local path = Stickers.dir() .. "/" .. it.here + local fh = io.open(path .. ".part", "wb") + if not fh then err = "write"; break end + fh:write(svg) + fh:close() + os.rename(path .. ".part", path) else - os.remove(part) - err = over and "too_big" or type(code) == "number" and ("http_" .. code) or "unreachable" + err = (over or zerr == "too big") and "too_big" or type(code) ~= "number" and "unreachable" + or code ~= 200 and ("http_" .. code) or "not_svg" if err == "unreachable" then break end end end @@ -179,14 +190,36 @@ function Stickers.size(item, k) return item.w * f, item.h * f end ---- The sticker's picture as the drawing keeps it: a PNG data URL, or nil. -function Stickers.dataURL(item) +--- Sticker `item` drawn from its SVG `w` x `h` pixels (its shape kept, +--- centred): a BlitBuffer (RGB with a clear ground), or nil. +function Stickers.render(item, w, h) local p = Stickers.path(item) - local f = p and io.open(p, "rb") - if not f then return nil end - local data = f:read("*a") - f:close() - if not data or #data == 0 then return nil end + if not p then return nil end + local ok, bb = pcall(function() + return require("ui/renderimage"):renderSVGImageFile(p, math.max(1, math.floor(w + 0.5)), math.max(1, math.floor(h + 0.5))) + end) + if not ok or not bb then + Log.warn("stickers: couldn't draw", item.here, ok and "" or tostring(bb)) + return nil + end + return bb +end + +--- The sticker's picture as the drawing keeps it, for a sticker `w` x `h` +--- drawing units: drawn from its SVG at that size (PX_PER_UNIT, at most +--- MAX_SIDE a side), as a PNG data URL; or nil. +function Stickers.dataURL(item, w, h) + local k = math.min(Stickers.PX_PER_UNIT, Stickers.MAX_SIDE / math.max(w, h)) + local bb = Stickers.render(item, w * k, h * k) + if not bb then return nil end + local tmp = Stickers.dir() .. "/stamp.png" + local ok = pcall(bb.writePNG, bb, tmp) + bb:free() + local f = ok and io.open(tmp, "rb") + local data = f and f:read("*a") + if f then f:close() end + os.remove(tmp) + if not data or data:sub(1, 8) ~= "\137PNG\r\n\26\n" then return nil end return "data:image/png;base64," .. require("ffi/sha2").bin_to_base64(data) end @@ -205,7 +238,7 @@ function Stickers.find(index, slug, n) end --- The number of a sticker in its category (0-based, as its file). -function Stickers.number(item) return tonumber(item.file:match("/(%d+)%.png$")) end +function Stickers.number(item) return tonumber(item.file:match("/(%d+)%.svgz$")) end --- Why fetching failed, in words. function Stickers.why(err) @@ -213,6 +246,7 @@ function Stickers.why(err) if err == "no_server" then return _("Stickers come from your Memos server: sign in to Memos first (Settings → Accounts and services → Memos).") end if err == "no_stickers" then return _("Your Memos server has no stickers. They come with the Memos fork's Kid Pix stickers (sticker pictures from November 2026 on).") end if err == "unreachable" then return _("Couldn't reach your Memos server for the stickers.") end + if err == "no_gzip" then return _("This Kindle can't unpack the stickers (no zlib).") end return _("Couldn't fetch the stickers.") .. " (" .. tostring(err) .. ")" end diff --git a/tools/gzreader/emulator/demo/mock_memos.py b/tools/gzreader/emulator/demo/mock_memos.py index 5be49fa17..8fc8b4634 100644 --- a/tools/gzreader/emulator/demo/mock_memos.py +++ b/tools/gzreader/emulator/demo/mock_memos.py @@ -24,9 +24,9 @@ GET /api/immich/albums [{id, name, photoCount, thumbnailPhotoId}] GET /api/immich/photos ?album=&next= -> {photos: [{id, fileName, mimeType, takenAt, width, height}], next ("p:2")} GET /api/immich/photos//thumbnail | /preview (a small JPEG) ---stickers: the fork's Kid Pix stickers as PNG pictures (public files, no sign-in; without it: 404, as a stock Memos): - GET /kidpix/sticker-png/index.json two small categories (STICKER_INDEX) - GET /kidpix/sticker-png//.png a coloured disc on a clear ground, twice the listed size +--stickers: the fork's Kid Pix stickers as gzipped SVG pictures (public files, no sign-in; without it: 404, as a stock Memos): + GET /kidpix/sticker-svg/index.json two small categories (STICKER_INDEX) + GET /kidpix/sticker-svg//.svgz a coloured disc on a clear ground, gzipped Sign-in: "Authorization: Bearer " (TOKEN below). python3 -I mock_memos.py PORT [--sample] [--prefix /api] [--memos26] [--spaces] [--journal] [--drawings] @@ -59,7 +59,7 @@ JOURNAL = "--journal" in sys.argv DAWARICH = "--dawarich" in sys.argv # (with --journal: Dawarich connected to the fork) IMMICH = "--immich" in sys.argv -STICKERS = "--stickers" in sys.argv # (the fork's Kid Pix stickers as PNGs: /kidpix/sticker-png/) +STICKERS = "--stickers" in sys.argv # (the fork's Kid Pix stickers as gzipped SVGs: /kidpix/sticker-svg/) # a small grey JPEG (96 x 64): what the Immich proxy sends as a thumbnail or a preview TEST_JPEG = base64.b64decode("/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA0JCgsKCA0LCgsODg0PEyAVExISEyccHhcgLikxMC4pLSwzOko+MzZGNywtQFdBRkxOUlNSMj5aYVpQYEpRUk//wAALCABAAGABAREA/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/9oACAEBAAA/AL/iTxC+hyWccVi1290WVVV9pyNuABg5zurO/wCEt1j/AKFK+/N//iKP+Et1j/oUr783/wDiKP8AhLdY/wChSvvzf/4ij/hLdY/6FK+/N/8A4ij/AIS3WP8AoUr783/+Io/4S3WP+hSvvzf/AOIo/wCEt1j/AKFK+/N//iKP+Et1j/oUr783/wDiKP8AhLdY/wChSvvzf/4ij/hLdY/6FK+/N/8A4itHw34hfXJLyOWxa0e1Kqys+45O7IIwMY21neMv+Rh8M/8AX3/7PHXXUUUVRutZ020fZPdxhskELliCOoOM4/GmQa9pU7lUvYwQM/OCg/NgK0aKKK5Hwb/yMPib/r7/APZ5KPGX/Iw+Gf8Ar7/9njrrqKK4/wAR+IPP32Vg/wC66SSg/f8AYe3v3+nXmaK3PD2utpzi3uSWtGP1MZ9R7eo/H69yjK6K6MGVhkEHII9aWiuR8G/8jD4m/wCvv/2eSjxl/wAjD4Z/6+//AGeOuuoqjrly1po11MmdwTaCGwQWOM59s5rzeiiiu98J3LXGior5zC5jyWzkcEfocfhWzRXI+Df+Rh8Tf9ff/s8lHjL/AJGHwz/19/8As8dddRWd4hhafQrtEIBCb+fRSGP6CvOqKKK7rwfC0Wi72IxLKzrjsOF5/FTW5RXI+Df+Rh8Tf9ff/s8lHjL/AJGHwz/19/8As8dddRRXC+IdCbTnNxbAtaMfqYz6H29D+H1w6K1ND0aXVZ8nKWyH55PX2Hv/AC/n6BFGkMKRRjakahVGc4A4FOorkfBv/Iw+Jv8Ar7/9nko8Zf8AIw+Gf+vv/wBnjrrqKKR1V0ZHUMrDBBGQR6Vj3XhjTLh9ypJAcknymwDn2OcfhimQeFNMics/nTDGNrvgD3+UCtqKKOGMRwxpGg6KowB+FOoorkfBv/Iw+Jv+vv8A9nkrR8SeHn1ySzkivmtHtSzKypuOTtwQcjGNtZ3/AAiWsf8AQ2335P8A/F0f8IlrH/Q2335P/wDF0f8ACJax/wBDbffk/wD8XR/wiWsf9Dbffk//AMXR/wAIlrH/AENt9+T/APxdH/CJax/0Nt9+T/8AxdH/AAiWsf8AQ2335P8A/F0f8IlrH/Q2335P/wDF0f8ACJax/wBDbffk/wD8XR/wiWsf9Dbffk//AMXWj4b8PPocl5JLfNdvdFWZmTacjdkk5Oc7q//Z") @@ -133,31 +133,25 @@ def chunk(t, d): + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")) -def sticker_png(w, h, rgb): - """A test sticker: a coloured disc on a clear ground (RGBA PNG).""" - rows = b"" - for y in range(h): - row = bytearray([0]) - for x in range(w): - inside = (x - w / 2) ** 2 + (y - h / 2) ** 2 <= (min(w, h) / 2 - 1) ** 2 - row += bytes(rgb) + bytes([255]) if inside else b"\0\0\0\0" - rows += bytes(row) - def chunk(t, d): - c = struct.pack(">I", len(d)) + t + d - return c + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF) - return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) - + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")) +def sticker_svgz(w, h, rgb): + """A test sticker: a coloured disc with an outline on a clear ground, as a gzipped SVG.""" + import gzip + r = min(w, h) / 2 - 1 + svg = ('' + '\n') % ( + w, h, w, h, w / 2, h / 2, r, rgb[0], rgb[1], rgb[2]) + return gzip.compress(svg.encode(), mtime=0) # the fork's index.json (two small categories); each picture twice its size -STICKER_INDEX = {"version": 1, "scale": 2, "categories": [ +STICKER_INDEX = {"version": 1, "categories": [ {"slug": "animals", "name": "Animals", "items": [ - {"name": "Armadillo", "file": "animals/0.png", "width": 40, "height": 30}, - {"name": "Baby Zebra", "file": "animals/1.png", "width": 30, "height": 40}, - {"name": "Blue Bunny", "file": "animals/2.png", "width": 20, "height": 20}]}, + {"name": "Armadillo", "file": "animals/0.svgz", "width": 40, "height": 30}, + {"name": "Baby Zebra", "file": "animals/1.svgz", "width": 30, "height": 40}, + {"name": "Blue Bunny", "file": "animals/2.svgz", "width": 20, "height": 20}]}, {"slug": "food", "name": "Food", "items": [ - {"name": "Apple", "file": "food/0.png", "width": 25, "height": 25}, - {"name": "Pie", "file": "food/1.png", "width": 35, "height": 20}]}, + {"name": "Apple", "file": "food/0.svgz", "width": 25, "height": 25}, + {"name": "Pie", "file": "food/1.svgz", "width": 35, "height": 20}]}, ]} STICKER_COLOURS = {"animals": (200, 40, 40), "food": (40, 160, 60)} @@ -430,18 +424,18 @@ def do_GET(self): return self.send(200, [{"lat": "42.36", "lon": "-71.06", "name": "Example Deli", "display_name": "Example Deli, Exampleton"}]) if u.path == "/__osm/reverse": return self.send(200, {"name": "", "address": {"suburb": "Example Square", "city": "Exampleton"}}) - if u.path.startswith("/kidpix/sticker-png/"): + if u.path.startswith("/kidpix/sticker-svg/"): # (public files of the web app: no sign-in) if not STICKERS: return self.send(404, raw=b"404 page not found", ctype="text/plain") - rest = u.path[len("/kidpix/sticker-png/"):] + rest = u.path[len("/kidpix/sticker-svg/"):] STATE.setdefault("stickers_fetched", []).append(rest) if rest == "index.json": return self.send(200, STICKER_INDEX) for cat in STICKER_INDEX["categories"]: for it in cat["items"]: if it["file"] == rest: - return self.send(200, raw=sticker_png(it["width"] * 2, it["height"] * 2, STICKER_COLOURS[cat["slug"]]), ctype="image/png") + return self.send(200, raw=sticker_svgz(it["width"], it["height"], STICKER_COLOURS[cat["slug"]]), ctype="application/gzip") return self.send(404, raw=b"404 page not found", ctype="text/plain") if u.path.startswith("/api/immich/"): if not (IMMICH or JOURNAL): # (stock Memos: no such address) diff --git a/tools/gzreader/tests/run_tests.lua b/tools/gzreader/tests/run_tests.lua index 537296cb8..bf04686b9 100644 --- a/tools/gzreader/tests/run_tests.lua +++ b/tools/gzreader/tests/run_tests.lua @@ -15113,17 +15113,18 @@ print("Stickers in drawings (gzreader_stickers.lua): the Memos fork's Kid Pix st -- the fork's list, checked local good = { version = 1, scale = 2, categories = { - { slug = "animals", name = "Animals", items = { { name = "Fox", file = "animals/0.png", width = 40, height = 30 }, - { name = "Bad", file = "../../etc/passwd", width = 1, height = 1 }, { name = "Owl", file = "animals/2.png", width = 20, height = 25 } } }, - { slug = "../x", name = "Nope", items = { { name = "a", file = "../x/0.png", width = 1, height = 1 } } }, + { slug = "animals", name = "Animals", items = { { name = "Fox", file = "animals/0.svgz", width = 40, height = 30 }, + { name = "Bad", file = "../../etc/passwd", width = 1, height = 1 }, { name = "Owl", file = "animals/2.svgz", width = 20, height = 25 } } }, + { slug = "../x", name = "Nope", items = { { name = "a", file = "../x/0.svgz", width = 1, height = 1 } } }, } } local idx = Stickers.parseIndex(good) local many = { version = 1, categories = { { slug = "lots", name = "Lots", items = {} } } } - for k = 1, 600 do many.categories[1].items[k] = { name = "x", file = "lots/" .. (k - 1) .. ".png", width = 1, height = 1 } end + for k = 1, 600 do many.categories[1].items[k] = { name = "x", file = "lots/" .. (k - 1) .. ".svgz", width = 1, height = 1 } end check(#Stickers.parseIndex(many).categories[1].items == Stickers.MAX_ITEMS, "stickers: a list naming too many stickers: only the first " .. Stickers.MAX_ITEMS .. " of a category") - check(idx and #idx.categories == 1 and #idx.categories[1].items == 2 and idx.categories[1].items[2].file == "animals/2.png" + check(idx and #idx.categories == 1 and #idx.categories[1].items == 2 and idx.categories[1].items[2].file == "animals/2.svgz" + and idx.categories[1].items[2].here == "animals/2.svg" and idx.categories[1].items[1].w == 40 and Stickers.parseIndex({ version = 2, categories = {} }) == nil and Stickers.parseIndex("x") == nil, - "stickers: the fork's list read; a file name that isn't /.png (or a strange category) left out") + "stickers: the fork's list read; a file name that isn't /.svgz (or a strange category) left out; kept unzipped as .svg") local saved_memos = plugin.store.memos plugin.store.memos = nil check(Stickers.server(plugin) == nil, "stickers: no Memos sign-in: no server to fetch them from") @@ -15153,8 +15154,9 @@ print("Stickers in drawings (gzreader_stickers.lua): the Memos fork's Kid Pix st local before = #fetched() Stickers.fetchCategory(server, animals) check(#fetched() == before, "…and kept: opened again, nothing is fetched") - local f = io.open(Stickers.path(animals.items[2]), "rb"); local head = f:read(8); f:close() - check(head == "\137PNG\r\n\26\n", "…each a PNG") + local f = io.open(Stickers.path(animals.items[2]), "rb"); local svgtext = f:read("*a"); f:close() + check(Stickers.path(animals.items[2]):match("animals/1%.svg$") and svgtext:match("^= el.width * sk.per_unit, "drawing: a tap with the Stickers tool puts the sticker down there (Medium), only that part of the page drawn again") check(sk:undo() and #sk:movablePictures() == 0, "…Undo takes it off") + package.loaded["ui/renderimage"] = RI -- its panel local rows = DS.flyoutRows(fake, "sticker") local labels = {}