diff --git a/Makefile b/Makefile index fccd333..33170f4 100644 --- a/Makefile +++ b/Makefile @@ -46,6 +46,7 @@ SD_DIR := $(LIBDIR)/tinyblocks-sdl2 PY_DIR := $(LIBDIR)/tinyblocks-python MC_DIR := $(LIBDIR)/tinyblocks-mcp A11Y_DIR := $(LIBDIR)/tinyblocks-a11y +QR_DIR := $(LIBDIR)/tinyblocks-qr MCPS_DIR := $(LIBDIR)/tinyblocks-mcp-server GFX_INC := $(GX_DIR)/include @@ -103,6 +104,7 @@ LIBM_A := $(LIBM_DIR)/build/libtinyblocks-libman.a SYN_A := $(SYN_DIR)/build/libtinyblocks-syntax.a SB_A := $(SB_DIR)/build/libtinyblocks-scratchblocks.a A11Y_A := $(A11Y_DIR)/build/libtinyblocks-a11y.a +QR_A := $(QR_DIR)/build/libtinyblocks-qr.a MCPS_A := $(MCPS_DIR)/build/libtinyblocks-mcp-server.a LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \ $(foreach l,$(CAT_LIBS),-L$(LIBDIR)/tinyblocks-$(l)/build) -L$(BUILD) @@ -110,7 +112,7 @@ LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \ .PHONY: all help debug release static shared example sdl2 clean run python-lib mcp-lib json \ editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \ appdir appimage run-appimage icon \ - test-toml test-plugin test-blueprint test-a11y test-mcp test-mcp-server test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \ + test-toml test-plugin test-blueprint test-qr test-a11y test-mcp test-mcp-server test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \ test-tensor test-ai test-http test-archive test-plot test-3d test-syntax test-os test-value test-vars test-scratchblocks test-input test-stdlib test-regex test-markdown test-opentype \ category-libs category-sos libs app-libs \ lib-events lib-control lib-errors lib-input lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \ @@ -177,12 +179,15 @@ $(foreach l,$(APP_LIBS),$(eval $(call CAT_LIB_TARGET,$(l)))) app-libs: $(foreach l,$(APP_LIBS),lib-$(l)) ## Compila tensor e as outras libraries do app (.a/.so) -lib-editor: lib-a11y lib-mcp-server +lib-editor: lib-a11y lib-mcp-server lib-qr $(MAKE) -C $(ED_DIR) lib-a11y: $(MAKE) -C $(A11Y_DIR) +lib-qr: + $(MAKE) -C $(QR_DIR) + lib-mcp-server: $(MAKE) -C $(MCPS_DIR) @@ -308,7 +313,7 @@ $(BUILD)/editor: examples/editor/main.c static libs -I$(JSON_DIR)/include -I$(XML_DIR)/include -I$(CSV_DIR)/include -I$(BP_DIR)/include \ -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(SYN_DIR)/include -I$(A11Y_DIR)/include -I$(MCPS_DIR)/include \ $< -o $@ \ - -Wl,--start-group $(ED_A) $(A11Y_A) $(MCPS_A) $(GX_A) $(SD_A) $(TOML_A) $(JSON_A) $(XML_A) $(CSV_A) $(BP_A) $(SB_A) $(API_A) $(LIBM_A) $(SYN_A) $(CAT_A) $(APP_A) $(LIB_A) -Wl,--end-group \ + -Wl,--start-group $(ED_A) $(A11Y_A) $(QR_A) $(MCPS_A) $(GX_A) $(SD_A) $(TOML_A) $(JSON_A) $(XML_A) $(CSV_A) $(BP_A) $(SB_A) $(API_A) $(LIBM_A) $(SYN_A) $(CAT_A) $(APP_A) $(LIB_A) -Wl,--end-group \ $(SDL2_LIBS) $(SDL2TTF_LIBS) $(APP_LDLIBS) -ldl -lm -rdynamic \ '-Wl,-rpath,$$ORIGIN' @@ -465,10 +470,10 @@ $(BUILD)/editor_harness: tests/editor_harness.c $(SRCS) \ $(EFILES_DIR)/include/tb_editor_files.h \ $(GX_DIR)/src/tb_graphics.c $(A11Y_DIR)/src/tb_a11y.c $(A11Y_DIR)/include/tb_a11y.h \ $(EDITOR_SRC)/tb_editor_mcp.c $(EDITOR_SRC)/tb_editor_jit.c $(MCPS_DIR)/src/tb_mcp_server.c $(MCPS_DIR)/src/tb_mcp_http.c \ - lib-blueprint ed-modules + lib-blueprint ed-modules lib-qr @mkdir -p $(BUILD) $(CC) $(CFLAGS_DBG) \ - -I$(ED_DIR)/include -I$(A11Y_DIR)/include -I$(MCPS_DIR)/include -DTB_EDITOR_PRIVATE_API -DTB_MCP_SERVER_PRIVATE_API -I$(EW_DIR)/include -I$(EIMG_DIR)/include -I$(EFILES_DIR)/include -I$(GFX_INC) $(CAT_INCS) -I$(BP_DIR)/include \ + -I$(ED_DIR)/include -I$(A11Y_DIR)/include -I$(QR_DIR)/include -I$(MCPS_DIR)/include -DTB_EDITOR_PRIVATE_API -DTB_MCP_SERVER_PRIVATE_API -I$(EW_DIR)/include -I$(EIMG_DIR)/include -I$(EFILES_DIR)/include -I$(GFX_INC) $(CAT_INCS) -I$(BP_DIR)/include \ -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(EN_DIR)/include -I$(TOML_DIR)/include -I$(CV_DIR)/include -I$(B64_DIR)/include -I$(PPM_DIR)/include -I$(SYN_DIR)/include -I$(SB_DIR)/include \ $(SRCS) \ $(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage_widget.c \ @@ -479,7 +484,7 @@ $(BUILD)/editor_harness: tests/editor_harness.c $(SRCS) \ $(API_DIR)/src/tb_api.c $(LIBM_DIR)/src/tb_libman.c \ $(TOML_LIB_SRCS) $(TOML_DIR)/src/tb_toml.c \ $(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/src/tb_$(l).c) \ - $(CV_DIR)/src/tb_curves.c $(B64_DIR)/src/tb_base64.c $(PPM_DIR)/src/tb_ppm.c $(SYN_DIR)/src/tb_syntax.c $(SB_DIR)/src/tb_scratchblocks.c tests/editor_harness.c -o $@ -ldl -lm -rdynamic + $(CV_DIR)/src/tb_curves.c $(B64_DIR)/src/tb_base64.c $(PPM_DIR)/src/tb_ppm.c $(SYN_DIR)/src/tb_syntax.c $(SB_DIR)/src/tb_scratchblocks.c tests/editor_harness.c $(QR_A) -o $@ -ldl -lm -rdynamic $(BUILD)/vm_bench: tests/vm_bench.c $(IMG_DIR)/src/tb_imglib.c $(SRCS) \ $(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage_widget.c \ @@ -489,10 +494,10 @@ $(BUILD)/vm_bench: tests/vm_bench.c $(IMG_DIR)/src/tb_imglib.c $(SRCS) \ $(EFILES_DIR)/include/tb_editor_files.h \ $(GX_DIR)/src/tb_graphics.c $(A11Y_DIR)/src/tb_a11y.c $(A11Y_DIR)/include/tb_a11y.h \ $(EDITOR_SRC)/tb_editor_mcp.c $(EDITOR_SRC)/tb_editor_jit.c $(MCPS_DIR)/src/tb_mcp_server.c $(MCPS_DIR)/src/tb_mcp_http.c \ - lib-blueprint ed-modules + lib-blueprint ed-modules lib-qr @mkdir -p $(BUILD) $(CC) $(CFLAGS_REL) -g -I$(IMG_DIR)/include \ - -I$(ED_DIR)/include -I$(A11Y_DIR)/include -I$(MCPS_DIR)/include -DTB_EDITOR_PRIVATE_API -DTB_MCP_SERVER_PRIVATE_API -I$(EW_DIR)/include -I$(EIMG_DIR)/include -I$(EFILES_DIR)/include -I$(GFX_INC) $(CAT_INCS) -I$(BP_DIR)/include \ + -I$(ED_DIR)/include -I$(A11Y_DIR)/include -I$(QR_DIR)/include -I$(MCPS_DIR)/include -DTB_EDITOR_PRIVATE_API -DTB_MCP_SERVER_PRIVATE_API -I$(EW_DIR)/include -I$(EIMG_DIR)/include -I$(EFILES_DIR)/include -I$(GFX_INC) $(CAT_INCS) -I$(BP_DIR)/include \ -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(EN_DIR)/include -I$(TOML_DIR)/include -I$(CV_DIR)/include -I$(B64_DIR)/include -I$(PPM_DIR)/include -I$(SYN_DIR)/include -I$(SB_DIR)/include \ $(SRCS) \ $(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage_widget.c \ @@ -503,7 +508,7 @@ $(BUILD)/vm_bench: tests/vm_bench.c $(IMG_DIR)/src/tb_imglib.c $(SRCS) \ $(API_DIR)/src/tb_api.c $(LIBM_DIR)/src/tb_libman.c \ $(TOML_LIB_SRCS) $(TOML_DIR)/src/tb_toml.c \ $(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/src/tb_$(l).c) \ - $(CV_DIR)/src/tb_curves.c $(B64_DIR)/src/tb_base64.c $(PPM_DIR)/src/tb_ppm.c $(SYN_DIR)/src/tb_syntax.c $(SB_DIR)/src/tb_scratchblocks.c $(IMG_DIR)/src/tb_imglib.c tests/vm_bench.c -o $@ -ldl -lm -rdynamic + $(CV_DIR)/src/tb_curves.c $(B64_DIR)/src/tb_base64.c $(PPM_DIR)/src/tb_ppm.c $(SYN_DIR)/src/tb_syntax.c $(SB_DIR)/src/tb_scratchblocks.c $(IMG_DIR)/src/tb_imglib.c tests/vm_bench.c $(QR_A) -o $@ -ldl -lm -rdynamic bench-vm: $(BUILD)/vm_bench ## Mede a VM do editor num projeto (BENCH=projeto.json) ./$(BUILD)/vm_bench $(BENCH) 10 @@ -583,6 +588,14 @@ $(BUILD)/mcp_server_test: tests/mcp_server_test.c $(MCPS_DIR)/src/tb_mcp_server. test-mcp-server: $(BUILD)/mcp_server_test ## Roda o teste do servidor MCP (ASan/UBSan) ./$(BUILD)/mcp_server_test +# -- Teste da library qr (gerar e ler QR code) --- +$(BUILD)/qr_test: tests/qr_test.c lib-qr + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) -I$(QR_DIR)/include tests/qr_test.c $(QR_A) -o $@ -lm + +test-qr: $(BUILD)/qr_test ## Roda o teste do QR code (gerar e ler) + ./$(BUILD)/qr_test + # -- Teste da library a11y (arvore acessivel) --- $(BUILD)/a11y_test: tests/a11y_test.c $(A11Y_DIR)/src/tb_a11y.c $(A11Y_DIR)/include/tb_a11y.h static @mkdir -p $(BUILD) diff --git a/libraries/tinyblocks-editor/Makefile b/libraries/tinyblocks-editor/Makefile index e5779ca..53307a5 100644 --- a/libraries/tinyblocks-editor/Makefile +++ b/libraries/tinyblocks-editor/Makefile @@ -16,7 +16,7 @@ CFLAGS := -std=c11 -O2 -Wall -Wextra -pedantic -fvisibility=hidden \ -I../tinyblocks-libman/include \ -I../tinyblocks-syntax/include \ -I../tinyblocks-scratchblocks/include \ - -I../tinyblocks-a11y/include \ + -I../tinyblocks-a11y/include -I../tinyblocks-qr/include \ -I../tinyblocks-mcp-server/include \ -Ilibraries/tinyblocks-editor-widgets/include \ -Ilibraries/tinyblocks-editor-image/include \ diff --git a/libraries/tinyblocks-editor/include/tb_editor.h b/libraries/tinyblocks-editor/include/tb_editor.h index b2e54a9..5ae2d9a 100644 --- a/libraries/tinyblocks-editor/include/tb_editor.h +++ b/libraries/tinyblocks-editor/include/tb_editor.h @@ -40,6 +40,9 @@ TB_API void tb_editor_preload(const char* path); * NULL se a acessibilidade estiver desligada (TINYBLOCKS_A11Y=0). */ typedef struct TinyBlocks_A11yTree TinyBlocks_A11yTree; TB_API TinyBlocks_A11yTree* tb_editor_accessible(TinyBlocks_Block* scene); +/* Para testes: entrega ao leitor de QR aberto um texto como se a camera o + * tivesse lido ("Receber blocos") */ +TB_API void tb_editor_qr_feed(TinyBlocks_Block* scene, const char* text); /* Servidor MCP do editor (tb_mcp_server.h, da tinyblocks-mcp-server): as * ferramentas para agentes lerem e editarem as pilhas. Escuta em diff --git a/libraries/tinyblocks-editor/include/tb_editor_internal.h b/libraries/tinyblocks-editor/include/tb_editor_internal.h index 67b4f31..196dd0c 100644 --- a/libraries/tinyblocks-editor/include/tb_editor_internal.h +++ b/libraries/tinyblocks-editor/include/tb_editor_internal.h @@ -552,6 +552,20 @@ typedef struct { float x, w; } Part; +/* Rolagem animada: de `from` a `to` a partir de t0 (curva standard do M3) */ +typedef struct { bool on; float from, to; unsigned t0; } ScrollAnim; + +/* Bloco apagado saindo de cena: os comandos de desenho dele (na tela) */ +#define GHOST_MAX 8 +typedef struct { + TinyBlocks_DrawCmd* cmds; + int n; + float cx, cy; + unsigned t0; + bool clip; + float clip_r[4]; +} Ghost; + typedef struct { bool used; bool dragging; @@ -586,6 +600,13 @@ typedef struct { const void* jst_T; int jst_bi, jst_depth; uint32_t jst_gen; + /* animacao: deslize ao mudar de lugar na pilha (offset que vai a zero) e + surgir (blocos criados por codigo); l_* = o ultimo layout visto */ + float an_dx, an_dy; + unsigned an_t0, ap_t0; + bool l_ok; + int l_root; + float l_x, l_y, l_rx, l_ry; } EdBlock; /* Um trecho colorido do editor de codigo (vindo do tinyblocks-syntax). */ @@ -690,7 +711,8 @@ typedef enum { SN_NONE, SN_NEXT, SN_SUB, SN_ABOVE, SN_ARG, SN_STACK } SnapKind; enum { CM_DUPLICATE, CM_DELETE, CM_EDIT_DEF, CM_CLEANUP, CM_NEW_COMPOSITE, CM_EXP_JSON, CM_EXP_XML, CM_EXP_CSV, CM_EXP_SB, CM_PASTE_SB, CM_GROUP_NEW, CM_GROUP_STACK, CM_GROUP_RENAME, CM_GROUP_COLOR, CM_GROUP_DELETE, - CM_MB_OPEN, CM_MB_SAVE, CM_MB_EXPORT, CM_MB_LIBMAN, CM_MB_LIB, CM_MB_CFG }; + CM_MB_OPEN, CM_MB_SAVE, CM_MB_EXPORT, CM_MB_LIBMAN, CM_MB_LIB, CM_MB_CFG, + CM_SOURCE, CM_SHARE_STACK, CM_SHARE_TAB, CM_RECEIVE }; /* Modos da barra de caminho do menu (path_input) */ enum { PM_NONE, PM_LIB, PM_LOAD, PM_SAVE, PM_EXP_JSON, PM_EXP_XML, PM_EXP_CSV, @@ -1048,6 +1070,35 @@ typedef struct Ed { /* Servidor MCP: agentes leem e editam as pilhas por ferramentas */ struct TbMcpServer* mcp; + /* Animacoes (curvas do M3). anim_off: TINYBLOCKS_REDUCE_MOTION=1 (e os + testes): tudo vai direto ao fim */ + unsigned t_ms; /* relogio do quadro */ + bool anim_off; + bool appear_batch; /* blocos criados agora surgem animados */ + int appear_k; /* ordem dentro do lote (cascata) */ + ScrollAnim sa_ws_x, sa_ws_y, sa_fly, sa_cat, sa_lm, sa_st; + int sa_ws_tab; + struct { bool on; float from, to, ax, ay; unsigned t0; int tab; } za; /* zoom */ + Ghost ghosts[GHOST_MAX]; /* blocos apagados saindo de cena */ + int ghost_n; + + /* QR: compartilhar (painel com os QR em loop, 1 s cada) e receber (camera) */ + bool qrs_open; + char* qrs_text; /* scratchblocks inteiro */ + int qrs_n; /* quantas partes */ + unsigned qrs_t0; + char qrs_id[8]; + char qrs_title[64]; + bool qrr_open, qrr_cam; + struct TbQrReader* qrr_reader; + unsigned char* qrr_gray; + TinyBlocks_Image* qrr_img; /* previa da camera */ + char qrr_id[8]; + int qrr_n, qrr_got; + char** qrr_part; + float qrr_x, qrr_y; /* onde os blocos recebidos entram */ + char qrr_msg[200]; + /* Edicao de texto (te_*): o campo em edicao tem cursor e selecao; o editor de codigo tem os dele (code_caret/code_anchor). Alcas e barra de acoes (toque) servem aos dois (te_owner). */ @@ -1090,6 +1141,8 @@ static Ed* g_active_ed TB_EW_UNUSED = NULL; void bubble_clear(Ed* ed); void palette_rebuild(Ed* ed); +/* Bloco (ou a pilha a partir dele) saindo de cena: fantasma animado */ +void ghost_capture(Ed* ed, Tab* T, int bi, bool chain, float wsx, float wsy, bool clip); void utf8_pop(char* s); void append_text(char* dst, size_t cap, const char* add); /* Campo de texto em edicao (cursor, selecao, Ctrl+A/C/X/V): as teclas e o diff --git a/libraries/tinyblocks-editor/include/tb_editor_m3.h b/libraries/tinyblocks-editor/include/tb_editor_m3.h index 2ac960f..c9960bb 100644 --- a/libraries/tinyblocks-editor/include/tb_editor_m3.h +++ b/libraries/tinyblocks-editor/include/tb_editor_m3.h @@ -116,6 +116,10 @@ #define MI_REFRESH 0xe5d5 #define MI_SAVE 0xe161 #define MI_SEARCH 0xef7a +#define MI_SHARE 0xe80d +#define MI_QR_CODE 0xe00a +#define MI_QR_SCANNER 0xf206 +#define MI_SOURCE 0xf1c8 #define MI_SELECT 0xf74d #define MI_SETTINGS 0xe8b8 #define MI_STOP 0xe047 @@ -130,6 +134,28 @@ #define MI_ZOOM_IN 0xe8ff #define MI_ZOOM_OUT 0xe900 +/* == Movimento: curvas do M3 (cubic-bezier, como no CSS) === */ +static inline float m3_bezier(float x1, float y1, float x2, float y2, float t) { + if (t <= 0.f) return 0.f; + if (t >= 1.f) return 1.f; + float lo = 0.f, hi = 1.f, u = t; + for (int i = 0; i < 24; i++) { /* acha u com x(u) = t (bissecao) */ + u = (lo + hi) * 0.5f; + float iu = 1.f - u; + float x = 3.f * iu * iu * u * x1 + 3.f * iu * u * u * x2 + u * u * u; + if (x < t) lo = u; else hi = u; + } + float iu = 1.f - u; + return 3.f * iu * iu * u * y1 + 3.f * iu * u * u * y2 + u * u * u; +} +#define M3_EASE_STANDARD(t) m3_bezier(0.2f, 0.f, 0.f, 1.f, (t)) +#define M3_EASE_EMPH_DECEL(t) m3_bezier(0.05f, 0.7f, 0.1f, 1.f, (t)) /* entrar */ +#define M3_EASE_EMPH_ACCEL(t) m3_bezier(0.3f, 0.f, 0.8f, 0.15f, (t)) /* sair */ +#define M3_DUR_SCROLL 260u /* ms */ +#define M3_DUR_SLIDE 280u +#define M3_DUR_APPEAR 380u +#define M3_DUR_EXIT 220u + /* == Utilitarios === */ static inline Col m3_alpha(Col c, float a) { c.a = a; return c; } diff --git a/libraries/tinyblocks-editor/libraries/tinyblocks-editor-files/src/tb_editor_files.c b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-files/src/tb_editor_files.c index 803c5b7..3f566b7 100644 --- a/libraries/tinyblocks-editor/libraries/tinyblocks-editor-files/src/tb_editor_files.c +++ b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-files/src/tb_editor_files.c @@ -32,8 +32,6 @@ #define FD_BTN_H 36 static const Col COL_FD_FOLDER = C(255,191, 38); -static const Col COL_FD_FOLDER_DARK = C(222,150, 10); -static const Col COL_FD_SIDE = C(242,246,252); static const Col COL_FD_JSON = C(255,140, 26); static const Col COL_FD_IMAGE = C( 15,189,140); static const Col COL_FD_LIB = C(153,102,255); diff --git a/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/src/tb_editor_image.c b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/src/tb_editor_image.c index 7d33ee8..46a3e64 100644 --- a/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/src/tb_editor_image.c +++ b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/src/tb_editor_image.c @@ -25,7 +25,6 @@ static void img_clear_layer(Tab* T); static const Col COL_PAINT_BG = C(233,238,242); static const Col COL_PAINT_LINE = C(212,220,228); static const Col COL_PAINT_SHAD = C(196,205,214); -static const Col COL_PAINT_BTN = C(255,255,255); static const Col COL_L_RASTER = C(255,152, 0); static const Col COL_L_VECTOR = C( 0,151,167); static const Col COL_CHK_A = C(255,255,255); diff --git a/libraries/tinyblocks-editor/src/tb_editor.c b/libraries/tinyblocks-editor/src/tb_editor.c index ac9bd42..60a5aa5 100644 --- a/libraries/tinyblocks-editor/src/tb_editor.c +++ b/libraries/tinyblocks-editor/src/tb_editor.c @@ -27,6 +27,8 @@ #include #include #include +#include +#include #include #include #include @@ -470,12 +472,23 @@ void blk_release(Tab* T, int i) { parametros de uma camada da tinyblocks-tensor. */ static uint64_t s_blk_uid; +/* Criado por codigo (agente MCP, scratchblocks colado): surge animado, em + cascata na ordem de criacao */ +static void blk_mark_appear(Tab* T, int i) { + Ed* ed = g_active_ed; + if (!ed || !ed->appear_batch || ed->anim_off || T == &ed->fly) return; + int k = ed->appear_k < 24 ? ed->appear_k : 24; + ed->appear_k++; + T->ws[i].ap_t0 = (ed->t_ms ? ed->t_ms : 1) + (unsigned)k * 30u; +} + static int blk_alloc(Tab* T) { if (T->free_n > 0) { int i = T->free_ids[--T->free_n]; blk_slot_clear(T, i); T->ws[i].used = true; T->ws[i].uid = ++s_blk_uid; + blk_mark_appear(T, i); return i; } if (T->ws_n >= MAX_WS) return -1; @@ -484,6 +497,7 @@ static int blk_alloc(Tab* T) { blk_slot_clear(T, i); T->ws[i].used = true; T->ws[i].uid = ++s_blk_uid; + blk_mark_appear(T, i); return i; } @@ -647,7 +661,10 @@ void free_tree(Ed* ed, Tab* T, int bi) { } /* Apaga só bi (com o que está encaixado nele); os blocos abaixo sobem */ +void ghost_capture(Ed* ed, Tab* T, int bi, bool chain, float wsx, float wsy, bool clip); + void delete_heal(Ed* ed, Tab* T, int bi) { + if (T == &CT && AREA(V_SCRIPTS).shown) ghost_capture(ed, T, bi, false, WS_X, WS_Y, true); EdBlock* b = &T->ws[bi]; int nx = b->next, par = b->parent, rel = b->prel; if (nx >= 0) { b->next = -1; T->ws[nx].parent = -1; T->ws[nx].prel = REL_NONE; } @@ -964,12 +981,38 @@ static void place_chain(Tab* T, int head, float x, float y) { for (int c = head; c >= 0; c = T->ws[c].next) { place(T, c, x, y); y += T->ws[c].h; } } +/* Bloco que mudou de lugar dentro da mesma pilha (algo entrou ou saiu + acima dele): desliza do lugar antigo em vez de pular. Arrastar a pilha + (a raiz anda) ou trocar de pilha nao anima. */ +static void blk_slide_off(Ed* ed, const EdBlock* b, float* dx, float* dy); +static void anim_track(Tab* T) { + Ed* ed = g_active_ed; + if (!ed || T == &ed->fly) return; + for (int i = 0; i < T->ws_n; i++) { + EdBlock* b = &T->ws[i]; + if (!b->used) continue; + int r = stack_root(T, i); + float rx = T->ws[r].x, ry = T->ws[r].y; + if (b->l_ok && !ed->anim_off && !b->dragging && r == b->l_root && rx == b->l_rx && ry == b->l_ry && + fabsf(b->ay - b->l_y) > 0.5f) { + float ox, oy; + blk_slide_off(ed, b, &ox, &oy); + b->an_dx = b->l_x + ox - b->ax; + b->an_dy = b->l_y + oy - b->ay; + b->an_t0 = ed->t_ms ? ed->t_ms : 1; + } + b->l_ok = true; b->l_root = r; b->l_rx = rx; b->l_ry = ry; + b->l_x = b->ax; b->l_y = b->ay; + } +} + void layout_tab(Tab* T) { for (int i = 0; i < T->top_n; i++) { int h = T->top[i]; measure_chain(T, h); place_chain(T, h, T->ws[h].x, T->ws[h].y); } + anim_track(T); } /* === @@ -1262,6 +1305,46 @@ void ed_cull_pane(Ed* ed, bool on, float x, float y, float w, float h) { ed->cull_on = on; ed->cull_x = x; ed->cull_y = y; ed->cull_w = w; ed->cull_h = h; } +/* == Animacao dos blocos (curvas do M3) === */ +/* Progresso 0..1 desde t0 (0 = ainda nao comecou: cascata) */ +static float anim_k(Ed* ed, unsigned t0, unsigned dur) { + if (ed->anim_off || !t0) return 1.f; + int dt = (int)(ed->t_ms - t0); + if (dt <= 0) return 0.f; + return (unsigned)dt >= dur ? 1.f : (float)dt / (float)dur; +} + +static void blk_slide_off(Ed* ed, const EdBlock* b, float* dx, float* dy) { + *dx = *dy = 0.f; + if (!b->an_t0) return; + float k = anim_k(ed, b->an_t0, M3_DUR_SLIDE); + if (k >= 1.f) return; + float r = 1.f - M3_EASE_STANDARD(k); + *dx = b->an_dx * r; *dy = b->an_dy * r; +} + +/* Escala (em torno de cx, cy) e opacidade dos comandos a partir de first */ +static void rb_fx_from(TinyBlocks_RenderableBlock* rb, uint32_t first, float cx, float cy, float s, float a) { + for (uint32_t i = first; i < rb->count; i++) { + TinyBlocks_DrawCmd* c = &rb->cmds[i]; + if (c->kind == TB_DRAW_CLEAR || c->kind == TB_DRAW_CLEAR_CLIP || c->kind == TB_DRAW_SET_CLIP) continue; + c->a *= a; + if (s == 1.f) continue; + if (c->kind == TB_DRAW_FILL_POLY) { + float xy[2 * TB_POLY_MAX]; + int n = tb_draw_poly_get(c, xy); + for (int k = 0; k < n; k++) { xy[2*k] = cx + (xy[2*k] - cx) * s; xy[2*k+1] = cy + (xy[2*k+1] - cy) * s; } + tb_draw_poly_set(c, xy, n); + continue; + } + c->x = cx + (c->x - cx) * s; c->y = cy + (c->y - cy) * s; + if (c->kind == TB_DRAW_STROKE_LINE) { c->w = cx + (c->w - cx) * s; c->h = cy + (c->h - cy) * s; } + else { c->w *= s; c->h *= s; } + if (c->kind != TB_DRAW_TEXT) c->param *= s; + c->font_size *= s; + } +} + static bool culled(const Ed* ed, const EdBlock* b, float ox, float oy) { if (!ed->cull_on) return false; const float M = 80.f; /* folga: valores encaixados passam do corpo */ @@ -1270,12 +1353,15 @@ static bool culled(const Ed* ed, const EdBlock* b, float ox, float oy) { y + b->h < ed->cull_y - M || y > ed->cull_y + ed->cull_h + M; } -static void render_block(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int bi, float ox, float oy) { +static void render_block(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int bi, float ox, float oy); +static void render_block_body(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int bi, float ox, float oy) { EdBlock* b = &T->ws[bi]; if (culled(ed, b, ox, oy)) return; Shape sh = shape_of(b->type); Col c, d; block_cols(ed, b, &c, &d); - float x = b->ax + ox, y = b->ay + oy, w = b->w, h = b->h; + float sdx, sdy; /* deslize: so o desenho deste bloco */ + blk_slide_off(ed, b, &sdx, &sdy); + float x = b->ax + ox + sdx, y = b->ay + oy + sdy, w = b->w, h = b->h; /* == Corpo: contorno escuro + preenchimento === */ switch (sh) { @@ -1397,6 +1483,18 @@ static void render_block(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int bi, } /* Desenha de baixo para cima, para cada encaixe cobrir o bloco seguinte */ +/* Bloco surgindo (criado por codigo): cresce e aparece com a curva de + entrada do M3; os filhos tem a propria animacao */ +static void render_block(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int bi, float ox, float oy) { + EdBlock* b = &T->ws[bi]; + float k = b->ap_t0 ? anim_k(ed, b->ap_t0, M3_DUR_APPEAR) : 1.f; + if (k >= 1.f) { b->ap_t0 = 0; render_block_body(ed, rb, T, bi, ox, oy); return; } + uint32_t from = rb->count; + render_block_body(ed, rb, T, bi, ox, oy); + float e = M3_EASE_EMPH_DECEL(k); + rb_fx_from(rb, from, b->ax + ox + b->w * 0.5f, b->ay + oy + b->h * 0.5f, 0.6f + 0.4f * e, e); +} + static void render_chain(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int head, float ox, float oy) { int* ids = T->ws_n > 0 ? (int*)malloc((size_t)T->ws_n * sizeof(int)) : NULL; int n = 0; @@ -1405,6 +1503,69 @@ static void render_chain(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int hea free(ids); } +/* == Blocos apagados saindo de cena === + * Na hora de apagar, o desenho do bloco (como esta na tela) vira um + * "fantasma" que encolhe e some com a curva de saida do M3. */ +static void rb_scale_from(TinyBlocks_RenderableBlock* rb, uint32_t first, float ox, float oy, float s); + +static void ghost_free(Ed* ed, int i) { + free(ed->ghosts[i].cmds); + memmove(&ed->ghosts[i], &ed->ghosts[i + 1], (size_t)(ed->ghost_n - i - 1) * sizeof(Ghost)); + ed->ghost_n--; +} + +void ghost_capture(Ed* ed, Tab* T, int bi, bool chain, float wsx, float wsy, bool clip) { + if (ed->anim_off || bi < 0 || bi >= T->ws_n || !T->ws[bi].used) return; + TinyBlocks_RenderableBlock* rb = tb_renderable_acquire(); + if (!rb) return; + bool editing = ed->editing; + ed->editing = false; /* sem cursor no fantasma */ + float ox = wsx - T->ws_sx, oy = wsy - T->ws_sy; + if (chain) render_chain(ed, rb, T, bi, ox, oy); + else render_block(ed, rb, T, bi, ox, oy); + ed->editing = editing; + rb_scale_from(rb, 0, wsx, wsy, tab_zoom(T)); + if (ed->ghost_n == GHOST_MAX) ghost_free(ed, 0); + Ghost* g = &ed->ghosts[ed->ghost_n]; + memset(g, 0, sizeof(*g)); + g->cmds = (TinyBlocks_DrawCmd*)malloc(rb->count * sizeof(TinyBlocks_DrawCmd)); + float x0 = 1e9f, y0 = 1e9f, x1 = -1e9f, y1 = -1e9f; + for (uint32_t i = 0; g->cmds && i < rb->count; i++) { + const TinyBlocks_DrawCmd* c = &rb->cmds[i]; + /* imagens podem morrer com o bloco; o clip e o da area */ + if (c->kind == TB_DRAW_IMAGE || c->kind == TB_DRAW_SET_CLIP || c->kind == TB_DRAW_CLEAR_CLIP || + c->kind == TB_DRAW_CLEAR) continue; + g->cmds[g->n++] = *c; + if (c->kind == TB_DRAW_FILL_RECT || c->kind == TB_DRAW_FILL_RRECT || c->kind == TB_DRAW_FILL_POLY) { + x0 = fminf(x0, c->x); y0 = fminf(y0, c->y); + x1 = fmaxf(x1, c->x + c->w); y1 = fmaxf(y1, c->y + c->h); + } + } + tb_renderable_release(rb); + if (!g->cmds || !g->n) { free(g->cmds); return; } + g->cx = (x0 + x1) * 0.5f; g->cy = (y0 + y1) * 0.5f; + g->t0 = ed->t_ms ? ed->t_ms : 1; + g->clip = clip; + if (clip) { g->clip_r[0] = WS_X; g->clip_r[1] = WS_Y; g->clip_r[2] = WS_W; g->clip_r[3] = WS_H; } + ed->ghost_n++; +} + +static void ghosts_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { + for (int i = 0; i < ed->ghost_n; ) { + Ghost* g = &ed->ghosts[i]; + float k = anim_k(ed, g->t0, M3_DUR_EXIT); + if (k >= 1.f || rb->count + (uint32_t)g->n + 2 > TB_DRAW_CMD_CAP) { ghost_free(ed, i); continue; } + float e = M3_EASE_EMPH_ACCEL(k); + if (g->clip) tb_draw_set_clip(rb, g->clip_r[0], g->clip_r[1], g->clip_r[2], g->clip_r[3]); + uint32_t from = rb->count; + memcpy(&rb->cmds[rb->count], g->cmds, (size_t)g->n * sizeof(TinyBlocks_DrawCmd)); + rb->count += (uint32_t)g->n; + rb_fx_from(rb, from, g->cx, g->cy, 1.f - 0.3f * e, 1.f - e); + if (g->clip) tb_draw_clear_clip(rb); + i++; + } +} + /* === * Execução * === */ @@ -2839,18 +3000,6 @@ static int detach_btn_at(Ed* ed, float mx, float my) { return -1; } -/* Icone: duas janelas (destacar) ou janela com o canto cheio (recolher) */ -static void draw_window_icon(TinyBlocks_RenderableBlock* rb, float x, float y, float s, bool detached, Col c) { - float k = s / 32.f; - if (detached) { - rb_stroke_rect(rb, x + 9*k, y + 7*k, 22*k, 18*k, 1.5f, c); - rb_fill_rect(rb, x + 12*k, y + 15*k, 10*k, 7*k, c); - } else { - rb_stroke_rect(rb, x + 9*k, y + 11*k, 15*k, 13*k, 1.5f, c); - rb_stroke_rect(rb, x + 16*k, y + 6*k, 15*k, 13*k, 1.5f, c); - } -} - static void draw_detach_btn(Ed* ed, TinyBlocks_RenderableBlock* rb, int v) { if (v == V_STAGE || !ed->area[v].shown || ed->compact) return; float bx, by; @@ -2960,6 +3109,27 @@ static float cat_max_scroll(Ed* ed) { return m > 0 ? m : 0; } +/* == Rolagem suave (curva standard do M3) === + * A roda define o alvo; o valor anda ate ele em M3_DUR_SCROLL. Ticks + * seguidos somam no alvo, sem recomecar do zero. */ +static float sa_base(const ScrollAnim* a, float cur) { return a->on ? a->to : cur; } +static void sa_to(Ed* ed, ScrollAnim* a, float* var, float target) { + if (ed->anim_off) { a->on = false; *var = target; return; } + a->from = *var; a->to = target; a->t0 = ed->t_ms ? ed->t_ms : 1; a->on = true; +} +static void sa_step(Ed* ed, ScrollAnim* a, float* var) { + if (!a->on) return; + float k = anim_k(ed, a->t0, M3_DUR_SCROLL); + *var = a->from + (a->to - a->from) * M3_EASE_STANDARD(k); + if (k >= 1.f) a->on = false; +} +static void sa_step_i(Ed* ed, ScrollAnim* a, int* var) { + if (!a->on) return; + float v = (float)*var; + sa_step(ed, a, &v); + *var = (int)lroundf(v); +} + static void cat_scroll_by(Ed* ed, float d) { ed->cat_scroll += d; if (ed->cat_scroll > cat_max_scroll(ed)) ed->cat_scroll = cat_max_scroll(ed); @@ -3775,7 +3945,16 @@ static bool sb_import_file(Ed* ed, const char* path) { } /* Texto em scratchblocks -> aba nova chamada `name` */ +static bool sb_import_text_(Ed* ed, const char* text, const char* name); +/* Colado/importado por codigo: os blocos surgem animados */ static bool sb_import_text(Ed* ed, const char* text, const char* name) { + bool was = ed->appear_batch; + if (!was) { ed->appear_batch = true; ed->appear_k = 0; } + bool ok = sb_import_text_(ed, text, name); + ed->appear_batch = was; + return ok; +} +static bool sb_import_text_(Ed* ed, const char* text, const char* name) { TbBpTab* B = calloc(1, sizeof(TbBpTab)); if (!B) return false; TbSbLabel* labels = NULL; @@ -6229,6 +6408,10 @@ static unsigned ctx_icon(int id) { case CM_MB_LIBMAN: return MI_LIBRARY_BOOKS; case CM_MB_LIB: return MI_UPLOAD_FILE; case CM_MB_CFG: return MI_SETTINGS; + case CM_SOURCE: return MI_SOURCE; + case CM_SHARE_STACK: return MI_SHARE; + case CM_SHARE_TAB: return MI_QR_CODE; + case CM_RECEIVE: return MI_QR_SCANNER; default: return 0; } } @@ -6255,6 +6438,10 @@ static const char* ctx_label(int id) { case CM_MB_LIBMAN: return "Bibliotecas"; case CM_MB_LIB: return "Carregar library..."; case CM_MB_CFG: return "Configurações"; + case CM_SOURCE: return "Ver código-fonte"; + case CM_SHARE_STACK: return "Compartilhar pilha (QR)"; + case CM_SHARE_TAB: return "Compartilhar blueprint (QR)"; + case CM_RECEIVE: return "Receber blocos (QR)"; default: return ""; } } @@ -7746,6 +7933,9 @@ static void menu_action(Ed* ed, int id) { } } +static void qr_share_open(Ed* ed, const char* title, char* text); +static void qr_recv_open(Ed* ed, float wx, float wy); + static void ctx_exec(Ed* ed, int id) { Tab* T = &CT; int bi = ed->ctx_menu_bi; @@ -7795,6 +7985,16 @@ static void ctx_exec(Ed* ed, int id) { case CM_MB_LIBMAN: case CM_MB_LIB: case CM_MB_CFG: menu_action(ed, id - CM_MB_OPEN); break; + case CM_SOURCE: { /* a funcao C do bloco, na aba de codigo */ + const TinyBlocks_BlockMeta* m = bi >= 0 ? tb_meta_find(T->ws[bi].type_name) : NULL; + if (m && m->file) open_code_at(ed, m->file, tb_meta_line(m) > 0 ? tb_meta_line(m) : 1); + break; + } + case CM_SHARE_STACK: + if (bi >= 0) qr_share_open(ed, "Compartilhar pilha", ed_scratchblocks_export(ed, T, stack_root(T, bi))); + break; + case CM_SHARE_TAB: qr_share_open(ed, "Compartilhar blueprint", ed_scratchblocks_export(ed, T, -1)); break; + case CM_RECEIVE: qr_recv_open(ed, ed->ctx_wx, ed->ctx_wy); break; default: break; } } @@ -7814,11 +8014,23 @@ struct ModalClass { }; static bool settings_is_open(Ed* ed) { return ed->settings_open; } -static void settings_scroll_m(Ed* ed, float dy) { settings_scroll_by(ed, dy); } +/* Rolagem animada de uma lista com clamp proprio: calcula o alvo a partir do + alvo atual e anima ate ele (arrastar com o dedo vai direto) */ +static void modal_scroll_anim(Ed* ed, ScrollAnim* a, int* var, void (*by)(Ed*, float), float dy) { + if (ed->anim_off || ed->modal_drag) { a->on = false; by(ed, dy); return; } + int cur = *var; + *var = (int)lroundf(sa_base(a, (float)cur)); + by(ed, dy); + int target = *var; + *var = cur; + float v = (float)cur; + sa_to(ed, a, &v, (float)target); +} +static void settings_scroll_m(Ed* ed, float dy) { modal_scroll_anim(ed, &ed->sa_st, &ed->settings_scroll, settings_scroll_by, dy); } static bool libman_is_open(Ed* ed) { return ed->libman_open; } static void libman_key_m(Ed* ed, int sc, bool ctrl) { (void)ctrl; libman_key(ed, sc); } -static void libman_scroll_m(Ed* ed, float dy) { libman_scroll_by(ed, dy); } +static void libman_scroll_m(Ed* ed, float dy) { modal_scroll_anim(ed, &ed->sa_lm, &ed->libman_scroll, libman_scroll_by, dy); } /* o explorador vem do modulo do editor (pode faltar) */ static bool files_is_open(Ed* ed) { return ed->fdlg.open; } @@ -7839,7 +8051,299 @@ static bool dlg_is_open(Ed* ed) { return ed->comp_dialog_open; } static void dlg_key_m(Ed* ed, int sc, bool ctrl) { (void)ctrl; dlg_key(ed, sc); } static void dlg_click_m(Ed* ed, float mx, float my) { dlg_click(ed, mx, my); } + +/* === + * QR: compartilhar e receber blocos entre instancias do editor + * Conteudo = scratchblocks. Cada QR leva "TB1|id|parte|total|" + um pedaco + * de ate QR_CHUNK bytes; o painel mostra as partes em loop (1 s cada) e o + * receptor junta em qualquer ordem, quantas voltas forem precisas. + * === */ +#define QR_CHUNK 220 +#define QR_PART_MS 1000u +#define QR_GRAY_CAP (1920 * 1088) + +/* Fim do pedaco que comeca em pos (sem cortar uma letra UTF-8) */ +static int qr_cut(const char* t, int len, int pos) { + int end = pos + QR_CHUNK; + if (end >= len) return len; + while (end > pos && ((unsigned char)t[end] & 0xC0) == 0x80) end--; + return end; +} + +static void qr_share_close(Ed* ed) { + free(ed->qrs_text); + ed->qrs_text = NULL; + ed->qrs_open = false; +} + +static void qr_share_open(Ed* ed, const char* title, char* text) { + qr_share_close(ed); + if (!text || !text[0]) { + free(text); + snprintf(ed->hot_status, sizeof(ed->hot_status), "Nada para compartilhar"); + ed->hot_status_ok = false; + return; + } + ed->qrs_text = text; + int len = (int)strlen(text), n = 0; + for (int p = 0; p < len; p = qr_cut(text, len, p)) n++; + ed->qrs_n = n; + ed->qrs_t0 = ed->t_ms ? ed->t_ms : 1; + snprintf(ed->qrs_id, sizeof(ed->qrs_id), "%04x", (unsigned)((now_ms() * 2654435761u) >> 16) & 0xffffu); + scopy(ed->qrs_title, sizeof(ed->qrs_title), title); + ed->qrs_open = true; +} + +/* Texto do QR da parte i (0..n-1) */ +static void qr_part_text(Ed* ed, int i, char* out, size_t cap) { + const char* t = ed->qrs_text; + int len = (int)strlen(t), p = 0; + for (int k = 0; k < i && p < len; k++) p = qr_cut(t, len, p); + int e = qr_cut(t, len, p); + snprintf(out, cap, "TB1|%s|%d|%d|%.*s", ed->qrs_id, i + 1, ed->qrs_n, e - p, t + p); +} + +static bool qrs_is_open(Ed* ed) { return ed->qrs_open; } + +static void qrs_geom(Ed* ed, float* x, float* y, float* w, float* h) { + *w = fminf(440.f, WIN_W - 32.f); + *h = *w + 128.f; + if (*h > WIN_H - 32.f) { *h = WIN_H - 32.f; *w = *h - 128.f; } + *x = (WIN_W - *w) * 0.5f; *y = (WIN_H - *h) * 0.5f; +} + +/* Modulos escuros do QR como faixas horizontais (uma por sequencia) */ +static void draw_qr(TinyBlocks_RenderableBlock* rb, const unsigned char* mods, int side, float x, float y, float m) { + Col ink = COLA(20, 22, 30, 255); + for (int r = 0; r < side; r++) + for (int c = 0; c < side; ) { + if (!mods[r * side + c]) { c++; continue; } + int c0 = c; + while (c < side && mods[r * side + c]) c++; + /* um pouco maior que o modulo: sem frestas entre as faixas em + nenhuma escala (a densidade do celular nao e inteira) */ + rb_fill_rect(rb, x + c0 * m, y + r * m, (c - c0) * m + 0.6f, m + 0.6f, ink); + } +} + +static void qrs_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { + if (!ed->qrs_open || !ed->qrs_text) return; + float x, y, w, h; + qrs_geom(ed, &x, &y, &w, &h); + m3_scrim(rb, WIN_W, WIN_H); + m3_dialog_surface(rb, x, y, w, h); + tb_a11y_set_states(ax(ed), ax_push(ed, TB_A11Y_DIALOG, ed->qrs_title, x, y, w, h), TB_A11Y_MODAL); + rb_icon(rb, x + 24 + 12, y + 34, MI_QR_CODE, 24.f, M3_PRIMARY, false); + rb_text_f(rb, x + 24 + 24 + 12, y + 34, ed->qrs_title, M3_ON_SURFACE, M3_HEADLINE_S, TB_FONT_REGULAR); + + int n = ed->qrs_n, i = n > 1 ? (int)(((ed->t_ms - ed->qrs_t0) / QR_PART_MS) % (unsigned)n) : 0; + static char part[QR_CHUNK + 64]; + static unsigned char mods[TB_QR_MAX_SIDE * TB_QR_MAX_SIDE]; + qr_part_text(ed, i, part, sizeof(part)); + int side = tb_qr_encode(part, mods, (int)sizeof(mods)); + float q = w - 48.f, qx = x + 24.f, qy = y + 62.f; + rb_fill_rrect(rb, qx, qy, q, q, M3_SHAPE_M, COL_WHITE); /* QR com margem clara */ + if (side > 0) { + float m = floorf(q / (float)(side + 8)); + float off = floorf((q - m * side) * 0.5f); + draw_qr(rb, mods, side, floorf(qx) + off, floorf(qy) + off, m); + } + char lab[64]; + snprintf(lab, sizeof(lab), "Parte %d de %d", i + 1, n); + float ty = qy + q + 22.f; + rb_text_f(rb, x + 24, ty, lab, M3_ON_SURFACE, M3_TITLE_S, TB_FONT_MEDIUM); + tb_a11y_set_value(ax(ed), ax_add(ed, TB_A11Y_LABEL, "Parte", x + 24, ty - 10, 120, 20), lab); + if (n > 1 && n <= 24) /* qual parte esta no ar */ + for (int k = 0; k < n; k++) + rb_fill_circle(rb, x + w - 24 - (n - 1 - k) * 12, ty, k == i ? 4.f : 3.f, + k == i ? M3_PRIMARY : M3_OUTLINE_VAR); + rb_text_f(rb, x + 24, ty + 22, "No outro TinyBlocks: botão direito na área › Receber blocos", + M3_ON_SURFACE_VAR, M3_BODY_S, TB_FONT_REGULAR); + float bx = x + w - 24 - 90, by = y + h - 48; + m3_button(rb, M3_TEXT, bx, by, 90, 36, "Fechar", 0, M3_PRIMARY, in_rect(ed->mouse_x, ed->mouse_y, bx, by, 90, 36), false); + ax_button(ed, "Fechar", bx, by, 90, 36); + ax_pop(ed); +} + +static void qrs_click(Ed* ed, float mx, float my) { + float x, y, w, h; + qrs_geom(ed, &x, &y, &w, &h); + if (!in_rect(mx, my, x, y, w, h) || in_rect(mx, my, x + w - 24 - 90, y + h - 48, 90, 36)) qr_share_close(ed); +} + +static void qrs_key(Ed* ed, int sc, bool ctrl) { + (void)ctrl; + if (sc == TB_KEY_ESCAPE || sc == TB_KEY_RETURN) qr_share_close(ed); +} + +/* -- Receber --- */ +static void qr_recv_reset(Ed* ed) { + for (int i = 0; ed->qrr_part && i < ed->qrr_n; i++) free(ed->qrr_part[i]); + free(ed->qrr_part); + ed->qrr_part = NULL; + ed->qrr_n = ed->qrr_got = 0; + ed->qrr_id[0] = 0; +} + +static void qr_recv_close(Ed* ed) { + if (ed->qrr_cam) tb_camera_close(); + ed->qrr_cam = false; + qr_recv_reset(ed); + tb_qr_reader_free(ed->qrr_reader); + ed->qrr_reader = NULL; + free(ed->qrr_gray); + ed->qrr_gray = NULL; + if (ed->qrr_img) tb_image_release(ed->qrr_img); + ed->qrr_img = NULL; + ed->qrr_open = false; +} + +static void qr_recv_open(Ed* ed, float wx, float wy) { + qr_recv_close(ed); + if (!tab_class(&CT)->blocks) return; + ed->qrr_open = true; + ed->qrr_x = wx; ed->qrr_y = wy; + ed->qrr_reader = tb_qr_reader_new(); + ed->qrr_gray = (unsigned char*)malloc(QR_GRAY_CAP); + ed->qrr_cam = tb_camera_open(640, 480); + snprintf(ed->qrr_msg, sizeof(ed->qrr_msg), "%s", + ed->qrr_cam ? "Aponte a câmera para o QR do outro TinyBlocks" : tb_camera_error()); +} + +/* Um QR lido: guarda a parte; com todas, importa os blocos */ +static void qr_recv_text(Ed* ed, const char* t, int len) { + char id[8]; + int i = 0, n = 0, hl = 0; + if (len < 8 || strncmp(t, "TB1|", 4) != 0) return; + if (sscanf(t + 4, "%7[0-9a-f]|%d|%d|%n", id, &i, &n, &hl) < 3 || hl <= 0) return; + if (n < 1 || n > 4096 || i < 1 || i > n) return; + if (strcmp(id, ed->qrr_id) != 0 || n != ed->qrr_n) { /* outro compartilhamento: recomeca */ + qr_recv_reset(ed); + ed->qrr_part = (char**)calloc((size_t)n, sizeof(char*)); + if (!ed->qrr_part) return; + ed->qrr_n = n; + scopy(ed->qrr_id, sizeof(ed->qrr_id), id); + } + if (ed->qrr_part[i - 1]) return; + const char* body = t + 4 + hl; + int bl = len - (int)(body - t); + char* p = (char*)malloc((size_t)bl + 1); + if (!p) return; + memcpy(p, body, (size_t)bl); p[bl] = 0; + ed->qrr_part[i - 1] = p; + ed->qrr_got++; + if (ed->qrr_got < ed->qrr_n) return; + size_t total = 1; + for (int k = 0; k < n; k++) total += strlen(ed->qrr_part[k]); + char* all = (char*)malloc(total); + if (!all) return; + all[0] = 0; + for (int k = 0; k < n; k++) strcat(all, ed->qrr_part[k]); + int heads[64]; + char warn[200] = ""; + ed->appear_batch = true; ed->appear_k = 0; /* os blocos surgem animados */ + int got = ed_scratchblocks_import(ed, &CT, all, ed->qrr_x, ed->qrr_y, heads, 64, warn, sizeof(warn)); + ed->appear_batch = false; + free(all); + layout_tab(&CT); + if (got > 0) snprintf(ed->hot_status, sizeof(ed->hot_status), "Recebido: %d pilha(s)%s%s", got, + warn[0] ? " - " : "", warn); + else snprintf(ed->hot_status, sizeof(ed->hot_status), "O QR não trouxe blocos%s%s", warn[0] ? ": " : "", warn); + ed->hot_status_ok = got > 0; + qr_recv_close(ed); +} + +static void qr_found_cb(const char* t, int len, void* user) { + Ed* ed = (Ed*)user; + if (ed->qrr_open) qr_recv_text(ed, t, len); +} + +/* A cada quadro: quadro novo da camera -> previa + leitura */ +static void qr_recv_poll(Ed* ed) { + if (!ed->qrr_open || !ed->qrr_cam || !ed->qrr_gray) return; + int w = 0, h = 0; + if (!tb_camera_frame(ed->qrr_gray, QR_GRAY_CAP, &w, &h)) return; + if (!ed->qrr_img || tb_image_width(ed->qrr_img) != w || tb_image_height(ed->qrr_img) != h) { + if (ed->qrr_img) tb_image_release(ed->qrr_img); + ed->qrr_img = tb_image_new(w, h, 4); + } + if (ed->qrr_img) { + uint8_t* px = tb_image_data(ed->qrr_img); + for (int k = 0; k < w * h; k++) { + uint8_t g = ed->qrr_gray[k]; + px[4*k] = px[4*k+1] = px[4*k+2] = g; px[4*k+3] = 255; + } + } + tb_qr_reader_scan(ed->qrr_reader, ed->qrr_gray, w, h, qr_found_cb, ed); +} + +TB_API void tb_editor_qr_feed(TinyBlocks_Block* scene, const char* text) { + Ed* ed = scene && scene->userdata ? *(Ed**)scene->userdata : NULL; + if (ed && ed->qrr_open && text) qr_recv_text(ed, text, (int)strlen(text)); +} + +static bool qrr_is_open(Ed* ed) { return ed->qrr_open; } + +static void qrr_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { + if (!ed->qrr_open) return; + float x, y, w, h; + qrs_geom(ed, &x, &y, &w, &h); + m3_scrim(rb, WIN_W, WIN_H); + m3_dialog_surface(rb, x, y, w, h); + tb_a11y_set_states(ax(ed), ax_push(ed, TB_A11Y_DIALOG, "Receber blocos", x, y, w, h), TB_A11Y_MODAL); + rb_icon(rb, x + 24 + 12, y + 34, MI_QR_SCANNER, 24.f, M3_PRIMARY, false); + rb_text_f(rb, x + 24 + 24 + 12, y + 34, "Receber blocos", M3_ON_SURFACE, M3_HEADLINE_S, TB_FONT_REGULAR); + float q = w - 48.f, qx = x + 24.f, qy = y + 62.f; + rb_fill_rrect(rb, qx, qy, q, q, M3_SHAPE_M, M3_INVERSE_SURFACE); + if (ed->qrr_img) { /* previa da camera, sem deformar */ + float iw = (float)tb_image_width(ed->qrr_img), ih = (float)tb_image_height(ed->qrr_img); + float k = fminf(q / iw, q / ih), dw = iw * k, dh = ih * k; + tb_draw_image(rb, qx + (q - dw) * 0.5f, qy + (q - dh) * 0.5f, dw, dh, ed->qrr_img); + } else { + rb_icon(rb, qx + q * 0.5f, qy + q * 0.5f, MI_QR_SCANNER, 64.f, m3_alpha(COL_WHITE, 0.5f), false); + } + { /* cantos da mira */ + float c = q * 0.18f, m0 = q * 0.14f, t = 4.f; + float l = qx + m0, r = qx + q - m0, tp = qy + m0, bt = qy + q - m0; + Col wc = m3_alpha(COL_WHITE, 0.85f); + rb_fill_rect(rb, l, tp, c, t, wc); rb_fill_rect(rb, l, tp, t, c, wc); + rb_fill_rect(rb, r - c, tp, c, t, wc); rb_fill_rect(rb, r - t, tp, t, c, wc); + rb_fill_rect(rb, l, bt - t, c, t, wc); rb_fill_rect(rb, l, bt - c, t, c, wc); + rb_fill_rect(rb, r - c, bt - t, c, t, wc); rb_fill_rect(rb, r - t, bt - c, t, c, wc); + } + float ty = qy + q + 22.f; + char st[96]; + if (ed->qrr_n > 0) snprintf(st, sizeof(st), "Recebidas %d de %d partes", ed->qrr_got, ed->qrr_n); + else snprintf(st, sizeof(st), "%s", ed->qrr_cam ? "Procurando QR..." : "Sem câmera"); + rb_text_f(rb, x + 24, ty, st, M3_ON_SURFACE, M3_TITLE_S, TB_FONT_MEDIUM); + tb_a11y_set_value(ax(ed), ax_add(ed, TB_A11Y_STATUS, "Recebimento", x + 24, ty - 10, w - 48, 20), st); + if (ed->qrr_n > 0) { /* indicador de progresso linear do M3 */ + float pw = w - 48.f, k = (float)ed->qrr_got / (float)ed->qrr_n; + rb_fill_rrect(rb, x + 24, ty + 14, pw, 4, 2, M3_SECONDARY_CONTAINER); + rb_fill_rrect(rb, x + 24, ty + 14, fmaxf(4.f, pw * k), 4, 2, M3_PRIMARY); + } + rb_text_f(rb, x + 24, ty + 34, ed->qrr_msg, ed->qrr_cam ? M3_ON_SURFACE_VAR : COL_ERR_TEXT, M3_BODY_S, + TB_FONT_REGULAR); + float bx = x + w - 24 - 100, by = y + h - 48; + m3_button(rb, M3_TEXT, bx, by, 100, 36, "Cancelar", 0, M3_PRIMARY, in_rect(ed->mouse_x, ed->mouse_y, bx, by, 100, 36), false); + ax_button(ed, "Cancelar", bx, by, 100, 36); + ax_pop(ed); +} + +static void qrr_click(Ed* ed, float mx, float my) { + float x, y, w, h; + qrs_geom(ed, &x, &y, &w, &h); + if (!in_rect(mx, my, x, y, w, h) || in_rect(mx, my, x + w - 24 - 100, y + h - 48, 100, 36)) qr_recv_close(ed); +} + +static void qrr_key(Ed* ed, int sc, bool ctrl) { + (void)ctrl; + if (sc == TB_KEY_ESCAPE) qr_recv_close(ed); +} + static const ModalClass s_modals[] = { /* do mais alto para o mais baixo */ + { "receber", qrr_is_open, qrr_render, qrr_click, qrr_key, NULL, NULL }, + { "compartilhar", qrs_is_open, qrs_render, qrs_click, qrs_key, NULL, NULL }, { "configurações", settings_is_open, settings_render, settings_click, settings_key, settings_text, settings_scroll_m }, { "bibliotecas", libman_is_open, libman_render, libman_click, libman_key_m, libman_text, libman_scroll_m }, { "explorador", files_is_open, files_render_m, files_click_m, files_key_m, files_text_m, files_scroll_m }, @@ -8039,6 +8543,7 @@ static void on_lmb_down(Ed* ed, float mx, float my) { return; } ed->state = ES_PAN; + ed->sa_ws_x.on = ed->sa_ws_y.on = ed->za.on = false; /* o dedo manda */ ed->pan_mx = mx; ed->pan_my = my; ed->pan_sx = CT.ws_sx; ed->pan_sy = CT.ws_sy; return; @@ -8160,7 +8665,10 @@ static void on_lmb_up(Ed* ed, float mx, float my) { if (ed->state == ES_DRAG && ed->drag_bi >= 0) { mark_drag(&CT, ed->drag_bi, false); int tgt = ws_ctx_at(ed, mx, my); - if (view_at(ed, mx, my) == V_PALETTE) free_tree(ed, &CT, ed->drag_bi); /* solto na paleta = apagar */ + if (view_at(ed, mx, my) == V_PALETTE) { /* solto na paleta = apagar */ + ghost_capture(ed, &CT, ed->drag_bi, true, ed->drag_ws_x, ed->drag_ws_y, false); + free_tree(ed, &CT, ed->drag_bi); + } else if (tgt != -2 && tgt != ed->tabctx) drag_to_ctx(ed, tgt); else apply_snap(ed); } else if (ed->state == ES_PRESS) { @@ -8201,6 +8709,9 @@ static void on_rmb_down(Ed* ed, float mx, float my) { ed->ctx_items[ed->ctx_n++] = CM_DELETE; if (is_def || (t && strncmp(t->type_name, "User.", 5) == 0)) ed->ctx_items[ed->ctx_n++] = CM_EDIT_DEF; ed->ctx_items[ed->ctx_n++] = CM_GROUP_STACK; + const TinyBlocks_BlockMeta* m = tb_meta_find(CT.ws[bi].type_name); + if (m && m->file && m->file[0]) ed->ctx_items[ed->ctx_n++] = CM_SOURCE; + ed->ctx_items[ed->ctx_n++] = CM_SHARE_STACK; } else if (g >= 0) { ed->ctx_items[ed->ctx_n++] = CM_GROUP_RENAME; ed->ctx_items[ed->ctx_n++] = CM_GROUP_COLOR; @@ -8210,6 +8721,8 @@ static void on_rmb_down(Ed* ed, float mx, float my) { ed->ctx_items[ed->ctx_n++] = CM_CLEANUP; ed->ctx_items[ed->ctx_n++] = CM_NEW_COMPOSITE; ed->ctx_items[ed->ctx_n++] = CM_GROUP_NEW; + if (CT.top_n > 0) ed->ctx_items[ed->ctx_n++] = CM_SHARE_TAB; + ed->ctx_items[ed->ctx_n++] = CM_RECEIVE; } ed->ctx_menu_open = true; ed->ctx_export = false; @@ -8456,7 +8969,7 @@ static void pointer_motion(Ed* ed, float mx, float my, int from) { if (!ed->fly_pan_cats && ed->fly_press_item >= 0 && fabsf(dx) > fabsf(dy) * 0.8f) { ed->state = ES_IDLE; spawn_from_fly(ed, ed->fly_press_item, ed->press_mx, ed->press_my); - } else ed->state = ES_FLYPAN; + } else { ed->state = ES_FLYPAN; ed->sa_fly.on = ed->sa_cat.on = false; } } } if (ed->state == ES_FLYPAN) { @@ -8640,7 +9153,9 @@ static void pinch_update(Ed* ed, TinyBlocks_Block* evb, float ox, float oy) { /* Para conferir o visual sem clicar (com TINYBLOCKS_SHOT): TINYBLOCKS_OPEN * abre uma tela no inicio - bloco, config, bibliotecas, abrir, menu, - * nova-aba, exportar, codigo, imagem */ + * nova-aba, exportar, codigo, imagem, compartilhar, receber */ +static void qr_share_open(Ed* ed, const char* title, char* text); +static void qr_recv_open(Ed* ed, float wx, float wy); static void dev_open(Ed* ed) { const char* w = getenv("TINYBLOCKS_OPEN"); if (!w || !w[0]) return; @@ -8667,6 +9182,8 @@ static void dev_open(Ed* ed) { CT.code_hl_dirty = true; } else if (!strcmp(w, "imagem")) { tab_new_kind(ed, "Imagem", false, TK_IMAGE); palette_rebuild(ed); } + else if (!strcmp(w, "compartilhar")) qr_share_open(ed, "Compartilhar blueprint", ed_scratchblocks_export(ed, &CT, -1)); + else if (!strcmp(w, "receber")) qr_recv_open(ed, 40, 40); } static void ed_handle_input(Ed* ed, TinyBlocks_Block* evb, int from) { @@ -8678,7 +9195,24 @@ static void ed_handle_input(Ed* ed, TinyBlocks_Block* evb, int from) { } if (from < 0) { ed->frame_no++; - tb_ed_w.anim_now((double)now_ms()); + ed->t_ms = now_ms(); + if (!ed->t_ms) ed->t_ms = 1; + tb_ed_w.anim_now((double)ed->t_ms); + /* rolagens e zoom animados andam um quadro */ + if (ed->sa_ws_tab == ed->cur_tab) { + sa_step(ed, &ed->sa_ws_x, &CT.ws_sx); + sa_step(ed, &ed->sa_ws_y, &CT.ws_sy); + if (ed->za.on && ed->za.tab == ed->cur_tab) { + float k = anim_k(ed, ed->za.t0, M3_DUR_SCROLL); + ws_zoom_at(ed, &CT, ed->za.from + (ed->za.to - ed->za.from) * M3_EASE_STANDARD(k), ed->za.ax, ed->za.ay); + if (k >= 1.f) ed->za.on = false; + } + } + sa_step(ed, &ed->sa_fly, &ed->fly_scroll); + sa_step(ed, &ed->sa_cat, &ed->cat_scroll); + sa_step_i(ed, &ed->sa_lm, &ed->libman_scroll); + sa_step_i(ed, &ed->sa_st, &ed->settings_scroll); + qr_recv_poll(ed); /* leitor de QR: camera -> partes */ int ww = (int)ev_int(evb, GFX_IN_WIN_W); int wh = (int)ev_int(evb, GFX_IN_WIN_H); if (ww > 0) ed->win_w = ww; @@ -8758,16 +9292,37 @@ static void ed_handle_input(Ed* ed, TinyBlocks_Block* evb, int from) { } else if (in_ws(ed, mx, my)) { /* roda = vertical, Shift+roda = horizontal, Ctrl+roda = zoom no ponteiro */ int mods = (int)ev_int(evb, GFX_IN_MOD_STATE); + if (ed->sa_ws_tab != ed->cur_tab) { /* outra aba: anima do zero */ + ed->sa_ws_x.on = ed->sa_ws_y.on = ed->za.on = false; + ed->sa_ws_tab = ed->cur_tab; + } if (mods & TB_MOD_CTRL) { - if (sdy != 0.0) ws_zoom_at(ed, &CT, tab_zoom(&CT) * powf(1.1f, (float)sdy), mx, my); + if (sdy != 0.0) { + float z0 = ed->za.on ? ed->za.to : tab_zoom(&CT); + float zt = fminf(WS_ZOOM_MAX, fmaxf(WS_ZOOM_MIN, z0 * powf(1.1f, (float)sdy))); + if (ed->anim_off) ws_zoom_at(ed, &CT, zt, mx, my); + else { + ed->sa_ws_x.on = ed->sa_ws_y.on = false; + ed->za.on = true; ed->za.from = tab_zoom(&CT); ed->za.to = zt; + ed->za.ax = mx; ed->za.ay = my; ed->za.t0 = ed->t_ms ? ed->t_ms : 1; + ed->za.tab = ed->cur_tab; + } + } } else { if (mods & TB_MOD_SHIFT) { sdx += sdy; sdy = 0.0; } - CT.ws_sx -= (float)sdx * 40.f / tab_zoom(&CT); - CT.ws_sy -= (float)sdy * 40.f / tab_zoom(&CT); + float z = tab_zoom(&CT); + ed->za.on = false; + if (sdx != 0.0) sa_to(ed, &ed->sa_ws_x, &CT.ws_sx, sa_base(&ed->sa_ws_x, CT.ws_sx) - (float)sdx * 40.f / z); + if (sdy != 0.0) sa_to(ed, &ed->sa_ws_y, &CT.ws_sy, sa_base(&ed->sa_ws_y, CT.ws_sy) - (float)sdy * 40.f / z); } } else if (view_at(ed, mx, my) == V_PALETTE && my >= PAL_Y) { - if (mx < FLY_X) cat_scroll_by(ed, -(float)sdy * 48.f); - else fly_scroll_by(ed, -(float)sdy * 48.f); + if (mx < FLY_X) { + float t = fminf(cat_max_scroll(ed), fmaxf(0.f, sa_base(&ed->sa_cat, ed->cat_scroll) - (float)sdy * 48.f)); + sa_to(ed, &ed->sa_cat, &ed->cat_scroll, t); + } else { + float t = fminf(fly_max_scroll(ed), fmaxf(0.f, sa_base(&ed->sa_fly, ed->fly_scroll) - (float)sdy * 48.f)); + sa_to(ed, &ed->sa_fly, &ed->fly_scroll, t); + } } } @@ -9057,6 +9612,7 @@ static bool editor_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, /* A pilha arrastada fica por cima de tudo (pode passar sobre a paleta) */ if (ed->state == ES_DRAG && ed->drag_bi >= 0) render_drag_chain(ed, rb); + ghosts_render(ed, rb); /* blocos apagados saindo de cena */ render_areas_overlay(ed, rb); render_plus_menu(ed, rb); @@ -9121,6 +9677,10 @@ static bool editor_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) { ed->swap_pending[0] = ed->swap_pending[1] = -1; ed->mouse_owner = -1; ed->te_handle_drag = -1; + { /* TINYBLOCKS_REDUCE_MOTION=1: sem animacoes (acessibilidade, testes) */ + const char* rm = getenv("TINYBLOCKS_REDUCE_MOTION"); + ed->anim_off = rm && rm[0] && strcmp(rm, "0") != 0; + } ed->ax_tree = tb_a11y_tree_new(); tb_a11y_set_perform(ed->ax_tree, ax_perform, ed); { /* TINYBLOCKS_A11Y=0 desliga; =log escreve os eventos no stderr (um narrador de texto) */ @@ -9222,6 +9782,8 @@ static void editor_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { tab_doc_free(&ed->fly); /* pool da paleta */ free(ed->fly_items); free(ed->fdlg.ents); + qr_share_close(ed); + qr_recv_close(ed); free(ed->sbp_text); free(ed->run_blocks); jit_reset(ed); diff --git a/libraries/tinyblocks-editor/src/tb_editor_mcp.c b/libraries/tinyblocks-editor/src/tb_editor_mcp.c index f2c9193..6e26538 100644 --- a/libraries/tinyblocks-editor/src/tb_editor_mcp.c +++ b/libraries/tinyblocks-editor/src/tb_editor_mcp.c @@ -405,6 +405,7 @@ static void t_replace_stack(void* user, TbMcpRequest* rq) { warn[0] ? ": " : "", warn, head); return; } + if (T == &CT && AREA(V_SCRIPTS).shown) ghost_capture(ed, T, head, true, WS_X, WS_Y, true); /* sai de cena */ free_tree(ed, T, head); changed(ed, T); report_new_stacks(ed, rq, T, heads, n < 64 ? n : 64, warn); @@ -419,6 +420,7 @@ static void t_delete_stack(void* user, TbMcpRequest* rq) { head = stack_root(T, head); char label[TB_A11Y_NAME_MAX]; ax_block_label(T, head, label, sizeof(label), 0); + if (T == &CT && AREA(V_SCRIPTS).shown) ghost_capture(ed, T, head, true, WS_X, WS_Y, true); /* sai de cena */ free_tree(ed, T, head); changed(ed, T); tb_mcp_req_text(rq, "Pilha %d (\"%s\") apagada", head, label); @@ -616,6 +618,7 @@ static void t_delete_block(void* user, TbMcpRequest* rq) { char label[TB_A11Y_NAME_MAX]; ax_block_label(T, bi, label, sizeof(label), 0); if (tb_mcp_req_bool(rq, "with_below", false)) { + if (T == &CT && AREA(V_SCRIPTS).shown) ghost_capture(ed, T, bi, true, WS_X, WS_Y, true); if (T->ws[bi].parent >= 0) detach(T, bi); free_tree(ed, T, bi); } else { @@ -920,7 +923,12 @@ void ed_mcp_start(Ed* ed) { } void ed_mcp_poll(Ed* ed) { - if (ed->mcp) tb_mcp_server_poll(ed->mcp); + if (!ed->mcp) return; + /* blocos criados por agentes surgem animados (em cascata, por pedido) */ + ed->appear_batch = true; + ed->appear_k = 0; + tb_mcp_server_poll(ed->mcp); + ed->appear_batch = false; } void ed_mcp_stop(Ed* ed) { diff --git a/libraries/tinyblocks-qr/LICENSE-qrcodegen.txt b/libraries/tinyblocks-qr/LICENSE-qrcodegen.txt new file mode 100644 index 0000000..6e18127 --- /dev/null +++ b/libraries/tinyblocks-qr/LICENSE-qrcodegen.txt @@ -0,0 +1,23 @@ +/* + * QR Code generator library (C) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * - The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * - The Software is provided "as is", without warranty of any kind, express or + * implied, including but not limited to the warranties of merchantability, + * fitness for a particular purpose and noninfringement. In no event shall the + * authors or copyright holders be liable for any claim, damages or other + * liability, whether in an action of contract, tort or otherwise, arising from, + * out of or in connection with the Software or the use or other dealings in the + * Software. + */ + diff --git a/libraries/tinyblocks-qr/LICENSE-quirc.txt b/libraries/tinyblocks-qr/LICENSE-quirc.txt new file mode 100644 index 0000000..2db5a8f --- /dev/null +++ b/libraries/tinyblocks-qr/LICENSE-quirc.txt @@ -0,0 +1,19 @@ +quirc -- QR-code recognition library +Copyright (C) 2010-2012 Daniel Beer + +ISC License +=========== + +Permission to use, copy, modify, and/or distribute this software for +any purpose with or without fee is hereby granted, provided that the +above copyright notice and this permission notice appear in all +copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL +WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE +AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL +DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR +PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/libraries/tinyblocks-qr/Makefile b/libraries/tinyblocks-qr/Makefile new file mode 100644 index 0000000..601c7db --- /dev/null +++ b/libraries/tinyblocks-qr/Makefile @@ -0,0 +1,36 @@ +# Makefile da library qr (gerar e ler QR code + camera em cinza) +# Constroi build/libtinyblocks-qr.a e build/libtinyblocks-qr.so +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -O2 -Wall -Wextra -fvisibility=hidden \ + -D_DEFAULT_SOURCE -I../../include -Iinclude +# codigo de terceiros (qrcodegen, quirc): sem -pedantic, avisos deles nao +CFLAGS_3P := -std=c11 -O2 -w -fvisibility=hidden -Iinclude + +OBJ := $(BUILD)/tb_qr.o $(BUILD)/tb_camera.o \ + $(BUILD)/qrcodegen.o $(BUILD)/quirc.o $(BUILD)/decode.o $(BUILD)/identify.o $(BUILD)/version_db.o +LIB_A := $(BUILD)/libtinyblocks-qr.a +LIB_SO := $(BUILD)/libtinyblocks-qr.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(BUILD)/tb_%.o: src/tb_%.c include/tb_qr.h include/tb_camera.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(BUILD)/%.o: src/%.c + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_3P) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJ) + ar rcs $@ $^ + +$(LIB_SO): $(OBJ) + $(CC) -shared -o $@ $^ -lm + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-qr/include/tb_camera.h b/libraries/tinyblocks-qr/include/tb_camera.h new file mode 100644 index 0000000..899966c --- /dev/null +++ b/libraries/tinyblocks-qr/include/tb_camera.h @@ -0,0 +1,35 @@ +/* + * TinyBlocks - tb_camera.h + * + * Camera do aparelho, em tons de cinza (o que um leitor de QR precisa). + * Linux: V4L2 (/dev/video0, YUYV: o canal Y ja e o cinza). Android: Camera2 + * do NDK (camera2ndk + AImageReader, sem Java), com a permissao de camera + * pedida na hora. Sem camera (ou no Windows): tb_camera_open falha e + * tb_camera_error diz por que. + */ +#ifndef TB_CAMERA_H +#define TB_CAMERA_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Abre a camera (traseira, se houver) perto de want_w x want_h */ +TB_API bool tb_camera_open(int want_w, int want_h); + +/* Copia o quadro mais novo (cinza, 1 byte/pixel, de pe) para gray. + * Devolve false se nao chegou quadro novo desde a ultima chamada. */ +TB_API bool tb_camera_frame(unsigned char* gray, int cap, int* w, int* h); + +TB_API void tb_camera_close(void); +TB_API bool tb_camera_is_open(void); +TB_API const char* tb_camera_error(void); + +#ifdef __cplusplus +} +#endif + +#endif /* TB_CAMERA_H */ diff --git a/libraries/tinyblocks-qr/include/tb_qr.h b/libraries/tinyblocks-qr/include/tb_qr.h new file mode 100644 index 0000000..6c1ecb8 --- /dev/null +++ b/libraries/tinyblocks-qr/include/tb_qr.h @@ -0,0 +1,41 @@ +/* + * TinyBlocks - tb_qr.h + * + * QR code: gerar (qrcodegen, de Project Nayuki, MIT) e ler de uma imagem em + * tons de cinza (quirc, de Daniel Beer, ISC). Mais a camera do aparelho para + * o leitor (tb_camera.h). Usada pelo editor para mandar blocos de uma + * instancia para outra por QR. + */ +#ifndef TB_QR_H +#define TB_QR_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Lado maximo (modulos) de um QR: versao 40 */ +#define TB_QR_MAX_SIDE 177 + +/* Gera o QR do texto (correcao media; a menor versao que couber). + * mods recebe lado*lado bytes, 1 = modulo escuro. Devolve o lado, ou 0 se o + * texto nao couber num QR. */ +TB_API int tb_qr_encode(const char* text, unsigned char* mods, int cap); + +/* Leitor: acha e decodifica os QRs de uma imagem em cinza (1 byte/pixel) */ +typedef struct TbQrReader TbQrReader; +typedef void (*TbQrFound)(const char* text, int len, void* user); + +TB_API TbQrReader* tb_qr_reader_new(void); +/* Chama found para cada QR lido; devolve quantos foram lidos */ +TB_API int tb_qr_reader_scan(TbQrReader* r, const unsigned char* gray, int w, int h, + TbQrFound found, void* user); +TB_API void tb_qr_reader_free(TbQrReader* r); + +#ifdef __cplusplus +} +#endif + +#endif /* TB_QR_H */ diff --git a/libraries/tinyblocks-qr/library.toml b/libraries/tinyblocks-qr/library.toml new file mode 100644 index 0000000..c0b9d7c --- /dev/null +++ b/libraries/tinyblocks-qr/library.toml @@ -0,0 +1,19 @@ +# Metadados da library qr. Nao tem blocos: gera e le QR codes e abre a +# camera em cinza; o editor usa para mandar blocos de uma instancia para +# outra (compartilhar / receber). Codigo de terceiros: qrcodegen (MIT) e +# quirc (ISC), ver LICENSE-*.txt. +[library] +name = "tinyblocks-qr" +private = true +version = "1.0.0" +category = "QR" +description = "QR code (gerar e ler) e camera em cinza" +color = [76, 151, 255, 255] +dark = [51, 115, 230, 255] + +[build] +sources = ["src/tb_qr.c", "src/tb_camera.c", "src/qrcodegen.c", "src/quirc.c", "src/decode.c", "src/identify.c", "src/version_db.c"] +includes = ["include"] +shared = "build/libtinyblocks-qr.so" +static = "build/libtinyblocks-qr.a" +depends = [] diff --git a/libraries/tinyblocks-qr/src/decode.c b/libraries/tinyblocks-qr/src/decode.c new file mode 100644 index 0000000..a27a59a --- /dev/null +++ b/libraries/tinyblocks-qr/src/decode.c @@ -0,0 +1,948 @@ +/* quirc -- QR-code recognition library + * Copyright (C) 2010-2012 Daniel Beer + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include "quirc_internal.h" + +#include +#include + +#define MAX_POLY 64 + +/************************************************************************ + * Galois fields + */ + +struct galois_field { + int p; + const uint8_t *log; + const uint8_t *exp; +}; + +static const uint8_t gf16_exp[16] = { + 0x01, 0x02, 0x04, 0x08, 0x03, 0x06, 0x0c, 0x0b, + 0x05, 0x0a, 0x07, 0x0e, 0x0f, 0x0d, 0x09, 0x01 +}; + +static const uint8_t gf16_log[16] = { + 0x00, 0x0f, 0x01, 0x04, 0x02, 0x08, 0x05, 0x0a, + 0x03, 0x0e, 0x09, 0x07, 0x06, 0x0d, 0x0b, 0x0c +}; + +static const struct galois_field gf16 = { + .p = 15, + .log = gf16_log, + .exp = gf16_exp +}; + +static const uint8_t gf256_exp[256] = { + 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, + 0x1d, 0x3a, 0x74, 0xe8, 0xcd, 0x87, 0x13, 0x26, + 0x4c, 0x98, 0x2d, 0x5a, 0xb4, 0x75, 0xea, 0xc9, + 0x8f, 0x03, 0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, + 0x9d, 0x27, 0x4e, 0x9c, 0x25, 0x4a, 0x94, 0x35, + 0x6a, 0xd4, 0xb5, 0x77, 0xee, 0xc1, 0x9f, 0x23, + 0x46, 0x8c, 0x05, 0x0a, 0x14, 0x28, 0x50, 0xa0, + 0x5d, 0xba, 0x69, 0xd2, 0xb9, 0x6f, 0xde, 0xa1, + 0x5f, 0xbe, 0x61, 0xc2, 0x99, 0x2f, 0x5e, 0xbc, + 0x65, 0xca, 0x89, 0x0f, 0x1e, 0x3c, 0x78, 0xf0, + 0xfd, 0xe7, 0xd3, 0xbb, 0x6b, 0xd6, 0xb1, 0x7f, + 0xfe, 0xe1, 0xdf, 0xa3, 0x5b, 0xb6, 0x71, 0xe2, + 0xd9, 0xaf, 0x43, 0x86, 0x11, 0x22, 0x44, 0x88, + 0x0d, 0x1a, 0x34, 0x68, 0xd0, 0xbd, 0x67, 0xce, + 0x81, 0x1f, 0x3e, 0x7c, 0xf8, 0xed, 0xc7, 0x93, + 0x3b, 0x76, 0xec, 0xc5, 0x97, 0x33, 0x66, 0xcc, + 0x85, 0x17, 0x2e, 0x5c, 0xb8, 0x6d, 0xda, 0xa9, + 0x4f, 0x9e, 0x21, 0x42, 0x84, 0x15, 0x2a, 0x54, + 0xa8, 0x4d, 0x9a, 0x29, 0x52, 0xa4, 0x55, 0xaa, + 0x49, 0x92, 0x39, 0x72, 0xe4, 0xd5, 0xb7, 0x73, + 0xe6, 0xd1, 0xbf, 0x63, 0xc6, 0x91, 0x3f, 0x7e, + 0xfc, 0xe5, 0xd7, 0xb3, 0x7b, 0xf6, 0xf1, 0xff, + 0xe3, 0xdb, 0xab, 0x4b, 0x96, 0x31, 0x62, 0xc4, + 0x95, 0x37, 0x6e, 0xdc, 0xa5, 0x57, 0xae, 0x41, + 0x82, 0x19, 0x32, 0x64, 0xc8, 0x8d, 0x07, 0x0e, + 0x1c, 0x38, 0x70, 0xe0, 0xdd, 0xa7, 0x53, 0xa6, + 0x51, 0xa2, 0x59, 0xb2, 0x79, 0xf2, 0xf9, 0xef, + 0xc3, 0x9b, 0x2b, 0x56, 0xac, 0x45, 0x8a, 0x09, + 0x12, 0x24, 0x48, 0x90, 0x3d, 0x7a, 0xf4, 0xf5, + 0xf7, 0xf3, 0xfb, 0xeb, 0xcb, 0x8b, 0x0b, 0x16, + 0x2c, 0x58, 0xb0, 0x7d, 0xfa, 0xe9, 0xcf, 0x83, + 0x1b, 0x36, 0x6c, 0xd8, 0xad, 0x47, 0x8e, 0x01 +}; + +static const uint8_t gf256_log[256] = { + 0x00, 0xff, 0x01, 0x19, 0x02, 0x32, 0x1a, 0xc6, + 0x03, 0xdf, 0x33, 0xee, 0x1b, 0x68, 0xc7, 0x4b, + 0x04, 0x64, 0xe0, 0x0e, 0x34, 0x8d, 0xef, 0x81, + 0x1c, 0xc1, 0x69, 0xf8, 0xc8, 0x08, 0x4c, 0x71, + 0x05, 0x8a, 0x65, 0x2f, 0xe1, 0x24, 0x0f, 0x21, + 0x35, 0x93, 0x8e, 0xda, 0xf0, 0x12, 0x82, 0x45, + 0x1d, 0xb5, 0xc2, 0x7d, 0x6a, 0x27, 0xf9, 0xb9, + 0xc9, 0x9a, 0x09, 0x78, 0x4d, 0xe4, 0x72, 0xa6, + 0x06, 0xbf, 0x8b, 0x62, 0x66, 0xdd, 0x30, 0xfd, + 0xe2, 0x98, 0x25, 0xb3, 0x10, 0x91, 0x22, 0x88, + 0x36, 0xd0, 0x94, 0xce, 0x8f, 0x96, 0xdb, 0xbd, + 0xf1, 0xd2, 0x13, 0x5c, 0x83, 0x38, 0x46, 0x40, + 0x1e, 0x42, 0xb6, 0xa3, 0xc3, 0x48, 0x7e, 0x6e, + 0x6b, 0x3a, 0x28, 0x54, 0xfa, 0x85, 0xba, 0x3d, + 0xca, 0x5e, 0x9b, 0x9f, 0x0a, 0x15, 0x79, 0x2b, + 0x4e, 0xd4, 0xe5, 0xac, 0x73, 0xf3, 0xa7, 0x57, + 0x07, 0x70, 0xc0, 0xf7, 0x8c, 0x80, 0x63, 0x0d, + 0x67, 0x4a, 0xde, 0xed, 0x31, 0xc5, 0xfe, 0x18, + 0xe3, 0xa5, 0x99, 0x77, 0x26, 0xb8, 0xb4, 0x7c, + 0x11, 0x44, 0x92, 0xd9, 0x23, 0x20, 0x89, 0x2e, + 0x37, 0x3f, 0xd1, 0x5b, 0x95, 0xbc, 0xcf, 0xcd, + 0x90, 0x87, 0x97, 0xb2, 0xdc, 0xfc, 0xbe, 0x61, + 0xf2, 0x56, 0xd3, 0xab, 0x14, 0x2a, 0x5d, 0x9e, + 0x84, 0x3c, 0x39, 0x53, 0x47, 0x6d, 0x41, 0xa2, + 0x1f, 0x2d, 0x43, 0xd8, 0xb7, 0x7b, 0xa4, 0x76, + 0xc4, 0x17, 0x49, 0xec, 0x7f, 0x0c, 0x6f, 0xf6, + 0x6c, 0xa1, 0x3b, 0x52, 0x29, 0x9d, 0x55, 0xaa, + 0xfb, 0x60, 0x86, 0xb1, 0xbb, 0xcc, 0x3e, 0x5a, + 0xcb, 0x59, 0x5f, 0xb0, 0x9c, 0xa9, 0xa0, 0x51, + 0x0b, 0xf5, 0x16, 0xeb, 0x7a, 0x75, 0x2c, 0xd7, + 0x4f, 0xae, 0xd5, 0xe9, 0xe6, 0xe7, 0xad, 0xe8, + 0x74, 0xd6, 0xf4, 0xea, 0xa8, 0x50, 0x58, 0xaf +}; + +static const struct galois_field gf256 = { + .p = 255, + .log = gf256_log, + .exp = gf256_exp +}; + +/************************************************************************ + * Polynomial operations + */ + +static void poly_add(uint8_t *dst, const uint8_t *src, uint8_t c, + int shift, const struct galois_field *gf) +{ + int i; + int log_c = gf->log[c]; + + if (!c) + return; + + for (i = 0; i < MAX_POLY; i++) { + int p = i + shift; + uint8_t v = src[i]; + + if (p < 0 || p >= MAX_POLY) + continue; + if (!v) + continue; + + dst[p] ^= gf->exp[(gf->log[v] + log_c) % gf->p]; + } +} + +static uint8_t poly_eval(const uint8_t *s, uint8_t x, + const struct galois_field *gf) +{ + int i; + uint8_t sum = 0; + uint8_t log_x = gf->log[x]; + + if (!x) + return s[0]; + + for (i = 0; i < MAX_POLY; i++) { + uint8_t c = s[i]; + + if (!c) + continue; + + sum ^= gf->exp[(gf->log[c] + log_x * i) % gf->p]; + } + + return sum; +} + +/************************************************************************ + * Berlekamp-Massey algorithm for finding error locator polynomials. + */ + +static void berlekamp_massey(const uint8_t *s, int N, + const struct galois_field *gf, + uint8_t *sigma) +{ + uint8_t C[MAX_POLY]; + uint8_t B[MAX_POLY]; + int L = 0; + int m = 1; + uint8_t b = 1; + int n; + + memset(B, 0, sizeof(B)); + memset(C, 0, sizeof(C)); + B[0] = 1; + C[0] = 1; + + for (n = 0; n < N; n++) { + uint8_t d = s[n]; + uint8_t mult; + int i; + + for (i = 1; i <= L; i++) { + if (!(C[i] && s[n - i])) + continue; + + d ^= gf->exp[(gf->log[C[i]] + + gf->log[s[n - i]]) % + gf->p]; + } + + mult = gf->exp[(gf->p - gf->log[b] + gf->log[d]) % gf->p]; + + if (!d) { + m++; + } else if (L * 2 <= n) { + uint8_t T[MAX_POLY]; + + memcpy(T, C, sizeof(T)); + poly_add(C, B, mult, m, gf); + memcpy(B, T, sizeof(B)); + L = n + 1 - L; + b = d; + m = 1; + } else { + poly_add(C, B, mult, m, gf); + m++; + } + } + + memcpy(sigma, C, MAX_POLY); +} + +/************************************************************************ + * Code stream error correction + * + * Generator polynomial for GF(2^8) is x^8 + x^4 + x^3 + x^2 + 1 + */ + +static int block_syndromes(const uint8_t *data, int bs, int npar, uint8_t *s) +{ + int nonzero = 0; + int i; + + memset(s, 0, MAX_POLY); + + for (i = 0; i < npar; i++) { + int j; + + for (j = 0; j < bs; j++) { + uint8_t c = data[bs - j - 1]; + + if (!c) + continue; + + s[i] ^= gf256_exp[((int)gf256_log[c] + + i * j) % 255]; + } + + if (s[i]) + nonzero = 1; + } + + return nonzero; +} + +static void eloc_poly(uint8_t *omega, + const uint8_t *s, const uint8_t *sigma, + int npar) +{ + int i; + + memset(omega, 0, MAX_POLY); + + for (i = 0; i < npar; i++) { + const uint8_t a = sigma[i]; + const uint8_t log_a = gf256_log[a]; + int j; + + if (!a) + continue; + + for (j = 0; j + 1 < MAX_POLY; j++) { + const uint8_t b = s[j + 1]; + + if (i + j >= npar) + break; + + if (!b) + continue; + + omega[i + j] ^= + gf256_exp[(log_a + gf256_log[b]) % 255]; + } + } +} + +static quirc_decode_error_t correct_block(uint8_t *data, + const struct quirc_rs_params *ecc) +{ + int npar = ecc->bs - ecc->dw; + uint8_t s[MAX_POLY]; + uint8_t sigma[MAX_POLY]; + uint8_t sigma_deriv[MAX_POLY]; + uint8_t omega[MAX_POLY]; + int i; + + /* Compute syndrome vector */ + if (!block_syndromes(data, ecc->bs, npar, s)) + return QUIRC_SUCCESS; + + berlekamp_massey(s, npar, &gf256, sigma); + + /* Compute derivative of sigma */ + memset(sigma_deriv, 0, MAX_POLY); + for (i = 0; i + 1 < MAX_POLY; i += 2) + sigma_deriv[i] = sigma[i + 1]; + + /* Compute error evaluator polynomial */ + eloc_poly(omega, s, sigma, npar - 1); + + /* Find error locations and magnitudes */ + for (i = 0; i < ecc->bs; i++) { + uint8_t xinv = gf256_exp[255 - i]; + + if (!poly_eval(sigma, xinv, &gf256)) { + uint8_t sd_x = poly_eval(sigma_deriv, xinv, &gf256); + uint8_t omega_x = poly_eval(omega, xinv, &gf256); + uint8_t error = gf256_exp[(255 - gf256_log[sd_x] + + gf256_log[omega_x]) % 255]; + + data[ecc->bs - i - 1] ^= error; + } + } + + if (block_syndromes(data, ecc->bs, npar, s)) + return QUIRC_ERROR_DATA_ECC; + + return QUIRC_SUCCESS; +} + +/************************************************************************ + * Format value error correction + * + * Generator polynomial for GF(2^4) is x^4 + x + 1 + */ + +#define FORMAT_MAX_ERROR 3 +#define FORMAT_SYNDROMES (FORMAT_MAX_ERROR * 2) +#define FORMAT_BITS 15 + +static int format_syndromes(uint16_t u, uint8_t *s) +{ + int i; + int nonzero = 0; + + memset(s, 0, MAX_POLY); + + for (i = 0; i < FORMAT_SYNDROMES; i++) { + int j; + + s[i] = 0; + for (j = 0; j < FORMAT_BITS; j++) + if (u & (1 << j)) + s[i] ^= gf16_exp[((i + 1) * j) % 15]; + + if (s[i]) + nonzero = 1; + } + + return nonzero; +} + +static quirc_decode_error_t correct_format(uint16_t *f_ret) +{ + uint16_t u = *f_ret; + int i; + uint8_t s[MAX_POLY]; + uint8_t sigma[MAX_POLY]; + + /* Evaluate U (received codeword) at each of alpha_1 .. alpha_6 + * to get S_1 .. S_6 (but we index them from 0). + */ + if (!format_syndromes(u, s)) + return QUIRC_SUCCESS; + + berlekamp_massey(s, FORMAT_SYNDROMES, &gf16, sigma); + + /* Now, find the roots of the polynomial */ + for (i = 0; i < 15; i++) + if (!poly_eval(sigma, gf16_exp[15 - i], &gf16)) + u ^= (1 << i); + + if (format_syndromes(u, s)) + return QUIRC_ERROR_FORMAT_ECC; + + *f_ret = u; + return QUIRC_SUCCESS; +} + +/************************************************************************ + * Decoder algorithm + */ + +struct datastream { + uint8_t *raw; + int data_bits; + int ptr; + + uint8_t data[QUIRC_MAX_PAYLOAD]; +}; + +static inline int grid_bit(const struct quirc_code *code, int x, int y) +{ + int p = y * code->size + x; + return (code->cell_bitmap[p >> 3] >> (p & 7)) & 1; +} + +static quirc_decode_error_t read_format(const struct quirc_code *code, + struct quirc_data *data, int which) +{ + int i; + uint16_t format = 0; + uint16_t fdata; + quirc_decode_error_t err; + + if (which) { + for (i = 0; i < 7; i++) + format = (format << 1) | + grid_bit(code, 8, code->size - 1 - i); + for (i = 0; i < 8; i++) + format = (format << 1) | + grid_bit(code, code->size - 8 + i, 8); + } else { + static const int xs[15] = { + 8, 8, 8, 8, 8, 8, 8, 8, 7, 5, 4, 3, 2, 1, 0 + }; + static const int ys[15] = { + 0, 1, 2, 3, 4, 5, 7, 8, 8, 8, 8, 8, 8, 8, 8 + }; + + for (i = 14; i >= 0; i--) + format = (format << 1) | grid_bit(code, xs[i], ys[i]); + } + + format ^= 0x5412; + + err = correct_format(&format); + if (err) + return err; + + fdata = format >> 10; + data->ecc_level = fdata >> 3; + data->mask = fdata & 7; + + return QUIRC_SUCCESS; +} + +static int mask_bit(int mask, int i, int j) +{ + switch (mask) { + case 0: return !((i + j) % 2); + case 1: return !(i % 2); + case 2: return !(j % 3); + case 3: return !((i + j) % 3); + case 4: return !(((i / 2) + (j / 3)) % 2); + case 5: return !((i * j) % 2 + (i * j) % 3); + case 6: return !(((i * j) % 2 + (i * j) % 3) % 2); + case 7: return !(((i * j) % 3 + (i + j) % 2) % 2); + } + + return 0; +} + +static int reserved_cell(int version, int i, int j) +{ + const struct quirc_version_info *ver = &quirc_version_db[version]; + int size = version * 4 + 17; + int ai = -1, aj = -1, a; + + /* Finder + format: top left */ + if (i < 9 && j < 9) + return 1; + + /* Finder + format: bottom left */ + if (i + 8 >= size && j < 9) + return 1; + + /* Finder + format: top right */ + if (i < 9 && j + 8 >= size) + return 1; + + /* Exclude timing patterns */ + if (i == 6 || j == 6) + return 1; + + /* Exclude version info, if it exists. Version info sits adjacent to + * the top-right and bottom-left finders in three rows, bounded by + * the timing pattern. + */ + if (version >= 7) { + if (i < 6 && j + 11 >= size) + return 1; + if (i + 11 >= size && j < 6) + return 1; + } + + /* Exclude alignment patterns */ + for (a = 0; a < QUIRC_MAX_ALIGNMENT && ver->apat[a]; a++) { + int p = ver->apat[a]; + + if (abs(p - i) < 3) + ai = a; + if (abs(p - j) < 3) + aj = a; + } + + if (ai >= 0 && aj >= 0) { + a--; + if (ai > 0 && ai < a) + return 1; + if (aj > 0 && aj < a) + return 1; + if (aj == a && ai == a) + return 1; + } + + return 0; +} + +static void read_bit(const struct quirc_code *code, + struct quirc_data *data, + struct datastream *ds, int i, int j) +{ + int bitpos = ds->data_bits & 7; + int bytepos = ds->data_bits >> 3; + int v = grid_bit(code, j, i); + + if (mask_bit(data->mask, i, j)) + v ^= 1; + + if (v) + ds->raw[bytepos] |= (0x80 >> bitpos); + + ds->data_bits++; +} + +static void read_data(const struct quirc_code *code, + struct quirc_data *data, + struct datastream *ds) +{ + int y = code->size - 1; + int x = code->size - 1; + int dir = -1; + + while (x > 0) { + if (x == 6) + x--; + + if (!reserved_cell(data->version, y, x)) + read_bit(code, data, ds, y, x); + + if (!reserved_cell(data->version, y, x - 1)) + read_bit(code, data, ds, y, x - 1); + + y += dir; + if (y < 0 || y >= code->size) { + dir = -dir; + x -= 2; + y += dir; + } + } +} + +static quirc_decode_error_t codestream_ecc(struct quirc_data *data, + struct datastream *ds) +{ + const struct quirc_version_info *ver = + &quirc_version_db[data->version]; + const struct quirc_rs_params *sb_ecc = &ver->ecc[data->ecc_level]; + struct quirc_rs_params lb_ecc; + const int lb_count = + (ver->data_bytes - sb_ecc->bs * sb_ecc->ns) / (sb_ecc->bs + 1); + const int bc = lb_count + sb_ecc->ns; + const int ecc_offset = sb_ecc->dw * bc + lb_count; + int dst_offset = 0; + int i; + + memcpy(&lb_ecc, sb_ecc, sizeof(lb_ecc)); + lb_ecc.dw++; + lb_ecc.bs++; + + for (i = 0; i < bc; i++) { + uint8_t *dst = ds->data + dst_offset; + const struct quirc_rs_params *ecc = + (i < sb_ecc->ns) ? sb_ecc : &lb_ecc; + const int num_ec = ecc->bs - ecc->dw; + quirc_decode_error_t err; + int j; + + for (j = 0; j < ecc->dw; j++) + dst[j] = ds->raw[j * bc + i]; + for (j = 0; j < num_ec; j++) + dst[ecc->dw + j] = ds->raw[ecc_offset + j * bc + i]; + + err = correct_block(dst, ecc); + if (err) + return err; + + dst_offset += ecc->dw; + } + + ds->data_bits = dst_offset * 8; + + return QUIRC_SUCCESS; +} + +static inline int bits_remaining(const struct datastream *ds) +{ + return ds->data_bits - ds->ptr; +} + +static int take_bits(struct datastream *ds, int len) +{ + int ret = 0; + + while (len && (ds->ptr < ds->data_bits)) { + uint8_t b = ds->data[ds->ptr >> 3]; + int bitpos = ds->ptr & 7; + + ret <<= 1; + if ((b << bitpos) & 0x80) + ret |= 1; + + ds->ptr++; + len--; + } + + return ret; +} + +static int numeric_tuple(struct quirc_data *data, + struct datastream *ds, + int bits, int digits) +{ + int tuple; + int i; + + if (bits_remaining(ds) < bits) + return -1; + + tuple = take_bits(ds, bits); + + for (i = digits - 1; i >= 0; i--) { + data->payload[data->payload_len + i] = tuple % 10 + '0'; + tuple /= 10; + } + + data->payload_len += digits; + return 0; +} + +static quirc_decode_error_t decode_numeric(struct quirc_data *data, + struct datastream *ds) +{ + int bits = 14; + int count; + + if (data->version < 10) + bits = 10; + else if (data->version < 27) + bits = 12; + + count = take_bits(ds, bits); + if (data->payload_len + count + 1 > QUIRC_MAX_PAYLOAD) + return QUIRC_ERROR_DATA_OVERFLOW; + + while (count >= 3) { + if (numeric_tuple(data, ds, 10, 3) < 0) + return QUIRC_ERROR_DATA_UNDERFLOW; + count -= 3; + } + + if (count >= 2) { + if (numeric_tuple(data, ds, 7, 2) < 0) + return QUIRC_ERROR_DATA_UNDERFLOW; + count -= 2; + } + + if (count) { + if (numeric_tuple(data, ds, 4, 1) < 0) + return QUIRC_ERROR_DATA_UNDERFLOW; + count--; + } + + return QUIRC_SUCCESS; +} + +static int alpha_tuple(struct quirc_data *data, + struct datastream *ds, + int bits, int digits) +{ + int tuple; + int i; + + if (bits_remaining(ds) < bits) + return -1; + + tuple = take_bits(ds, bits); + + for (i = 0; i < digits; i++) { + static const char *alpha_map = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; + + data->payload[data->payload_len + digits - i - 1] = + alpha_map[tuple % 45]; + tuple /= 45; + } + + data->payload_len += digits; + return 0; +} + +static quirc_decode_error_t decode_alpha(struct quirc_data *data, + struct datastream *ds) +{ + int bits = 13; + int count; + + if (data->version < 10) + bits = 9; + else if (data->version < 27) + bits = 11; + + count = take_bits(ds, bits); + if (data->payload_len + count + 1 > QUIRC_MAX_PAYLOAD) + return QUIRC_ERROR_DATA_OVERFLOW; + + while (count >= 2) { + if (alpha_tuple(data, ds, 11, 2) < 0) + return QUIRC_ERROR_DATA_UNDERFLOW; + count -= 2; + } + + if (count) { + if (alpha_tuple(data, ds, 6, 1) < 0) + return QUIRC_ERROR_DATA_UNDERFLOW; + count--; + } + + return QUIRC_SUCCESS; +} + +static quirc_decode_error_t decode_byte(struct quirc_data *data, + struct datastream *ds) +{ + int bits = 16; + int count; + int i; + + if (data->version < 10) + bits = 8; + + count = take_bits(ds, bits); + if (data->payload_len + count + 1 > QUIRC_MAX_PAYLOAD) + return QUIRC_ERROR_DATA_OVERFLOW; + if (bits_remaining(ds) < count * 8) + return QUIRC_ERROR_DATA_UNDERFLOW; + + for (i = 0; i < count; i++) + data->payload[data->payload_len++] = take_bits(ds, 8); + + return QUIRC_SUCCESS; +} + +static quirc_decode_error_t decode_kanji(struct quirc_data *data, + struct datastream *ds) +{ + int bits = 12; + int count; + int i; + + if (data->version < 10) + bits = 8; + else if (data->version < 27) + bits = 10; + + count = take_bits(ds, bits); + if (data->payload_len + count * 2 + 1 > QUIRC_MAX_PAYLOAD) + return QUIRC_ERROR_DATA_OVERFLOW; + if (bits_remaining(ds) < count * 13) + return QUIRC_ERROR_DATA_UNDERFLOW; + + for (i = 0; i < count; i++) { + int d = take_bits(ds, 13); + int msB = d / 0xc0; + int lsB = d % 0xc0; + int intermediate = (msB << 8) | lsB; + uint16_t sjw; + + if (intermediate + 0x8140 <= 0x9ffc) { + /* bytes are in the range 0x8140 to 0x9FFC */ + sjw = intermediate + 0x8140; + } else { + /* bytes are in the range 0xE040 to 0xEBBF */ + sjw = intermediate + 0xc140; + } + + data->payload[data->payload_len++] = sjw >> 8; + data->payload[data->payload_len++] = sjw & 0xff; + } + + return QUIRC_SUCCESS; +} + +static quirc_decode_error_t decode_eci(struct quirc_data *data, + struct datastream *ds) +{ + if (bits_remaining(ds) < 8) + return QUIRC_ERROR_DATA_UNDERFLOW; + + data->eci = take_bits(ds, 8); + + if ((data->eci & 0xc0) == 0x80) { + if (bits_remaining(ds) < 8) + return QUIRC_ERROR_DATA_UNDERFLOW; + + data->eci = (data->eci << 8) | take_bits(ds, 8); + } else if ((data->eci & 0xe0) == 0xc0) { + if (bits_remaining(ds) < 16) + return QUIRC_ERROR_DATA_UNDERFLOW; + + data->eci = (data->eci << 16) | take_bits(ds, 16); + } + + return QUIRC_SUCCESS; +} + +static quirc_decode_error_t decode_payload(struct quirc_data *data, + struct datastream *ds) +{ + while (bits_remaining(ds) >= 4) { + quirc_decode_error_t err = QUIRC_SUCCESS; + int type = take_bits(ds, 4); + + switch (type) { + case QUIRC_DATA_TYPE_NUMERIC: + err = decode_numeric(data, ds); + break; + + case QUIRC_DATA_TYPE_ALPHA: + err = decode_alpha(data, ds); + break; + + case QUIRC_DATA_TYPE_BYTE: + err = decode_byte(data, ds); + break; + + case QUIRC_DATA_TYPE_KANJI: + err = decode_kanji(data, ds); + break; + + case 7: + err = decode_eci(data, ds); + break; + + default: + goto done; + } + + if (err) + return err; + + if (!(type & (type - 1)) && (type > data->data_type)) + data->data_type = type; + } +done: + + /* Add nul terminator to all payloads */ + if (data->payload_len >= (int) sizeof(data->payload)) + data->payload_len--; + data->payload[data->payload_len] = 0; + + return QUIRC_SUCCESS; +} + +quirc_decode_error_t quirc_decode(const struct quirc_code *code, + struct quirc_data *data) +{ + quirc_decode_error_t err; + struct datastream ds; + + if (code->size > QUIRC_MAX_GRID_SIZE) + return QUIRC_ERROR_INVALID_GRID_SIZE; + + if ((code->size - 17) % 4) + return QUIRC_ERROR_INVALID_GRID_SIZE; + + memset(data, 0, sizeof(*data)); + memset(&ds, 0, sizeof(ds)); + + data->version = (code->size - 17) / 4; + + if (data->version < 1 || + data->version > QUIRC_MAX_VERSION) + return QUIRC_ERROR_INVALID_VERSION; + + /* Read format information -- try both locations */ + err = read_format(code, data, 0); + if (err) + err = read_format(code, data, 1); + if (err) + return err; + + /* + * Borrow data->payload to store the raw bits. + * It's only used during read_data + coddestream_ecc below. + * + * This trick saves the size of struct datastream, which we allocate + * on the stack. + */ + + ds.raw = data->payload; + + read_data(code, data, &ds); + err = codestream_ecc(data, &ds); + if (err) + return err; + + ds.raw = NULL; /* We've done with this buffer. */ + + err = decode_payload(data, &ds); + if (err) + return err; + + return QUIRC_SUCCESS; +} + +void quirc_flip(struct quirc_code *code) +{ + struct quirc_code flipped = {0}; + unsigned int offset = 0; + for (int y = 0; y < code->size; y++) { + for (int x = 0; x < code->size; x++) { + if (grid_bit(code, y, x)) { + flipped.cell_bitmap[offset >> 3u] |= (1u << (offset & 7u)); + } + offset++; + } + } + memcpy(&code->cell_bitmap, &flipped.cell_bitmap, sizeof(flipped.cell_bitmap)); +} diff --git a/libraries/tinyblocks-qr/src/identify.c b/libraries/tinyblocks-qr/src/identify.c new file mode 100644 index 0000000..c149c21 --- /dev/null +++ b/libraries/tinyblocks-qr/src/identify.c @@ -0,0 +1,1160 @@ +/* quirc - QR-code recognition library + * Copyright (C) 2010-2012 Daniel Beer + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include +#include +#include +#ifdef QUIRC_USE_TGMATH +#include +#else +#include +#endif // QUIRC_USE_TGMATH +#include "quirc_internal.h" + +/************************************************************************ + * Linear algebra routines + */ + +static int line_intersect(const struct quirc_point *p0, + const struct quirc_point *p1, + const struct quirc_point *q0, + const struct quirc_point *q1, + struct quirc_point *r) +{ + /* (a, b) is perpendicular to line p */ + int a = -(p1->y - p0->y); + int b = p1->x - p0->x; + + /* (c, d) is perpendicular to line q */ + int c = -(q1->y - q0->y); + int d = q1->x - q0->x; + + /* e and f are dot products of the respective vectors with p and q */ + int e = a * p1->x + b * p1->y; + int f = c * q1->x + d * q1->y; + + /* Now we need to solve: + * [a b] [rx] [e] + * [c d] [ry] = [f] + * + * We do this by inverting the matrix and applying it to (e, f): + * [ d -b] [e] [rx] + * 1/det [-c a] [f] = [ry] + */ + int det = (a * d) - (b * c); + + if (!det) + return 0; + + r->x = (d * e - b * f) / det; + r->y = (-c * e + a * f) / det; + + return 1; +} + +static void perspective_setup(quirc_float_t *c, + const struct quirc_point *rect, + quirc_float_t w, quirc_float_t h) +{ + quirc_float_t x0 = rect[0].x; + quirc_float_t y0 = rect[0].y; + quirc_float_t x1 = rect[1].x; + quirc_float_t y1 = rect[1].y; + quirc_float_t x2 = rect[2].x; + quirc_float_t y2 = rect[2].y; + quirc_float_t x3 = rect[3].x; + quirc_float_t y3 = rect[3].y; + + quirc_float_t wden = (quirc_float_t)1 / (w * (x2*y3 - x3*y2 + (x3-x2)*y1 + x1*(y2-y3))); + quirc_float_t hden = (quirc_float_t)1 / (h * (x2*y3 + x1*(y2-y3) - x3*y2 + (x3-x2)*y1)); + + c[0] = (x1*(x2*y3-x3*y2) + x0*(-x2*y3+x3*y2+(x2-x3)*y1) + + x1*(x3-x2)*y0) * wden; + c[1] = -(x0*(x2*y3+x1*(y2-y3)-x2*y1) - x1*x3*y2 + x2*x3*y1 + + (x1*x3-x2*x3)*y0) * hden; + c[2] = x0; + c[3] = (y0*(x1*(y3-y2)-x2*y3+x3*y2) + y1*(x2*y3-x3*y2) + + x0*y1*(y2-y3)) * wden; + c[4] = (x0*(y1*y3-y2*y3) + x1*y2*y3 - x2*y1*y3 + + y0*(x3*y2-x1*y2+(x2-x3)*y1)) * hden; + c[5] = y0; + c[6] = (x1*(y3-y2) + x0*(y2-y3) + (x2-x3)*y1 + (x3-x2)*y0) * wden; + c[7] = (-x2*y3 + x1*y3 + x3*y2 + x0*(y1-y2) - x3*y1 + (x2-x1)*y0) * + hden; +} + +static void perspective_map(const quirc_float_t *c, + quirc_float_t u, quirc_float_t v, struct quirc_point *ret) +{ + quirc_float_t den = (quirc_float_t)1 / (c[6]*u + c[7]*v + (quirc_float_t)1.0); + quirc_float_t x = (c[0]*u + c[1]*v + c[2]) * den; + quirc_float_t y = (c[3]*u + c[4]*v + c[5]) * den; + + ret->x = (int) rint(x); + ret->y = (int) rint(y); +} + +static void perspective_unmap(const quirc_float_t *c, + const struct quirc_point *in, + quirc_float_t *u, quirc_float_t *v) +{ + quirc_float_t x = in->x; + quirc_float_t y = in->y; + quirc_float_t den = (quirc_float_t)1 / (-c[0]*c[7]*y + c[1]*c[6]*y + (c[3]*c[7]-c[4]*c[6])*x + + c[0]*c[4] - c[1]*c[3]); + + *u = -(c[1]*(y-c[5]) - c[2]*c[7]*y + (c[5]*c[7]-c[4])*x + c[2]*c[4]) * + den; + *v = (c[0]*(y-c[5]) - c[2]*c[6]*y + (c[5]*c[6]-c[3])*x + c[2]*c[3]) * + den; +} + +/************************************************************************ + * Span-based floodfill routine + */ + +typedef void (*span_func_t)(void *user_data, int y, int left, int right); + +static void flood_fill_line(struct quirc *q, int x, int y, + int from, int to, + span_func_t func, void *user_data, + int *leftp, int *rightp) +{ + quirc_pixel_t *row; + int left; + int right; + int i; + + row = q->pixels + y * q->w; + QUIRC_ASSERT(row[x] == from); + + left = x; + right = x; + + while (left > 0 && row[left - 1] == from) + left--; + + while (right < q->w - 1 && row[right + 1] == from) + right++; + + /* Fill the extent */ + for (i = left; i <= right; i++) + row[i] = to; + + /* Return the processed range */ + *leftp = left; + *rightp = right; + + if (func) + func(user_data, y, left, right); +} + +static struct quirc_flood_fill_vars *flood_fill_call_next( + struct quirc *q, + quirc_pixel_t *row, + int from, int to, + span_func_t func, void *user_data, + struct quirc_flood_fill_vars *vars, + int direction) +{ + int *leftp; + + if (direction < 0) { + leftp = &vars->left_up; + } else { + leftp = &vars->left_down; + } + + while (*leftp <= vars->right) { + if (row[*leftp] == from) { + struct quirc_flood_fill_vars *next_vars; + int next_left; + + /* Set up the next context */ + next_vars = vars + 1; + next_vars->y = vars->y + direction; + + /* Fill the extent */ + flood_fill_line(q, + *leftp, + next_vars->y, + from, to, + func, user_data, + &next_left, + &next_vars->right); + next_vars->left_down = next_left; + next_vars->left_up = next_left; + + return next_vars; + } + (*leftp)++; + } + return NULL; +} + +static void flood_fill_seed(struct quirc *q, + int x0, int y0, + int from, int to, + span_func_t func, void *user_data) +{ + struct quirc_flood_fill_vars *const stack = q->flood_fill_vars; + const size_t stack_size = q->num_flood_fill_vars; + const struct quirc_flood_fill_vars *const last_vars = + &stack[stack_size - 1]; + + QUIRC_ASSERT(from != to); + QUIRC_ASSERT(q->pixels[y0 * q->w + x0] == from); + + struct quirc_flood_fill_vars *next_vars; + int next_left; + + /* Set up the first context */ + next_vars = stack; + next_vars->y = y0; + + /* Fill the extent */ + flood_fill_line(q, x0, next_vars->y, from, to, + func, user_data, + &next_left, &next_vars->right); + next_vars->left_down = next_left; + next_vars->left_up = next_left; + + while (true) { + struct quirc_flood_fill_vars * const vars = next_vars; + quirc_pixel_t *row; + + if (vars == last_vars) { + /* + * "Stack overflow". + * Just stop and return. + * This can be caused by very complex shapes in + * the image, which is not likely a part of + * a valid QR code anyway. + */ + break; + } + + /* Seed new flood-fills */ + if (vars->y > 0) { + row = q->pixels + (vars->y - 1) * q->w; + + next_vars = flood_fill_call_next(q, row, + from, to, + func, user_data, + vars, -1); + if (next_vars != NULL) { + continue; + } + } + + if (vars->y < q->h - 1) { + row = q->pixels + (vars->y + 1) * q->w; + + next_vars = flood_fill_call_next(q, row, + from, to, + func, user_data, + vars, 1); + if (next_vars != NULL) { + continue; + } + } + + if (vars > stack) { + /* Restore the previous context */ + next_vars = vars - 1; + continue; + } + + /* We've done. */ + break; + } +} + +/************************************************************************ + * Adaptive thresholding + */ + +static uint8_t otsu(const struct quirc *q) +{ + size_t num_pixels = quirc_pixel_count(q); + + // Calculate histogram + size_t histogram[UINT8_MAX + 1]; + (void)memset(histogram, 0, sizeof(histogram)); + uint8_t* ptr = q->image; + size_t length = num_pixels; + while (length--) { + uint8_t value = *ptr++; + histogram[value]++; + } + + // Calculate weighted sum of histogram values + quirc_float_t sum = (quirc_float_t)0; + unsigned int i = 0; + for (i = 0; i <= UINT8_MAX; ++i) { + sum += (quirc_float_t)i * histogram[i]; + } + + // Compute threshold + quirc_float_t sumB = (quirc_float_t)0; + size_t q1 = 0; + quirc_float_t max = (quirc_float_t)0; + uint8_t threshold = 0; + for (i = 0; i <= UINT8_MAX; ++i) { + // Weighted background + q1 += histogram[i]; + if (q1 == 0) + continue; + + // Weighted foreground + const size_t q2 = num_pixels - q1; + if (q2 == 0) + break; + + sumB += (quirc_float_t)i * histogram[i]; + const quirc_float_t m1 = sumB / q1; + const quirc_float_t m2 = (sum - sumB) / q2; + const quirc_float_t m1m2 = m1 - m2; + const quirc_float_t variance = m1m2 * m1m2 * q1 * q2; + if (variance >= max) { + threshold = i; + max = variance; + } + } + + return threshold; +} + +static void area_count(void *user_data, int y, int left, int right) +{ + ((struct quirc_region *)user_data)->count += right - left + 1; +} + +static int region_code(struct quirc *q, int x, int y) +{ + int pixel; + struct quirc_region *box; + int region; + + if (x < 0 || y < 0 || x >= q->w || y >= q->h) + return -1; + + pixel = q->pixels[y * q->w + x]; + + if (pixel >= QUIRC_PIXEL_REGION) + return pixel; + + if (pixel == QUIRC_PIXEL_WHITE) + return -1; + + if (q->num_regions >= QUIRC_MAX_REGIONS) + return -1; + + region = q->num_regions; + box = &q->regions[q->num_regions++]; + + memset(box, 0, sizeof(*box)); + + box->seed.x = x; + box->seed.y = y; + box->capstone = -1; + + flood_fill_seed(q, x, y, pixel, region, area_count, box); + + return region; +} + +struct polygon_score_data { + struct quirc_point ref; + + int scores[4]; + struct quirc_point *corners; +}; + +static void find_one_corner(void *user_data, int y, int left, int right) +{ + struct polygon_score_data *psd = + (struct polygon_score_data *)user_data; + int xs[2] = {left, right}; + int dy = y - psd->ref.y; + int i; + + for (i = 0; i < 2; i++) { + int dx = xs[i] - psd->ref.x; + int d = dx * dx + dy * dy; + + if (d > psd->scores[0]) { + psd->scores[0] = d; + psd->corners[0].x = xs[i]; + psd->corners[0].y = y; + } + } +} + +static void find_other_corners(void *user_data, int y, int left, int right) +{ + struct polygon_score_data *psd = + (struct polygon_score_data *)user_data; + int xs[2] = {left, right}; + int i; + + for (i = 0; i < 2; i++) { + int up = xs[i] * psd->ref.x + y * psd->ref.y; + int right = xs[i] * -psd->ref.y + y * psd->ref.x; + int scores[4] = {up, right, -up, -right}; + int j; + + for (j = 0; j < 4; j++) { + if (scores[j] > psd->scores[j]) { + psd->scores[j] = scores[j]; + psd->corners[j].x = xs[i]; + psd->corners[j].y = y; + } + } + } +} + +static void find_region_corners(struct quirc *q, + int rcode, const struct quirc_point *ref, + struct quirc_point *corners) +{ + struct quirc_region *region = &q->regions[rcode]; + struct polygon_score_data psd; + int i; + + memset(&psd, 0, sizeof(psd)); + psd.corners = corners; + + memcpy(&psd.ref, ref, sizeof(psd.ref)); + psd.scores[0] = -1; + flood_fill_seed(q, region->seed.x, region->seed.y, + rcode, QUIRC_PIXEL_BLACK, + find_one_corner, &psd); + + psd.ref.x = psd.corners[0].x - psd.ref.x; + psd.ref.y = psd.corners[0].y - psd.ref.y; + + for (i = 0; i < 4; i++) + memcpy(&psd.corners[i], ®ion->seed, + sizeof(psd.corners[i])); + + i = region->seed.x * psd.ref.x + region->seed.y * psd.ref.y; + psd.scores[0] = i; + psd.scores[2] = -i; + i = region->seed.x * -psd.ref.y + region->seed.y * psd.ref.x; + psd.scores[1] = i; + psd.scores[3] = -i; + + flood_fill_seed(q, region->seed.x, region->seed.y, + QUIRC_PIXEL_BLACK, rcode, + find_other_corners, &psd); +} + +static void record_capstone(struct quirc *q, int ring, int stone) +{ + struct quirc_region *stone_reg = &q->regions[stone]; + struct quirc_region *ring_reg = &q->regions[ring]; + struct quirc_capstone *capstone; + int cs_index; + + if (q->num_capstones >= QUIRC_MAX_CAPSTONES) + return; + + cs_index = q->num_capstones; + capstone = &q->capstones[q->num_capstones++]; + + memset(capstone, 0, sizeof(*capstone)); + + capstone->qr_grid = -1; + capstone->ring = ring; + capstone->stone = stone; + stone_reg->capstone = cs_index; + ring_reg->capstone = cs_index; + + /* Find the corners of the ring */ + find_region_corners(q, ring, &stone_reg->seed, capstone->corners); + + /* Set up the perspective transform and find the center */ + perspective_setup(capstone->c, capstone->corners, 7.0, 7.0); + perspective_map(capstone->c, 3.5, 3.5, &capstone->center); +} + +static void test_capstone(struct quirc *q, unsigned int x, unsigned int y, + unsigned int *pb) +{ + int ring_right = region_code(q, x - pb[4], y); + int stone = region_code(q, x - pb[4] - pb[3] - pb[2], y); + int ring_left = region_code(q, x - pb[4] - pb[3] - + pb[2] - pb[1] - pb[0], + y); + struct quirc_region *stone_reg; + struct quirc_region *ring_reg; + unsigned int ratio; + + if (ring_left < 0 || ring_right < 0 || stone < 0) + return; + + /* Left and ring of ring should be connected */ + if (ring_left != ring_right) + return; + + /* Ring should be disconnected from stone */ + if (ring_left == stone) + return; + + stone_reg = &q->regions[stone]; + ring_reg = &q->regions[ring_left]; + + /* Already detected */ + if (stone_reg->capstone >= 0 || ring_reg->capstone >= 0) + return; + + /* Ratio should ideally be 37.5 */ + ratio = stone_reg->count * 100 / ring_reg->count; + if (ratio < 10 || ratio > 70) + return; + + record_capstone(q, ring_left, stone); +} + +static void finder_scan(struct quirc *q, unsigned int y) +{ + quirc_pixel_t *row = q->pixels + y * q->w; + unsigned int x; + int last_color = 0; + unsigned int run_length = 0; + unsigned int run_count = 0; + unsigned int pb[5]; + + memset(pb, 0, sizeof(pb)); + for (x = 0; x < q->w; x++) { + int color = row[x] ? 1 : 0; + + if (x && color != last_color) { + memmove(pb, pb + 1, sizeof(pb[0]) * 4); + pb[4] = run_length; + run_length = 0; + run_count++; + + if (!color && run_count >= 5) { + const int scale = 16; + static const unsigned int check[5] = {1, 1, 3, 1, 1}; + unsigned int avg, err; + unsigned int i; + int ok = 1; + + avg = (pb[0] + pb[1] + pb[3] + pb[4]) * scale / 4; + err = avg * 3 / 4; + + for (i = 0; i < 5; i++) + if (pb[i] * scale < check[i] * avg - err || + pb[i] * scale > check[i] * avg + err) + ok = 0; + + if (ok) + test_capstone(q, x, y, pb); + } + } + + run_length++; + last_color = color; + } +} + +static void find_alignment_pattern(struct quirc *q, int index) +{ + struct quirc_grid *qr = &q->grids[index]; + struct quirc_capstone *c0 = &q->capstones[qr->caps[0]]; + struct quirc_capstone *c2 = &q->capstones[qr->caps[2]]; + struct quirc_point a; + struct quirc_point b; + struct quirc_point c; + int size_estimate; + int step_size = 1; + int dir = 0; + quirc_float_t u, v; + + /* Grab our previous estimate of the alignment pattern corner */ + memcpy(&b, &qr->align, sizeof(b)); + + /* Guess another two corners of the alignment pattern so that we + * can estimate its size. + */ + perspective_unmap(c0->c, &b, &u, &v); + perspective_map(c0->c, u, v + (quirc_float_t)1.0, &a); + perspective_unmap(c2->c, &b, &u, &v); + perspective_map(c2->c, u + (quirc_float_t)1.0, v, &c); + + size_estimate = abs((a.x - b.x) * -(c.y - b.y) + + (a.y - b.y) * (c.x - b.x)); + + /* Spiral outwards from the estimate point until we find something + * roughly the right size. Don't look too far from the estimate + * point. + * + * A degenerate perspective transform (near-zero denominator) can make + * size_estimate enormous, spinning this spiral for hundreds of millions + * of iterations on a tiny image (denial of service on a crafted QR). The + * alignment pattern must lie within the image, so also cap the search + * radius at the image size. + */ + const int max_step = (q->w > q->h ? q->w : q->h) + 1; + while (step_size * step_size < size_estimate * 100 && step_size <= max_step) { + static const int dx_map[] = {1, 0, -1, 0}; + static const int dy_map[] = {0, -1, 0, 1}; + int i; + + for (i = 0; i < step_size; i++) { + int code = region_code(q, b.x, b.y); + + if (code >= 0) { + struct quirc_region *reg = &q->regions[code]; + + if (reg->count >= size_estimate / 2 && + reg->count <= size_estimate * 2) { + qr->align_region = code; + return; + } + } + + b.x += dx_map[dir]; + b.y += dy_map[dir]; + } + + dir = (dir + 1) % 4; + if (!(dir & 1)) + step_size++; + } +} + +static void find_leftmost_to_line(void *user_data, int y, int left, int right) +{ + struct polygon_score_data *psd = + (struct polygon_score_data *)user_data; + int xs[2] = {left, right}; + int i; + + for (i = 0; i < 2; i++) { + int d = -psd->ref.y * xs[i] + psd->ref.x * y; + + if (d < psd->scores[0]) { + psd->scores[0] = d; + psd->corners[0].x = xs[i]; + psd->corners[0].y = y; + } + } +} + +static quirc_float_t length(struct quirc_point a, struct quirc_point b) +{ + quirc_float_t x = abs(a.x - b.x) + 1; + quirc_float_t y = abs(a.y - b.y) + 1; + return sqrt(x * x + y * y); +} +/* Estimate grid size by determing distance between capstones + */ +static void measure_grid_size(struct quirc *q, int index) +{ + struct quirc_grid *qr = &q->grids[index]; + + struct quirc_capstone *a = &(q->capstones[qr->caps[0]]); + struct quirc_capstone *b = &(q->capstones[qr->caps[1]]); + struct quirc_capstone *c = &(q->capstones[qr->caps[2]]); + + quirc_float_t ab = length(b->corners[0], a->corners[3]); + quirc_float_t capstone_ab_size = (length(b->corners[0], b->corners[3]) + length(a->corners[0], a->corners[3]))/2.0; + quirc_float_t ver_grid = (quirc_float_t)7.0 * ab / capstone_ab_size; + + quirc_float_t bc = length(b->corners[0], c->corners[1]); + quirc_float_t capstone_bc_size = (length(b->corners[0], b->corners[1]) + length(c->corners[0], c->corners[1]))/2.0; + quirc_float_t hor_grid = (quirc_float_t)7.0 * bc / capstone_bc_size; + + quirc_float_t grid_size_estimate = (ver_grid + hor_grid) * (quirc_float_t)(0.5); + + int ver = (int)((grid_size_estimate - (quirc_float_t)(17.0 - 2.0)) * (quirc_float_t)(1./4)); + + qr->grid_size = 4*ver + 17; +} + +/* Read a cell from a grid using the currently set perspective + * transform. Returns +/- 1 for black/white, 0 for cells which are + * out of image bounds. + */ +static int read_cell(const struct quirc *q, int index, int x, int y) +{ + const struct quirc_grid *qr = &q->grids[index]; + struct quirc_point p; + + perspective_map(qr->c, x + (quirc_float_t)0.5, y + (quirc_float_t)0.5, &p); + if (p.y < 0 || p.y >= q->h || p.x < 0 || p.x >= q->w) + return 0; + + return q->pixels[p.y * q->w + p.x] ? 1 : -1; +} + +static int fitness_cell(const struct quirc *q, int index, int x, int y) +{ + const struct quirc_grid *qr = &q->grids[index]; + int score = 0; + int u, v; + + for (v = 0; v < 3; v++) + for (u = 0; u < 3; u++) { + static const quirc_float_t offsets[] = {0.3, 0.5, 0.7}; + struct quirc_point p; + + perspective_map(qr->c, x + offsets[u], + y + offsets[v], &p); + if (p.y < 0 || p.y >= q->h || p.x < 0 || p.x >= q->w) + continue; + + if (q->pixels[p.y * q->w + p.x]) + score++; + else + score--; + } + + return score; +} + +static int fitness_ring(const struct quirc *q, int index, int cx, int cy, + int radius) +{ + int i; + int score = 0; + + for (i = 0; i < radius * 2; i++) { + score += fitness_cell(q, index, cx - radius + i, cy - radius); + score += fitness_cell(q, index, cx - radius, cy + radius - i); + score += fitness_cell(q, index, cx + radius, cy - radius + i); + score += fitness_cell(q, index, cx + radius - i, cy + radius); + } + + return score; +} + +static int fitness_apat(const struct quirc *q, int index, int cx, int cy) +{ + return fitness_cell(q, index, cx, cy) - + fitness_ring(q, index, cx, cy, 1) + + fitness_ring(q, index, cx, cy, 2); +} + +static int fitness_capstone(const struct quirc *q, int index, int x, int y) +{ + x += 3; + y += 3; + + return fitness_cell(q, index, x, y) + + fitness_ring(q, index, x, y, 1) - + fitness_ring(q, index, x, y, 2) + + fitness_ring(q, index, x, y, 3); +} + +/* Compute a fitness score for the currently configured perspective + * transform, using the features we expect to find by scanning the + * grid. + */ +static int fitness_all(const struct quirc *q, int index) +{ + const struct quirc_grid *qr = &q->grids[index]; + int version = (qr->grid_size - 17) / 4; + const struct quirc_version_info *info = &quirc_version_db[version]; + int score = 0; + int i, j; + int ap_count; + + /* Check the timing pattern */ + for (i = 0; i < qr->grid_size - 14; i++) { + int expect = (i & 1) ? 1 : -1; + + score += fitness_cell(q, index, i + 7, 6) * expect; + score += fitness_cell(q, index, 6, i + 7) * expect; + } + + /* Check capstones */ + score += fitness_capstone(q, index, 0, 0); + score += fitness_capstone(q, index, qr->grid_size - 7, 0); + score += fitness_capstone(q, index, 0, qr->grid_size - 7); + + if (version < 0 || version > QUIRC_MAX_VERSION) + return score; + + /* Check alignment patterns */ + ap_count = 0; + while ((ap_count < QUIRC_MAX_ALIGNMENT) && info->apat[ap_count]) + ap_count++; + + for (i = 1; i + 1 < ap_count; i++) { + score += fitness_apat(q, index, 6, info->apat[i]); + score += fitness_apat(q, index, info->apat[i], 6); + } + + for (i = 1; i < ap_count; i++) + for (j = 1; j < ap_count; j++) + score += fitness_apat(q, index, + info->apat[i], info->apat[j]); + + return score; +} + +static void jiggle_perspective(struct quirc *q, int index) +{ + struct quirc_grid *qr = &q->grids[index]; + int best = fitness_all(q, index); + int pass; + quirc_float_t adjustments[8]; + int i; + + for (i = 0; i < 8; i++) + adjustments[i] = qr->c[i] * (quirc_float_t)0.02; + + for (pass = 0; pass < 5; pass++) { + for (i = 0; i < 16; i++) { + int j = i >> 1; + int test; + quirc_float_t old = qr->c[j]; + quirc_float_t step = adjustments[j]; + quirc_float_t new; + + if (i & 1) + new = old + step; + else + new = old - step; + + qr->c[j] = new; + test = fitness_all(q, index); + + if (test > best) + best = test; + else + qr->c[j] = old; + } + + for (i = 0; i < 8; i++) + adjustments[i] *= 0.5; + } +} + +/* Once the capstones are in place and an alignment point has been + * chosen, we call this function to set up a grid-reading perspective + * transform. + */ +static void setup_qr_perspective(struct quirc *q, int index) +{ + struct quirc_grid *qr = &q->grids[index]; + struct quirc_point rect[4]; + + /* Set up the perspective map for reading the grid */ + memcpy(&rect[0], &q->capstones[qr->caps[1]].corners[0], + sizeof(rect[0])); + memcpy(&rect[1], &q->capstones[qr->caps[2]].corners[0], + sizeof(rect[0])); + memcpy(&rect[2], &qr->align, sizeof(rect[0])); + memcpy(&rect[3], &q->capstones[qr->caps[0]].corners[0], + sizeof(rect[0])); + perspective_setup(qr->c, rect, qr->grid_size - 7, qr->grid_size - 7); + + jiggle_perspective(q, index); +} + +/* Rotate the capstone with so that corner 0 is the leftmost with respect + * to the given reference line. + */ +static void rotate_capstone(struct quirc_capstone *cap, + const struct quirc_point *h0, + const struct quirc_point *hd) +{ + struct quirc_point copy[4]; + int j; + int best = 0; + int best_score = INT_MAX; + + for (j = 0; j < 4; j++) { + struct quirc_point *p = &cap->corners[j]; + int score = (p->x - h0->x) * -hd->y + + (p->y - h0->y) * hd->x; + + if (!j || score < best_score) { + best = j; + best_score = score; + } + } + + /* Rotate the capstone */ + for (j = 0; j < 4; j++) + memcpy(©[j], &cap->corners[(j + best) % 4], + sizeof(copy[j])); + memcpy(cap->corners, copy, sizeof(cap->corners)); + perspective_setup(cap->c, cap->corners, 7.0, 7.0); +} + +static void record_qr_grid(struct quirc *q, int a, int b, int c) +{ + struct quirc_point h0, hd; + int i; + int qr_index; + struct quirc_grid *qr; + + if (q->num_grids >= QUIRC_MAX_GRIDS) + return; + + /* Construct the hypotenuse line from A to C. B should be to + * the left of this line. + */ + memcpy(&h0, &q->capstones[a].center, sizeof(h0)); + hd.x = q->capstones[c].center.x - q->capstones[a].center.x; + hd.y = q->capstones[c].center.y - q->capstones[a].center.y; + + /* Make sure A-B-C is clockwise */ + if ((q->capstones[b].center.x - h0.x) * -hd.y + + (q->capstones[b].center.y - h0.y) * hd.x > 0) { + int swap = a; + + a = c; + c = swap; + hd.x = -hd.x; + hd.y = -hd.y; + } + + /* Record the grid and its components */ + qr_index = q->num_grids; + qr = &q->grids[q->num_grids++]; + + memset(qr, 0, sizeof(*qr)); + qr->caps[0] = a; + qr->caps[1] = b; + qr->caps[2] = c; + qr->align_region = -1; + + /* Rotate each capstone so that corner 0 is top-left with respect + * to the grid. + */ + for (i = 0; i < 3; i++) { + struct quirc_capstone *cap = &q->capstones[qr->caps[i]]; + + rotate_capstone(cap, &h0, &hd); + cap->qr_grid = qr_index; + } + + /* Check the timing pattern by measuring grid size. This doesn't require a perspective + * transform. + */ + measure_grid_size(q, qr_index); + /* Make an estimate based for the alignment pattern based on extending + * lines from capstones A and C. + */ + if (!line_intersect(&q->capstones[a].corners[0], + &q->capstones[a].corners[1], + &q->capstones[c].corners[0], + &q->capstones[c].corners[3], + &qr->align)) + goto fail; + + /* On V2+ grids, we should use the alignment pattern. */ + if (qr->grid_size > 21) { + /* Try to find the actual location of the alignment pattern. */ + find_alignment_pattern(q, qr_index); + + /* Find the point of the alignment pattern closest to the + * top-left of the QR grid. + */ + if (qr->align_region >= 0) { + struct polygon_score_data psd; + struct quirc_region *reg = + &q->regions[qr->align_region]; + + /* Start from some point inside the alignment pattern */ + memcpy(&qr->align, ®->seed, sizeof(qr->align)); + + memcpy(&psd.ref, &hd, sizeof(psd.ref)); + psd.corners = &qr->align; + psd.scores[0] = -hd.y * qr->align.x + + hd.x * qr->align.y; + + flood_fill_seed(q, reg->seed.x, reg->seed.y, + qr->align_region, QUIRC_PIXEL_BLACK, + NULL, NULL); + flood_fill_seed(q, reg->seed.x, reg->seed.y, + QUIRC_PIXEL_BLACK, qr->align_region, + find_leftmost_to_line, &psd); + } + } + + setup_qr_perspective(q, qr_index); + return; + +fail: + /* We've been unable to complete setup for this grid. Undo what we've + * recorded and pretend it never happened. + */ + for (i = 0; i < 3; i++) + q->capstones[qr->caps[i]].qr_grid = -1; + q->num_grids--; +} + +struct neighbour { + int index; + quirc_float_t distance; +}; + +struct neighbour_list { + struct neighbour n[QUIRC_MAX_CAPSTONES]; + int count; +}; + +static void test_neighbours(struct quirc *q, int i, + const struct neighbour_list *hlist, + const struct neighbour_list *vlist) +{ + /* Test each possible grouping */ + for (int j = 0; j < hlist->count; j++) { + const struct neighbour *hn = &hlist->n[j]; + for (int k = 0; k < vlist->count; k++) { + const struct neighbour *vn = &vlist->n[k]; + quirc_float_t squareness = fabs((quirc_float_t)1.0 - hn->distance / vn->distance); + if (squareness < (quirc_float_t)0.2) + record_qr_grid(q, hn->index, i, vn->index); + } + } +} + +static void test_grouping(struct quirc *q, unsigned int i) +{ + struct quirc_capstone *c1 = &q->capstones[i]; + int j; + struct neighbour_list hlist; + struct neighbour_list vlist; + + hlist.count = 0; + vlist.count = 0; + + /* Look for potential neighbours by examining the relative gradients + * from this capstone to others. + */ + for (j = 0; j < q->num_capstones; j++) { + struct quirc_capstone *c2 = &q->capstones[j]; + quirc_float_t u, v; + + if (i == j) + continue; + + perspective_unmap(c1->c, &c2->center, &u, &v); + + u = fabs(u - (quirc_float_t)3.5); + v = fabs(v - (quirc_float_t)3.5); + + if (u < (quirc_float_t)0.2 * v) { + struct neighbour *n = &hlist.n[hlist.count++]; + + n->index = j; + n->distance = v; + } + + if (v < (quirc_float_t)0.2 * u) { + struct neighbour *n = &vlist.n[vlist.count++]; + + n->index = j; + n->distance = u; + } + } + + if (!(hlist.count && vlist.count)) + return; + + test_neighbours(q, i, &hlist, &vlist); +} + +static void pixels_setup(struct quirc *q, uint8_t threshold) +{ + if (QUIRC_PIXEL_ALIAS_IMAGE) { + q->pixels = (quirc_pixel_t *)q->image; + } + + uint8_t* source = q->image; + quirc_pixel_t* dest = q->pixels; + size_t length = quirc_pixel_count(q); + while (length--) { + uint8_t value = *source++; + *dest++ = (value < threshold) ? QUIRC_PIXEL_BLACK : QUIRC_PIXEL_WHITE; + } +} + +uint8_t *quirc_begin(struct quirc *q, int *w, int *h) +{ + q->num_regions = QUIRC_PIXEL_REGION; + q->num_capstones = 0; + q->num_grids = 0; + + if (w) + *w = q->w; + if (h) + *h = q->h; + + return q->image; +} + +void quirc_end(struct quirc *q) +{ + int i; + + uint8_t threshold = otsu(q); + pixels_setup(q, threshold); + + for (i = 0; i < q->h; i++) + finder_scan(q, i); + + for (i = 0; i < q->num_capstones; i++) + test_grouping(q, i); +} + +void quirc_extract(const struct quirc *q, int index, + struct quirc_code *code) +{ + const struct quirc_grid *qr = &q->grids[index]; + int y; + int i = 0; + + memset(code, 0, sizeof(*code)); + + if (index < 0 || index > q->num_grids) + return; + + perspective_map(qr->c, 0.0, 0.0, &code->corners[0]); + perspective_map(qr->c, qr->grid_size, 0.0, &code->corners[1]); + perspective_map(qr->c, qr->grid_size, qr->grid_size, + &code->corners[2]); + perspective_map(qr->c, 0.0, qr->grid_size, &code->corners[3]); + + code->size = qr->grid_size; + + /* Skip out early so as not to overrun the buffer. quirc_decode + * will return an error on interpreting the code. + */ + if (code->size > QUIRC_MAX_GRID_SIZE) + return; + + for (y = 0; y < qr->grid_size; y++) { + int x; + for (x = 0; x < qr->grid_size; x++) { + if (read_cell(q, index, x, y) > 0) { + code->cell_bitmap[i >> 3] |= (1 << (i & 7)); + } + i++; + } + } +} diff --git a/libraries/tinyblocks-qr/src/qrcodegen.c b/libraries/tinyblocks-qr/src/qrcodegen.c new file mode 100644 index 0000000..34f1002 --- /dev/null +++ b/libraries/tinyblocks-qr/src/qrcodegen.c @@ -0,0 +1,1027 @@ +/* + * QR Code generator library (C) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * - The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * - The Software is provided "as is", without warranty of any kind, express or + * implied, including but not limited to the warranties of merchantability, + * fitness for a particular purpose and noninfringement. In no event shall the + * authors or copyright holders be liable for any claim, damages or other + * liability, whether in an action of contract, tort or otherwise, arising from, + * out of or in connection with the Software or the use or other dealings in the + * Software. + */ + +#include +#include +#include +#include +#include "qrcodegen.h" + +#ifndef QRCODEGEN_TEST + #define testable static // Keep functions private +#else + #define testable // Expose private functions +#endif + + +/*---- Forward declarations for private functions ----*/ + +// Regarding all public and private functions defined in this source file: +// - They require all pointer/array arguments to be not null unless the array length is zero. +// - They only read input scalar/array arguments, write to output pointer/array +// arguments, and return scalar values; they are "pure" functions. +// - They don't read mutable global variables or write to any global variables. +// - They don't perform I/O, read the clock, print to console, etc. +// - They allocate a small and constant amount of stack memory. +// - They don't allocate or free any memory on the heap. +// - They don't recurse or mutually recurse. All the code +// could be inlined into the top-level public functions. +// - They run in at most quadratic time with respect to input arguments. +// Most functions run in linear time, and some in constant time. +// There are no unbounded loops or non-obvious termination conditions. +// - They are completely thread-safe if the caller does not give the +// same writable buffer to concurrent calls to these functions. + +testable void appendBitsToBuffer(unsigned int val, int numBits, uint8_t buffer[], int *bitLen); + +testable void addEccAndInterleave(uint8_t data[], int version, enum qrcodegen_Ecc ecl, uint8_t result[]); +testable int getNumDataCodewords(int version, enum qrcodegen_Ecc ecl); +testable int getNumRawDataModules(int ver); + +testable void reedSolomonComputeDivisor(int degree, uint8_t result[]); +testable void reedSolomonComputeRemainder(const uint8_t data[], int dataLen, + const uint8_t generator[], int degree, uint8_t result[]); +testable uint8_t reedSolomonMultiply(uint8_t x, uint8_t y); + +testable void initializeFunctionModules(int version, uint8_t qrcode[]); +static void drawLightFunctionModules(uint8_t qrcode[], int version); +static void drawFormatBits(enum qrcodegen_Ecc ecl, enum qrcodegen_Mask mask, uint8_t qrcode[]); +testable int getAlignmentPatternPositions(int version, uint8_t result[7]); +static void fillRectangle(int left, int top, int width, int height, uint8_t qrcode[]); + +static void drawCodewords(const uint8_t data[], int dataLen, uint8_t qrcode[]); +static void applyMask(const uint8_t functionModules[], uint8_t qrcode[], enum qrcodegen_Mask mask); +static long getPenaltyScore(const uint8_t qrcode[]); +static int finderPenaltyCountPatterns(const int runHistory[7], int qrsize); +static int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, int runHistory[7], int qrsize); +static void finderPenaltyAddHistory(int currentRunLength, int runHistory[7], int qrsize); + +testable bool getModuleBounded(const uint8_t qrcode[], int x, int y); +testable void setModuleBounded(uint8_t qrcode[], int x, int y, bool isDark); +testable void setModuleUnbounded(uint8_t qrcode[], int x, int y, bool isDark); +static bool getBit(int x, int i); + +testable int calcSegmentBitLength(enum qrcodegen_Mode mode, size_t numChars); +testable int getTotalBits(const struct qrcodegen_Segment segs[], size_t len, int version); +static int numCharCountBits(enum qrcodegen_Mode mode, int version); + + + +/*---- Private tables of constants ----*/ + +// The set of all legal characters in alphanumeric mode, where each character +// value maps to the index in the string. For checking text and encoding segments. +static const char *ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; + +// Sentinel value for use in only some functions. +#define LENGTH_OVERFLOW -1 + +// For generating error correction codes. +testable const int8_t ECC_CODEWORDS_PER_BLOCK[4][41] = { + // Version: (note that index 0 is for padding, and is set to an illegal value) + //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level + {-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Low + {-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, // Medium + {-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile + {-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High +}; + +#define qrcodegen_REED_SOLOMON_DEGREE_MAX 30 // Based on the table above + +// For generating error correction codes. +testable const int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41] = { + // Version: (note that index 0 is for padding, and is set to an illegal value) + //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level + {-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low + {-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium + {-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile + {-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High +}; + +// For automatic mask pattern selection. +static const int PENALTY_N1 = 3; +static const int PENALTY_N2 = 3; +static const int PENALTY_N3 = 40; +static const int PENALTY_N4 = 10; + + + +/*---- High-level QR Code encoding functions ----*/ + +// Public function - see documentation comment in header file. +bool qrcodegen_encodeText(const char *text, uint8_t tempBuffer[], uint8_t qrcode[], + enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl) { + + size_t textLen = strlen(text); + if (textLen == 0) + return qrcodegen_encodeSegmentsAdvanced(NULL, 0, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode); + size_t bufLen = (size_t)qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion); + + struct qrcodegen_Segment seg; + if (qrcodegen_isNumeric(text)) { + if (qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_NUMERIC, textLen) > bufLen) + goto fail; + seg = qrcodegen_makeNumeric(text, tempBuffer); + } else if (qrcodegen_isAlphanumeric(text)) { + if (qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_ALPHANUMERIC, textLen) > bufLen) + goto fail; + seg = qrcodegen_makeAlphanumeric(text, tempBuffer); + } else { + if (textLen > bufLen) + goto fail; + for (size_t i = 0; i < textLen; i++) + tempBuffer[i] = (uint8_t)text[i]; + seg.mode = qrcodegen_Mode_BYTE; + seg.bitLength = calcSegmentBitLength(seg.mode, textLen); + if (seg.bitLength == LENGTH_OVERFLOW) + goto fail; + seg.numChars = (int)textLen; + seg.data = tempBuffer; + } + return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode); + +fail: + qrcode[0] = 0; // Set size to invalid value for safety + return false; +} + + +// Public function - see documentation comment in header file. +bool qrcodegen_encodeBinary(uint8_t dataAndTemp[], size_t dataLen, uint8_t qrcode[], + enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl) { + + struct qrcodegen_Segment seg; + seg.mode = qrcodegen_Mode_BYTE; + seg.bitLength = calcSegmentBitLength(seg.mode, dataLen); + if (seg.bitLength == LENGTH_OVERFLOW) { + qrcode[0] = 0; // Set size to invalid value for safety + return false; + } + seg.numChars = (int)dataLen; + seg.data = dataAndTemp; + return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, dataAndTemp, qrcode); +} + + +// Appends the given number of low-order bits of the given value to the given byte-based +// bit buffer, increasing the bit length. Requires 0 <= numBits <= 16 and val < 2^numBits. +testable void appendBitsToBuffer(unsigned int val, int numBits, uint8_t buffer[], int *bitLen) { + assert(0 <= numBits && numBits <= 16 && (unsigned long)val >> numBits == 0); + for (int i = numBits - 1; i >= 0; i--, (*bitLen)++) + buffer[*bitLen >> 3] |= ((val >> i) & 1) << (7 - (*bitLen & 7)); +} + + + +/*---- Low-level QR Code encoding functions ----*/ + +// Public function - see documentation comment in header file. +bool qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[], size_t len, + enum qrcodegen_Ecc ecl, uint8_t tempBuffer[], uint8_t qrcode[]) { + return qrcodegen_encodeSegmentsAdvanced(segs, len, ecl, + qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true, tempBuffer, qrcode); +} + + +// Public function - see documentation comment in header file. +bool qrcodegen_encodeSegmentsAdvanced(const struct qrcodegen_Segment segs[], size_t len, enum qrcodegen_Ecc ecl, + int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl, uint8_t tempBuffer[], uint8_t qrcode[]) { + assert(segs != NULL || len == 0); + assert(qrcodegen_VERSION_MIN <= minVersion && minVersion <= maxVersion && maxVersion <= qrcodegen_VERSION_MAX); + assert(0 <= (int)ecl && (int)ecl <= 3 && -1 <= (int)mask && (int)mask <= 7); + + // Find the minimal version number to use + int version, dataUsedBits; + for (version = minVersion; ; version++) { + int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available + dataUsedBits = getTotalBits(segs, len, version); + if (dataUsedBits != LENGTH_OVERFLOW && dataUsedBits <= dataCapacityBits) + break; // This version number is found to be suitable + if (version >= maxVersion) { // All versions in the range could not fit the given data + qrcode[0] = 0; // Set size to invalid value for safety + return false; + } + } + assert(dataUsedBits != LENGTH_OVERFLOW); + + // Increase the error correction level while the data still fits in the current version number + for (int i = (int)qrcodegen_Ecc_MEDIUM; i <= (int)qrcodegen_Ecc_HIGH; i++) { // From low to high + if (boostEcl && dataUsedBits <= getNumDataCodewords(version, (enum qrcodegen_Ecc)i) * 8) + ecl = (enum qrcodegen_Ecc)i; + } + + // Concatenate all segments to create the data bit string + memset(qrcode, 0, (size_t)qrcodegen_BUFFER_LEN_FOR_VERSION(version) * sizeof(qrcode[0])); + int bitLen = 0; + for (size_t i = 0; i < len; i++) { + const struct qrcodegen_Segment *seg = &segs[i]; + appendBitsToBuffer((unsigned int)seg->mode, 4, qrcode, &bitLen); + appendBitsToBuffer((unsigned int)seg->numChars, numCharCountBits(seg->mode, version), qrcode, &bitLen); + for (int j = 0; j < seg->bitLength; j++) { + int bit = (seg->data[j >> 3] >> (7 - (j & 7))) & 1; + appendBitsToBuffer((unsigned int)bit, 1, qrcode, &bitLen); + } + } + assert(bitLen == dataUsedBits); + + // Add terminator and pad up to a byte if applicable + int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; + assert(bitLen <= dataCapacityBits); + int terminatorBits = dataCapacityBits - bitLen; + if (terminatorBits > 4) + terminatorBits = 4; + appendBitsToBuffer(0, terminatorBits, qrcode, &bitLen); + appendBitsToBuffer(0, (8 - bitLen % 8) % 8, qrcode, &bitLen); + assert(bitLen % 8 == 0); + + // Pad with alternating bytes until data capacity is reached + for (uint8_t padByte = 0xEC; bitLen < dataCapacityBits; padByte ^= 0xEC ^ 0x11) + appendBitsToBuffer(padByte, 8, qrcode, &bitLen); + + // Compute ECC, draw modules + addEccAndInterleave(qrcode, version, ecl, tempBuffer); + initializeFunctionModules(version, qrcode); + drawCodewords(tempBuffer, getNumRawDataModules(version) / 8, qrcode); + drawLightFunctionModules(qrcode, version); + initializeFunctionModules(version, tempBuffer); + + // Do masking + if (mask == qrcodegen_Mask_AUTO) { // Automatically choose best mask + long minPenalty = LONG_MAX; + for (int i = 0; i < 8; i++) { + enum qrcodegen_Mask msk = (enum qrcodegen_Mask)i; + applyMask(tempBuffer, qrcode, msk); + drawFormatBits(ecl, msk, qrcode); + long penalty = getPenaltyScore(qrcode); + if (penalty < minPenalty) { + mask = msk; + minPenalty = penalty; + } + applyMask(tempBuffer, qrcode, msk); // Undoes the mask due to XOR + } + } + assert(0 <= (int)mask && (int)mask <= 7); + applyMask(tempBuffer, qrcode, mask); // Apply the final choice of mask + drawFormatBits(ecl, mask, qrcode); // Overwrite old format bits + return true; +} + + + +/*---- Error correction code generation functions ----*/ + +// Appends error correction bytes to each block of the given data array, then interleaves +// bytes from the blocks and stores them in the result array. data[0 : dataLen] contains +// the input data. data[dataLen : rawCodewords] is used as a temporary work area and will +// be clobbered by this function. The final answer is stored in result[0 : rawCodewords]. +testable void addEccAndInterleave(uint8_t data[], int version, enum qrcodegen_Ecc ecl, uint8_t result[]) { + // Calculate parameter numbers + assert(0 <= (int)ecl && (int)ecl < 4 && qrcodegen_VERSION_MIN <= version && version <= qrcodegen_VERSION_MAX); + int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[(int)ecl][version]; + int blockEccLen = ECC_CODEWORDS_PER_BLOCK [(int)ecl][version]; + int rawCodewords = getNumRawDataModules(version) / 8; + int dataLen = getNumDataCodewords(version, ecl); + int numShortBlocks = numBlocks - rawCodewords % numBlocks; + int shortBlockDataLen = rawCodewords / numBlocks - blockEccLen; + + // Split data into blocks, calculate ECC, and interleave + // (not concatenate) the bytes into a single sequence + uint8_t rsdiv[qrcodegen_REED_SOLOMON_DEGREE_MAX]; + reedSolomonComputeDivisor(blockEccLen, rsdiv); + const uint8_t *dat = data; + for (int i = 0; i < numBlocks; i++) { + int datLen = shortBlockDataLen + (i < numShortBlocks ? 0 : 1); + uint8_t *ecc = &data[dataLen]; // Temporary storage + reedSolomonComputeRemainder(dat, datLen, rsdiv, blockEccLen, ecc); + for (int j = 0, k = i; j < datLen; j++, k += numBlocks) { // Copy data + if (j == shortBlockDataLen) + k -= numShortBlocks; + result[k] = dat[j]; + } + for (int j = 0, k = dataLen + i; j < blockEccLen; j++, k += numBlocks) // Copy ECC + result[k] = ecc[j]; + dat += datLen; + } +} + + +// Returns the number of 8-bit codewords that can be used for storing data (not ECC), +// for the given version number and error correction level. The result is in the range [9, 2956]. +testable int getNumDataCodewords(int version, enum qrcodegen_Ecc ecl) { + int v = version, e = (int)ecl; + assert(0 <= e && e < 4); + return getNumRawDataModules(v) / 8 + - ECC_CODEWORDS_PER_BLOCK [e][v] + * NUM_ERROR_CORRECTION_BLOCKS[e][v]; +} + + +// Returns the number of data bits that can be stored in a QR Code of the given version number, after +// all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. +// The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. +testable int getNumRawDataModules(int ver) { + assert(qrcodegen_VERSION_MIN <= ver && ver <= qrcodegen_VERSION_MAX); + int result = (16 * ver + 128) * ver + 64; + if (ver >= 2) { + int numAlign = ver / 7 + 2; + result -= (25 * numAlign - 10) * numAlign - 55; + if (ver >= 7) + result -= 36; + } + assert(208 <= result && result <= 29648); + return result; +} + + + +/*---- Reed-Solomon ECC generator functions ----*/ + +// Computes a Reed-Solomon ECC generator polynomial for the given degree, storing in result[0 : degree]. +// This could be implemented as a lookup table over all possible parameter values, instead of as an algorithm. +testable void reedSolomonComputeDivisor(int degree, uint8_t result[]) { + assert(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX); + // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. + // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}. + memset(result, 0, (size_t)degree * sizeof(result[0])); + result[degree - 1] = 1; // Start off with the monomial x^0 + + // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), + // drop the highest monomial term which is always 1x^degree. + // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). + uint8_t root = 1; + for (int i = 0; i < degree; i++) { + // Multiply the current product by (x - r^i) + for (int j = 0; j < degree; j++) { + result[j] = reedSolomonMultiply(result[j], root); + if (j + 1 < degree) + result[j] ^= result[j + 1]; + } + root = reedSolomonMultiply(root, 0x02); + } +} + + +// Computes the Reed-Solomon error correction codeword for the given data and divisor polynomials. +// The remainder when data[0 : dataLen] is divided by divisor[0 : degree] is stored in result[0 : degree]. +// All polynomials are in big endian, and the generator has an implicit leading 1 term. +testable void reedSolomonComputeRemainder(const uint8_t data[], int dataLen, + const uint8_t generator[], int degree, uint8_t result[]) { + assert(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX); + memset(result, 0, (size_t)degree * sizeof(result[0])); + for (int i = 0; i < dataLen; i++) { // Polynomial division + uint8_t factor = data[i] ^ result[0]; + memmove(&result[0], &result[1], (size_t)(degree - 1) * sizeof(result[0])); + result[degree - 1] = 0; + for (int j = 0; j < degree; j++) + result[j] ^= reedSolomonMultiply(generator[j], factor); + } +} + +#undef qrcodegen_REED_SOLOMON_DEGREE_MAX + + +// Returns the product of the two given field elements modulo GF(2^8/0x11D). +// All inputs are valid. This could be implemented as a 256*256 lookup table. +testable uint8_t reedSolomonMultiply(uint8_t x, uint8_t y) { + // Russian peasant multiplication + uint8_t z = 0; + for (int i = 7; i >= 0; i--) { + z = (uint8_t)((z << 1) ^ ((z >> 7) * 0x11D)); + z ^= ((y >> i) & 1) * x; + } + return z; +} + + + +/*---- Drawing function modules ----*/ + +// Clears the given QR Code grid with light modules for the given +// version's size, then marks every function module as dark. +testable void initializeFunctionModules(int version, uint8_t qrcode[]) { + // Initialize QR Code + int qrsize = version * 4 + 17; + memset(qrcode, 0, (size_t)((qrsize * qrsize + 7) / 8 + 1) * sizeof(qrcode[0])); + qrcode[0] = (uint8_t)qrsize; + + // Fill horizontal and vertical timing patterns + fillRectangle(6, 0, 1, qrsize, qrcode); + fillRectangle(0, 6, qrsize, 1, qrcode); + + // Fill 3 finder patterns (all corners except bottom right) and format bits + fillRectangle(0, 0, 9, 9, qrcode); + fillRectangle(qrsize - 8, 0, 8, 9, qrcode); + fillRectangle(0, qrsize - 8, 9, 8, qrcode); + + // Fill numerous alignment patterns + uint8_t alignPatPos[7]; + int numAlign = getAlignmentPatternPositions(version, alignPatPos); + for (int i = 0; i < numAlign; i++) { + for (int j = 0; j < numAlign; j++) { + // Don't draw on the three finder corners + if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))) + fillRectangle(alignPatPos[i] - 2, alignPatPos[j] - 2, 5, 5, qrcode); + } + } + + // Fill version blocks + if (version >= 7) { + fillRectangle(qrsize - 11, 0, 3, 6, qrcode); + fillRectangle(0, qrsize - 11, 6, 3, qrcode); + } +} + + +// Draws light function modules and possibly some dark modules onto the given QR Code, without changing +// non-function modules. This does not draw the format bits. This requires all function modules to be previously +// marked dark (namely by initializeFunctionModules()), because this may skip redrawing dark function modules. +static void drawLightFunctionModules(uint8_t qrcode[], int version) { + // Draw horizontal and vertical timing patterns + int qrsize = qrcodegen_getSize(qrcode); + for (int i = 7; i < qrsize - 7; i += 2) { + setModuleBounded(qrcode, 6, i, false); + setModuleBounded(qrcode, i, 6, false); + } + + // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) + for (int dy = -4; dy <= 4; dy++) { + for (int dx = -4; dx <= 4; dx++) { + int dist = abs(dx); + if (abs(dy) > dist) + dist = abs(dy); + if (dist == 2 || dist == 4) { + setModuleUnbounded(qrcode, 3 + dx, 3 + dy, false); + setModuleUnbounded(qrcode, qrsize - 4 + dx, 3 + dy, false); + setModuleUnbounded(qrcode, 3 + dx, qrsize - 4 + dy, false); + } + } + } + + // Draw numerous alignment patterns + uint8_t alignPatPos[7]; + int numAlign = getAlignmentPatternPositions(version, alignPatPos); + for (int i = 0; i < numAlign; i++) { + for (int j = 0; j < numAlign; j++) { + if ((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)) + continue; // Don't draw on the three finder corners + for (int dy = -1; dy <= 1; dy++) { + for (int dx = -1; dx <= 1; dx++) + setModuleBounded(qrcode, alignPatPos[i] + dx, alignPatPos[j] + dy, dx == 0 && dy == 0); + } + } + } + + // Draw version blocks + if (version >= 7) { + // Calculate error correction code and pack bits + int rem = version; // version is uint6, in the range [7, 40] + for (int i = 0; i < 12; i++) + rem = (rem << 1) ^ ((rem >> 11) * 0x1F25); + long bits = (long)version << 12 | rem; // uint18 + assert(bits >> 18 == 0); + + // Draw two copies + for (int i = 0; i < 6; i++) { + for (int j = 0; j < 3; j++) { + int k = qrsize - 11 + j; + setModuleBounded(qrcode, k, i, (bits & 1) != 0); + setModuleBounded(qrcode, i, k, (bits & 1) != 0); + bits >>= 1; + } + } + } +} + + +// Draws two copies of the format bits (with its own error correction code) based +// on the given mask and error correction level. This always draws all modules of +// the format bits, unlike drawLightFunctionModules() which might skip dark modules. +static void drawFormatBits(enum qrcodegen_Ecc ecl, enum qrcodegen_Mask mask, uint8_t qrcode[]) { + // Calculate error correction code and pack bits + assert(0 <= (int)mask && (int)mask <= 7); + static const int table[] = {1, 0, 3, 2}; + int data = table[(int)ecl] << 3 | (int)mask; // errCorrLvl is uint2, mask is uint3 + int rem = data; + for (int i = 0; i < 10; i++) + rem = (rem << 1) ^ ((rem >> 9) * 0x537); + int bits = (data << 10 | rem) ^ 0x5412; // uint15 + assert(bits >> 15 == 0); + + // Draw first copy + for (int i = 0; i <= 5; i++) + setModuleBounded(qrcode, 8, i, getBit(bits, i)); + setModuleBounded(qrcode, 8, 7, getBit(bits, 6)); + setModuleBounded(qrcode, 8, 8, getBit(bits, 7)); + setModuleBounded(qrcode, 7, 8, getBit(bits, 8)); + for (int i = 9; i < 15; i++) + setModuleBounded(qrcode, 14 - i, 8, getBit(bits, i)); + + // Draw second copy + int qrsize = qrcodegen_getSize(qrcode); + for (int i = 0; i < 8; i++) + setModuleBounded(qrcode, qrsize - 1 - i, 8, getBit(bits, i)); + for (int i = 8; i < 15; i++) + setModuleBounded(qrcode, 8, qrsize - 15 + i, getBit(bits, i)); + setModuleBounded(qrcode, 8, qrsize - 8, true); // Always dark +} + + +// Calculates and stores an ascending list of positions of alignment patterns +// for this version number, returning the length of the list (in the range [0,7]). +// Each position is in the range [0,177), and are used on both the x and y axes. +// This could be implemented as lookup table of 40 variable-length lists of unsigned bytes. +testable int getAlignmentPatternPositions(int version, uint8_t result[7]) { + if (version == 1) + return 0; + int numAlign = version / 7 + 2; + int step = (version * 8 + numAlign * 3 + 5) / (numAlign * 4 - 4) * 2; + for (int i = numAlign - 1, pos = version * 4 + 10; i >= 1; i--, pos -= step) + result[i] = (uint8_t)pos; + result[0] = 6; + return numAlign; +} + + +// Sets every module in the range [left : left + width] * [top : top + height] to dark. +static void fillRectangle(int left, int top, int width, int height, uint8_t qrcode[]) { + for (int dy = 0; dy < height; dy++) { + for (int dx = 0; dx < width; dx++) + setModuleBounded(qrcode, left + dx, top + dy, true); + } +} + + + +/*---- Drawing data modules and masking ----*/ + +// Draws the raw codewords (including data and ECC) onto the given QR Code. This requires the initial state of +// the QR Code to be dark at function modules and light at codeword modules (including unused remainder bits). +static void drawCodewords(const uint8_t data[], int dataLen, uint8_t qrcode[]) { + int qrsize = qrcodegen_getSize(qrcode); + int i = 0; // Bit index into the data + // Do the funny zigzag scan + for (int right = qrsize - 1; right >= 1; right -= 2) { // Index of right column in each column pair + if (right == 6) + right = 5; + for (int vert = 0; vert < qrsize; vert++) { // Vertical counter + for (int j = 0; j < 2; j++) { + int x = right - j; // Actual x coordinate + bool upward = ((right + 1) & 2) == 0; + int y = upward ? qrsize - 1 - vert : vert; // Actual y coordinate + if (!getModuleBounded(qrcode, x, y) && i < dataLen * 8) { + bool dark = getBit(data[i >> 3], 7 - (i & 7)); + setModuleBounded(qrcode, x, y, dark); + i++; + } + // If this QR Code has any remainder bits (0 to 7), they were assigned as + // 0/false/light by the constructor and are left unchanged by this method + } + } + } + assert(i == dataLen * 8); +} + + +// XORs the codeword modules in this QR Code with the given mask pattern +// and given pattern of function modules. The codeword bits must be drawn +// before masking. Due to the arithmetic of XOR, calling applyMask() with +// the same mask value a second time will undo the mask. A final well-formed +// QR Code needs exactly one (not zero, two, etc.) mask applied. +static void applyMask(const uint8_t functionModules[], uint8_t qrcode[], enum qrcodegen_Mask mask) { + assert(0 <= (int)mask && (int)mask <= 7); // Disallows qrcodegen_Mask_AUTO + int qrsize = qrcodegen_getSize(qrcode); + for (int y = 0; y < qrsize; y++) { + for (int x = 0; x < qrsize; x++) { + if (getModuleBounded(functionModules, x, y)) + continue; + bool invert; + switch ((int)mask) { + case 0: invert = (x + y) % 2 == 0; break; + case 1: invert = y % 2 == 0; break; + case 2: invert = x % 3 == 0; break; + case 3: invert = (x + y) % 3 == 0; break; + case 4: invert = (x / 3 + y / 2) % 2 == 0; break; + case 5: invert = x * y % 2 + x * y % 3 == 0; break; + case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; + case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; + default: assert(false); return; + } + bool val = getModuleBounded(qrcode, x, y); + setModuleBounded(qrcode, x, y, val ^ invert); + } + } +} + + +// Calculates and returns the penalty score based on state of the given QR Code's current modules. +// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. +static long getPenaltyScore(const uint8_t qrcode[]) { + int qrsize = qrcodegen_getSize(qrcode); + long result = 0; + + // Adjacent modules in row having same color, and finder-like patterns + for (int y = 0; y < qrsize; y++) { + bool runColor = false; + int runX = 0; + int runHistory[7] = {0}; + for (int x = 0; x < qrsize; x++) { + if (getModuleBounded(qrcode, x, y) == runColor) { + runX++; + if (runX == 5) + result += PENALTY_N1; + else if (runX > 5) + result++; + } else { + finderPenaltyAddHistory(runX, runHistory, qrsize); + if (!runColor) + result += finderPenaltyCountPatterns(runHistory, qrsize) * PENALTY_N3; + runColor = getModuleBounded(qrcode, x, y); + runX = 1; + } + } + result += finderPenaltyTerminateAndCount(runColor, runX, runHistory, qrsize) * PENALTY_N3; + } + // Adjacent modules in column having same color, and finder-like patterns + for (int x = 0; x < qrsize; x++) { + bool runColor = false; + int runY = 0; + int runHistory[7] = {0}; + for (int y = 0; y < qrsize; y++) { + if (getModuleBounded(qrcode, x, y) == runColor) { + runY++; + if (runY == 5) + result += PENALTY_N1; + else if (runY > 5) + result++; + } else { + finderPenaltyAddHistory(runY, runHistory, qrsize); + if (!runColor) + result += finderPenaltyCountPatterns(runHistory, qrsize) * PENALTY_N3; + runColor = getModuleBounded(qrcode, x, y); + runY = 1; + } + } + result += finderPenaltyTerminateAndCount(runColor, runY, runHistory, qrsize) * PENALTY_N3; + } + + // 2*2 blocks of modules having same color + for (int y = 0; y < qrsize - 1; y++) { + for (int x = 0; x < qrsize - 1; x++) { + bool color = getModuleBounded(qrcode, x, y); + if ( color == getModuleBounded(qrcode, x + 1, y) && + color == getModuleBounded(qrcode, x, y + 1) && + color == getModuleBounded(qrcode, x + 1, y + 1)) + result += PENALTY_N2; + } + } + + // Balance of dark and light modules + int dark = 0; + for (int y = 0; y < qrsize; y++) { + for (int x = 0; x < qrsize; x++) { + if (getModuleBounded(qrcode, x, y)) + dark++; + } + } + int total = qrsize * qrsize; // Note that size is odd, so dark/total != 1/2 + // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)% + int k = (int)((labs(dark * 20L - total * 10L) + total - 1) / total) - 1; + assert(0 <= k && k <= 9); + result += k * PENALTY_N4; + assert(0 <= result && result <= 2568888L); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4 + return result; +} + + +// Can only be called immediately after a light run is added, and +// returns either 0, 1, or 2. A helper function for getPenaltyScore(). +static int finderPenaltyCountPatterns(const int runHistory[7], int qrsize) { + int n = runHistory[1]; + assert(n <= qrsize * 3); (void)qrsize; + bool core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n; + // The maximum QR Code size is 177, hence the dark run length n <= 177. + // Arithmetic is promoted to int, so n*4 will not overflow. + return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) + + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0); +} + + +// Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). +static int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, int runHistory[7], int qrsize) { + if (currentRunColor) { // Terminate dark run + finderPenaltyAddHistory(currentRunLength, runHistory, qrsize); + currentRunLength = 0; + } + currentRunLength += qrsize; // Add light border to final run + finderPenaltyAddHistory(currentRunLength, runHistory, qrsize); + return finderPenaltyCountPatterns(runHistory, qrsize); +} + + +// Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). +static void finderPenaltyAddHistory(int currentRunLength, int runHistory[7], int qrsize) { + if (runHistory[0] == 0) + currentRunLength += qrsize; // Add light border to initial run + memmove(&runHistory[1], &runHistory[0], 6 * sizeof(runHistory[0])); + runHistory[0] = currentRunLength; +} + + + +/*---- Basic QR Code information ----*/ + +// Public function - see documentation comment in header file. +int qrcodegen_getSize(const uint8_t qrcode[]) { + assert(qrcode != NULL); + int result = qrcode[0]; + assert((qrcodegen_VERSION_MIN * 4 + 17) <= result + && result <= (qrcodegen_VERSION_MAX * 4 + 17)); + return result; +} + + +// Public function - see documentation comment in header file. +bool qrcodegen_getModule(const uint8_t qrcode[], int x, int y) { + assert(qrcode != NULL); + int qrsize = qrcode[0]; + return (0 <= x && x < qrsize && 0 <= y && y < qrsize) && getModuleBounded(qrcode, x, y); +} + + +// Returns the color of the module at the given coordinates, which must be in bounds. +testable bool getModuleBounded(const uint8_t qrcode[], int x, int y) { + int qrsize = qrcode[0]; + assert(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize); + int index = y * qrsize + x; + return getBit(qrcode[(index >> 3) + 1], index & 7); +} + + +// Sets the color of the module at the given coordinates, which must be in bounds. +testable void setModuleBounded(uint8_t qrcode[], int x, int y, bool isDark) { + int qrsize = qrcode[0]; + assert(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize); + int index = y * qrsize + x; + int bitIndex = index & 7; + int byteIndex = (index >> 3) + 1; + if (isDark) + qrcode[byteIndex] |= 1 << bitIndex; + else + qrcode[byteIndex] &= (1 << bitIndex) ^ 0xFF; +} + + +// Sets the color of the module at the given coordinates, doing nothing if out of bounds. +testable void setModuleUnbounded(uint8_t qrcode[], int x, int y, bool isDark) { + int qrsize = qrcode[0]; + if (0 <= x && x < qrsize && 0 <= y && y < qrsize) + setModuleBounded(qrcode, x, y, isDark); +} + + +// Returns true iff the i'th bit of x is set to 1. Requires x >= 0 and 0 <= i <= 14. +static bool getBit(int x, int i) { + return ((x >> i) & 1) != 0; +} + + + +/*---- Segment handling ----*/ + +// Public function - see documentation comment in header file. +bool qrcodegen_isNumeric(const char *text) { + assert(text != NULL); + for (; *text != '\0'; text++) { + if (*text < '0' || *text > '9') + return false; + } + return true; +} + + +// Public function - see documentation comment in header file. +bool qrcodegen_isAlphanumeric(const char *text) { + assert(text != NULL); + for (; *text != '\0'; text++) { + if (strchr(ALPHANUMERIC_CHARSET, *text) == NULL) + return false; + } + return true; +} + + +// Public function - see documentation comment in header file. +size_t qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode, size_t numChars) { + int temp = calcSegmentBitLength(mode, numChars); + if (temp == LENGTH_OVERFLOW) + return SIZE_MAX; + assert(0 <= temp && temp <= INT16_MAX); + return ((size_t)temp + 7) / 8; +} + + +// Returns the number of data bits needed to represent a segment +// containing the given number of characters using the given mode. Notes: +// - Returns LENGTH_OVERFLOW on failure, i.e. numChars > INT16_MAX +// or the number of needed bits exceeds INT16_MAX (i.e. 32767). +// - Otherwise, all valid results are in the range [0, INT16_MAX]. +// - For byte mode, numChars measures the number of bytes, not Unicode code points. +// - For ECI mode, numChars must be 0, and the worst-case number of bits is returned. +// An actual ECI segment can have shorter data. For non-ECI modes, the result is exact. +testable int calcSegmentBitLength(enum qrcodegen_Mode mode, size_t numChars) { + // All calculations are designed to avoid overflow on all platforms + if (numChars > (unsigned int)INT16_MAX) + return LENGTH_OVERFLOW; + long result = (long)numChars; + if (mode == qrcodegen_Mode_NUMERIC) + result = (result * 10 + 2) / 3; // ceil(10/3 * n) + else if (mode == qrcodegen_Mode_ALPHANUMERIC) + result = (result * 11 + 1) / 2; // ceil(11/2 * n) + else if (mode == qrcodegen_Mode_BYTE) + result *= 8; + else if (mode == qrcodegen_Mode_KANJI) + result *= 13; + else if (mode == qrcodegen_Mode_ECI && numChars == 0) + result = 3 * 8; + else { // Invalid argument + assert(false); + return LENGTH_OVERFLOW; + } + assert(result >= 0); + if (result > INT16_MAX) + return LENGTH_OVERFLOW; + return (int)result; +} + + +// Public function - see documentation comment in header file. +struct qrcodegen_Segment qrcodegen_makeBytes(const uint8_t data[], size_t len, uint8_t buf[]) { + assert(data != NULL || len == 0); + struct qrcodegen_Segment result; + result.mode = qrcodegen_Mode_BYTE; + result.bitLength = calcSegmentBitLength(result.mode, len); + assert(result.bitLength != LENGTH_OVERFLOW); + result.numChars = (int)len; + if (len > 0) + memcpy(buf, data, len * sizeof(buf[0])); + result.data = buf; + return result; +} + + +// Public function - see documentation comment in header file. +struct qrcodegen_Segment qrcodegen_makeNumeric(const char *digits, uint8_t buf[]) { + assert(digits != NULL); + struct qrcodegen_Segment result; + size_t len = strlen(digits); + result.mode = qrcodegen_Mode_NUMERIC; + int bitLen = calcSegmentBitLength(result.mode, len); + assert(bitLen != LENGTH_OVERFLOW); + result.numChars = (int)len; + if (bitLen > 0) + memset(buf, 0, ((size_t)bitLen + 7) / 8 * sizeof(buf[0])); + result.bitLength = 0; + + unsigned int accumData = 0; + int accumCount = 0; + for (; *digits != '\0'; digits++) { + char c = *digits; + assert('0' <= c && c <= '9'); + accumData = accumData * 10 + (unsigned int)(c - '0'); + accumCount++; + if (accumCount == 3) { + appendBitsToBuffer(accumData, 10, buf, &result.bitLength); + accumData = 0; + accumCount = 0; + } + } + if (accumCount > 0) // 1 or 2 digits remaining + appendBitsToBuffer(accumData, accumCount * 3 + 1, buf, &result.bitLength); + assert(result.bitLength == bitLen); + result.data = buf; + return result; +} + + +// Public function - see documentation comment in header file. +struct qrcodegen_Segment qrcodegen_makeAlphanumeric(const char *text, uint8_t buf[]) { + assert(text != NULL); + struct qrcodegen_Segment result; + size_t len = strlen(text); + result.mode = qrcodegen_Mode_ALPHANUMERIC; + int bitLen = calcSegmentBitLength(result.mode, len); + assert(bitLen != LENGTH_OVERFLOW); + result.numChars = (int)len; + if (bitLen > 0) + memset(buf, 0, ((size_t)bitLen + 7) / 8 * sizeof(buf[0])); + result.bitLength = 0; + + unsigned int accumData = 0; + int accumCount = 0; + for (; *text != '\0'; text++) { + const char *temp = strchr(ALPHANUMERIC_CHARSET, *text); + assert(temp != NULL); + accumData = accumData * 45 + (unsigned int)(temp - ALPHANUMERIC_CHARSET); + accumCount++; + if (accumCount == 2) { + appendBitsToBuffer(accumData, 11, buf, &result.bitLength); + accumData = 0; + accumCount = 0; + } + } + if (accumCount > 0) // 1 character remaining + appendBitsToBuffer(accumData, 6, buf, &result.bitLength); + assert(result.bitLength == bitLen); + result.data = buf; + return result; +} + + +// Public function - see documentation comment in header file. +struct qrcodegen_Segment qrcodegen_makeEci(long assignVal, uint8_t buf[]) { + struct qrcodegen_Segment result; + result.mode = qrcodegen_Mode_ECI; + result.numChars = 0; + result.bitLength = 0; + if (assignVal < 0) + assert(false); + else if (assignVal < (1 << 7)) { + memset(buf, 0, 1 * sizeof(buf[0])); + appendBitsToBuffer((unsigned int)assignVal, 8, buf, &result.bitLength); + } else if (assignVal < (1 << 14)) { + memset(buf, 0, 2 * sizeof(buf[0])); + appendBitsToBuffer(2, 2, buf, &result.bitLength); + appendBitsToBuffer((unsigned int)assignVal, 14, buf, &result.bitLength); + } else if (assignVal < 1000000L) { + memset(buf, 0, 3 * sizeof(buf[0])); + appendBitsToBuffer(6, 3, buf, &result.bitLength); + appendBitsToBuffer((unsigned int)(assignVal >> 10), 11, buf, &result.bitLength); + appendBitsToBuffer((unsigned int)(assignVal & 0x3FF), 10, buf, &result.bitLength); + } else + assert(false); + result.data = buf; + return result; +} + + +// Calculates the number of bits needed to encode the given segments at the given version. +// Returns a non-negative number if successful. Otherwise returns LENGTH_OVERFLOW if a segment +// has too many characters to fit its length field, or the total bits exceeds INT16_MAX. +testable int getTotalBits(const struct qrcodegen_Segment segs[], size_t len, int version) { + assert(segs != NULL || len == 0); + long result = 0; + for (size_t i = 0; i < len; i++) { + int numChars = segs[i].numChars; + int bitLength = segs[i].bitLength; + assert(0 <= numChars && numChars <= INT16_MAX); + assert(0 <= bitLength && bitLength <= INT16_MAX); + int ccbits = numCharCountBits(segs[i].mode, version); + assert(0 <= ccbits && ccbits <= 16); + if (numChars >= (1L << ccbits)) + return LENGTH_OVERFLOW; // The segment's length doesn't fit the field's bit width + result += 4L + ccbits + bitLength; + if (result > INT16_MAX) + return LENGTH_OVERFLOW; // The sum might overflow an int type + } + assert(0 <= result && result <= INT16_MAX); + return (int)result; +} + + +// Returns the bit width of the character count field for a segment in the given mode +// in a QR Code at the given version number. The result is in the range [0, 16]. +static int numCharCountBits(enum qrcodegen_Mode mode, int version) { + assert(qrcodegen_VERSION_MIN <= version && version <= qrcodegen_VERSION_MAX); + int i = (version + 7) / 17; + switch (mode) { + case qrcodegen_Mode_NUMERIC : { static const int temp[] = {10, 12, 14}; return temp[i]; } + case qrcodegen_Mode_ALPHANUMERIC: { static const int temp[] = { 9, 11, 13}; return temp[i]; } + case qrcodegen_Mode_BYTE : { static const int temp[] = { 8, 16, 16}; return temp[i]; } + case qrcodegen_Mode_KANJI : { static const int temp[] = { 8, 10, 12}; return temp[i]; } + case qrcodegen_Mode_ECI : return 0; + default: assert(false); return -1; // Dummy value + } +} + + +#undef LENGTH_OVERFLOW diff --git a/libraries/tinyblocks-qr/src/qrcodegen.h b/libraries/tinyblocks-qr/src/qrcodegen.h new file mode 100644 index 0000000..6bbc157 --- /dev/null +++ b/libraries/tinyblocks-qr/src/qrcodegen.h @@ -0,0 +1,385 @@ +/* + * QR Code generator library (C) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * - The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * - The Software is provided "as is", without warranty of any kind, express or + * implied, including but not limited to the warranties of merchantability, + * fitness for a particular purpose and noninfringement. In no event shall the + * authors or copyright holders be liable for any claim, damages or other + * liability, whether in an action of contract, tort or otherwise, arising from, + * out of or in connection with the Software or the use or other dealings in the + * Software. + */ + +#pragma once + +#include +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +/* + * This library creates QR Code symbols, which is a type of two-dimension barcode. + * Invented by Denso Wave and described in the ISO/IEC 18004 standard. + * A QR Code structure is an immutable square grid of dark and light cells. + * The library provides functions to create a QR Code from text or binary data. + * The library covers the QR Code Model 2 specification, supporting all versions (sizes) + * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. + * + * Ways to create a QR Code object: + * - High level: Take the payload data and call qrcodegen_encodeText() or qrcodegen_encodeBinary(). + * - Low level: Custom-make the list of segments and call + * qrcodegen_encodeSegments() or qrcodegen_encodeSegmentsAdvanced(). + * (Note that all ways require supplying the desired error correction level and various byte buffers.) + */ + + +/*---- Enum and struct types----*/ + +/* + * The error correction level in a QR Code symbol. + */ +enum qrcodegen_Ecc { + // Must be declared in ascending order of error protection + // so that an internal qrcodegen function works properly + qrcodegen_Ecc_LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords + qrcodegen_Ecc_MEDIUM , // The QR Code can tolerate about 15% erroneous codewords + qrcodegen_Ecc_QUARTILE, // The QR Code can tolerate about 25% erroneous codewords + qrcodegen_Ecc_HIGH , // The QR Code can tolerate about 30% erroneous codewords +}; + + +/* + * The mask pattern used in a QR Code symbol. + */ +enum qrcodegen_Mask { + // A special value to tell the QR Code encoder to + // automatically select an appropriate mask pattern + qrcodegen_Mask_AUTO = -1, + // The eight actual mask patterns + qrcodegen_Mask_0 = 0, + qrcodegen_Mask_1, + qrcodegen_Mask_2, + qrcodegen_Mask_3, + qrcodegen_Mask_4, + qrcodegen_Mask_5, + qrcodegen_Mask_6, + qrcodegen_Mask_7, +}; + + +/* + * Describes how a segment's data bits are interpreted. + */ +enum qrcodegen_Mode { + qrcodegen_Mode_NUMERIC = 0x1, + qrcodegen_Mode_ALPHANUMERIC = 0x2, + qrcodegen_Mode_BYTE = 0x4, + qrcodegen_Mode_KANJI = 0x8, + qrcodegen_Mode_ECI = 0x7, +}; + + +/* + * A segment of character/binary/control data in a QR Code symbol. + * The mid-level way to create a segment is to take the payload data + * and call a factory function such as qrcodegen_makeNumeric(). + * The low-level way to create a segment is to custom-make the bit buffer + * and initialize a qrcodegen_Segment struct with appropriate values. + * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. + * Any segment longer than this is meaningless for the purpose of generating QR Codes. + * Moreover, the maximum allowed bit length is 32767 because + * the largest QR Code (version 40) has 31329 modules. + */ +struct qrcodegen_Segment { + // The mode indicator of this segment. + enum qrcodegen_Mode mode; + + // The length of this segment's unencoded data. Measured in characters for + // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. + // Always zero or positive. Not the same as the data's bit length. + int numChars; + + // The data bits of this segment, packed in bitwise big endian. + // Can be null if the bit length is zero. + uint8_t *data; + + // The number of valid data bits used in the buffer. Requires + // 0 <= bitLength <= 32767, and bitLength <= (capacity of data array) * 8. + // The character count (numChars) must agree with the mode and the bit buffer length. + int bitLength; +}; + + + +/*---- Macro constants and functions ----*/ + +#define qrcodegen_VERSION_MIN 1 // The minimum version number supported in the QR Code Model 2 standard +#define qrcodegen_VERSION_MAX 40 // The maximum version number supported in the QR Code Model 2 standard + +// Calculates the number of bytes needed to store any QR Code up to and including the given version number, +// as a compile-time constant. For example, 'uint8_t buffer[qrcodegen_BUFFER_LEN_FOR_VERSION(25)];' +// can store any single QR Code from version 1 to 25 (inclusive). The result fits in an int (or int16). +// Requires qrcodegen_VERSION_MIN <= n <= qrcodegen_VERSION_MAX. +#define qrcodegen_BUFFER_LEN_FOR_VERSION(n) ((((n) * 4 + 17) * ((n) * 4 + 17) + 7) / 8 + 1) + +// The worst-case number of bytes needed to store one QR Code, up to and including +// version 40. This value equals 3918, which is just under 4 kilobytes. +// Use this more convenient value to avoid calculating tighter memory bounds for buffers. +#define qrcodegen_BUFFER_LEN_MAX qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX) + + + +/*---- Functions (high level) to generate QR Codes ----*/ + +/* + * Encodes the given text string to a QR Code, returning true if successful. + * If the data is too long to fit in any version in the given range + * at the given ECC level, then false is returned. + * + * The input text must be encoded in UTF-8 and contain no NULs. + * Requires 1 <= minVersion <= maxVersion <= 40. + * + * The smallest possible QR Code version within the given range is automatically + * chosen for the output. Iff boostEcl is true, then the ECC level of the result + * may be higher than the ecl argument if it can be done without increasing the + * version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or + * qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow). + * + * About the arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion): + * - Before calling the function: + * - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow + * reading and writing; hence each array must have a length of at least len. + * - The two ranges must not overlap (aliasing). + * - The initial state of both ranges can be uninitialized + * because the function always writes before reading. + * - After the function returns: + * - Both ranges have no guarantee on which elements are initialized and what values are stored. + * - tempBuffer contains no useful data and should be treated as entirely uninitialized. + * - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule(). + * + * If successful, the resulting QR Code may use numeric, + * alphanumeric, or byte mode to encode the text. + * + * In the most optimistic case, a QR Code at version 40 with low ECC + * can hold any UTF-8 string up to 2953 bytes, or any alphanumeric string + * up to 4296 characters, or any digit string up to 7089 characters. + * These numbers represent the hard upper limit of the QR Code standard. + * + * Please consult the QR Code specification for information on + * data capacities per version, ECC level, and text encoding mode. + */ +bool qrcodegen_encodeText(const char *text, uint8_t tempBuffer[], uint8_t qrcode[], + enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl); + + +/* + * Encodes the given binary data to a QR Code, returning true if successful. + * If the data is too long to fit in any version in the given range + * at the given ECC level, then false is returned. + * + * Requires 1 <= minVersion <= maxVersion <= 40. + * + * The smallest possible QR Code version within the given range is automatically + * chosen for the output. Iff boostEcl is true, then the ECC level of the result + * may be higher than the ecl argument if it can be done without increasing the + * version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or + * qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow). + * + * About the arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion): + * - Before calling the function: + * - The array ranges dataAndTemp[0 : len] and qrcode[0 : len] must allow + * reading and writing; hence each array must have a length of at least len. + * - The two ranges must not overlap (aliasing). + * - The input array range dataAndTemp[0 : dataLen] should normally be + * valid UTF-8 text, but is not required by the QR Code standard. + * - The initial state of dataAndTemp[dataLen : len] and qrcode[0 : len] + * can be uninitialized because the function always writes before reading. + * - After the function returns: + * - Both ranges have no guarantee on which elements are initialized and what values are stored. + * - dataAndTemp contains no useful data and should be treated as entirely uninitialized. + * - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule(). + * + * If successful, the resulting QR Code will use byte mode to encode the data. + * + * In the most optimistic case, a QR Code at version 40 with low ECC can hold any byte + * sequence up to length 2953. This is the hard upper limit of the QR Code standard. + * + * Please consult the QR Code specification for information on + * data capacities per version, ECC level, and text encoding mode. + */ +bool qrcodegen_encodeBinary(uint8_t dataAndTemp[], size_t dataLen, uint8_t qrcode[], + enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl); + + +/*---- Functions (low level) to generate QR Codes ----*/ + +/* + * Encodes the given segments to a QR Code, returning true if successful. + * If the data is too long to fit in any version at the given ECC level, + * then false is returned. + * + * The smallest possible QR Code version is automatically chosen for + * the output. The ECC level of the result may be higher than the + * ecl argument if it can be done without increasing the version. + * + * About the byte arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX): + * - Before calling the function: + * - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow + * reading and writing; hence each array must have a length of at least len. + * - The two ranges must not overlap (aliasing). + * - The initial state of both ranges can be uninitialized + * because the function always writes before reading. + * - The input array segs can contain segments whose data buffers overlap with tempBuffer. + * - After the function returns: + * - Both ranges have no guarantee on which elements are initialized and what values are stored. + * - tempBuffer contains no useful data and should be treated as entirely uninitialized. + * - Any segment whose data buffer overlaps with tempBuffer[0 : len] + * must be treated as having invalid values in that array. + * - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule(). + * + * Please consult the QR Code specification for information on + * data capacities per version, ECC level, and text encoding mode. + * + * This function allows the user to create a custom sequence of segments that switches + * between modes (such as alphanumeric and byte) to encode text in less space. + * This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary(). + */ +bool qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[], size_t len, + enum qrcodegen_Ecc ecl, uint8_t tempBuffer[], uint8_t qrcode[]); + + +/* + * Encodes the given segments to a QR Code, returning true if successful. + * If the data is too long to fit in any version in the given range + * at the given ECC level, then false is returned. + * + * Requires 1 <= minVersion <= maxVersion <= 40. + * + * The smallest possible QR Code version within the given range is automatically + * chosen for the output. Iff boostEcl is true, then the ECC level of the result + * may be higher than the ecl argument if it can be done without increasing the + * version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or + * qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow). + * + * About the byte arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX): + * - Before calling the function: + * - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow + * reading and writing; hence each array must have a length of at least len. + * - The two ranges must not overlap (aliasing). + * - The initial state of both ranges can be uninitialized + * because the function always writes before reading. + * - The input array segs can contain segments whose data buffers overlap with tempBuffer. + * - After the function returns: + * - Both ranges have no guarantee on which elements are initialized and what values are stored. + * - tempBuffer contains no useful data and should be treated as entirely uninitialized. + * - Any segment whose data buffer overlaps with tempBuffer[0 : len] + * must be treated as having invalid values in that array. + * - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule(). + * + * Please consult the QR Code specification for information on + * data capacities per version, ECC level, and text encoding mode. + * + * This function allows the user to create a custom sequence of segments that switches + * between modes (such as alphanumeric and byte) to encode text in less space. + * This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary(). + */ +bool qrcodegen_encodeSegmentsAdvanced(const struct qrcodegen_Segment segs[], size_t len, enum qrcodegen_Ecc ecl, + int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl, uint8_t tempBuffer[], uint8_t qrcode[]); + + +/* + * Tests whether the given string can be encoded as a segment in numeric mode. + * A string is encodable iff each character is in the range 0 to 9. + */ +bool qrcodegen_isNumeric(const char *text); + + +/* + * Tests whether the given string can be encoded as a segment in alphanumeric mode. + * A string is encodable iff each character is in the following set: 0 to 9, A to Z + * (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. + */ +bool qrcodegen_isAlphanumeric(const char *text); + + +/* + * Returns the number of bytes (uint8_t) needed for the data buffer of a segment + * containing the given number of characters using the given mode. Notes: + * - Returns SIZE_MAX on failure, i.e. numChars > INT16_MAX or the internal + * calculation of the number of needed bits exceeds INT16_MAX (i.e. 32767). + * - Otherwise, all valid results are in the range [0, ceil(INT16_MAX / 8)], i.e. at most 4096. + * - It is okay for the user to allocate more bytes for the buffer than needed. + * - For byte mode, numChars measures the number of bytes, not Unicode code points. + * - For ECI mode, numChars must be 0, and the worst-case number of bytes is returned. + * An actual ECI segment can have shorter data. For non-ECI modes, the result is exact. + */ +size_t qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode, size_t numChars); + + +/* + * Returns a segment representing the given binary data encoded in + * byte mode. All input byte arrays are acceptable. Any text string + * can be converted to UTF-8 bytes and encoded as a byte mode segment. + */ +struct qrcodegen_Segment qrcodegen_makeBytes(const uint8_t data[], size_t len, uint8_t buf[]); + + +/* + * Returns a segment representing the given string of decimal digits encoded in numeric mode. + */ +struct qrcodegen_Segment qrcodegen_makeNumeric(const char *digits, uint8_t buf[]); + + +/* + * Returns a segment representing the given text string encoded in alphanumeric mode. + * The characters allowed are: 0 to 9, A to Z (uppercase only), space, + * dollar, percent, asterisk, plus, hyphen, period, slash, colon. + */ +struct qrcodegen_Segment qrcodegen_makeAlphanumeric(const char *text, uint8_t buf[]); + + +/* + * Returns a segment representing an Extended Channel Interpretation + * (ECI) designator with the given assignment value. + */ +struct qrcodegen_Segment qrcodegen_makeEci(long assignVal, uint8_t buf[]); + + +/*---- Functions to extract raw data from QR Codes ----*/ + +/* + * Returns the side length of the given QR Code, assuming that encoding succeeded. + * The result is in the range [21, 177]. Note that the length of the array buffer + * is related to the side length - every 'uint8_t qrcode[]' must have length at least + * qrcodegen_BUFFER_LEN_FOR_VERSION(version), which equals ceil(size^2 / 8 + 1). + */ +int qrcodegen_getSize(const uint8_t qrcode[]); + + +/* + * Returns the color of the module (pixel) at the given coordinates, which is false + * for light or true for dark. The top left corner has the coordinates (x=0, y=0). + * If the given coordinates are out of bounds, then false (light) is returned. + */ +bool qrcodegen_getModule(const uint8_t qrcode[], int x, int y); + + +#ifdef __cplusplus +} +#endif diff --git a/libraries/tinyblocks-qr/src/quirc.c b/libraries/tinyblocks-qr/src/quirc.c new file mode 100644 index 0000000..493def2 --- /dev/null +++ b/libraries/tinyblocks-qr/src/quirc.c @@ -0,0 +1,171 @@ +/* quirc -- QR-code recognition library + * Copyright (C) 2010-2012 Daniel Beer + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include +#include "quirc_internal.h" + +const char *quirc_version(void) +{ + return "1.0"; +} + +struct quirc *quirc_new(void) +{ + struct quirc *q = malloc(sizeof(*q)); + + if (!q) + return NULL; + + memset(q, 0, sizeof(*q)); + return q; +} + +void quirc_destroy(struct quirc *q) +{ + free(q->image); + /* q->pixels may alias q->image when their type representation is of the + same size, so we need to be careful here to avoid a double free */ + if (!QUIRC_PIXEL_ALIAS_IMAGE) + free(q->pixels); + free(q->flood_fill_vars); + free(q); +} + +int quirc_resize(struct quirc *q, int w, int h) +{ + uint8_t *image = NULL; + quirc_pixel_t *pixels = NULL; + size_t num_vars; + size_t vars_byte_size; + struct quirc_flood_fill_vars *vars = NULL; + + /* + * XXX: w and h should be size_t (or at least unsigned) as negatives + * values would not make much sense. The downside is that it would break + * both the API and ABI. Thus, at the moment, let's just do a sanity + * check. + */ + if (w < 0 || h < 0) + goto fail; + + /* + * alloc a new buffer for q->image. We avoid realloc(3) because we want + * on failure to be leave `q` in a consistant, unmodified state. + */ + image = calloc(w, h); + if (!image) + goto fail; + + /* compute the "old" (i.e. currently allocated) and the "new" + (i.e. requested) image dimensions. Cast to size_t *before* + multiplying: w, h and q->w, q->h are int, so "w * h" would + otherwise be evaluated in (signed) int arithmetic and can + overflow for large-but-valid dimensions (e.g. 50000x50000), + corrupting the memcpy() bound below via a bogus wrapped + value instead of failing safely. */ + size_t olddim = quirc_pixel_count(q); + size_t newdim = quirc_image_size(w, h); + size_t min = (olddim < newdim ? olddim : newdim); + + /* + * copy the data into the new buffer, avoiding (a) to read beyond the + * old buffer when the new size is greater and (b) to write beyond the + * new buffer when the new size is smaller, hence the min computation. + */ + if (min > 0) + (void)memcpy(image, q->image, min); + + /* alloc a new buffer for q->pixels if needed */ + if (!QUIRC_PIXEL_ALIAS_IMAGE) { + pixels = calloc(newdim, sizeof(quirc_pixel_t)); + if (!pixels) + goto fail; + } + + /* + * alloc the work area for the flood filling logic. + * + * the size was chosen with the following assumptions and observations: + * + * - rings are the regions which requires the biggest work area. + * - they consumes the most when they are rotated by about 45 degree. + * in that case, the necessary depth is about (2 * height_of_the_ring). + * - the maximum height of rings would be about 1/3 of the image height. + */ + + if ((size_t)h * 2 / 2 != h) { + goto fail; /* size_t overflow */ + } + num_vars = (size_t)h * 2 / 3; + if (num_vars == 0) { + num_vars = 1; + } + + vars_byte_size = sizeof(*vars) * num_vars; + if (vars_byte_size / sizeof(*vars) != num_vars) { + goto fail; /* size_t overflow */ + } + vars = malloc(vars_byte_size); + if (!vars) + goto fail; + + /* alloc succeeded, update `q` with the new size and buffers */ + q->w = w; + q->h = h; + free(q->image); + q->image = image; + if (!QUIRC_PIXEL_ALIAS_IMAGE) { + free(q->pixels); + q->pixels = pixels; + } + free(q->flood_fill_vars); + q->flood_fill_vars = vars; + q->num_flood_fill_vars = num_vars; + + return 0; + /* NOTREACHED */ +fail: + free(image); + free(pixels); + free(vars); + + return -1; +} + +int quirc_count(const struct quirc *q) +{ + return q->num_grids; +} + +static const char *const error_table[] = { + [QUIRC_SUCCESS] = "Success", + [QUIRC_ERROR_INVALID_GRID_SIZE] = "Invalid grid size", + [QUIRC_ERROR_INVALID_VERSION] = "Invalid version", + [QUIRC_ERROR_FORMAT_ECC] = "Format data ECC failure", + [QUIRC_ERROR_DATA_ECC] = "ECC failure", + [QUIRC_ERROR_UNKNOWN_DATA_TYPE] = "Unknown data type", + [QUIRC_ERROR_DATA_OVERFLOW] = "Data overflow", + [QUIRC_ERROR_DATA_UNDERFLOW] = "Data underflow" +}; + +const char *quirc_strerror(quirc_decode_error_t err) +{ + if (err >= 0 && err < sizeof(error_table) / sizeof(error_table[0])) + return error_table[err]; + + return "Unknown error"; +} diff --git a/libraries/tinyblocks-qr/src/quirc.h b/libraries/tinyblocks-qr/src/quirc.h new file mode 100644 index 0000000..d8d250d --- /dev/null +++ b/libraries/tinyblocks-qr/src/quirc.h @@ -0,0 +1,178 @@ +/* quirc -- QR-code recognition library + * Copyright (C) 2010-2012 Daniel Beer + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef QUIRC_H_ +#define QUIRC_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct quirc; + +/* Obtain the library version string. */ +const char *quirc_version(void); + +/* Construct a new QR-code recognizer. This function will return NULL + * if sufficient memory could not be allocated. + */ +struct quirc *quirc_new(void); + +/* Destroy a QR-code recognizer. */ +void quirc_destroy(struct quirc *q); + +/* Resize the QR-code recognizer. The size of an image must be + * specified before codes can be analyzed. + * + * This function returns 0 on success, or -1 if sufficient memory could + * not be allocated. + */ +int quirc_resize(struct quirc *q, int w, int h); + +/* These functions are used to process images for QR-code recognition. + * quirc_begin() must first be called to obtain access to a buffer into + * which the input image should be placed. Optionally, the current + * width and height may be returned. + * + * After filling the buffer, quirc_end() should be called to process + * the image for QR-code recognition. The locations and content of each + * code may be obtained using accessor functions described below. + */ +uint8_t *quirc_begin(struct quirc *q, int *w, int *h); +void quirc_end(struct quirc *q); + +/* This structure describes a location in the input image buffer. */ +struct quirc_point { + int x; + int y; +}; + +/* This enum describes the various decoder errors which may occur. */ +typedef enum { + QUIRC_SUCCESS = 0, + QUIRC_ERROR_INVALID_GRID_SIZE, + QUIRC_ERROR_INVALID_VERSION, + QUIRC_ERROR_FORMAT_ECC, + QUIRC_ERROR_DATA_ECC, + QUIRC_ERROR_UNKNOWN_DATA_TYPE, + QUIRC_ERROR_DATA_OVERFLOW, + QUIRC_ERROR_DATA_UNDERFLOW +} quirc_decode_error_t; + +/* Return a string error message for an error code. */ +const char *quirc_strerror(quirc_decode_error_t err); + +/* Limits on the maximum size of QR-codes and their content. */ +#define QUIRC_MAX_VERSION 40 +#define QUIRC_MAX_GRID_SIZE (QUIRC_MAX_VERSION * 4 + 17) +#define QUIRC_MAX_BITMAP (((QUIRC_MAX_GRID_SIZE * QUIRC_MAX_GRID_SIZE) + 7) / 8) +#define QUIRC_MAX_PAYLOAD 8896 + +/* QR-code ECC types. */ +#define QUIRC_ECC_LEVEL_M 0 +#define QUIRC_ECC_LEVEL_L 1 +#define QUIRC_ECC_LEVEL_H 2 +#define QUIRC_ECC_LEVEL_Q 3 + +/* QR-code data types. */ +#define QUIRC_DATA_TYPE_NUMERIC 1 +#define QUIRC_DATA_TYPE_ALPHA 2 +#define QUIRC_DATA_TYPE_BYTE 4 +#define QUIRC_DATA_TYPE_KANJI 8 + +/* Common character encodings */ +#define QUIRC_ECI_ISO_8859_1 1 +#define QUIRC_ECI_IBM437 2 +#define QUIRC_ECI_ISO_8859_2 4 +#define QUIRC_ECI_ISO_8859_3 5 +#define QUIRC_ECI_ISO_8859_4 6 +#define QUIRC_ECI_ISO_8859_5 7 +#define QUIRC_ECI_ISO_8859_6 8 +#define QUIRC_ECI_ISO_8859_7 9 +#define QUIRC_ECI_ISO_8859_8 10 +#define QUIRC_ECI_ISO_8859_9 11 +#define QUIRC_ECI_WINDOWS_874 13 +#define QUIRC_ECI_ISO_8859_13 15 +#define QUIRC_ECI_ISO_8859_15 17 +#define QUIRC_ECI_SHIFT_JIS 20 +#define QUIRC_ECI_UTF_8 26 + +/* This structure is used to return information about detected QR codes + * in the input image. + */ +struct quirc_code { + /* The four corners of the QR-code, from top left, clockwise */ + struct quirc_point corners[4]; + + /* The number of cells across in the QR-code. The cell bitmap + * is a bitmask giving the actual values of cells. If the cell + * at (x, y) is black, then the following bit is set: + * + * cell_bitmap[i >> 3] & (1 << (i & 7)) + * + * where i = (y * size) + x. + */ + int size; + uint8_t cell_bitmap[QUIRC_MAX_BITMAP]; +}; + +/* This structure holds the decoded QR-code data */ +struct quirc_data { + /* Various parameters of the QR-code. These can mostly be + * ignored if you only care about the data. + */ + int version; + int ecc_level; + int mask; + + /* This field is the highest-valued data type found in the QR + * code. + */ + int data_type; + + /* Data payload. For the Kanji datatype, payload is encoded as + * Shift-JIS. For all other datatypes, payload is ASCII text. + */ + uint8_t payload[QUIRC_MAX_PAYLOAD]; + int payload_len; + + /* ECI assignment number */ + uint32_t eci; +}; + +/* Return the number of QR-codes identified in the last processed + * image. + */ +int quirc_count(const struct quirc *q); + +/* Extract the QR-code specified by the given index. */ +void quirc_extract(const struct quirc *q, int index, + struct quirc_code *code); + +/* Decode a QR-code, returning the payload data. */ +quirc_decode_error_t quirc_decode(const struct quirc_code *code, + struct quirc_data *data); + +/* Flip a QR-code according to optional mirror feature of ISO 18004:2015 */ +void quirc_flip(struct quirc_code *code); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libraries/tinyblocks-qr/src/quirc_internal.h b/libraries/tinyblocks-qr/src/quirc_internal.h new file mode 100644 index 0000000..5274d35 --- /dev/null +++ b/libraries/tinyblocks-qr/src/quirc_internal.h @@ -0,0 +1,153 @@ +/* quirc -- QR-code recognition library + * Copyright (C) 2010-2012 Daniel Beer + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef QUIRC_INTERNAL_H_ +#define QUIRC_INTERNAL_H_ + +#include +#include + +#include "quirc.h" + +#define QUIRC_ASSERT(a) assert(a) + +#define QUIRC_PIXEL_WHITE 0 +#define QUIRC_PIXEL_BLACK 1 +#define QUIRC_PIXEL_REGION 2 + +#ifndef QUIRC_MAX_REGIONS +#define QUIRC_MAX_REGIONS 254 +#endif +#define QUIRC_MAX_CAPSTONES 32 +#define QUIRC_MAX_GRIDS (QUIRC_MAX_CAPSTONES * 2) + +#define QUIRC_PERSPECTIVE_PARAMS 8 + +#if QUIRC_MAX_REGIONS < UINT8_MAX +#define QUIRC_PIXEL_ALIAS_IMAGE 1 +typedef uint8_t quirc_pixel_t; +#elif QUIRC_MAX_REGIONS < UINT16_MAX +#define QUIRC_PIXEL_ALIAS_IMAGE 0 +typedef uint16_t quirc_pixel_t; +#else +#error "QUIRC_MAX_REGIONS > 65534 is not supported" +#endif + +#ifdef QUIRC_FLOAT_TYPE +/* Quirc uses double precision floating point internally by default. + * On platforms with a single precision FPU but no double precision FPU, + * this can be changed to float by defining QUIRC_FLOAT_TYPE. + * + * When setting QUIRC_FLOAT_TYPE to 'float', consider also defining QUIRC_USE_TGMATH. + * This will use the type-generic math functions (tgmath.h, C99 or later) instead of the normal ones, + * which will allow the compiler to use the correct overloaded functions for the type. + */ +typedef QUIRC_FLOAT_TYPE quirc_float_t; +#else +typedef double quirc_float_t; +#endif + +struct quirc_region { + struct quirc_point seed; + int count; + int capstone; +}; + +struct quirc_capstone { + int ring; + int stone; + + struct quirc_point corners[4]; + struct quirc_point center; + quirc_float_t c[QUIRC_PERSPECTIVE_PARAMS]; + + int qr_grid; +}; + +struct quirc_grid { + /* Capstone indices */ + int caps[3]; + + /* Alignment pattern region and corner */ + int align_region; + struct quirc_point align; + + /* Timing pattern endpoints */ + struct quirc_point tpep[3]; + + /* Grid size and perspective transform */ + int grid_size; + quirc_float_t c[QUIRC_PERSPECTIVE_PARAMS]; +}; + +struct quirc_flood_fill_vars { + int y; + int right; + int left_up; + int left_down; +}; + +struct quirc { + uint8_t *image; + quirc_pixel_t *pixels; + int w; + int h; + + int num_regions; + struct quirc_region regions[QUIRC_MAX_REGIONS]; + + int num_capstones; + struct quirc_capstone capstones[QUIRC_MAX_CAPSTONES]; + + int num_grids; + struct quirc_grid grids[QUIRC_MAX_GRIDS]; + + size_t num_flood_fill_vars; + struct quirc_flood_fill_vars *flood_fill_vars; +}; + +static inline size_t quirc_image_size(int w, int h) +{ + return (size_t)w * (size_t)h; +} + +static inline size_t quirc_pixel_count(const struct quirc *q) +{ + return quirc_image_size(q->w, q->h); +} + +/************************************************************************ + * QR-code version information database + */ + +#define QUIRC_MAX_VERSION 40 +#define QUIRC_MAX_ALIGNMENT 7 + +struct quirc_rs_params { + int bs; /* Small block size */ + int dw; /* Small data words */ + int ns; /* Number of small blocks */ +}; + +struct quirc_version_info { + int data_bytes; + int apat[QUIRC_MAX_ALIGNMENT]; + struct quirc_rs_params ecc[4]; +}; + +extern const struct quirc_version_info quirc_version_db[QUIRC_MAX_VERSION + 1]; + +#endif diff --git a/libraries/tinyblocks-qr/src/tb_camera.c b/libraries/tinyblocks-qr/src/tb_camera.c new file mode 100644 index 0000000..77edb5d --- /dev/null +++ b/libraries/tinyblocks-qr/src/tb_camera.c @@ -0,0 +1,268 @@ +/* + * TinyBlocks - tb_camera.c + * Camera em tons de cinza: V4L2 (Linux), Camera2 por JNI (Android), nada + * nos outros sistemas. + */ +#include +#include +#include +#include "../include/tb_camera.h" + +static char s_err[200] = ""; +static bool s_open = false; + +static void set_err(const char* m) { snprintf(s_err, sizeof(s_err), "%s", m); } +const char* tb_camera_error(void) { return s_err; } +bool tb_camera_is_open(void) { return s_open; } + +#if defined(__ANDROID__) +/* == Android: Camera2 do NDK (camera2ndk + AImageReader), sem Java === + * A permissao vem do SDL_AndroidRequestPermission (pergunta ao usuario). Os + * quadros sao lidos sob demanda (acquireLatestImage), sem thread nossa. */ +#include +#include +#include +#include +#include + +static ACameraManager* s_mgr; +static ACameraDevice* s_dev; +static AImageReader* s_reader; +static ANativeWindow* s_win; +static ACaptureSessionOutputContainer* s_cont; +static ACaptureSessionOutput* s_out; +static ACameraOutputTarget* s_target; +static ACaptureRequest* s_req; +static ACameraCaptureSession* s_session; +static int s_rot; /* orientacao do sensor (graus) */ + +static void dev_disconnected(void* ctx, ACameraDevice* d) { (void)ctx; (void)d; set_err("Camera desconectada"); } +static void dev_error(void* ctx, ACameraDevice* d, int e) { (void)ctx; (void)d; char m[64]; snprintf(m, sizeof(m), "Erro na camera (%d)", e); set_err(m); } +static void ses_noop(void* ctx, ACameraCaptureSession* s) { (void)ctx; (void)s; } + +static void cam_free(void) { + if (s_session) { ACameraCaptureSession_stopRepeating(s_session); ACameraCaptureSession_close(s_session); } + if (s_req) ACaptureRequest_free(s_req); + if (s_target) ACameraOutputTarget_free(s_target); + if (s_cont && s_out) ACaptureSessionOutputContainer_remove(s_cont, s_out); + if (s_out) ACaptureSessionOutput_free(s_out); + if (s_cont) ACaptureSessionOutputContainer_free(s_cont); + if (s_dev) ACameraDevice_close(s_dev); + if (s_reader) AImageReader_delete(s_reader); + if (s_mgr) ACameraManager_delete(s_mgr); + s_session = NULL; s_req = NULL; s_target = NULL; s_out = NULL; s_cont = NULL; + s_dev = NULL; s_reader = NULL; s_win = NULL; s_mgr = NULL; +} + +bool tb_camera_open(int want_w, int want_h) { + if (s_open) return true; + if (!SDL_AndroidRequestPermission("android.permission.CAMERA")) { + set_err("Sem permissao para usar a camera"); + return false; + } + s_mgr = ACameraManager_create(); + ACameraIdList* ids = NULL; + if (!s_mgr || ACameraManager_getCameraIdList(s_mgr, &ids) != ACAMERA_OK || !ids || ids->numCameras < 1) { + if (ids) ACameraManager_deleteCameraIdList(ids); + set_err("Nenhuma camera no aparelho"); + cam_free(); + return false; + } + const char* id = ids->cameraIds[0]; /* a traseira, se houver */ + s_rot = 0; + for (int i = 0; i < ids->numCameras; i++) { + ACameraMetadata* meta = NULL; + if (ACameraManager_getCameraCharacteristics(s_mgr, ids->cameraIds[i], &meta) != ACAMERA_OK) continue; + ACameraMetadata_const_entry e; + bool back = ACameraMetadata_getConstEntry(meta, ACAMERA_LENS_FACING, &e) == ACAMERA_OK && + e.data.u8[0] == ACAMERA_LENS_FACING_BACK; + if (back || i == 0) { + id = ids->cameraIds[i]; + if (ACameraMetadata_getConstEntry(meta, ACAMERA_SENSOR_ORIENTATION, &e) == ACAMERA_OK) s_rot = e.data.i32[0]; + } + ACameraMetadata_free(meta); + if (back) break; + } + ACameraDevice_StateCallbacks dcb = { NULL, dev_disconnected, dev_error }; + camera_status_t st = ACameraManager_openCamera(s_mgr, id, &dcb, &s_dev); + ACameraManager_deleteCameraIdList(ids); + if (st != ACAMERA_OK) { set_err("Camera ocupada ou sem permissao"); cam_free(); return false; } + + if (AImageReader_new(want_w, want_h, AIMAGE_FORMAT_YUV_420_888, 2, &s_reader) != AMEDIA_OK || + AImageReader_getWindow(s_reader, &s_win) != AMEDIA_OK) { + set_err("Falha ao criar o leitor de imagens"); + cam_free(); + return false; + } + ACameraCaptureSession_stateCallbacks scb = { NULL, ses_noop, ses_noop, ses_noop }; + if (ACaptureSessionOutputContainer_create(&s_cont) != ACAMERA_OK || + ACaptureSessionOutput_create(s_win, &s_out) != ACAMERA_OK || + ACaptureSessionOutputContainer_add(s_cont, s_out) != ACAMERA_OK || + ACameraOutputTarget_create(s_win, &s_target) != ACAMERA_OK || + ACameraDevice_createCaptureRequest(s_dev, TEMPLATE_PREVIEW, &s_req) != ACAMERA_OK || + ACaptureRequest_addTarget(s_req, s_target) != ACAMERA_OK) { + set_err("Falha ao preparar a camera"); + cam_free(); + return false; + } + uint8_t af = ACAMERA_CONTROL_AF_MODE_CONTINUOUS_PICTURE; + ACaptureRequest_setEntry_u8(s_req, ACAMERA_CONTROL_AF_MODE, 1, &af); + if (ACameraDevice_createCaptureSession(s_dev, s_cont, &scb, &s_session) != ACAMERA_OK || + ACameraCaptureSession_setRepeatingRequest(s_session, NULL, 1, &s_req, NULL) != ACAMERA_OK) { + set_err("Falha ao iniciar a camera"); + cam_free(); + return false; + } + s_open = true; + s_err[0] = 0; + return true; +} + +/* Canal Y do quadro mais novo, girado conforme o sensor (de pe) */ +bool tb_camera_frame(unsigned char* gray, int cap, int* w, int* h) { + if (!s_open || !s_reader) return false; + AImage* img = NULL; + if (AImageReader_acquireLatestImage(s_reader, &img) != AMEDIA_OK || !img) return false; + int32_t iw = 0, ih = 0, rs = 0, ps = 1; + uint8_t* data = NULL; + int len = 0; + bool ok = AImage_getWidth(img, &iw) == AMEDIA_OK && AImage_getHeight(img, &ih) == AMEDIA_OK && + AImage_getPlaneRowStride(img, 0, &rs) == AMEDIA_OK && + AImage_getPlanePixelStride(img, 0, &ps) == AMEDIA_OK && + AImage_getPlaneData(img, 0, &data, &len) == AMEDIA_OK && data && iw * ih <= cap; + if (ok) { + bool swap = s_rot == 90 || s_rot == 270; + int ow = swap ? ih : iw, oh = swap ? iw : ih; + for (int y = 0; y < ih; y++) { + const uint8_t* row = data + (size_t)y * (size_t)rs; + for (int x = 0; x < iw; x++) { + int dx, dy; + switch (s_rot) { + case 90: dx = ih - 1 - y; dy = x; break; + case 180: dx = iw - 1 - x; dy = ih - 1 - y; break; + case 270: dx = y; dy = iw - 1 - x; break; + default: dx = x; dy = y; break; + } + gray[dy * ow + dx] = row[x * ps]; + } + } + *w = ow; *h = oh; + } + AImage_delete(img); + return ok; +} + +void tb_camera_close(void) { + if (!s_open && !s_mgr) return; + s_open = false; + cam_free(); +} + +#elif defined(__linux__) +/* == Linux: V4L2 em YUYV (o canal Y e o cinza) === */ +#include +#include +#include +#include +#include +#include + +#define CAM_BUFS 4 +static int s_fd = -1; +static void* s_map[CAM_BUFS]; +static size_t s_len[CAM_BUFS]; +static int s_nbuf, s_w, s_h; + +static int xioctl(int fd, unsigned long req, void* arg) { + int r; + do r = ioctl(fd, req, arg); while (r < 0 && errno == EINTR); + return r; +} + +bool tb_camera_open(int want_w, int want_h) { + if (s_open) return true; + const char* dev = getenv("TINYBLOCKS_CAMERA"); + if (!dev || !dev[0]) dev = "/dev/video0"; + s_fd = open(dev, O_RDWR | O_NONBLOCK); + if (s_fd < 0) { set_err("Nenhuma camera encontrada (/dev/video0)"); return false; } + struct v4l2_format f; + memset(&f, 0, sizeof(f)); + f.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + f.fmt.pix.width = (unsigned)want_w; + f.fmt.pix.height = (unsigned)want_h; + f.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV; + f.fmt.pix.field = V4L2_FIELD_ANY; + if (xioctl(s_fd, VIDIOC_S_FMT, &f) < 0 || f.fmt.pix.pixelformat != V4L2_PIX_FMT_YUYV) { + set_err("A camera nao entrega YUYV"); + close(s_fd); s_fd = -1; + return false; + } + s_w = (int)f.fmt.pix.width; s_h = (int)f.fmt.pix.height; + struct v4l2_requestbuffers rq; + memset(&rq, 0, sizeof(rq)); + rq.count = CAM_BUFS; rq.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; rq.memory = V4L2_MEMORY_MMAP; + if (xioctl(s_fd, VIDIOC_REQBUFS, &rq) < 0 || rq.count < 2) { + set_err("A camera nao aceitou os buffers"); + close(s_fd); s_fd = -1; + return false; + } + s_nbuf = (int)(rq.count < CAM_BUFS ? rq.count : CAM_BUFS); + for (int i = 0; i < s_nbuf; i++) { + struct v4l2_buffer b; + memset(&b, 0, sizeof(b)); + b.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; b.memory = V4L2_MEMORY_MMAP; b.index = (unsigned)i; + if (xioctl(s_fd, VIDIOC_QUERYBUF, &b) < 0) { set_err("Falha em QUERYBUF"); tb_camera_close(); return false; } + s_len[i] = b.length; + s_map[i] = mmap(NULL, b.length, PROT_READ | PROT_WRITE, MAP_SHARED, s_fd, b.m.offset); + if (s_map[i] == MAP_FAILED) { s_map[i] = NULL; set_err("Falha no mmap"); tb_camera_close(); return false; } + xioctl(s_fd, VIDIOC_QBUF, &b); + } + enum v4l2_buf_type t = V4L2_BUF_TYPE_VIDEO_CAPTURE; + if (xioctl(s_fd, VIDIOC_STREAMON, &t) < 0) { set_err("Falha em STREAMON"); tb_camera_close(); return false; } + s_open = true; + s_err[0] = 0; + return true; +} + +bool tb_camera_frame(unsigned char* gray, int cap, int* w, int* h) { + if (!s_open || s_w * s_h > cap) return false; + struct v4l2_buffer b; + bool got = false; + for (;;) { /* esvazia a fila: fica o mais novo */ + memset(&b, 0, sizeof(b)); + b.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; b.memory = V4L2_MEMORY_MMAP; + if (xioctl(s_fd, VIDIOC_DQBUF, &b) < 0) break; + if (b.index < (unsigned)s_nbuf && s_map[b.index]) { + const unsigned char* p = (const unsigned char*)s_map[b.index]; + for (int i = 0; i < s_w * s_h; i++) gray[i] = p[2 * i]; + got = true; + } + xioctl(s_fd, VIDIOC_QBUF, &b); + } + if (got) { *w = s_w; *h = s_h; } + return got; +} + +void tb_camera_close(void) { + if (s_fd >= 0) { + enum v4l2_buf_type t = V4L2_BUF_TYPE_VIDEO_CAPTURE; + xioctl(s_fd, VIDIOC_STREAMOFF, &t); + for (int i = 0; i < s_nbuf; i++) if (s_map[i]) { munmap(s_map[i], s_len[i]); s_map[i] = NULL; } + close(s_fd); + } + s_fd = -1; s_nbuf = 0; s_open = false; +} + +#else +/* == Sem camera (Windows...) === */ +bool tb_camera_open(int want_w, int want_h) { + (void)want_w; (void)want_h; + set_err("Camera nao suportada neste sistema"); + return false; +} +bool tb_camera_frame(unsigned char* gray, int cap, int* w, int* h) { + (void)gray; (void)cap; (void)w; (void)h; + return false; +} +void tb_camera_close(void) { s_open = false; } +#endif diff --git a/libraries/tinyblocks-qr/src/tb_qr.c b/libraries/tinyblocks-qr/src/tb_qr.c new file mode 100644 index 0000000..82e27a6 --- /dev/null +++ b/libraries/tinyblocks-qr/src/tb_qr.c @@ -0,0 +1,69 @@ +/* + * TinyBlocks - tb_qr.c + * Gerar (qrcodegen) e ler (quirc) QR codes. + */ +#include +#include +#include "../include/tb_qr.h" +#include "qrcodegen.h" +#include "quirc.h" + +int tb_qr_encode(const char* text, unsigned char* mods, int cap) { + if (!text || !mods) return 0; + uint8_t tmp[qrcodegen_BUFFER_LEN_MAX], qr[qrcodegen_BUFFER_LEN_MAX]; + if (!qrcodegen_encodeText(text, tmp, qr, qrcodegen_Ecc_MEDIUM, qrcodegen_VERSION_MIN, + qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true)) + return 0; + int side = qrcodegen_getSize(qr); + if (side * side > cap) return 0; + for (int y = 0; y < side; y++) + for (int x = 0; x < side; x++) + mods[y * side + x] = qrcodegen_getModule(qr, x, y) ? 1 : 0; + return side; +} + +struct TbQrReader { + struct quirc* q; + int w, h; +}; + +TbQrReader* tb_qr_reader_new(void) { + TbQrReader* r = (TbQrReader*)calloc(1, sizeof(*r)); + if (!r) return NULL; + r->q = quirc_new(); + if (!r->q) { free(r); return NULL; } + return r; +} + +int tb_qr_reader_scan(TbQrReader* r, const unsigned char* gray, int w, int h, TbQrFound found, void* user) { + if (!r || !gray || w <= 0 || h <= 0) return 0; + if (w != r->w || h != r->h) { + if (quirc_resize(r->q, w, h) < 0) return 0; + r->w = w; r->h = h; + } + int qw = 0, qh = 0; + uint8_t* buf = quirc_begin(r->q, &qw, &qh); + memcpy(buf, gray, (size_t)w * (size_t)h); + quirc_end(r->q); + int n = quirc_count(r->q), got = 0; + for (int i = 0; i < n; i++) { + struct quirc_code code; + struct quirc_data data; + quirc_extract(r->q, i, &code); + quirc_decode_error_t e = quirc_decode(&code, &data); + if (e == QUIRC_ERROR_DATA_ECC) { /* visto no espelho (camera frontal) */ + quirc_flip(&code); + e = quirc_decode(&code, &data); + } + if (e) continue; + got++; + if (found) found((const char*)data.payload, data.payload_len, user); + } + return got; +} + +void tb_qr_reader_free(TbQrReader* r) { + if (!r) return; + quirc_destroy(r->q); + free(r); +} diff --git a/libraries/tinyblocks-qr/src/version_db.c b/libraries/tinyblocks-qr/src/version_db.c new file mode 100644 index 0000000..fea8146 --- /dev/null +++ b/libraries/tinyblocks-qr/src/version_db.c @@ -0,0 +1,421 @@ +/* quirc -- QR-code recognition library + * Copyright (C) 2010-2012 Daniel Beer + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include "quirc_internal.h" + +const struct quirc_version_info quirc_version_db[QUIRC_MAX_VERSION + 1] = { + {0}, + { /* Version 1 */ + .data_bytes = 26, + .apat = {0}, + .ecc = { + {.bs = 26, .dw = 16, .ns = 1}, + {.bs = 26, .dw = 19, .ns = 1}, + {.bs = 26, .dw = 9, .ns = 1}, + {.bs = 26, .dw = 13, .ns = 1} + } + }, + { /* Version 2 */ + .data_bytes = 44, + .apat = {6, 18, 0}, + .ecc = { + {.bs = 44, .dw = 28, .ns = 1}, + {.bs = 44, .dw = 34, .ns = 1}, + {.bs = 44, .dw = 16, .ns = 1}, + {.bs = 44, .dw = 22, .ns = 1} + } + }, + { /* Version 3 */ + .data_bytes = 70, + .apat = {6, 22, 0}, + .ecc = { + {.bs = 70, .dw = 44, .ns = 1}, + {.bs = 70, .dw = 55, .ns = 1}, + {.bs = 35, .dw = 13, .ns = 2}, + {.bs = 35, .dw = 17, .ns = 2} + } + }, + { /* Version 4 */ + .data_bytes = 100, + .apat = {6, 26, 0}, + .ecc = { + {.bs = 50, .dw = 32, .ns = 2}, + {.bs = 100, .dw = 80, .ns = 1}, + {.bs = 25, .dw = 9, .ns = 4}, + {.bs = 50, .dw = 24, .ns = 2} + } + }, + { /* Version 5 */ + .data_bytes = 134, + .apat = {6, 30, 0}, + .ecc = { + {.bs = 67, .dw = 43, .ns = 2}, + {.bs = 134, .dw = 108, .ns = 1}, + {.bs = 33, .dw = 11, .ns = 2}, + {.bs = 33, .dw = 15, .ns = 2} + } + }, + { /* Version 6 */ + .data_bytes = 172, + .apat = {6, 34, 0}, + .ecc = { + {.bs = 43, .dw = 27, .ns = 4}, + {.bs = 86, .dw = 68, .ns = 2}, + {.bs = 43, .dw = 15, .ns = 4}, + {.bs = 43, .dw = 19, .ns = 4} + } + }, + { /* Version 7 */ + .data_bytes = 196, + .apat = {6, 22, 38, 0}, + .ecc = { + {.bs = 49, .dw = 31, .ns = 4}, + {.bs = 98, .dw = 78, .ns = 2}, + {.bs = 39, .dw = 13, .ns = 4}, + {.bs = 32, .dw = 14, .ns = 2} + } + }, + { /* Version 8 */ + .data_bytes = 242, + .apat = {6, 24, 42, 0}, + .ecc = { + {.bs = 60, .dw = 38, .ns = 2}, + {.bs = 121, .dw = 97, .ns = 2}, + {.bs = 40, .dw = 14, .ns = 4}, + {.bs = 40, .dw = 18, .ns = 4} + } + }, + { /* Version 9 */ + .data_bytes = 292, + .apat = {6, 26, 46, 0}, + .ecc = { + {.bs = 58, .dw = 36, .ns = 3}, + {.bs = 146, .dw = 116, .ns = 2}, + {.bs = 36, .dw = 12, .ns = 4}, + {.bs = 36, .dw = 16, .ns = 4} + } + }, + { /* Version 10 */ + .data_bytes = 346, + .apat = {6, 28, 50, 0}, + .ecc = { + {.bs = 69, .dw = 43, .ns = 4}, + {.bs = 86, .dw = 68, .ns = 2}, + {.bs = 43, .dw = 15, .ns = 6}, + {.bs = 43, .dw = 19, .ns = 6} + } + }, + { /* Version 11 */ + .data_bytes = 404, + .apat = {6, 30, 54, 0}, + .ecc = { + {.bs = 80, .dw = 50, .ns = 1}, + {.bs = 101, .dw = 81, .ns = 4}, + {.bs = 36, .dw = 12, .ns = 3}, + {.bs = 50, .dw = 22, .ns = 4} + } + }, + { /* Version 12 */ + .data_bytes = 466, + .apat = {6, 32, 58, 0}, + .ecc = { + {.bs = 58, .dw = 36, .ns = 6}, + {.bs = 116, .dw = 92, .ns = 2}, + {.bs = 42, .dw = 14, .ns = 7}, + {.bs = 46, .dw = 20, .ns = 4} + } + }, + { /* Version 13 */ + .data_bytes = 532, + .apat = {6, 34, 62, 0}, + .ecc = { + {.bs = 59, .dw = 37, .ns = 8}, + {.bs = 133, .dw = 107, .ns = 4}, + {.bs = 33, .dw = 11, .ns = 12}, + {.bs = 44, .dw = 20, .ns = 8} + } + }, + { /* Version 14 */ + .data_bytes = 581, + .apat = {6, 26, 46, 66, 0}, + .ecc = { + {.bs = 64, .dw = 40, .ns = 4}, + {.bs = 145, .dw = 115, .ns = 3}, + {.bs = 36, .dw = 12, .ns = 11}, + {.bs = 36, .dw = 16, .ns = 11} + } + }, + { /* Version 15 */ + .data_bytes = 655, + .apat = {6, 26, 48, 70, 0}, + .ecc = { + {.bs = 65, .dw = 41, .ns = 5}, + {.bs = 109, .dw = 87, .ns = 5}, + {.bs = 36, .dw = 12, .ns = 11}, + {.bs = 54, .dw = 24, .ns = 5} + } + }, + { /* Version 16 */ + .data_bytes = 733, + .apat = {6, 26, 50, 74, 0}, + .ecc = { + {.bs = 73, .dw = 45, .ns = 7}, + {.bs = 122, .dw = 98, .ns = 5}, + {.bs = 45, .dw = 15, .ns = 3}, + {.bs = 43, .dw = 19, .ns = 15} + } + }, + { /* Version 17 */ + .data_bytes = 815, + .apat = {6, 30, 54, 78, 0}, + .ecc = { + {.bs = 74, .dw = 46, .ns = 10}, + {.bs = 135, .dw = 107, .ns = 1}, + {.bs = 42, .dw = 14, .ns = 2}, + {.bs = 50, .dw = 22, .ns = 1} + } + }, + { /* Version 18 */ + .data_bytes = 901, + .apat = {6, 30, 56, 82, 0}, + .ecc = { + {.bs = 69, .dw = 43, .ns = 9}, + {.bs = 150, .dw = 120, .ns = 5}, + {.bs = 42, .dw = 14, .ns = 2}, + {.bs = 50, .dw = 22, .ns = 17} + } + }, + { /* Version 19 */ + .data_bytes = 991, + .apat = {6, 30, 58, 86, 0}, + .ecc = { + {.bs = 70, .dw = 44, .ns = 3}, + {.bs = 141, .dw = 113, .ns = 3}, + {.bs = 39, .dw = 13, .ns = 9}, + {.bs = 47, .dw = 21, .ns = 17} + } + }, + { /* Version 20 */ + .data_bytes = 1085, + .apat = {6, 34, 62, 90, 0}, + .ecc = { + {.bs = 67, .dw = 41, .ns = 3}, + {.bs = 135, .dw = 107, .ns = 3}, + {.bs = 43, .dw = 15, .ns = 15}, + {.bs = 54, .dw = 24, .ns = 15} + } + }, + { /* Version 21 */ + .data_bytes = 1156, + .apat = {6, 28, 50, 72, 92, 0}, + .ecc = { + {.bs = 68, .dw = 42, .ns = 17}, + {.bs = 144, .dw = 116, .ns = 4}, + {.bs = 46, .dw = 16, .ns = 19}, + {.bs = 50, .dw = 22, .ns = 17} + } + }, + { /* Version 22 */ + .data_bytes = 1258, + .apat = {6, 26, 50, 74, 98, 0}, + .ecc = { + {.bs = 74, .dw = 46, .ns = 17}, + {.bs = 139, .dw = 111, .ns = 2}, + {.bs = 37, .dw = 13, .ns = 34}, + {.bs = 54, .dw = 24, .ns = 7} + } + }, + { /* Version 23 */ + .data_bytes = 1364, + .apat = {6, 30, 54, 78, 102, 0}, + .ecc = { + {.bs = 75, .dw = 47, .ns = 4}, + {.bs = 151, .dw = 121, .ns = 4}, + {.bs = 45, .dw = 15, .ns = 16}, + {.bs = 54, .dw = 24, .ns = 11} + } + }, + { /* Version 24 */ + .data_bytes = 1474, + .apat = {6, 28, 54, 80, 106, 0}, + .ecc = { + {.bs = 73, .dw = 45, .ns = 6}, + {.bs = 147, .dw = 117, .ns = 6}, + {.bs = 46, .dw = 16, .ns = 30}, + {.bs = 54, .dw = 24, .ns = 11} + } + }, + { /* Version 25 */ + .data_bytes = 1588, + .apat = {6, 32, 58, 84, 110, 0}, + .ecc = { + {.bs = 75, .dw = 47, .ns = 8}, + {.bs = 132, .dw = 106, .ns = 8}, + {.bs = 45, .dw = 15, .ns = 22}, + {.bs = 54, .dw = 24, .ns = 7} + } + }, + { /* Version 26 */ + .data_bytes = 1706, + .apat = {6, 30, 58, 86, 114, 0}, + .ecc = { + {.bs = 74, .dw = 46, .ns = 19}, + {.bs = 142, .dw = 114, .ns = 10}, + {.bs = 46, .dw = 16, .ns = 33}, + {.bs = 50, .dw = 22, .ns = 28} + } + }, + { /* Version 27 */ + .data_bytes = 1828, + .apat = {6, 34, 62, 90, 118, 0}, + .ecc = { + {.bs = 73, .dw = 45, .ns = 22}, + {.bs = 152, .dw = 122, .ns = 8}, + {.bs = 45, .dw = 15, .ns = 12}, + {.bs = 53, .dw = 23, .ns = 8} + } + }, + { /* Version 28 */ + .data_bytes = 1921, + .apat = {6, 26, 50, 74, 98, 122, 0}, + .ecc = { + {.bs = 73, .dw = 45, .ns = 3}, + {.bs = 147, .dw = 117, .ns = 3}, + {.bs = 45, .dw = 15, .ns = 11}, + {.bs = 54, .dw = 24, .ns = 4} + } + }, + { /* Version 29 */ + .data_bytes = 2051, + .apat = {6, 30, 54, 78, 102, 126, 0}, + .ecc = { + {.bs = 73, .dw = 45, .ns = 21}, + {.bs = 146, .dw = 116, .ns = 7}, + {.bs = 45, .dw = 15, .ns = 19}, + {.bs = 53, .dw = 23, .ns = 1} + } + }, + { /* Version 30 */ + .data_bytes = 2185, + .apat = {6, 26, 52, 78, 104, 130, 0}, + .ecc = { + {.bs = 75, .dw = 47, .ns = 19}, + {.bs = 145, .dw = 115, .ns = 5}, + {.bs = 45, .dw = 15, .ns = 23}, + {.bs = 54, .dw = 24, .ns = 15} + } + }, + { /* Version 31 */ + .data_bytes = 2323, + .apat = {6, 30, 56, 82, 108, 134, 0}, + .ecc = { + {.bs = 74, .dw = 46, .ns = 2}, + {.bs = 145, .dw = 115, .ns = 13}, + {.bs = 45, .dw = 15, .ns = 23}, + {.bs = 54, .dw = 24, .ns = 42} + } + }, + { /* Version 32 */ + .data_bytes = 2465, + .apat = {6, 34, 60, 86, 112, 138, 0}, + .ecc = { + {.bs = 74, .dw = 46, .ns = 10}, + {.bs = 145, .dw = 115, .ns = 17}, + {.bs = 45, .dw = 15, .ns = 19}, + {.bs = 54, .dw = 24, .ns = 10} + } + }, + { /* Version 33 */ + .data_bytes = 2611, + .apat = {6, 30, 58, 86, 114, 142, 0}, + .ecc = { + {.bs = 74, .dw = 46, .ns = 14}, + {.bs = 145, .dw = 115, .ns = 17}, + {.bs = 45, .dw = 15, .ns = 11}, + {.bs = 54, .dw = 24, .ns = 29} + } + }, + { /* Version 34 */ + .data_bytes = 2761, + .apat = {6, 34, 62, 90, 118, 146, 0}, + .ecc = { + {.bs = 74, .dw = 46, .ns = 14}, + {.bs = 145, .dw = 115, .ns = 13}, + {.bs = 46, .dw = 16, .ns = 59}, + {.bs = 54, .dw = 24, .ns = 44} + } + }, + { /* Version 35 */ + .data_bytes = 2876, + .apat = {6, 30, 54, 78, 102, 126, 150}, + .ecc = { + {.bs = 75, .dw = 47, .ns = 12}, + {.bs = 151, .dw = 121, .ns = 12}, + {.bs = 45, .dw = 15, .ns = 22}, + {.bs = 54, .dw = 24, .ns = 39} + } + }, + { /* Version 36 */ + .data_bytes = 3034, + .apat = {6, 24, 50, 76, 102, 128, 154}, + .ecc = { + {.bs = 75, .dw = 47, .ns = 6}, + {.bs = 151, .dw = 121, .ns = 6}, + {.bs = 45, .dw = 15, .ns = 2}, + {.bs = 54, .dw = 24, .ns = 46} + } + }, + { /* Version 37 */ + .data_bytes = 3196, + .apat = {6, 28, 54, 80, 106, 132, 158}, + .ecc = { + {.bs = 74, .dw = 46, .ns = 29}, + {.bs = 152, .dw = 122, .ns = 17}, + {.bs = 45, .dw = 15, .ns = 24}, + {.bs = 54, .dw = 24, .ns = 49} + } + }, + { /* Version 38 */ + .data_bytes = 3362, + .apat = {6, 32, 58, 84, 110, 136, 162}, + .ecc = { + {.bs = 74, .dw = 46, .ns = 13}, + {.bs = 152, .dw = 122, .ns = 4}, + {.bs = 45, .dw = 15, .ns = 42}, + {.bs = 54, .dw = 24, .ns = 48} + } + }, + { /* Version 39 */ + .data_bytes = 3532, + .apat = {6, 26, 54, 82, 110, 138, 166}, + .ecc = { + {.bs = 75, .dw = 47, .ns = 40}, + {.bs = 147, .dw = 117, .ns = 20}, + {.bs = 45, .dw = 15, .ns = 10}, + {.bs = 54, .dw = 24, .ns = 43} + } + }, + { /* Version 40 */ + .data_bytes = 3706, + .apat = {6, 30, 58, 86, 114, 142, 170}, + .ecc = { + {.bs = 75, .dw = 47, .ns = 18}, + {.bs = 148, .dw = 118, .ns = 19}, + {.bs = 45, .dw = 15, .ns = 20}, + {.bs = 54, .dw = 24, .ns = 34} + } + } +}; diff --git a/libraries/tinyblocks-sdl2/src/tb_sdl2.c b/libraries/tinyblocks-sdl2/src/tb_sdl2.c index 5b86d22..562d585 100644 --- a/libraries/tinyblocks-sdl2/src/tb_sdl2.c +++ b/libraries/tinyblocks-sdl2/src/tb_sdl2.c @@ -490,6 +490,8 @@ static void sdl2_execute(SDL_Renderer* ren, SDL_Surface* surf = TTF_RenderUTF8_Blended(font, cmd->text, col); if (surf) { SDL_Texture* tex = SDL_CreateTextureFromSurface(ren, surf); + if (tex && cmd->a < 1.f) /* o Blended nao usa o alfa da cor */ + SDL_SetTextureAlphaMod(tex, (Uint8)(fmaxf(0.f, cmd->a) * 255.f + 0.5f)); if (tex) { /* cmd->x,cmd->y é baseline-left; converte para o topo do retângulo usando o ascent real da fonte. */ @@ -755,6 +757,10 @@ static bool be_apply(SDL_Event* ev) { break; case SDL_MOUSEMOTION: if ((w = win_by_id(ev->motion.windowID))) { + /* depois de apertar/soltar neste quadro, o movimento fica para o + proximo: o editor precisa ver onde o dedo apertou e onde soltou + (um deslize rapido, como a roda no emulador, cabe num quadro) */ + if (w->in.l_down || w->in.l_up) return false; w->in.mouse_x = (float)ev->motion.x / S; w->in.mouse_y = (float)ev->motion.y / S; w->pos_fresh = 1; @@ -767,8 +773,9 @@ static bool be_apply(SDL_Event* ev) { w->in.mouse_x = (float)ev->button.x / S; w->in.mouse_y = (float)ev->button.y / S; w->pos_fresh = 1; - /* clique repetido no mesmo quadro: espera o proximo */ - if (ev->button.button == SDL_BUTTON_LEFT && (down ? w->in.l_down : w->in.l_up)) return false; + /* uma mudanca do botao esquerdo por quadro: apertar e soltar no + mesmo quadro viram dois (senao o deslize parece toque parado) */ + if (ev->button.button == SDL_BUTTON_LEFT && (w->in.l_down || w->in.l_up)) return false; if (ev->button.button == SDL_BUTTON_LEFT) { if (down) w->in.l_down = 1; else w->in.l_up = 1; } if (ev->button.button == SDL_BUTTON_RIGHT) { if (down) w->in.r_down = 1; else w->in.r_up = 1; } } @@ -920,7 +927,8 @@ static char* be_clipboard_get(void) { /* Captura para conferir o visual sem olhar a tela de ninguem: TINYBLOCKS_SHOT=arquivo.bmp salva a 1a janela depois de - TINYBLOCKS_SHOT_FRAMES quadros (padrao 30) e sai. */ + TINYBLOCKS_SHOT_FRAMES quadros (padrao 30) e sai. Com TINYBLOCKS_SHOT_COUNT=n + (e o caminho com %d), salva n quadros, um a cada TINYBLOCKS_SHOT_STEP. */ static void shot_check(SdlWin* w) { static int frames = 0; static bool done = false; @@ -930,14 +938,23 @@ static void shot_check(SdlWin* w) { while (first && first->next) first = first->next; /* a lista e LIFO */ if (w != first) return; const char* fe = getenv("TINYBLOCKS_SHOT_FRAMES"); - if (++frames < (fe && atoi(fe) > 0 ? atoi(fe) : 30)) return; - done = true; + const char* fc = getenv("TINYBLOCKS_SHOT_COUNT"); /* >1: sequencia (path com %d) */ + const char* fs = getenv("TINYBLOCKS_SHOT_STEP"); + int start = fe && atoi(fe) > 0 ? atoi(fe) : 30, count = fc && atoi(fc) > 1 ? atoi(fc) : 1; + int step = fs && atoi(fs) > 0 ? atoi(fs) : 1; + ++frames; + if (frames < start || (frames - start) % step) return; + int idx = (frames - start) / step; + char name[1200]; + if (count > 1) snprintf(name, sizeof(name), path, idx); else snprintf(name, sizeof(name), "%s", path); int pw = 0, ph = 0; SDL_GetRendererOutputSize(w->ren, &pw, &ph); SDL_Surface* s = SDL_CreateRGBSurfaceWithFormat(0, pw, ph, 32, SDL_PIXELFORMAT_ARGB8888); if (s && SDL_RenderReadPixels(w->ren, NULL, SDL_PIXELFORMAT_ARGB8888, s->pixels, s->pitch) == 0) - SDL_SaveBMP(s, path); + SDL_SaveBMP(s, name); if (s) SDL_FreeSurface(s); + if (idx + 1 < count) return; + done = true; exit(0); /* so para conferir: sai em seguida */ } diff --git a/packaging/android/AndroidManifest.xml b/packaging/android/AndroidManifest.xml index d9afcf4..9821ae0 100644 --- a/packaging/android/AndroidManifest.xml +++ b/packaging/android/AndroidManifest.xml @@ -20,6 +20,9 @@ + + + = 0, "qr: há uma pilha para compartilhar"); + ax_do(hat, TB_A11Y_ACT_MENU); + int menu = ax_in(0, TB_A11Y_MENU, "Menu de contexto"); + ax_do(ax_need(menu, TB_A11Y_MENU_ITEM, "Compartilhar pilha (QR)"), TB_A11Y_ACT_ACTIVATE); + frame(0, 0, 0, 0, 0, 0, NULL); + int dlg = ax_in(0, TB_A11Y_DIALOG, "Compartilhar pilha"); + CHECK(dlg >= 0 && !strncmp(ax_value(ax_in(dlg, TB_A11Y_LABEL, "Parte")), "Parte 1 de ", 11), + "compartilhar: painel com o QR (Parte 1 de N)"); + ax_do(ax_need(dlg, TB_A11Y_BUTTON, "Fechar"), TB_A11Y_ACT_ACTIVATE); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(ax_in(0, TB_A11Y_DIALOG, "Compartilhar pilha") < 0, "compartilhar: Fechar fecha"); + + /* ver o código-fonte: abre a aba de código no arquivo do bloco */ + cat("Caneta"); + ax_drop_at(pal_block("Caneta", "apague tudo"), ws(), 60, 60); + frame(0, 0, 0, 0, 0, 0, NULL); + ax_do(ws_block("apague tudo", 0), TB_A11Y_ACT_MENU); + menu = ax_in(0, TB_A11Y_MENU, "Menu de contexto"); + CHECK(ax_in(menu, TB_A11Y_MENU_ITEM, "Ver código-fonte") >= 0, "menu do bloco: Ver código-fonte"); + ax_do(ax_need(menu, TB_A11Y_MENU_ITEM, "Ver código-fonte"), TB_A11Y_ACT_ACTIVATE); + frame(0, 0, 0, 0, 0, 0, NULL); + int code = ax_in(0, TB_A11Y_TEXT_FIELD, "Código"); + CHECK(code >= 0 && strstr(N(code)->description, "tb_pen.c"), "Ver código-fonte abre o arquivo do bloco"); + + /* receber: numa folha em branco, botão direito no fundo da área */ + ax_do(ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Abas"), TB_A11Y_BUTTON, "Nova aba"), TB_A11Y_ACT_ACTIVATE); + ax_do(ax_in(ax_in(0, TB_A11Y_MENU, "Nova aba"), TB_A11Y_MENU_ITEM, "Blueprint"), TB_A11Y_ACT_ACTIVATE); + frame(0, 0, 0, 0, 0, 0, NULL); + int w = ws(); + float rx = N(w)->x + N(w)->w - 60, ry = N(w)->y + N(w)->h - 60; + frame(rx, ry, 0, 0, 1, 0, NULL); + frame(rx, ry, 0, 0, 0, 0, NULL); + menu = ax_in(0, TB_A11Y_MENU, "Menu de contexto"); + ax_do(ax_need(menu, TB_A11Y_MENU_ITEM, "Receber blocos (QR)"), TB_A11Y_ACT_ACTIVATE); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(ax_in(0, TB_A11Y_DIALOG, "Receber blocos") >= 0, "receber: abre o leitor"); + int before = ws_count("via qr"); + tb_editor_qr_feed(scene, "TB1|beef|2|2|[via qr]\n"); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(!strcmp(ax_value(ax_in(ax_in(0, TB_A11Y_DIALOG, "Receber blocos"), TB_A11Y_STATUS, "Recebimento")), + "Recebidas 1 de 2 partes"), "receber: conta as partes (1 de 2)"); + tb_editor_qr_feed(scene, "TB1|beef|1|2|when flag clicked\nsay "); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(ax_in(0, TB_A11Y_DIALOG, "Receber blocos") < 0 && ws_count("via qr") == before + 1, + "receber: com todas as partes (fora de ordem), os blocos entram"); + frame(rx - 300, ry, 0, 0, 1, 0, NULL); + frame(rx - 300, ry, 0, 0, 0, 0, NULL); + CHECK(ax_in(ax_in(0, TB_A11Y_MENU, "Menu de contexto"), TB_A11Y_MENU_ITEM, "Compartilhar blueprint (QR)") >= 0, + "menu do fundo: Compartilhar blueprint (com blocos na aba)"); + key(TB_KEY_ESCAPE, 0, 0); + } + tinyblocks_deinit(&rt); printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails); return fails != 0; diff --git a/tests/qr_test.c b/tests/qr_test.c new file mode 100644 index 0000000..1a12cd8 --- /dev/null +++ b/tests/qr_test.c @@ -0,0 +1,47 @@ +/* Teste da tinyblocks-qr: gerar um QR, desenhar numa imagem cinza e ler */ +#include +#include +#include +#include + +static int fails = 0; +#define CHECK(c, m) do { if (c) printf("ok %s\n", m); else { printf("FAIL %s\n", m); fails++; } } while (0) + +static char got[4096]; +static void found(const char* t, int n, void* u) { (void)u; snprintf(got, sizeof(got), "%.*s", n, t); } + +/* QR -> imagem cinza: s pixels por modulo, margem de 4 modulos, fundo claro */ +static int roundtrip(const char* text, int s) { + static unsigned char mods[TB_QR_MAX_SIDE * TB_QR_MAX_SIDE]; + int side = tb_qr_encode(text, mods, (int)sizeof(mods)); + if (!side) return 0; + int W = (side + 8) * s, H = W; + unsigned char* img = malloc((size_t)W * H); + memset(img, 230, (size_t)W * H); + for (int y = 0; y < side; y++) + for (int x = 0; x < side; x++) + if (mods[y * side + x]) + for (int dy = 0; dy < s; dy++) + memset(img + (size_t)((y + 4) * s + dy) * W + (x + 4) * s, 25, (size_t)s); + TbQrReader* r = tb_qr_reader_new(); + got[0] = 0; + int n = tb_qr_reader_scan(r, img, W, H, found, NULL); + tb_qr_reader_free(r); + free(img); + return n; +} + +int main(void) { + const char* small = "TB1|a1b2|1|1|when flag clicked\nsay [olá]\n"; + CHECK(roundtrip(small, 4) == 1 && !strcmp(got, small), "QR pequeno (com acento) vai e volta"); + char big[300]; + for (int i = 0; i < 299; i++) big[i] = (char)('a' + i % 26); + big[299] = 0; + CHECK(roundtrip(big, 3) == 1 && !strcmp(got, big), "QR de 299 bytes vai e volta"); + static unsigned char mods[TB_QR_MAX_SIDE * TB_QR_MAX_SIDE]; + char huge[4000]; + memset(huge, 'x', sizeof(huge) - 1); huge[sizeof(huge) - 1] = 0; + CHECK(tb_qr_encode(huge, mods, (int)sizeof(mods)) == 0, "texto grande demais: nao gera"); + printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails); + return fails != 0; +}