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..5ecf6ca01 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 @@ -765,6 +782,7 @@ 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 @@ -775,7 +793,7 @@ function DrawScreen:selected(t) 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 @@ -2427,6 +2466,16 @@ function DrawScreen:use(t) 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) + 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.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 @@ -2657,6 +2706,44 @@ 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 + 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 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_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_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..959c749e5 --- /dev/null +++ b/plugins/gzreader.koplugin/gzreader_stickergrid.lua @@ -0,0 +1,235 @@ +--[[-- +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 + -- (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 +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..527dc4c36 --- /dev/null +++ b/plugins/gzreader.koplugin/gzreader_stickers.lua @@ -0,0 +1,253 @@ +--[[-- +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 SVG pictures, gzipped (its +web/scripts/render-kidpix-stickers.mjs; swf.ts's svg()): + + /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), 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: 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") +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-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) + -- 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 "/.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 = {} } + 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) .. ".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 + 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 SVG's path), or nil when it isn't there yet. +function Stickers.path(item) + local p = Stickers.dir() .. "/" .. item.here + 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 + +--- 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") + 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/svg+xml, application/gzip, 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 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 + 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 +--- (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 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 + 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 + 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 + +--- 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) + 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 + +--- 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+)%.svgz$")) 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 + 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 + +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..8fc8b4634 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 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] @@ -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 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") @@ -129,6 +133,29 @@ def chunk(t, d): + 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, "categories": [ + {"slug": "animals", "name": "Animals", "items": [ + {"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.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)} + + def pdf(): text = "BT /F1 24 Tf 72 720 Td (Trail map: Springer Mountain to Neels Gap) Tj ET" objs = [ @@ -349,7 +376,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 +424,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-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-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_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) 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..bf04686b9 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,148 @@ 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.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) .. ".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.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 /.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") + 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 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 = {} + 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.