Adiciona tinyblocks-blueprint e libraries json/xml/csv; abrir/salvar/exportar projeto
- tinyblocks-blueprint: dona do estado de edicao (abas, pool de blocos, vinculos parent/prel/next/sub/args, blocos compostos e variaveis) e da serializacao. JSON nativo (to/from) usando a AST JSON do core e export JSON/XML/CSV. Testado com round-trip (test-blueprint). - tinyblocks-json: lexer + parser + emissor JSON independentes. - tinyblocks-xml: lexer + parser de XML -> AST JSON do core + emissor. - tinyblocks-csv: divisor de linhas/campos + parser/emissor sobre a AST JSON. - Editor: botoes Abrir / Salvar / Exportar JSON XML CSV no menu; converte Ed <-> TbBlueprint; barra de caminho com modo; .json pode ser arrastado. - Variaveis: tb_variables_clear e tb_variables_set_text. - Harness: teste de salvar/abrir projeto; tests/blueprint_test.c.
This commit is contained in:
1 parent
dc23b92d15
commit
1199d2d7c7
39 files changed
+3462
-24
No files matched your search
@@ -19,6 +19,10 @@ AP_DIR := $(LIBDIR)/tinyblocks-appearance
|
|||||||
PN_DIR := $(LIBDIR)/tinyblocks-pen
|
PN_DIR := $(LIBDIR)/tinyblocks-pen
|
||||||
FS_DIR := $(LIBDIR)/tinyblocks-fs
|
FS_DIR := $(LIBDIR)/tinyblocks-fs
|
||||||
TOML_DIR := $(LIBDIR)/tinyblocks-toml
|
TOML_DIR := $(LIBDIR)/tinyblocks-toml
|
||||||
|
JSON_DIR := $(LIBDIR)/tinyblocks-json
|
||||||
|
XML_DIR := $(LIBDIR)/tinyblocks-xml
|
||||||
|
CSV_DIR := $(LIBDIR)/tinyblocks-csv
|
||||||
|
BP_DIR := $(LIBDIR)/tinyblocks-blueprint
|
||||||
ED_DIR := $(LIBDIR)/tinyblocks-editor
|
ED_DIR := $(LIBDIR)/tinyblocks-editor
|
||||||
GX_DIR := $(LIBDIR)/tinyblocks-graphics
|
GX_DIR := $(LIBDIR)/tinyblocks-graphics
|
||||||
SD_DIR := $(LIBDIR)/tinyblocks-sdl2
|
SD_DIR := $(LIBDIR)/tinyblocks-sdl2
|
||||||
@@ -59,15 +63,20 @@ ED_A := $(ED_DIR)/build/libtinyblocks-editor.a
|
|||||||
GX_A := $(GX_DIR)/build/libtinyblocks-graphics.a
|
GX_A := $(GX_DIR)/build/libtinyblocks-graphics.a
|
||||||
SD_A := $(SD_DIR)/build/libtinyblocks-sdl2.a
|
SD_A := $(SD_DIR)/build/libtinyblocks-sdl2.a
|
||||||
TOML_A := $(TOML_DIR)/build/libtinyblocks-toml.a
|
TOML_A := $(TOML_DIR)/build/libtinyblocks-toml.a
|
||||||
|
JSON_A := $(JSON_DIR)/build/libtinyblocks-json.a
|
||||||
|
XML_A := $(XML_DIR)/build/libtinyblocks-xml.a
|
||||||
|
CSV_A := $(CSV_DIR)/build/libtinyblocks-csv.a
|
||||||
|
BP_A := $(BP_DIR)/build/libtinyblocks-blueprint.a
|
||||||
LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \
|
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)
|
$(foreach l,$(CAT_LIBS),-L$(LIBDIR)/tinyblocks-$(l)/build) -L$(BUILD)
|
||||||
|
|
||||||
.PHONY: all help debug release static shared example sdl2 clean run python-lib mcp-lib json \
|
.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 \
|
editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \
|
||||||
test-toml test-plugin \
|
test-toml test-plugin test-blueprint \
|
||||||
category-libs category-sos libs \
|
category-libs category-sos libs \
|
||||||
lib-events lib-control lib-operators lib-variables lib-appearance lib-pen lib-fs \
|
lib-events lib-control lib-operators lib-variables lib-appearance lib-pen lib-fs \
|
||||||
lib-editor lib-graphics lib-sdl2 lib-python lib-mcp lib-toml
|
lib-editor lib-graphics lib-sdl2 lib-python lib-mcp lib-toml \
|
||||||
|
lib-json lib-xml lib-csv lib-blueprint
|
||||||
|
|
||||||
all: static example ## Compila a biblioteca estática e o exemplo hello (padrão)
|
all: static example ## Compila a biblioteca estática e o exemplo hello (padrão)
|
||||||
|
|
||||||
@@ -130,6 +139,18 @@ lib-editor:
|
|||||||
lib-toml:
|
lib-toml:
|
||||||
$(MAKE) -C $(TOML_DIR)
|
$(MAKE) -C $(TOML_DIR)
|
||||||
|
|
||||||
|
lib-json:
|
||||||
|
$(MAKE) -C $(JSON_DIR)
|
||||||
|
|
||||||
|
lib-xml:
|
||||||
|
$(MAKE) -C $(XML_DIR)
|
||||||
|
|
||||||
|
lib-csv:
|
||||||
|
$(MAKE) -C $(CSV_DIR)
|
||||||
|
|
||||||
|
lib-blueprint:
|
||||||
|
$(MAKE) -C $(BP_DIR)
|
||||||
|
|
||||||
lib-graphics:
|
lib-graphics:
|
||||||
$(MAKE) -C $(GX_DIR)
|
$(MAKE) -C $(GX_DIR)
|
||||||
|
|
||||||
@@ -143,8 +164,9 @@ lib-mcp:
|
|||||||
$(MAKE) -C $(MC_DIR)
|
$(MAKE) -C $(MC_DIR)
|
||||||
|
|
||||||
libs: static lib-events lib-control lib-operators lib-variables \
|
libs: static lib-events lib-control lib-operators lib-variables \
|
||||||
lib-appearance lib-pen lib-fs lib-graphics lib-sdl2 lib-toml lib-editor
|
lib-appearance lib-pen lib-fs lib-graphics lib-sdl2 lib-toml \
|
||||||
@echo "Libraries OK: category + graphics + sdl2 + toml + editor"
|
lib-json lib-xml lib-csv lib-blueprint lib-editor
|
||||||
|
@echo "Libraries OK: category + graphics + sdl2 + toml + json + xml + csv + blueprint + editor"
|
||||||
|
|
||||||
category-libs: static $(foreach l,$(CAT_LIBS),lib-$(l)) ## Compila as libraries de categoria (.a/.so)
|
category-libs: static $(foreach l,$(CAT_LIBS),lib-$(l)) ## Compila as libraries de categoria (.a/.so)
|
||||||
@echo "Build category libs OK"
|
@echo "Build category libs OK"
|
||||||
@@ -180,8 +202,9 @@ $(BUILD)/editor: examples/editor/main.c static libs
|
|||||||
$(CC) $(CFLAGS_REL) \
|
$(CC) $(CFLAGS_REL) \
|
||||||
-I$(ED_DIR)/include -I$(GFX_INC) $(CAT_INCS) \
|
-I$(ED_DIR)/include -I$(GFX_INC) $(CAT_INCS) \
|
||||||
-I$(FS_DIR)/include -I$(TOML_DIR)/include \
|
-I$(FS_DIR)/include -I$(TOML_DIR)/include \
|
||||||
|
-I$(JSON_DIR)/include -I$(XML_DIR)/include -I$(CSV_DIR)/include -I$(BP_DIR)/include \
|
||||||
$< -o $@ \
|
$< -o $@ \
|
||||||
-Wl,--start-group $(ED_A) $(GX_A) $(SD_A) $(TOML_A) $(CAT_A) $(LIB_A) -Wl,--end-group \
|
-Wl,--start-group $(ED_A) $(GX_A) $(SD_A) $(TOML_A) $(JSON_A) $(XML_A) $(CSV_A) $(BP_A) $(CAT_A) $(LIB_A) -Wl,--end-group \
|
||||||
$(SDL2_LIBS) $(SDL2TTF_LIBS) -ldl -lm -rdynamic \
|
$(SDL2_LIBS) $(SDL2TTF_LIBS) -ldl -lm -rdynamic \
|
||||||
'-Wl,-rpath,$$ORIGIN'
|
'-Wl,-rpath,$$ORIGIN'
|
||||||
|
|
||||||
@@ -251,10 +274,11 @@ $(BUILD)/editor_harness: tests/editor_harness.c $(SRCS) \
|
|||||||
$(GX_DIR)/src/tb_graphics.c
|
$(GX_DIR)/src/tb_graphics.c
|
||||||
@mkdir -p $(BUILD)
|
@mkdir -p $(BUILD)
|
||||||
$(CC) $(CFLAGS_DBG) \
|
$(CC) $(CFLAGS_DBG) \
|
||||||
-I$(ED_DIR)/include -I$(EDITOR_SRC) -I$(GFX_INC) $(CAT_INCS) \
|
-I$(ED_DIR)/include -I$(EDITOR_SRC) -I$(GFX_INC) $(CAT_INCS) -I$(BP_DIR)/include \
|
||||||
$(SRCS) \
|
$(SRCS) \
|
||||||
$(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage_widget.c \
|
$(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage_widget.c \
|
||||||
$(GX_DIR)/src/tb_graphics.c \
|
$(GX_DIR)/src/tb_graphics.c \
|
||||||
|
$(BP_DIR)/src/blueprint.c $(BP_DIR)/src/serialize.c \
|
||||||
$(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/src/tb_$(l).c) \
|
$(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/src/tb_$(l).c) \
|
||||||
tests/editor_harness.c -o $@ -ldl -lm
|
tests/editor_harness.c -o $@ -ldl -lm
|
||||||
|
|
||||||
@@ -271,6 +295,17 @@ $(BUILD)/toml_test: tests/toml_test.c $(TOML_LIB_SRCS) $(TOML_DIR)/include/ast.h
|
|||||||
test-toml: $(BUILD)/toml_test ## Roda o teste do parser TOML (ASan/UBSan)
|
test-toml: $(BUILD)/toml_test ## Roda o teste do parser TOML (ASan/UBSan)
|
||||||
./$(BUILD)/toml_test
|
./$(BUILD)/toml_test
|
||||||
|
|
||||||
|
# -- Teste da blueprint (modelo + serializacao) ---
|
||||||
|
BP_LIB_SRCS := $(BP_DIR)/src/blueprint.c $(BP_DIR)/src/serialize.c
|
||||||
|
|
||||||
|
$(BUILD)/blueprint_test: tests/blueprint_test.c $(BP_LIB_SRCS) static
|
||||||
|
@mkdir -p $(BUILD)
|
||||||
|
$(CC) $(CFLAGS_DBG) -I$(BP_DIR)/include $(BP_LIB_SRCS) tests/blueprint_test.c -o $@ \
|
||||||
|
-Wl,--start-group $(LIB_A) -Wl,--end-group
|
||||||
|
|
||||||
|
test-blueprint: $(BUILD)/blueprint_test ## Roda o teste da blueprint (ASan/UBSan)
|
||||||
|
./$(BUILD)/blueprint_test
|
||||||
|
|
||||||
# -- Teste de plugin .so standalone ---
|
# -- Teste de plugin .so standalone ---
|
||||||
FS_SO := $(FS_DIR)/build/libtinyblocks-fs.so
|
FS_SO := $(FS_DIR)/build/libtinyblocks-fs.so
|
||||||
|
|
||||||
@@ -286,7 +321,8 @@ test-plugin: $(BUILD)/plugin_test ## Carrega library-fs .so via dlopen e testa
|
|||||||
clean: ## Remove os diretórios build/ (raiz e libraries)
|
clean: ## Remove os diretórios build/ (raiz e libraries)
|
||||||
$(RM) -r $(BUILD)
|
$(RM) -r $(BUILD)
|
||||||
@for d in $(EV_DIR) $(CT_DIR) $(OP_DIR) $(VR_DIR) $(AP_DIR) $(PN_DIR) $(FS_DIR) \
|
@for d in $(EV_DIR) $(CT_DIR) $(OP_DIR) $(VR_DIR) $(AP_DIR) $(PN_DIR) $(FS_DIR) \
|
||||||
$(TOML_DIR) $(ED_DIR) $(GX_DIR) $(SD_DIR) $(PY_DIR) $(MC_DIR); do \
|
$(TOML_DIR) $(JSON_DIR) $(XML_DIR) $(CSV_DIR) $(BP_DIR) \
|
||||||
|
$(ED_DIR) $(GX_DIR) $(SD_DIR) $(PY_DIR) $(MC_DIR); do \
|
||||||
$(MAKE) -C $$d clean >/dev/null 2>&1 || true; \
|
$(MAKE) -C $$d clean >/dev/null 2>&1 || true; \
|
||||||
done
|
done
|
||||||
$(RM) $(MC_DIR)/src/tb_mcp_py.h
|
$(RM) $(MC_DIR)/src/tb_mcp_py.h
|
||||||
@@ -26,6 +26,10 @@
|
|||||||
#include <tb_pen.h>
|
#include <tb_pen.h>
|
||||||
#include <tb_fs.h>
|
#include <tb_fs.h>
|
||||||
#include <tb_toml.h>
|
#include <tb_toml.h>
|
||||||
|
#include <tb_json.h>
|
||||||
|
#include <tb_xml.h>
|
||||||
|
#include <tb_csv.h>
|
||||||
|
#include <tb_blueprint.h>
|
||||||
|
|
||||||
int main(int argc, char** argv) {
|
int main(int argc, char** argv) {
|
||||||
TinyBlocks* rt = NULL;
|
TinyBlocks* rt = NULL;
|
||||||
@@ -49,6 +53,10 @@ int main(int argc, char** argv) {
|
|||||||
tb_library_register(rt, tb_pen_get_library());
|
tb_library_register(rt, tb_pen_get_library());
|
||||||
tb_library_register(rt, tb_fs_get_library());
|
tb_library_register(rt, tb_fs_get_library());
|
||||||
tb_library_register(rt, tb_toml_get_library());
|
tb_library_register(rt, tb_toml_get_library());
|
||||||
|
tb_library_register(rt, tb_json_get_library());
|
||||||
|
tb_library_register(rt, tb_xml_get_library());
|
||||||
|
tb_library_register(rt, tb_csv_get_library());
|
||||||
|
tb_library_register(rt, tb_blueprint_get_library());
|
||||||
|
|
||||||
/* Interface gráfica: o editor mede texto e cria o palco ao nascer */
|
/* Interface gráfica: o editor mede texto e cria o palco ao nascer */
|
||||||
tb_library_register(rt, tb_graphics_get_library());
|
tb_library_register(rt, tb_graphics_get_library());
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Makefile da library blueprint (modelo de edicao + serializacao)
|
||||||
|
CC := gcc
|
||||||
|
BUILD := build
|
||||||
|
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||||
|
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude
|
||||||
|
|
||||||
|
OBJS := $(BUILD)/blueprint.o $(BUILD)/serialize.o $(BUILD)/tb_blueprint.o
|
||||||
|
LIB_A := $(BUILD)/libtinyblocks-blueprint.a
|
||||||
|
LIB_SO := $(BUILD)/libtinyblocks-blueprint.so
|
||||||
|
|
||||||
|
.PHONY: all static shared clean
|
||||||
|
all: static shared
|
||||||
|
static: $(LIB_A)
|
||||||
|
shared: $(LIB_SO)
|
||||||
|
|
||||||
|
$(BUILD)/blueprint.o: src/blueprint.c include/blueprint.h
|
||||||
|
@mkdir -p $(BUILD)
|
||||||
|
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||||
|
$(BUILD)/serialize.o: src/serialize.c include/blueprint.h
|
||||||
|
@mkdir -p $(BUILD)
|
||||||
|
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||||
|
$(BUILD)/tb_blueprint.o: src/tb_blueprint.c include/tb_blueprint.h include/blueprint.h
|
||||||
|
@mkdir -p $(BUILD)
|
||||||
|
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||||
|
|
||||||
|
$(LIB_A): $(OBJS)
|
||||||
|
ar rcs $@ $^
|
||||||
|
$(LIB_SO): $(OBJS)
|
||||||
|
$(CC) -shared -o $@ $^
|
||||||
|
|
||||||
|
clean:
|
||||||
|
$(RM) -r $(BUILD)
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-blueprint / include/blueprint.h
|
||||||
|
*
|
||||||
|
* TbBlueprint e o modelo de um "projeto" do editor (estilo Scratch):
|
||||||
|
* - abas (TbBpTab) com um pool estavel de blocos (TbBpBlock);
|
||||||
|
* - vinculos entre blocos por indice: parent/prel, next, sub[2], args[];
|
||||||
|
* - definicoes de blocos compostos (TbBpUserBlock);
|
||||||
|
* - variaveis (TbBpVar).
|
||||||
|
*
|
||||||
|
* A library e dona do estado de edicao e da logica de serializacao:
|
||||||
|
* converter para/de JSON (formato nativo) e exportar JSON/XML/CSV.
|
||||||
|
*
|
||||||
|
* A AST usada na serializacao e a do core (TinyBlocks_JsonValue).
|
||||||
|
*/
|
||||||
|
#ifndef TB_BLUEPRINT_H
|
||||||
|
#define TB_BLUEPRINT_H
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <tinyblocks/tb_json_block.h>
|
||||||
|
|
||||||
|
#define TB_BP_MAX_WS 256
|
||||||
|
#define TB_BP_MAX_INPUTS 16
|
||||||
|
#define TB_BP_MAX_TABS 8
|
||||||
|
#define TB_BP_MAX_UBLOCKS 16
|
||||||
|
#define TB_BP_MAX_UPARTS 16
|
||||||
|
#define TB_BP_MAX_USLOTS 8
|
||||||
|
#define TB_BP_MAX_VARS 64
|
||||||
|
#define TB_BP_LIT_CAP 512
|
||||||
|
|
||||||
|
/* Formatos de serializacao */
|
||||||
|
enum { TB_BP_FMT_JSON, TB_BP_FMT_XML, TB_BP_FMT_CSV };
|
||||||
|
|
||||||
|
/* Relacao de um bloco com o pai (identica ao editor) */
|
||||||
|
#define TB_BP_REL_NONE (-1)
|
||||||
|
#define TB_BP_REL_NEXT 0
|
||||||
|
#define TB_BP_REL_SUB0 1
|
||||||
|
#define TB_BP_REL_ARG0 3
|
||||||
|
|
||||||
|
/* -- Blocos e abas --- */
|
||||||
|
typedef struct {
|
||||||
|
bool used;
|
||||||
|
char type[64]; /* "Events.WhenRun", "User.X", ... */
|
||||||
|
float x, y;
|
||||||
|
int parent, prel;
|
||||||
|
int next;
|
||||||
|
int sub[2];
|
||||||
|
int args[TB_BP_MAX_INPUTS];
|
||||||
|
char in_text[TB_BP_MAX_INPUTS][64];
|
||||||
|
char lit[TB_BP_LIT_CAP];
|
||||||
|
} TbBpBlock;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
TbBpBlock blocks[TB_BP_MAX_WS];
|
||||||
|
int top[TB_BP_MAX_WS];
|
||||||
|
int top_n;
|
||||||
|
float ws_sx, ws_sy;
|
||||||
|
char name[48];
|
||||||
|
bool composite;
|
||||||
|
int comp_id; /* indice em user_blocks, ou -1 */
|
||||||
|
int color_idx;
|
||||||
|
} TbBpTab;
|
||||||
|
|
||||||
|
/* -- Blocos compostos (protótipo) --- */
|
||||||
|
typedef enum { TB_BP_PARAM_NUM, TB_BP_PARAM_BOOL, TB_BP_PARAM_LABEL } TbBpParamKind;
|
||||||
|
typedef struct { TbBpParamKind kind; char name[32]; } TbBpParam;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
char name[48];
|
||||||
|
int input_count, output_count;
|
||||||
|
char input_names[TB_BP_MAX_USLOTS][32];
|
||||||
|
char output_names[TB_BP_MAX_USLOTS][32];
|
||||||
|
TbBpParam parts[TB_BP_MAX_UPARTS];
|
||||||
|
int part_n;
|
||||||
|
int color_idx;
|
||||||
|
int tab_idx;
|
||||||
|
} TbBpUserBlock;
|
||||||
|
|
||||||
|
/* -- Variaveis --- */
|
||||||
|
typedef enum { TB_BP_VAL_INT, TB_BP_VAL_REAL, TB_BP_VAL_TEXT } TbBpValueKind;
|
||||||
|
typedef struct {
|
||||||
|
char name[32];
|
||||||
|
TbBpValueKind kind;
|
||||||
|
double num;
|
||||||
|
char text[128];
|
||||||
|
} TbBpVar;
|
||||||
|
|
||||||
|
/* -- Documento --- */
|
||||||
|
typedef struct {
|
||||||
|
TbBpTab tabs[TB_BP_MAX_TABS];
|
||||||
|
int tab_count;
|
||||||
|
TbBpUserBlock user_blocks[TB_BP_MAX_UBLOCKS];
|
||||||
|
int user_block_n;
|
||||||
|
TbBpVar vars[TB_BP_MAX_VARS];
|
||||||
|
int var_n;
|
||||||
|
int cur_tab;
|
||||||
|
} TbBlueprint;
|
||||||
|
|
||||||
|
/* -- Ciclo de vida / edicao --- */
|
||||||
|
TbBlueprint* tb_blueprint_new(void);
|
||||||
|
void tb_blueprint_free(TbBlueprint* bp);
|
||||||
|
void tb_blueprint_clear(TbBlueprint* bp);
|
||||||
|
|
||||||
|
/* Cria uma aba; devolve o indice ou -1. */
|
||||||
|
int tb_blueprint_add_tab(TbBlueprint* bp, const char* name, bool composite);
|
||||||
|
TbBpTab* tb_blueprint_tab(TbBlueprint* bp, int i);
|
||||||
|
|
||||||
|
/* Aloca um bloco no pool da aba; devolve o indice ou -1. */
|
||||||
|
int tb_blueprint_alloc_block(TbBpTab* t);
|
||||||
|
/* Liga child ao pai na relacao rel (child < 0 desliga). */
|
||||||
|
void tb_blueprint_link(TbBpTab* t, int parent, int rel, int child);
|
||||||
|
void tb_blueprint_top_add(TbBpTab* t, int bi);
|
||||||
|
|
||||||
|
/* Variaveis */
|
||||||
|
void tb_blueprint_var_set_text(TbBlueprint* bp, const char* name, const char* value);
|
||||||
|
|
||||||
|
/* -- Serializacao --- */
|
||||||
|
/* Formato nativo (JSON). to_json devolve ref nova; from_json nao consome 'root'. */
|
||||||
|
TinyBlocks_JsonValue* tb_blueprint_to_json(const TbBlueprint* bp);
|
||||||
|
TbBlueprint* tb_blueprint_from_json(const TinyBlocks_JsonValue* root);
|
||||||
|
|
||||||
|
/* Serializa para texto no formato pedido (malloc; libere com free). */
|
||||||
|
char* tb_blueprint_serialize(const TbBlueprint* bp, int fmt, bool pretty);
|
||||||
|
/* Le do texto. Suporta o formato nativo (JSON). */
|
||||||
|
TbBlueprint* tb_blueprint_parse(const char* text, int fmt, char* err, size_t errcap);
|
||||||
|
|
||||||
|
/* Arquivos */
|
||||||
|
bool tb_blueprint_save_file(const TbBlueprint* bp, const char* path, int fmt, bool pretty);
|
||||||
|
TbBlueprint* tb_blueprint_load_file(const char* path, char* err, size_t errcap);
|
||||||
|
const char* tb_blueprint_format_name(int fmt); /* "json"/"xml"/"csv" */
|
||||||
|
|
||||||
|
#endif /* TB_BLUEPRINT_H */
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tb_blueprint.h
|
||||||
|
* Library tinyblocks-blueprint: modelo de edicao (blueprint) e serializacao.
|
||||||
|
*/
|
||||||
|
#ifndef TINYBLOCKS_BLUEPRINT_H
|
||||||
|
#define TINYBLOCKS_BLUEPRINT_H
|
||||||
|
|
||||||
|
#include <tinyblocks/tinyblocks.h>
|
||||||
|
#include "blueprint.h"
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
TB_API const TinyBlocks_LibraryDescriptor* tb_blueprint_get_library(void);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* TINYBLOCKS_BLUEPRINT_H */
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Metadados da library blueprint.
|
||||||
|
[library]
|
||||||
|
name = "tinyblocks-blueprint"
|
||||||
|
version = "1.0.0"
|
||||||
|
category = "Blueprint"
|
||||||
|
description = "Modelo de edicao (abas/blocos/variaveis) e serializacao JSON/XML/CSV"
|
||||||
|
color = [110, 140, 255, 255]
|
||||||
|
dark = [70, 95, 210, 255]
|
||||||
|
|
||||||
|
[build]
|
||||||
|
sources = ["src/blueprint.c", "src/serialize.c", "src/tb_blueprint.c"]
|
||||||
|
includes = ["include"]
|
||||||
|
shared = "build/libtinyblocks-blueprint.so"
|
||||||
|
static = "build/libtinyblocks-blueprint.a"
|
||||||
|
depends = []
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-blueprint / src/blueprint.c
|
||||||
|
* Gestao do modelo de edicao (abas, blocos, vinculos, variaveis).
|
||||||
|
*/
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
#include "blueprint.h"
|
||||||
|
|
||||||
|
TbBlueprint* tb_blueprint_new(void) {
|
||||||
|
TbBlueprint* bp = (TbBlueprint*)calloc(1, sizeof(TbBlueprint));
|
||||||
|
if (!bp) return NULL;
|
||||||
|
tb_blueprint_clear(bp);
|
||||||
|
return bp;
|
||||||
|
}
|
||||||
|
|
||||||
|
void tb_blueprint_free(TbBlueprint* bp) {
|
||||||
|
free(bp);
|
||||||
|
}
|
||||||
|
|
||||||
|
void tb_blueprint_clear(TbBlueprint* bp) {
|
||||||
|
if (!bp) return;
|
||||||
|
memset(bp, 0, sizeof(*bp));
|
||||||
|
for (int i = 0; i < TB_BP_MAX_TABS; i++) {
|
||||||
|
TbBpTab* t = &bp->tabs[i];
|
||||||
|
t->comp_id = -1;
|
||||||
|
for (int b = 0; b < TB_BP_MAX_WS; b++) {
|
||||||
|
t->blocks[b].parent = -1;
|
||||||
|
t->blocks[b].prel = TB_BP_REL_NONE;
|
||||||
|
t->blocks[b].next = -1;
|
||||||
|
t->blocks[b].sub[0] = t->blocks[b].sub[1] = -1;
|
||||||
|
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) t->blocks[b].args[s] = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int u = 0; u < TB_BP_MAX_UBLOCKS; u++) bp->user_blocks[u].tab_idx = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int tb_blueprint_add_tab(TbBlueprint* bp, const char* name, bool composite) {
|
||||||
|
if (!bp || bp->tab_count >= TB_BP_MAX_TABS) return -1;
|
||||||
|
int idx = bp->tab_count++;
|
||||||
|
TbBpTab* t = &bp->tabs[idx];
|
||||||
|
memset(t, 0, sizeof(*t));
|
||||||
|
t->comp_id = -1;
|
||||||
|
t->composite = composite;
|
||||||
|
if (name && name[0]) snprintf(t->name, sizeof(t->name), "%s", name);
|
||||||
|
else snprintf(t->name, sizeof(t->name), "Codigo %d", idx + 1);
|
||||||
|
for (int b = 0; b < TB_BP_MAX_WS; b++) {
|
||||||
|
t->blocks[b].parent = -1;
|
||||||
|
t->blocks[b].prel = TB_BP_REL_NONE;
|
||||||
|
t->blocks[b].next = -1;
|
||||||
|
t->blocks[b].sub[0] = t->blocks[b].sub[1] = -1;
|
||||||
|
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) t->blocks[b].args[s] = -1;
|
||||||
|
}
|
||||||
|
return idx;
|
||||||
|
}
|
||||||
|
|
||||||
|
TbBpTab* tb_blueprint_tab(TbBlueprint* bp, int i) {
|
||||||
|
if (!bp || i < 0 || i >= bp->tab_count) return NULL;
|
||||||
|
return &bp->tabs[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
int tb_blueprint_alloc_block(TbBpTab* t) {
|
||||||
|
if (!t) return -1;
|
||||||
|
for (int i = 0; i < TB_BP_MAX_WS; i++) {
|
||||||
|
if (t->blocks[i].used) continue;
|
||||||
|
TbBpBlock* b = &t->blocks[i];
|
||||||
|
memset(b, 0, sizeof(*b));
|
||||||
|
b->used = true;
|
||||||
|
b->parent = -1;
|
||||||
|
b->prel = TB_BP_REL_NONE;
|
||||||
|
b->next = -1;
|
||||||
|
b->sub[0] = b->sub[1] = -1;
|
||||||
|
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) b->args[s] = -1;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
void tb_blueprint_link(TbBpTab* t, int parent, int rel, int child) {
|
||||||
|
if (!t || parent < 0 || parent >= TB_BP_MAX_WS) return;
|
||||||
|
TbBpBlock* p = &t->blocks[parent];
|
||||||
|
if (rel == TB_BP_REL_NEXT) p->next = child;
|
||||||
|
else if (rel < TB_BP_REL_ARG0) p->sub[rel - TB_BP_REL_SUB0] = child;
|
||||||
|
else p->args[rel - TB_BP_REL_ARG0] = child;
|
||||||
|
if (child >= 0 && child < TB_BP_MAX_WS) {
|
||||||
|
t->blocks[child].parent = parent;
|
||||||
|
t->blocks[child].prel = rel;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void tb_blueprint_top_add(TbBpTab* t, int bi) {
|
||||||
|
if (!t) return;
|
||||||
|
for (int i = 0; i < t->top_n; i++) {
|
||||||
|
if (t->top[i] != bi) continue;
|
||||||
|
memmove(&t->top[i], &t->top[i + 1], (size_t)(t->top_n - i - 1) * sizeof(int));
|
||||||
|
t->top_n--;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (t->top_n < TB_BP_MAX_WS) t->top[t->top_n++] = bi;
|
||||||
|
}
|
||||||
|
|
||||||
|
void tb_blueprint_var_set_text(TbBlueprint* bp, const char* name, const char* value) {
|
||||||
|
if (!bp || !name || !name[0]) return;
|
||||||
|
int idx = -1;
|
||||||
|
for (int i = 0; i < bp->var_n; i++)
|
||||||
|
if (strcmp(bp->vars[i].name, name) == 0) { idx = i; break; }
|
||||||
|
if (idx < 0) {
|
||||||
|
if (bp->var_n >= TB_BP_MAX_VARS) return;
|
||||||
|
idx = bp->var_n++;
|
||||||
|
memset(&bp->vars[idx], 0, sizeof(bp->vars[idx]));
|
||||||
|
snprintf(bp->vars[idx].name, sizeof(bp->vars[idx].name), "%s", name);
|
||||||
|
}
|
||||||
|
TbBpVar* v = &bp->vars[idx];
|
||||||
|
const char* s = value ? value : "";
|
||||||
|
char* end = NULL;
|
||||||
|
long long iv = strtoll(s, &end, 10);
|
||||||
|
if (end && *end == 0 && end != s) { v->kind = TB_BP_VAL_INT; v->num = (double)iv; v->text[0] = 0; return; }
|
||||||
|
double dv = strtod(s, &end);
|
||||||
|
if (end && *end == 0 && end != s) { v->kind = TB_BP_VAL_REAL; v->num = dv; v->text[0] = 0; return; }
|
||||||
|
v->kind = TB_BP_VAL_TEXT;
|
||||||
|
snprintf(v->text, sizeof(v->text), "%s", s);
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* tb_blueprint_format_name(int fmt) {
|
||||||
|
switch (fmt) {
|
||||||
|
case TB_BP_FMT_XML: return "xml";
|
||||||
|
case TB_BP_FMT_CSV: return "csv";
|
||||||
|
default: return "json";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,572 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-blueprint / src/serialize.c
|
||||||
|
* JSON nativo (to/from), exportacao JSON/XML/CSV e I/O de arquivo.
|
||||||
|
*/
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
#include "blueprint.h"
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Blueprint -> arvore JSON (formato nativo)
|
||||||
|
* ============================================================ */
|
||||||
|
#define PUT(o, k, val) do { TinyBlocks_JsonValue* _v = (val); tb_json_object_set((o), (k), _v); tb_json_release(_v); } while (0)
|
||||||
|
|
||||||
|
static TinyBlocks_JsonValue* jstr_arr_of(const char names[][32], int n) {
|
||||||
|
TinyBlocks_JsonValue* a = tb_json_array();
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
TinyBlocks_JsonValue* v = tb_json_string(names[i]);
|
||||||
|
tb_json_array_push(a, v);
|
||||||
|
tb_json_release(v);
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* tb_blueprint_to_json(const TbBlueprint* bp) {
|
||||||
|
if (!bp) return NULL;
|
||||||
|
TinyBlocks_JsonValue* root = tb_json_object();
|
||||||
|
if (!root) return NULL;
|
||||||
|
PUT(root, "format", tb_json_string("tinyblocks-project"));
|
||||||
|
PUT(root, "version", tb_json_number(1));
|
||||||
|
PUT(root, "cur_tab", tb_json_number(bp->cur_tab));
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* tabs = tb_json_array();
|
||||||
|
PUT(root, "tabs", tabs);
|
||||||
|
for (int ti = 0; ti < bp->tab_count; ti++) {
|
||||||
|
const TbBpTab* T = &bp->tabs[ti];
|
||||||
|
TinyBlocks_JsonValue* jt = tb_json_object();
|
||||||
|
PUT(jt, "name", tb_json_string(T->name));
|
||||||
|
PUT(jt, "composite", tb_json_bool(T->composite));
|
||||||
|
PUT(jt, "comp_id", tb_json_number(T->comp_id));
|
||||||
|
PUT(jt, "color", tb_json_number(T->color_idx));
|
||||||
|
PUT(jt, "ws_sx", tb_json_number(T->ws_sx));
|
||||||
|
PUT(jt, "ws_sy", tb_json_number(T->ws_sy));
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* jb = tb_json_array();
|
||||||
|
PUT(jt, "blocks", jb);
|
||||||
|
for (int i = 0; i < TB_BP_MAX_WS; i++) {
|
||||||
|
const TbBpBlock* b = &T->blocks[i];
|
||||||
|
if (!b->used) continue;
|
||||||
|
TinyBlocks_JsonValue* o = tb_json_object();
|
||||||
|
PUT(o, "i", tb_json_number(i));
|
||||||
|
PUT(o, "type", tb_json_string(b->type));
|
||||||
|
PUT(o, "x", tb_json_number(b->x));
|
||||||
|
PUT(o, "y", tb_json_number(b->y));
|
||||||
|
PUT(o, "parent", tb_json_number(b->parent));
|
||||||
|
PUT(o, "prel", tb_json_number(b->prel));
|
||||||
|
PUT(o, "next", tb_json_number(b->next));
|
||||||
|
TinyBlocks_JsonValue* sub = tb_json_array();
|
||||||
|
for (int k = 0; k < 2; k++) { TinyBlocks_JsonValue* e = tb_json_number(b->sub[k]); tb_json_array_push(sub, e); tb_json_release(e); }
|
||||||
|
PUT(o, "sub", sub);
|
||||||
|
TinyBlocks_JsonValue* args = tb_json_array();
|
||||||
|
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) { TinyBlocks_JsonValue* e = tb_json_number(b->args[s]); tb_json_array_push(args, e); tb_json_release(e); }
|
||||||
|
PUT(o, "args", args);
|
||||||
|
TinyBlocks_JsonValue* txt = tb_json_array();
|
||||||
|
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) { TinyBlocks_JsonValue* e = tb_json_string(b->in_text[s]); tb_json_array_push(txt, e); tb_json_release(e); }
|
||||||
|
PUT(o, "in_text", txt);
|
||||||
|
PUT(o, "lit", tb_json_string(b->lit));
|
||||||
|
tb_json_array_push(jb, o);
|
||||||
|
tb_json_release(o);
|
||||||
|
}
|
||||||
|
TinyBlocks_JsonValue* top = tb_json_array();
|
||||||
|
PUT(jt, "top", top);
|
||||||
|
for (int i = 0; i < T->top_n; i++) { TinyBlocks_JsonValue* e = tb_json_number(T->top[i]); tb_json_array_push(top, e); tb_json_release(e); }
|
||||||
|
tb_json_array_push(tabs, jt);
|
||||||
|
tb_json_release(jt);
|
||||||
|
}
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* ubs = tb_json_array();
|
||||||
|
PUT(root, "user_blocks", ubs);
|
||||||
|
for (int u = 0; u < bp->user_block_n; u++) {
|
||||||
|
const TbBpUserBlock* d = &bp->user_blocks[u];
|
||||||
|
TinyBlocks_JsonValue* jo = tb_json_object();
|
||||||
|
PUT(jo, "name", tb_json_string(d->name));
|
||||||
|
PUT(jo, "color", tb_json_number(d->color_idx));
|
||||||
|
PUT(jo, "tab", tb_json_number(d->tab_idx));
|
||||||
|
PUT(jo, "inputs", jstr_arr_of(d->input_names, d->input_count));
|
||||||
|
PUT(jo, "outputs", jstr_arr_of(d->output_names, d->output_count));
|
||||||
|
TinyBlocks_JsonValue* parts = tb_json_array();
|
||||||
|
for (int i = 0; i < d->part_n; i++) {
|
||||||
|
TinyBlocks_JsonValue* po = tb_json_object();
|
||||||
|
PUT(po, "kind", tb_json_number(d->parts[i].kind));
|
||||||
|
PUT(po, "name", tb_json_string(d->parts[i].name));
|
||||||
|
tb_json_array_push(parts, po);
|
||||||
|
tb_json_release(po);
|
||||||
|
}
|
||||||
|
PUT(jo, "parts", parts);
|
||||||
|
tb_json_array_push(ubs, jo);
|
||||||
|
tb_json_release(jo);
|
||||||
|
}
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* vars = tb_json_array();
|
||||||
|
PUT(root, "variables", vars);
|
||||||
|
for (int i = 0; i < bp->var_n; i++) {
|
||||||
|
const TbBpVar* v = &bp->vars[i];
|
||||||
|
TinyBlocks_JsonValue* jo = tb_json_object();
|
||||||
|
PUT(jo, "name", tb_json_string(v->name));
|
||||||
|
PUT(jo, "kind", tb_json_number(v->kind));
|
||||||
|
PUT(jo, "num", tb_json_number(v->num));
|
||||||
|
PUT(jo, "text", tb_json_string(v->text));
|
||||||
|
tb_json_array_push(vars, jo);
|
||||||
|
tb_json_release(jo);
|
||||||
|
}
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Arvore JSON -> Blueprint
|
||||||
|
* ============================================================ */
|
||||||
|
static const char* jget_str(const TinyBlocks_JsonValue* o, const char* k, const char* def) {
|
||||||
|
TinyBlocks_JsonValue* v = tb_json_object_get(o, k);
|
||||||
|
const char* s = v ? tb_json_as_string(v) : NULL;
|
||||||
|
tb_json_release(v);
|
||||||
|
return s ? s : def;
|
||||||
|
}
|
||||||
|
static double jget_num(const TinyBlocks_JsonValue* o, const char* k, double def) {
|
||||||
|
TinyBlocks_JsonValue* v = tb_json_object_get(o, k);
|
||||||
|
double d = v ? tb_json_as_number(v, def) : def;
|
||||||
|
tb_json_release(v);
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
static bool jget_bool(const TinyBlocks_JsonValue* o, const char* k, bool def) {
|
||||||
|
TinyBlocks_JsonValue* v = tb_json_object_get(o, k);
|
||||||
|
bool b = v ? tb_json_as_bool(v, def) : def;
|
||||||
|
tb_json_release(v);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
static void jcopy_names(const TinyBlocks_JsonValue* o, const char* k, char names[][32], int max, int* n) {
|
||||||
|
*n = 0;
|
||||||
|
TinyBlocks_JsonValue* a = tb_json_object_get(o, k);
|
||||||
|
for (uint32_t i = 0; a && i < tb_json_array_length(a) && *n < max; i++) {
|
||||||
|
TinyBlocks_JsonValue* e = tb_json_array_get(a, i);
|
||||||
|
const char* s = e ? tb_json_as_string(e) : NULL;
|
||||||
|
snprintf(names[*n], 32, "%.31s", s ? s : "");
|
||||||
|
(*n)++;
|
||||||
|
tb_json_release(e);
|
||||||
|
}
|
||||||
|
tb_json_release(a);
|
||||||
|
}
|
||||||
|
|
||||||
|
TbBlueprint* tb_blueprint_from_json(const TinyBlocks_JsonValue* root) {
|
||||||
|
if (!root) return NULL;
|
||||||
|
TbBlueprint* bp = tb_blueprint_new();
|
||||||
|
if (!bp) return NULL;
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* ubs = tb_json_object_get(root, "user_blocks");
|
||||||
|
for (uint32_t u = 0; ubs && u < tb_json_array_length(ubs) && bp->user_block_n < TB_BP_MAX_UBLOCKS; u++) {
|
||||||
|
TinyBlocks_JsonValue* jo = tb_json_array_get(ubs, u);
|
||||||
|
TbBpUserBlock* d = &bp->user_blocks[bp->user_block_n];
|
||||||
|
memset(d, 0, sizeof(*d));
|
||||||
|
snprintf(d->name, sizeof(d->name), "%s", jget_str(jo, "name", ""));
|
||||||
|
d->color_idx = (int)jget_num(jo, "color", 0);
|
||||||
|
d->tab_idx = (int)jget_num(jo, "tab", -1);
|
||||||
|
jcopy_names(jo, "inputs", d->input_names, TB_BP_MAX_USLOTS, &d->input_count);
|
||||||
|
jcopy_names(jo, "outputs", d->output_names, TB_BP_MAX_USLOTS, &d->output_count);
|
||||||
|
TinyBlocks_JsonValue* parts = tb_json_object_get(jo, "parts");
|
||||||
|
d->part_n = 0;
|
||||||
|
for (uint32_t i = 0; parts && i < tb_json_array_length(parts) && d->part_n < TB_BP_MAX_UPARTS; i++) {
|
||||||
|
TinyBlocks_JsonValue* po = tb_json_array_get(parts, i);
|
||||||
|
d->parts[d->part_n].kind = (TbBpParamKind)(int)jget_num(po, "kind", 0);
|
||||||
|
snprintf(d->parts[d->part_n].name, 32, "%.31s", jget_str(po, "name", ""));
|
||||||
|
d->part_n++;
|
||||||
|
tb_json_release(po);
|
||||||
|
}
|
||||||
|
tb_json_release(parts);
|
||||||
|
tb_json_release(jo);
|
||||||
|
bp->user_block_n++;
|
||||||
|
}
|
||||||
|
tb_json_release(ubs);
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* tabs = tb_json_object_get(root, "tabs");
|
||||||
|
for (uint32_t ti = 0; tabs && ti < tb_json_array_length(tabs) && bp->tab_count < TB_BP_MAX_TABS; ti++) {
|
||||||
|
TinyBlocks_JsonValue* jt = tb_json_array_get(tabs, ti);
|
||||||
|
int idx = tb_blueprint_add_tab(bp, jget_str(jt, "name", "Codigo"), jget_bool(jt, "composite", false));
|
||||||
|
TbBpTab* T = &bp->tabs[idx];
|
||||||
|
T->comp_id = (int)jget_num(jt, "comp_id", -1);
|
||||||
|
T->color_idx = (int)jget_num(jt, "color", 0);
|
||||||
|
T->ws_sx = (float)jget_num(jt, "ws_sx", 0);
|
||||||
|
T->ws_sy = (float)jget_num(jt, "ws_sy", 0);
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* jb = tb_json_object_get(jt, "blocks");
|
||||||
|
for (uint32_t bi = 0; jb && bi < tb_json_array_length(jb); bi++) {
|
||||||
|
TinyBlocks_JsonValue* o = tb_json_array_get(jb, bi);
|
||||||
|
int i = (int)jget_num(o, "i", -1);
|
||||||
|
if (i >= 0 && i < TB_BP_MAX_WS) {
|
||||||
|
TbBpBlock* b = &T->blocks[i];
|
||||||
|
b->used = true;
|
||||||
|
snprintf(b->type, sizeof(b->type), "%s", jget_str(o, "type", ""));
|
||||||
|
b->x = (float)jget_num(o, "x", 0);
|
||||||
|
b->y = (float)jget_num(o, "y", 0);
|
||||||
|
b->parent = (int)jget_num(o, "parent", -1);
|
||||||
|
b->prel = (int)jget_num(o, "prel", TB_BP_REL_NONE);
|
||||||
|
b->next = (int)jget_num(o, "next", -1);
|
||||||
|
TinyBlocks_JsonValue* sub = tb_json_object_get(o, "sub");
|
||||||
|
for (int k = 0; k < 2; k++) { TinyBlocks_JsonValue* e = tb_json_array_get(sub, (uint32_t)k); b->sub[k] = e ? (int)tb_json_as_number(e, -1) : -1; tb_json_release(e); }
|
||||||
|
tb_json_release(sub);
|
||||||
|
TinyBlocks_JsonValue* args = tb_json_object_get(o, "args");
|
||||||
|
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) { TinyBlocks_JsonValue* e = tb_json_array_get(args, (uint32_t)s); b->args[s] = e ? (int)tb_json_as_number(e, -1) : -1; tb_json_release(e); }
|
||||||
|
tb_json_release(args);
|
||||||
|
TinyBlocks_JsonValue* txt = tb_json_object_get(o, "in_text");
|
||||||
|
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) {
|
||||||
|
TinyBlocks_JsonValue* e = tb_json_array_get(txt, (uint32_t)s);
|
||||||
|
if (e) { const char* sv = tb_json_as_string(e); if (sv) snprintf(b->in_text[s], sizeof(b->in_text[s]), "%s", sv); }
|
||||||
|
tb_json_release(e);
|
||||||
|
}
|
||||||
|
tb_json_release(txt);
|
||||||
|
snprintf(b->lit, sizeof(b->lit), "%s", jget_str(o, "lit", ""));
|
||||||
|
}
|
||||||
|
tb_json_release(o);
|
||||||
|
}
|
||||||
|
tb_json_release(jb);
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* top = tb_json_object_get(jt, "top");
|
||||||
|
T->top_n = 0;
|
||||||
|
for (uint32_t i = 0; top && i < tb_json_array_length(top) && T->top_n < TB_BP_MAX_WS; i++) {
|
||||||
|
TinyBlocks_JsonValue* e = tb_json_array_get(top, i);
|
||||||
|
T->top[T->top_n++] = e ? (int)tb_json_as_number(e, 0) : 0;
|
||||||
|
tb_json_release(e);
|
||||||
|
}
|
||||||
|
tb_json_release(top);
|
||||||
|
tb_json_release(jt);
|
||||||
|
}
|
||||||
|
tb_json_release(tabs);
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* vars = tb_json_object_get(root, "variables");
|
||||||
|
for (uint32_t i = 0; vars && i < tb_json_array_length(vars) && bp->var_n < TB_BP_MAX_VARS; i++) {
|
||||||
|
TinyBlocks_JsonValue* o = tb_json_array_get(vars, i);
|
||||||
|
TbBpVar* v = &bp->vars[bp->var_n];
|
||||||
|
memset(v, 0, sizeof(*v));
|
||||||
|
snprintf(v->name, sizeof(v->name), "%s", jget_str(o, "name", ""));
|
||||||
|
v->kind = (TbBpValueKind)(int)jget_num(o, "kind", TB_BP_VAL_TEXT);
|
||||||
|
v->num = jget_num(o, "num", 0);
|
||||||
|
snprintf(v->text, sizeof(v->text), "%s", jget_str(o, "text", ""));
|
||||||
|
bp->var_n++;
|
||||||
|
tb_json_release(o);
|
||||||
|
}
|
||||||
|
tb_json_release(vars);
|
||||||
|
|
||||||
|
bp->cur_tab = (int)jget_num(root, "cur_tab", 0);
|
||||||
|
return bp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Buffer de saida + escritores JSON/XML/CSV
|
||||||
|
* ============================================================ */
|
||||||
|
typedef struct { char* p; size_t len, cap; } Buf;
|
||||||
|
|
||||||
|
static void bput(Buf* b, const char* s, size_t n) {
|
||||||
|
if (b->len + n + 1 > b->cap) {
|
||||||
|
size_t nc = b->cap ? b->cap : 128;
|
||||||
|
while (nc < b->len + n + 1) nc *= 2;
|
||||||
|
char* p = (char*)realloc(b->p, nc);
|
||||||
|
if (!p) return;
|
||||||
|
b->p = p; b->cap = nc;
|
||||||
|
}
|
||||||
|
memcpy(b->p + b->len, s, n); b->len += n; b->p[b->len] = 0;
|
||||||
|
}
|
||||||
|
static void bs(Buf* b, const char* s) { bput(b, s, strlen(s)); }
|
||||||
|
static void bc(Buf* b, char c) { bput(b, &c, 1); }
|
||||||
|
static void bindent(Buf* b, int depth) { for (int i = 0; i < depth; i++) bs(b, " "); }
|
||||||
|
|
||||||
|
static void quote(Buf* b, const char* s) {
|
||||||
|
bc(b, '"');
|
||||||
|
for (const unsigned char* p = (const unsigned char*)s; *p; p++) {
|
||||||
|
switch (*p) {
|
||||||
|
case '"': bs(b, "\\\""); break;
|
||||||
|
case '\\': bs(b, "\\\\"); break;
|
||||||
|
case '\n': bs(b, "\\n"); break;
|
||||||
|
case '\r': bs(b, "\\r"); break;
|
||||||
|
case '\t': bs(b, "\\t"); break;
|
||||||
|
default: bc(b, (char)*p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bc(b, '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
static void json_rec(Buf* b, const TinyBlocks_JsonValue* j, bool pretty, int depth) {
|
||||||
|
if (!j) { bs(b, "null"); return; }
|
||||||
|
char tmp[64];
|
||||||
|
switch (tb_json_kind(j)) {
|
||||||
|
case TB_JSON_NULL: bs(b, "null"); break;
|
||||||
|
case TB_JSON_BOOL: bs(b, tb_json_as_bool(j, false) ? "true" : "false"); break;
|
||||||
|
case TB_JSON_NUMBER: {
|
||||||
|
double d = tb_json_as_number(j, 0);
|
||||||
|
if (d == (double)(long long)d) snprintf(tmp, sizeof(tmp), "%lld", (long long)d);
|
||||||
|
else snprintf(tmp, sizeof(tmp), "%g", d);
|
||||||
|
bs(b, tmp);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case TB_JSON_STRING: quote(b, tb_json_as_string(j) ? tb_json_as_string(j) : ""); break;
|
||||||
|
case TB_JSON_ARRAY:
|
||||||
|
bc(b, '[');
|
||||||
|
for (uint32_t i = 0; i < tb_json_array_length(j); i++) {
|
||||||
|
TinyBlocks_JsonValue* e = tb_json_array_get(j, i);
|
||||||
|
if (i) bc(b, ',');
|
||||||
|
if (pretty) { bc(b, '\n'); bindent(b, depth + 1); }
|
||||||
|
json_rec(b, e, pretty, depth + 1);
|
||||||
|
tb_json_release(e);
|
||||||
|
}
|
||||||
|
if (pretty && tb_json_array_length(j)) { bc(b, '\n'); bindent(b, depth); }
|
||||||
|
bc(b, ']');
|
||||||
|
break;
|
||||||
|
case TB_JSON_OBJECT:
|
||||||
|
bc(b, '{');
|
||||||
|
for (uint32_t i = 0; i < tb_json_object_length(j); i++) {
|
||||||
|
const char* k = tb_json_object_key_at(j, i);
|
||||||
|
TinyBlocks_JsonValue* e = tb_json_object_get(j, k);
|
||||||
|
if (i) bc(b, ',');
|
||||||
|
if (pretty) { bc(b, '\n'); bindent(b, depth + 1); }
|
||||||
|
quote(b, k);
|
||||||
|
bc(b, ':');
|
||||||
|
if (pretty) bc(b, ' ');
|
||||||
|
json_rec(b, e, pretty, depth + 1);
|
||||||
|
tb_json_release(e);
|
||||||
|
}
|
||||||
|
if (pretty && tb_json_object_length(j)) { bc(b, '\n'); bindent(b, depth); }
|
||||||
|
bc(b, '}');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void esc_xml(Buf* b, const char* s) {
|
||||||
|
for (const char* q = s; *q; q++) {
|
||||||
|
switch (*q) {
|
||||||
|
case '<': bs(b, "<"); break;
|
||||||
|
case '>': bs(b, ">"); break;
|
||||||
|
case '&': bs(b, "&"); break;
|
||||||
|
case '"': bs(b, """); break;
|
||||||
|
default: bc(b, *q);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void xattr(Buf* b, const char* k, const char* v) {
|
||||||
|
bs(b, " "); bs(b, k); bs(b, "=\""); esc_xml(b, v ? v : ""); bs(b, "\"");
|
||||||
|
}
|
||||||
|
static void xattr_num(Buf* b, const char* k, long long v) {
|
||||||
|
char t[32]; snprintf(t, sizeof(t), "%lld", v); xattr(b, k, t);
|
||||||
|
}
|
||||||
|
static void xattr_real(Buf* b, const char* k, double v) {
|
||||||
|
char t[32];
|
||||||
|
if (v == (double)(long long)v) snprintf(t, sizeof(t), "%lld", (long long)v);
|
||||||
|
else snprintf(t, sizeof(t), "%g", v);
|
||||||
|
xattr(b, k, t);
|
||||||
|
}
|
||||||
|
static void xattr_bool(Buf* b, const char* k, bool v) { xattr(b, k, v ? "true" : "false"); }
|
||||||
|
|
||||||
|
/* XML completo do projeto (escrito direto do modelo). */
|
||||||
|
static void blueprint_xml(Buf* b, const TbBlueprint* bp) {
|
||||||
|
bs(b, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
|
||||||
|
bs(b, "<tinyblocks");
|
||||||
|
xattr(b, "format", "tinyblocks-project");
|
||||||
|
xattr_num(b, "version", 1);
|
||||||
|
bs(b, ">\n");
|
||||||
|
|
||||||
|
bindent(b, 1); bs(b, "<tabs>\n");
|
||||||
|
for (int ti = 0; ti < bp->tab_count; ti++) {
|
||||||
|
const TbBpTab* T = &bp->tabs[ti];
|
||||||
|
bindent(b, 2); bs(b, "<tab");
|
||||||
|
xattr(b, "name", T->name);
|
||||||
|
xattr_bool(b, "composite", T->composite);
|
||||||
|
xattr_num(b, "comp_id", T->comp_id);
|
||||||
|
xattr_num(b, "color", T->color_idx);
|
||||||
|
xattr_real(b, "ws_sx", T->ws_sx);
|
||||||
|
xattr_real(b, "ws_sy", T->ws_sy);
|
||||||
|
bs(b, ">\n");
|
||||||
|
bindent(b, 3); bs(b, "<top>");
|
||||||
|
for (int i = 0; i < T->top_n; i++) { char t[24]; snprintf(t, sizeof(t), "<i>%d</i>", T->top[i]); bs(b, t); }
|
||||||
|
bs(b, "</top>\n");
|
||||||
|
bindent(b, 3); bs(b, "<blocks>\n");
|
||||||
|
for (int i = 0; i < TB_BP_MAX_WS; i++) {
|
||||||
|
const TbBpBlock* bl = &T->blocks[i];
|
||||||
|
if (!bl->used) continue;
|
||||||
|
bindent(b, 4); bs(b, "<block");
|
||||||
|
xattr_num(b, "i", i);
|
||||||
|
xattr(b, "type", bl->type);
|
||||||
|
xattr_real(b, "x", bl->x);
|
||||||
|
xattr_real(b, "y", bl->y);
|
||||||
|
xattr_num(b, "parent", bl->parent);
|
||||||
|
xattr_num(b, "prel", bl->prel);
|
||||||
|
xattr_num(b, "next", bl->next);
|
||||||
|
bs(b, ">\n");
|
||||||
|
bindent(b, 5); bs(b, "<sub>");
|
||||||
|
for (int k = 0; k < 2; k++) { char t[24]; snprintf(t, sizeof(t), "<i>%d</i>", bl->sub[k]); bs(b, t); }
|
||||||
|
bs(b, "</sub>\n");
|
||||||
|
bindent(b, 5); bs(b, "<args>");
|
||||||
|
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) { char t[24]; snprintf(t, sizeof(t), "<i>%d</i>", bl->args[s]); bs(b, t); }
|
||||||
|
bs(b, "</args>\n");
|
||||||
|
bindent(b, 5); bs(b, "<in_text>");
|
||||||
|
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) { bs(b, "<s>"); esc_xml(b, bl->in_text[s]); bs(b, "</s>"); }
|
||||||
|
bs(b, "</in_text>\n");
|
||||||
|
bindent(b, 5); bs(b, "<lit>"); esc_xml(b, bl->lit); bs(b, "</lit>\n");
|
||||||
|
bindent(b, 4); bs(b, "</block>\n");
|
||||||
|
}
|
||||||
|
bindent(b, 3); bs(b, "</blocks>\n");
|
||||||
|
bindent(b, 2); bs(b, "</tab>\n");
|
||||||
|
}
|
||||||
|
bindent(b, 1); bs(b, "</tabs>\n");
|
||||||
|
|
||||||
|
bindent(b, 1); bs(b, "<user_blocks>\n");
|
||||||
|
for (int u = 0; u < bp->user_block_n; u++) {
|
||||||
|
const TbBpUserBlock* d = &bp->user_blocks[u];
|
||||||
|
bindent(b, 2); bs(b, "<user_block");
|
||||||
|
xattr(b, "name", d->name);
|
||||||
|
xattr_num(b, "color", d->color_idx);
|
||||||
|
xattr_num(b, "tab", d->tab_idx);
|
||||||
|
bs(b, ">\n");
|
||||||
|
bindent(b, 3); bs(b, "<inputs>");
|
||||||
|
for (int i = 0; i < d->input_count; i++) { bs(b, "<s>"); esc_xml(b, d->input_names[i]); bs(b, "</s>"); }
|
||||||
|
bs(b, "</inputs>\n");
|
||||||
|
bindent(b, 3); bs(b, "<outputs>");
|
||||||
|
for (int i = 0; i < d->output_count; i++) { bs(b, "<s>"); esc_xml(b, d->output_names[i]); bs(b, "</s>"); }
|
||||||
|
bs(b, "</outputs>\n");
|
||||||
|
bindent(b, 3); bs(b, "<parts>\n");
|
||||||
|
for (int i = 0; i < d->part_n; i++) {
|
||||||
|
bindent(b, 4); bs(b, "<part");
|
||||||
|
xattr_num(b, "kind", d->parts[i].kind);
|
||||||
|
xattr(b, "name", d->parts[i].name);
|
||||||
|
bs(b, "/>\n");
|
||||||
|
}
|
||||||
|
bindent(b, 3); bs(b, "</parts>\n");
|
||||||
|
bindent(b, 2); bs(b, "</user_block>\n");
|
||||||
|
}
|
||||||
|
bindent(b, 1); bs(b, "</user_blocks>\n");
|
||||||
|
|
||||||
|
bindent(b, 1); bs(b, "<variables>\n");
|
||||||
|
for (int i = 0; i < bp->var_n; i++) {
|
||||||
|
const TbBpVar* v = &bp->vars[i];
|
||||||
|
bindent(b, 2); bs(b, "<var");
|
||||||
|
xattr(b, "name", v->name);
|
||||||
|
xattr_num(b, "kind", v->kind);
|
||||||
|
xattr_real(b, "num", v->num);
|
||||||
|
xattr(b, "text", v->text);
|
||||||
|
bs(b, "/>\n");
|
||||||
|
}
|
||||||
|
bindent(b, 1); bs(b, "</variables>\n");
|
||||||
|
bs(b, "</tinyblocks>\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool csv_needs_quote(const char* s) {
|
||||||
|
for (; *s; s++) if (*s == ',' || *s == '"' || *s == '\n' || *s == '\r') return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
static void csv_field(Buf* b, const char* s) {
|
||||||
|
if (!csv_needs_quote(s)) { bs(b, s); return; }
|
||||||
|
bc(b, '"');
|
||||||
|
for (; *s; s++) { if (*s == '"') bc(b, '"'); bc(b, *s); }
|
||||||
|
bc(b, '"');
|
||||||
|
}
|
||||||
|
/* data = array de objetos; colunas vem das chaves do primeiro. */
|
||||||
|
static void csv_rec(Buf* b, const TinyBlocks_JsonValue* data) {
|
||||||
|
if (tb_json_kind(data) != TB_JSON_ARRAY) return;
|
||||||
|
TinyBlocks_JsonValue* first = tb_json_array_get(data, 0);
|
||||||
|
if (!first) { tb_json_release(first); return; }
|
||||||
|
uint32_t ncol = tb_json_object_length(first);
|
||||||
|
for (uint32_t j = 0; j < ncol; j++) { if (j) bc(b, ','); csv_field(b, tb_json_object_key_at(first, j)); }
|
||||||
|
bc(b, '\n');
|
||||||
|
for (uint32_t i = 0; i < tb_json_array_length(data); i++) {
|
||||||
|
TinyBlocks_JsonValue* o = tb_json_array_get(data, i);
|
||||||
|
for (uint32_t j = 0; j < ncol; j++) {
|
||||||
|
if (j) bc(b, ',');
|
||||||
|
TinyBlocks_JsonValue* v = tb_json_object_get(o, tb_json_object_key_at(first, j));
|
||||||
|
char num[32];
|
||||||
|
const char* s = "";
|
||||||
|
if (v && tb_json_kind(v) == TB_JSON_STRING) s = tb_json_as_string(v);
|
||||||
|
else if (v && tb_json_kind(v) == TB_JSON_NUMBER) {
|
||||||
|
double d = tb_json_as_number(v, 0);
|
||||||
|
if (d == (double)(long long)d) snprintf(num, sizeof(num), "%lld", (long long)d);
|
||||||
|
else snprintf(num, sizeof(num), "%g", d);
|
||||||
|
s = num;
|
||||||
|
} else if (v && tb_json_kind(v) == TB_JSON_BOOL) {
|
||||||
|
s = tb_json_as_bool(v, false) ? "true" : "false";
|
||||||
|
}
|
||||||
|
csv_field(b, s);
|
||||||
|
tb_json_release(v);
|
||||||
|
}
|
||||||
|
bc(b, '\n');
|
||||||
|
tb_json_release(o);
|
||||||
|
}
|
||||||
|
tb_json_release(first);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tabela plana de blocos para o CSV. */
|
||||||
|
static TinyBlocks_JsonValue* blueprint_csv_tree(const TbBlueprint* bp) {
|
||||||
|
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||||
|
for (int ti = 0; ti < bp->tab_count; ti++) {
|
||||||
|
const TbBpTab* T = &bp->tabs[ti];
|
||||||
|
for (int i = 0; i < TB_BP_MAX_WS; i++) {
|
||||||
|
const TbBpBlock* b = &T->blocks[i];
|
||||||
|
if (!b->used) continue;
|
||||||
|
TinyBlocks_JsonValue* o = tb_json_object();
|
||||||
|
PUT(o, "aba", tb_json_string(T->name));
|
||||||
|
PUT(o, "tipo", tb_json_string(b->type));
|
||||||
|
PUT(o, "x", tb_json_number(b->x));
|
||||||
|
PUT(o, "y", tb_json_number(b->y));
|
||||||
|
PUT(o, "texto", tb_json_string(b->in_text[0]));
|
||||||
|
tb_json_array_push(arr, o);
|
||||||
|
tb_json_release(o);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
|
||||||
|
char* tb_blueprint_serialize(const TbBlueprint* bp, int fmt, bool pretty) {
|
||||||
|
Buf b = {0};
|
||||||
|
if (fmt == TB_BP_FMT_CSV) {
|
||||||
|
TinyBlocks_JsonValue* data = blueprint_csv_tree(bp);
|
||||||
|
csv_rec(&b, data);
|
||||||
|
tb_json_release(data);
|
||||||
|
} else if (fmt == TB_BP_FMT_XML) {
|
||||||
|
blueprint_xml(&b, bp);
|
||||||
|
} else {
|
||||||
|
TinyBlocks_JsonValue* root = tb_blueprint_to_json(bp);
|
||||||
|
json_rec(&b, root, pretty, 0); bc(&b, '\n');
|
||||||
|
tb_json_release(root);
|
||||||
|
}
|
||||||
|
if (!b.p) { b.p = (char*)malloc(1); if (b.p) b.p[0] = 0; }
|
||||||
|
return b.p;
|
||||||
|
}
|
||||||
|
|
||||||
|
TbBlueprint* tb_blueprint_parse(const char* text, int fmt, char* err, size_t errcap) {
|
||||||
|
if (fmt != TB_BP_FMT_JSON) {
|
||||||
|
if (err && errcap) snprintf(err, errcap, "so o formato JSON e carregavel");
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
TinyBlocks_JsonValue* root = tb_json_parse(text, err, errcap);
|
||||||
|
if (!root) return NULL;
|
||||||
|
TinyBlocks_JsonValue* fv = tb_json_object_get(root, "format");
|
||||||
|
const char* fmt_s = fv ? tb_json_as_string(fv) : NULL;
|
||||||
|
bool ok = fmt_s && strcmp(fmt_s, "tinyblocks-project") == 0;
|
||||||
|
tb_json_release(fv);
|
||||||
|
if (!ok) { if (err && errcap) snprintf(err, errcap, "formato de projeto desconhecido"); tb_json_release(root); return NULL; }
|
||||||
|
TbBlueprint* bp = tb_blueprint_from_json(root);
|
||||||
|
tb_json_release(root);
|
||||||
|
return bp;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool tb_blueprint_save_file(const TbBlueprint* bp, const char* path, int fmt, bool pretty) {
|
||||||
|
char* s = tb_blueprint_serialize(bp, fmt, pretty);
|
||||||
|
if (!s) return false;
|
||||||
|
FILE* f = fopen(path, "wb");
|
||||||
|
if (!f) { free(s); return false; }
|
||||||
|
size_t n = strlen(s);
|
||||||
|
size_t w = fwrite(s, 1, n, f);
|
||||||
|
fclose(f);
|
||||||
|
free(s);
|
||||||
|
return w == n;
|
||||||
|
}
|
||||||
|
|
||||||
|
TbBlueprint* tb_blueprint_load_file(const char* path, char* err, size_t errcap) {
|
||||||
|
FILE* f = fopen(path, "rb");
|
||||||
|
if (!f) { if (err && errcap) snprintf(err, errcap, "nao abriu %s", path); return NULL; }
|
||||||
|
fseek(f, 0, SEEK_END); long sz = ftell(f); fseek(f, 0, SEEK_SET);
|
||||||
|
if (sz < 0 || sz > 256L * 1024 * 1024) { fclose(f); if (err && errcap) snprintf(err, errcap, "arquivo grande demais"); return NULL; }
|
||||||
|
char* buf = (char*)malloc((size_t)sz + 1);
|
||||||
|
if (!buf) { fclose(f); return NULL; }
|
||||||
|
size_t rd = fread(buf, 1, (size_t)sz, f);
|
||||||
|
buf[rd] = 0; fclose(f);
|
||||||
|
TbBlueprint* bp = tb_blueprint_parse(buf, TB_BP_FMT_JSON, err, errcap);
|
||||||
|
free(buf);
|
||||||
|
return bp;
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tb_blueprint.c
|
||||||
|
* Registro da library (categoria "Blueprint"). O modelo/serializacao fica em
|
||||||
|
* blueprint.c/serialize.c; aqui so expomos o descritor e um bloco informativo.
|
||||||
|
*/
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include <tinyblocks/tinyblocks.h>
|
||||||
|
#include "tb_blueprint.h"
|
||||||
|
|
||||||
|
#define CAT_COLOR 110/255.f, 140/255.f, 255/255.f, 1.f
|
||||||
|
#define CAT_DARK 70/255.f, 95/255.f, 210/255.f, 1.f
|
||||||
|
|
||||||
|
static void eval_format(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||||
|
(void)rt;
|
||||||
|
tb_block_set_output(self, 0, tb_value_text("tinyblocks-project"));
|
||||||
|
self->dirty = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void eval_version(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||||
|
(void)rt;
|
||||||
|
tb_block_set_output(self, 0, tb_value_integer(1));
|
||||||
|
self->dirty = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool blueprint_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||||
|
static const TinyBlocks_Category cat = { "Blueprint", {CAT_COLOR}, {CAT_DARK} };
|
||||||
|
tb_library_set_category(lib, &cat);
|
||||||
|
static const TinyBlocks_SlotDesc out_t[] = {{"formato", TB_VALUE_TEXT}};
|
||||||
|
static const TinyBlocks_SlotDesc out_i[] = {{"versao", TB_VALUE_INTEGER}};
|
||||||
|
TinyBlocks_TypeBlock* a = tb_type_block_create(rt, "Blueprint.Format", NULL, 0, out_t, 1, eval_format);
|
||||||
|
TinyBlocks_TypeBlock* b = tb_type_block_create(rt, "Blueprint.Version", NULL, 0, out_i, 1, eval_version);
|
||||||
|
return a && b && tb_library_add(lib, &a->base) && tb_library_add(lib, &b->base);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void blueprint_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { (void)rt; (void)lib; }
|
||||||
|
|
||||||
|
TINYBLOCKS_DEFINE_LIBRARY(blueprint,
|
||||||
|
"tinyblocks-blueprint",
|
||||||
|
"1.0.0",
|
||||||
|
blueprint_init,
|
||||||
|
blueprint_deinit)
|
||||||
|
|
||||||
|
const TinyBlocks_LibraryDescriptor* tb_blueprint_get_library(void) {
|
||||||
|
return &_tb_lib_desc_blueprint;
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Makefile da library csv (divisor + parser/emissor sobre a AST JSON do core)
|
||||||
|
CC := gcc
|
||||||
|
BUILD := build
|
||||||
|
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||||
|
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude
|
||||||
|
|
||||||
|
OBJS := $(BUILD)/lexer.o $(BUILD)/parser.o $(BUILD)/tb_csv.o
|
||||||
|
LIB_A := $(BUILD)/libtinyblocks-csv.a
|
||||||
|
LIB_SO := $(BUILD)/libtinyblocks-csv.so
|
||||||
|
|
||||||
|
.PHONY: all static shared clean
|
||||||
|
all: static shared
|
||||||
|
static: $(LIB_A)
|
||||||
|
shared: $(LIB_SO)
|
||||||
|
|
||||||
|
$(BUILD)/lexer.o: src/lexer.c include/lexeme.h
|
||||||
|
@mkdir -p $(BUILD)
|
||||||
|
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||||
|
$(BUILD)/parser.o: src/parser.c include/ast.h include/lexeme.h
|
||||||
|
@mkdir -p $(BUILD)
|
||||||
|
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||||
|
$(BUILD)/tb_csv.o: src/tb_csv.c include/tb_csv.h include/ast.h include/lexeme.h
|
||||||
|
@mkdir -p $(BUILD)
|
||||||
|
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||||
|
|
||||||
|
$(LIB_A): $(OBJS)
|
||||||
|
ar rcs $@ $^
|
||||||
|
$(LIB_SO): $(OBJS)
|
||||||
|
$(CC) -shared -o $@ $^
|
||||||
|
|
||||||
|
clean:
|
||||||
|
$(RM) -r $(BUILD)
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-csv / include/ast.h
|
||||||
|
*
|
||||||
|
* A AST do CSV e a arvore JSON do core:
|
||||||
|
* - sem cabecalho -> array de arrays de strings (linhas);
|
||||||
|
* - com cabecalho -> array de objetos { coluna: "valor", ... }.
|
||||||
|
*/
|
||||||
|
#ifndef TB_CSV_AST_H
|
||||||
|
#define TB_CSV_AST_H
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <tinyblocks/tb_json_block.h>
|
||||||
|
#include "lexeme.h"
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* csv_parse(const char* text, char delim, bool header, char* err, size_t errcap);
|
||||||
|
TinyBlocks_JsonValue* csv_parse_file(const char* path, char delim, bool header, char* err, size_t errcap);
|
||||||
|
char* csv_to_string(const TinyBlocks_JsonValue* data, char delim);
|
||||||
|
bool csv_write_file(const TinyBlocks_JsonValue* data, const char* path, char delim);
|
||||||
|
|
||||||
|
#endif /* TB_CSV_AST_H */
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-csv / include/lexeme.h
|
||||||
|
* Divisao de texto CSV em linhas/campos (com suporte a aspas).
|
||||||
|
*/
|
||||||
|
#ifndef TB_CSV_LEXEME_H
|
||||||
|
#define TB_CSV_LEXEME_H
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
|
||||||
|
typedef struct { char** fields; int count, cap; } CsvRow;
|
||||||
|
typedef struct { CsvRow* rows; int count, cap; } CsvTable;
|
||||||
|
|
||||||
|
/* Divide 'text' em linhas/campos. 'delim' costuma ser ',' ou ';'.
|
||||||
|
* Aspas duplas agrupam campos; "" dentro de aspas representa uma aspa. */
|
||||||
|
CsvTable* csv_split(const char* text, char delim, char* err, size_t errcap);
|
||||||
|
void csv_table_free(CsvTable* t);
|
||||||
|
|
||||||
|
#endif /* TB_CSV_LEXEME_H */
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tb_csv.h
|
||||||
|
* Library tinyblocks-csv: parser/emissor de CSV sobre a AST JSON do core.
|
||||||
|
*/
|
||||||
|
#ifndef TINYBLOCKS_CSV_H
|
||||||
|
#define TINYBLOCKS_CSV_H
|
||||||
|
|
||||||
|
#include <tinyblocks/tinyblocks.h>
|
||||||
|
#include "ast.h"
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
TB_API const TinyBlocks_LibraryDescriptor* tb_csv_get_library(void);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* TINYBLOCKS_CSV_H */
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Metadados da library csv.
|
||||||
|
[library]
|
||||||
|
name = "tinyblocks-csv"
|
||||||
|
version = "1.0.0"
|
||||||
|
category = "CSV"
|
||||||
|
description = "Parser e emissor de CSV (AST JSON do core)"
|
||||||
|
color = [120, 180, 90, 255]
|
||||||
|
dark = [80, 140, 55, 255]
|
||||||
|
|
||||||
|
[build]
|
||||||
|
sources = ["src/lexer.c", "src/parser.c", "src/tb_csv.c"]
|
||||||
|
includes = ["include"]
|
||||||
|
shared = "build/libtinyblocks-csv.so"
|
||||||
|
static = "build/libtinyblocks-csv.a"
|
||||||
|
depends = []
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-csv / src/lexer.c
|
||||||
|
*/
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
#include "lexeme.h"
|
||||||
|
|
||||||
|
static bool row_push_field(CsvRow* r, char* field) {
|
||||||
|
if (r->count >= r->cap) {
|
||||||
|
int nc = r->cap ? r->cap * 2 : 8;
|
||||||
|
char** nf = (char**)realloc(r->fields, (size_t)nc * sizeof(char*));
|
||||||
|
if (!nf) return false;
|
||||||
|
r->fields = nf; r->cap = nc;
|
||||||
|
}
|
||||||
|
r->fields[r->count++] = field;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool table_push_row(CsvTable* t, CsvRow* r) {
|
||||||
|
if (t->count >= t->cap) {
|
||||||
|
int nc = t->cap ? t->cap * 2 : 8;
|
||||||
|
CsvRow* nr = (CsvRow*)realloc(t->rows, (size_t)nc * sizeof(CsvRow));
|
||||||
|
if (!nr) return false;
|
||||||
|
t->rows = nr; t->cap = nc;
|
||||||
|
}
|
||||||
|
t->rows[t->count++] = *r;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static char* dup_range(const char* s, size_t n) {
|
||||||
|
char* p = (char*)malloc(n + 1);
|
||||||
|
if (!p) return NULL;
|
||||||
|
memcpy(p, s, n); p[n] = 0;
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
CsvTable* csv_split(const char* text, char delim, char* err, size_t errcap) {
|
||||||
|
CsvTable* t = (CsvTable*)calloc(1, sizeof(CsvTable));
|
||||||
|
if (!t) return NULL;
|
||||||
|
CsvRow row = {0};
|
||||||
|
size_t cap = 64, n = 0;
|
||||||
|
char* f = (char*)malloc(cap);
|
||||||
|
if (!f) { free(t); return NULL; }
|
||||||
|
bool in_quotes = false;
|
||||||
|
const char* p = text;
|
||||||
|
for (;;) {
|
||||||
|
char c = *p;
|
||||||
|
if (c == 0) break;
|
||||||
|
if (in_quotes) {
|
||||||
|
if (c == '"') {
|
||||||
|
if (p[1] == '"') { if (n + 1 >= cap) { cap *= 2; f = realloc(f, cap); } f[n++] = '"'; p += 2; continue; }
|
||||||
|
in_quotes = false; p++; continue;
|
||||||
|
}
|
||||||
|
if (n + 1 >= cap) { cap *= 2; f = realloc(f, cap); if (!f) { free(t); return NULL; } }
|
||||||
|
f[n++] = c; p++; continue;
|
||||||
|
}
|
||||||
|
if (c == '"') { in_quotes = true; p++; continue; }
|
||||||
|
if (c == delim) {
|
||||||
|
f[n] = 0; row_push_field(&row, dup_range(f, n)); n = 0; p++; continue;
|
||||||
|
}
|
||||||
|
if (c == '\r' || c == '\n') {
|
||||||
|
f[n] = 0; row_push_field(&row, dup_range(f, n)); n = 0;
|
||||||
|
table_push_row(t, &row);
|
||||||
|
memset(&row, 0, sizeof(row));
|
||||||
|
if (c == '\r' && p[1] == '\n') p += 2; else p++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (n + 1 >= cap) { cap *= 2; f = realloc(f, cap); if (!f) { free(t); return NULL; } }
|
||||||
|
f[n++] = c; p++;
|
||||||
|
}
|
||||||
|
if (in_quotes && err && errcap) snprintf(err, errcap, "aspas nao fechadas");
|
||||||
|
/* ultima linha sem quebra */
|
||||||
|
if (n > 0 || row.count > 0) {
|
||||||
|
f[n] = 0; row_push_field(&row, dup_range(f, n));
|
||||||
|
table_push_row(t, &row);
|
||||||
|
memset(&row, 0, sizeof(row));
|
||||||
|
}
|
||||||
|
free(f);
|
||||||
|
free(row.fields);
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
void csv_table_free(CsvTable* t) {
|
||||||
|
if (!t) return;
|
||||||
|
for (int i = 0; i < t->count; i++) {
|
||||||
|
for (int j = 0; j < t->rows[i].count; j++) free(t->rows[i].fields[j]);
|
||||||
|
free(t->rows[i].fields);
|
||||||
|
}
|
||||||
|
free(t->rows);
|
||||||
|
free(t);
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-csv / src/parser.c
|
||||||
|
*/
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
#include "ast.h"
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* csv_parse(const char* text, char delim, bool header, char* err, size_t errcap) {
|
||||||
|
CsvTable* t = csv_split(text, delim, err, errcap);
|
||||||
|
if (!t) return NULL;
|
||||||
|
TinyBlocks_JsonValue* root = tb_json_array();
|
||||||
|
if (!root) { csv_table_free(t); return NULL; }
|
||||||
|
|
||||||
|
int start = 0;
|
||||||
|
const CsvRow* head = NULL;
|
||||||
|
if (header && t->count >= 1) { head = &t->rows[0]; start = 1; }
|
||||||
|
|
||||||
|
for (int i = start; i < t->count; i++) {
|
||||||
|
const CsvRow* row = &t->rows[i];
|
||||||
|
if (head) {
|
||||||
|
TinyBlocks_JsonValue* obj = tb_json_object();
|
||||||
|
for (int j = 0; j < head->count; j++) {
|
||||||
|
const char* val = (j < row->count && row->fields[j]) ? row->fields[j] : "";
|
||||||
|
TinyBlocks_JsonValue* v = tb_json_string(val);
|
||||||
|
tb_json_object_set(obj, head->fields[j] ? head->fields[j] : "", v);
|
||||||
|
tb_json_release(v);
|
||||||
|
}
|
||||||
|
tb_json_array_push(root, obj);
|
||||||
|
tb_json_release(obj);
|
||||||
|
} else {
|
||||||
|
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||||
|
for (int j = 0; j < row->count; j++) {
|
||||||
|
TinyBlocks_JsonValue* v = tb_json_string(row->fields[j] ? row->fields[j] : "");
|
||||||
|
tb_json_array_push(arr, v);
|
||||||
|
tb_json_release(v);
|
||||||
|
}
|
||||||
|
tb_json_array_push(root, arr);
|
||||||
|
tb_json_release(arr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
csv_table_free(t);
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* csv_parse_file(const char* path, char delim, bool header, char* err, size_t errcap) {
|
||||||
|
FILE* f = fopen(path, "rb");
|
||||||
|
if (!f) { if (err && errcap) snprintf(err, errcap, "nao abriu o arquivo"); return NULL; }
|
||||||
|
fseek(f, 0, SEEK_END); long sz = ftell(f); fseek(f, 0, SEEK_SET);
|
||||||
|
if (sz < 0 || sz > 256L * 1024 * 1024) { fclose(f); return NULL; }
|
||||||
|
char* buf = (char*)malloc((size_t)sz + 1);
|
||||||
|
if (!buf) { fclose(f); return NULL; }
|
||||||
|
size_t rd = fread(buf, 1, (size_t)sz, f);
|
||||||
|
buf[rd] = 0; fclose(f);
|
||||||
|
TinyBlocks_JsonValue* v = csv_parse(buf, delim, header, err, errcap);
|
||||||
|
free(buf);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* === Emissor === */
|
||||||
|
typedef struct { char* p; size_t len, cap; } Buf;
|
||||||
|
|
||||||
|
static void bput(Buf* b, const char* s, size_t n) {
|
||||||
|
if (b->len + n + 1 > b->cap) {
|
||||||
|
size_t nc = b->cap ? b->cap : 128;
|
||||||
|
while (nc < b->len + n + 1) nc *= 2;
|
||||||
|
char* p = (char*)realloc(b->p, nc);
|
||||||
|
if (!p) return;
|
||||||
|
b->p = p; b->cap = nc;
|
||||||
|
}
|
||||||
|
memcpy(b->p + b->len, s, n); b->len += n; b->p[b->len] = 0;
|
||||||
|
}
|
||||||
|
static void bs(Buf* b, const char* s) { bput(b, s, strlen(s)); }
|
||||||
|
static void bc(Buf* b, char c) { bput(b, &c, 1); }
|
||||||
|
|
||||||
|
static bool needs_quote(const char* s, char delim) {
|
||||||
|
for (; *s; s++) if (*s == delim || *s == '"' || *s == '\n' || *s == '\r') return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void field(Buf* b, const char* s, char delim) {
|
||||||
|
if (!needs_quote(s, delim)) { bs(b, s); return; }
|
||||||
|
bc(b, '"');
|
||||||
|
for (; *s; s++) { if (*s == '"') bc(b, '"'); bc(b, *s); }
|
||||||
|
bc(b, '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
static void row_out(Buf* b, const TinyBlocks_JsonValue* row, char delim) {
|
||||||
|
for (uint32_t j = 0; j < tb_json_array_length(row); j++) {
|
||||||
|
if (j) bc(b, delim);
|
||||||
|
TinyBlocks_JsonValue* c = tb_json_array_get(row, j);
|
||||||
|
const char* s = tb_json_kind(c) == TB_JSON_STRING ? tb_json_as_string(c) : "";
|
||||||
|
field(b, s ? s : "", delim);
|
||||||
|
tb_json_release(c);
|
||||||
|
}
|
||||||
|
bc(b, '\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
char* csv_to_string(const TinyBlocks_JsonValue* data, char delim) {
|
||||||
|
Buf b = {0};
|
||||||
|
if (tb_json_kind(data) != TB_JSON_ARRAY) { b.p = (char*)malloc(1); if (b.p) b.p[0] = 0; return b.p; }
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* first = tb_json_array_get(data, 0);
|
||||||
|
if (first && tb_json_kind(first) == TB_JSON_OBJECT) {
|
||||||
|
uint32_t ncol = tb_json_object_length(first);
|
||||||
|
for (uint32_t j = 0; j < ncol; j++) {
|
||||||
|
if (j) bc(&b, delim);
|
||||||
|
field(&b, tb_json_object_key_at(first, j), delim);
|
||||||
|
}
|
||||||
|
bc(&b, '\n');
|
||||||
|
for (uint32_t i = 0; i < tb_json_array_length(data); i++) {
|
||||||
|
TinyBlocks_JsonValue* obj = tb_json_array_get(data, i);
|
||||||
|
for (uint32_t j = 0; j < ncol; j++) {
|
||||||
|
if (j) bc(&b, delim);
|
||||||
|
const char* key = tb_json_object_key_at(first, j);
|
||||||
|
TinyBlocks_JsonValue* v = tb_json_object_get(obj, key);
|
||||||
|
const char* s = v ? tb_json_as_string(v) : "";
|
||||||
|
field(&b, s ? s : "", delim);
|
||||||
|
tb_json_release(v);
|
||||||
|
}
|
||||||
|
bc(&b, '\n');
|
||||||
|
tb_json_release(obj);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (uint32_t i = 0; i < tb_json_array_length(data); i++) {
|
||||||
|
TinyBlocks_JsonValue* row = tb_json_array_get(data, i);
|
||||||
|
if (tb_json_kind(row) == TB_JSON_ARRAY) row_out(&b, row, delim);
|
||||||
|
tb_json_release(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tb_json_release(first);
|
||||||
|
if (!b.p) { b.p = (char*)malloc(1); if (b.p) b.p[0] = 0; }
|
||||||
|
return b.p;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool csv_write_file(const TinyBlocks_JsonValue* data, const char* path, char delim) {
|
||||||
|
char* s = csv_to_string(data, delim);
|
||||||
|
if (!s) return false;
|
||||||
|
FILE* f = fopen(path, "wb");
|
||||||
|
if (!f) { free(s); return false; }
|
||||||
|
size_t n = strlen(s);
|
||||||
|
size_t w = fwrite(s, 1, n, f);
|
||||||
|
fclose(f);
|
||||||
|
free(s);
|
||||||
|
return w == n;
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tb_csv.c
|
||||||
|
* Blocos Csv.Rows e Csv.Get.
|
||||||
|
*/
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include <tinyblocks/tinyblocks.h>
|
||||||
|
#include "tb_csv.h"
|
||||||
|
|
||||||
|
#define CAT_COLOR 120/255.f, 180/255.f, 90/255.f, 1.f
|
||||||
|
#define CAT_DARK 80/255.f, 140/255.f, 55/255.f, 1.f
|
||||||
|
|
||||||
|
static void eval_rows(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||||
|
TinyBlocks_Value text = tb_block_get_input(self, rt, 0);
|
||||||
|
const char* src = (text.kind == TB_VALUE_TEXT && text.as.text) ? text.as.text : "";
|
||||||
|
CsvTable* t = csv_split(src, ',', NULL, 0);
|
||||||
|
tb_block_set_output(self, 0, tb_value_integer(t ? t->count : 0));
|
||||||
|
csv_table_free(t);
|
||||||
|
self->dirty = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void eval_get(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||||
|
TinyBlocks_Value text = tb_block_get_input(self, rt, 0);
|
||||||
|
TinyBlocks_Value rv = tb_block_get_input(self, rt, 1);
|
||||||
|
TinyBlocks_Value cv = tb_block_get_input(self, rt, 2);
|
||||||
|
const char* src = (text.kind == TB_VALUE_TEXT && text.as.text) ? text.as.text : "";
|
||||||
|
int row = (rv.kind == TB_VALUE_INTEGER) ? (int)rv.as.integer : 0;
|
||||||
|
int col = (cv.kind == TB_VALUE_INTEGER) ? (int)cv.as.integer : 0;
|
||||||
|
CsvTable* t = csv_split(src, ',', NULL, 0);
|
||||||
|
const char* out = "";
|
||||||
|
if (t && row >= 0 && row < t->count && col >= 0 && col < t->rows[row].count)
|
||||||
|
out = t->rows[row].fields[col];
|
||||||
|
tb_block_set_output(self, 0, tb_value_text(out));
|
||||||
|
csv_table_free(t);
|
||||||
|
self->dirty = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool csv_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||||
|
static const TinyBlocks_Category cat = { "CSV", {CAT_COLOR}, {CAT_DARK} };
|
||||||
|
tb_library_set_category(lib, &cat);
|
||||||
|
static const TinyBlocks_SlotDesc rows_in[] = {{"texto", TB_VALUE_TEXT}};
|
||||||
|
static const TinyBlocks_SlotDesc get_in[] = {{"texto", TB_VALUE_TEXT}, {"linha", TB_VALUE_INTEGER}, {"coluna", TB_VALUE_INTEGER}};
|
||||||
|
static const TinyBlocks_SlotDesc out_i[] = {{"linhas", TB_VALUE_INTEGER}};
|
||||||
|
static const TinyBlocks_SlotDesc out_t[] = {{"valor", TB_VALUE_TEXT}};
|
||||||
|
TinyBlocks_TypeBlock* a = tb_type_block_create(rt, "Csv.Rows", rows_in, 1, out_i, 1, eval_rows);
|
||||||
|
TinyBlocks_TypeBlock* b = tb_type_block_create(rt, "Csv.Get", get_in, 3, out_t, 1, eval_get);
|
||||||
|
return a && b && tb_library_add(lib, &a->base) && tb_library_add(lib, &b->base);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void csv_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { (void)rt; (void)lib; }
|
||||||
|
|
||||||
|
TINYBLOCKS_DEFINE_LIBRARY(csv,
|
||||||
|
"tinyblocks-csv",
|
||||||
|
"1.0.0",
|
||||||
|
csv_init,
|
||||||
|
csv_deinit)
|
||||||
|
|
||||||
|
const TinyBlocks_LibraryDescriptor* tb_csv_get_library(void) {
|
||||||
|
return &_tb_lib_desc_csv;
|
||||||
|
}
|
||||||
@@ -9,7 +9,8 @@ CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
|
|||||||
-D_POSIX_C_SOURCE=200809L \
|
-D_POSIX_C_SOURCE=200809L \
|
||||||
-I../../include -Iinclude -Isrc \
|
-I../../include -Iinclude -Isrc \
|
||||||
-I../tinyblocks-graphics/include \
|
-I../tinyblocks-graphics/include \
|
||||||
-I../tinyblocks-variables/include
|
-I../tinyblocks-variables/include \
|
||||||
|
-I../tinyblocks-blueprint/include
|
||||||
|
|
||||||
OBJ := $(BUILD)/tb_editor.o $(BUILD)/tb_stage_widget.o
|
OBJ := $(BUILD)/tb_editor.o $(BUILD)/tb_stage_widget.o
|
||||||
LIB_A := $(BUILD)/libtinyblocks-editor.a
|
LIB_A := $(BUILD)/libtinyblocks-editor.a
|
||||||
@@ -22,7 +23,8 @@ shared: $(LIB_SO)
|
|||||||
|
|
||||||
$(BUILD)/tb_editor.o: src/tb_editor.c include/tb_editor.h src/tb_stage_widget.h \
|
$(BUILD)/tb_editor.o: src/tb_editor.c include/tb_editor.h src/tb_stage_widget.h \
|
||||||
../tinyblocks-graphics/include/tb_graphics.h \
|
../tinyblocks-graphics/include/tb_graphics.h \
|
||||||
../tinyblocks-variables/include/tb_variables.h
|
../tinyblocks-variables/include/tb_variables.h \
|
||||||
|
../tinyblocks-blueprint/include/tb_blueprint.h
|
||||||
@mkdir -p $(BUILD)
|
@mkdir -p $(BUILD)
|
||||||
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||||
|
|
||||||
|
|||||||
@@ -34,9 +34,11 @@
|
|||||||
|
|
||||||
#include <tinyblocks/tinyblocks.h>
|
#include <tinyblocks/tinyblocks.h>
|
||||||
#include <tinyblocks/tb_renderable_block.h>
|
#include <tinyblocks/tb_renderable_block.h>
|
||||||
|
#include <tinyblocks/tb_json_block.h>
|
||||||
#include <tb_graphics.h>
|
#include <tb_graphics.h>
|
||||||
#include <tinyblocks/tb_stage.h>
|
#include <tinyblocks/tb_stage.h>
|
||||||
#include <tb_variables.h>
|
#include <tb_variables.h>
|
||||||
|
#include <tb_blueprint.h>
|
||||||
#include "tb_stage_widget.h"
|
#include "tb_stage_widget.h"
|
||||||
#include "../include/tb_editor.h"
|
#include "../include/tb_editor.h"
|
||||||
|
|
||||||
@@ -81,8 +83,22 @@ TB_API void tb_editor_preload(const char* path) {
|
|||||||
#define WS_H (ed->win_h - WS_Y)
|
#define WS_H (ed->win_h - WS_Y)
|
||||||
#define TAB_W 150
|
#define TAB_W 150
|
||||||
#define PLUS_W 28
|
#define PLUS_W 28
|
||||||
#define LIB_BTN_X 150
|
|
||||||
#define LIB_BTN_W 170
|
/* Botoes de projeto no menu (geometria) */
|
||||||
|
#define OPEN_BTN_X 150
|
||||||
|
#define OPEN_BTN_W 64
|
||||||
|
#define SAVE_BTN_X 218
|
||||||
|
#define SAVE_BTN_W 70
|
||||||
|
#define EXP_LBL_X 296
|
||||||
|
#define EXP_LBL_W 60
|
||||||
|
#define EXP_JSON_X 360
|
||||||
|
#define EXP_JSON_W 54
|
||||||
|
#define EXP_XML_X 418
|
||||||
|
#define EXP_XML_W 44
|
||||||
|
#define EXP_CSV_X 466
|
||||||
|
#define EXP_CSV_W 44
|
||||||
|
#define LIB_BTN_X 522
|
||||||
|
#define LIB_BTN_W 168
|
||||||
|
|
||||||
/* == Geometria dos blocos === */
|
/* == Geometria dos blocos === */
|
||||||
#define FS 12 /* texto dos blocos */
|
#define FS 12 /* texto dos blocos */
|
||||||
@@ -309,6 +325,12 @@ typedef enum { ES_IDLE, ES_PRESS, ES_DRAG, ES_PAN } EdSt;
|
|||||||
typedef enum { SN_NONE, SN_NEXT, SN_SUB, SN_ABOVE, SN_ARG } SnapKind;
|
typedef enum { SN_NONE, SN_NEXT, SN_SUB, SN_ABOVE, SN_ARG } SnapKind;
|
||||||
enum { CM_DUPLICATE, CM_DELETE, CM_EDIT_DEF, CM_CLEANUP, CM_NEW_COMPOSITE };
|
enum { CM_DUPLICATE, CM_DELETE, CM_EDIT_DEF, CM_CLEANUP, CM_NEW_COMPOSITE };
|
||||||
|
|
||||||
|
/* 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 };
|
||||||
|
|
||||||
|
/* Formatos de exportacao */
|
||||||
|
enum { EX_JSON, EX_XML, EX_CSV };
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
TinyBlocks* rt;
|
TinyBlocks* rt;
|
||||||
|
|
||||||
@@ -399,6 +421,7 @@ typedef struct {
|
|||||||
bool path_input_active;
|
bool path_input_active;
|
||||||
char path_input_buf[512];
|
char path_input_buf[512];
|
||||||
int path_input_len;
|
int path_input_len;
|
||||||
|
int path_mode; /* PM_* - o que fazer no Enter */
|
||||||
|
|
||||||
int win_w, win_h;
|
int win_w, win_h;
|
||||||
} Ed;
|
} Ed;
|
||||||
@@ -1895,6 +1918,202 @@ static void save_composite_from_tab(Ed* ed) {
|
|||||||
ed->hot_status_ok = true;
|
ed->hot_status_ok = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ===
|
||||||
|
* Blueprint: conversao Ed <-> TbBlueprint e I/O de projeto
|
||||||
|
* === */
|
||||||
|
static TbBlueprint* ed_to_blueprint(Ed* ed) {
|
||||||
|
TbBlueprint* bp = tb_blueprint_new();
|
||||||
|
if (!bp) return NULL;
|
||||||
|
bp->cur_tab = ed->cur_tab;
|
||||||
|
|
||||||
|
for (int ti = 0; ti < ed->tab_n; ti++) {
|
||||||
|
Tab* T = &ed->tabs[ti];
|
||||||
|
int idx = tb_blueprint_add_tab(bp, T->name, T->is_composite);
|
||||||
|
if (idx < 0) break;
|
||||||
|
TbBpTab* B = &bp->tabs[idx];
|
||||||
|
B->comp_id = T->comp_id;
|
||||||
|
B->color_idx = T->color_idx;
|
||||||
|
B->ws_sx = T->ws_sx; B->ws_sy = T->ws_sy;
|
||||||
|
B->top_n = T->top_n;
|
||||||
|
for (int i = 0; i < T->top_n; i++) B->top[i] = T->top[i];
|
||||||
|
for (int i = 0; i < MAX_WS; i++) {
|
||||||
|
EdBlock* b = &T->ws[i];
|
||||||
|
if (!b->used) continue;
|
||||||
|
TbBpBlock* o = &B->blocks[i];
|
||||||
|
o->used = true;
|
||||||
|
snprintf(o->type, sizeof(o->type), "%s", b->type_name);
|
||||||
|
o->x = b->x; o->y = b->y;
|
||||||
|
o->parent = b->parent; o->prel = b->prel; o->next = b->next;
|
||||||
|
for (int k = 0; k < 2; k++) o->sub[k] = b->sub[k];
|
||||||
|
for (int s = 0; s < MAX_INPUTS; s++) {
|
||||||
|
o->args[s] = b->args[s];
|
||||||
|
snprintf(o->in_text[s], sizeof(o->in_text[s]), "%s", b->in_text[s]);
|
||||||
|
}
|
||||||
|
snprintf(o->lit, sizeof(o->lit), "%s", b->lit_text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int u = 0; u < ed->user_block_n && bp->user_block_n < TB_BP_MAX_UBLOCKS; u++) {
|
||||||
|
UserBlockDef* d = &ed->user_blocks[u];
|
||||||
|
TbBpUserBlock* o = &bp->user_blocks[bp->user_block_n++];
|
||||||
|
memset(o, 0, sizeof(*o));
|
||||||
|
snprintf(o->name, sizeof(o->name), "%s", d->name);
|
||||||
|
o->input_count = d->input_count;
|
||||||
|
o->output_count = d->output_count;
|
||||||
|
for (int i = 0; i < d->input_count && i < TB_BP_MAX_USLOTS; i++)
|
||||||
|
snprintf(o->input_names[i], 32, "%s", d->input_names[i]);
|
||||||
|
for (int i = 0; i < d->output_count && i < TB_BP_MAX_USLOTS; i++)
|
||||||
|
snprintf(o->output_names[i], 32, "%s", d->output_names[i]);
|
||||||
|
o->part_n = d->part_n;
|
||||||
|
for (int i = 0; i < d->part_n && i < TB_BP_MAX_UPARTS; i++) {
|
||||||
|
o->parts[i].kind = (TbBpParamKind)d->parts[i].kind;
|
||||||
|
snprintf(o->parts[i].name, 32, "%s", d->parts[i].name);
|
||||||
|
}
|
||||||
|
o->color_idx = d->color_idx;
|
||||||
|
o->tab_idx = d->tab_idx;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < tb_variables_count() && bp->var_n < TB_BP_MAX_VARS; i++) {
|
||||||
|
const TinyBlocks_Value* v = tb_variables_value(i);
|
||||||
|
TbBpVar* o = &bp->vars[bp->var_n++];
|
||||||
|
memset(o, 0, sizeof(*o));
|
||||||
|
snprintf(o->name, sizeof(o->name), "%s", tb_variables_name(i));
|
||||||
|
if (v && v->kind == TB_VALUE_INTEGER) { o->kind = TB_BP_VAL_INT; o->num = (double)v->as.integer; }
|
||||||
|
else if (v && v->kind == TB_VALUE_REAL) { o->kind = TB_BP_VAL_REAL; o->num = v->as.real; }
|
||||||
|
else if (v && v->kind == TB_VALUE_TEXT && v->as.text) { o->kind = TB_BP_VAL_TEXT; snprintf(o->text, sizeof(o->text), "%s", v->as.text); }
|
||||||
|
else o->kind = TB_BP_VAL_INT;
|
||||||
|
}
|
||||||
|
return bp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Descarta tudo do editor e reconstroi a partir da blueprint. */
|
||||||
|
static void blueprint_apply(Ed* ed, const TbBlueprint* bp) {
|
||||||
|
run_reset(ed);
|
||||||
|
invalidate_types(ed);
|
||||||
|
for (int u = 0; u < ed->user_block_n; u++) {
|
||||||
|
UserBlockDef* d = &ed->user_blocks[u];
|
||||||
|
if (d->reg_type) { tb_block_destroy(&d->reg_type->base, ed->rt); d->reg_type = NULL; }
|
||||||
|
free(d->snap); d->snap = NULL;
|
||||||
|
}
|
||||||
|
ed->user_block_n = 0;
|
||||||
|
for (int t = 0; t < ed->tab_n; t++) memset(&ed->tabs[t], 0, sizeof(Tab));
|
||||||
|
ed->tab_n = 0;
|
||||||
|
tb_variables_clear();
|
||||||
|
|
||||||
|
for (int u = 0; u < bp->user_block_n && ed->user_block_n < MAX_USER_BLOCKS; u++) {
|
||||||
|
const TbBpUserBlock* o = &bp->user_blocks[u];
|
||||||
|
UserBlockDef* d = &ed->user_blocks[ed->user_block_n++];
|
||||||
|
memset(d, 0, sizeof(*d));
|
||||||
|
snprintf(d->name, sizeof(d->name), "%s", o->name);
|
||||||
|
d->input_count = o->input_count;
|
||||||
|
d->output_count = o->output_count;
|
||||||
|
for (int i = 0; i < o->input_count && i < MAX_UBLK_SLOTS; i++)
|
||||||
|
snprintf(d->input_names[i], 32, "%s", o->input_names[i]);
|
||||||
|
for (int i = 0; i < o->output_count && i < MAX_UBLK_SLOTS; i++)
|
||||||
|
snprintf(d->output_names[i], 32, "%s", o->output_names[i]);
|
||||||
|
d->part_n = o->part_n;
|
||||||
|
for (int i = 0; i < o->part_n && i < MAX_UBLK_PARTS; i++) {
|
||||||
|
d->parts[i].kind = (ParamKind)o->parts[i].kind;
|
||||||
|
snprintf(d->parts[i].name, 32, "%s", o->parts[i].name);
|
||||||
|
}
|
||||||
|
d->color_idx = o->color_idx;
|
||||||
|
d->tab_idx = o->tab_idx;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int ti = 0; ti < bp->tab_count && ed->tab_n < MAX_TABS; ti++) {
|
||||||
|
const TbBpTab* B = &bp->tabs[ti];
|
||||||
|
int idx = ed->tab_n++;
|
||||||
|
Tab* T = &ed->tabs[idx];
|
||||||
|
memset(T, 0, sizeof(*T));
|
||||||
|
snprintf(T->name, sizeof(T->name), "%s", B->name);
|
||||||
|
T->is_composite = B->composite;
|
||||||
|
T->comp_id = B->comp_id;
|
||||||
|
T->color_idx = B->color_idx;
|
||||||
|
T->ws_sx = B->ws_sx; T->ws_sy = B->ws_sy;
|
||||||
|
for (int i = 0; i < MAX_WS; i++) {
|
||||||
|
T->ws[i].parent = -1; T->ws[i].prel = REL_NONE; T->ws[i].next = -1;
|
||||||
|
T->ws[i].sub[0] = T->ws[i].sub[1] = -1;
|
||||||
|
for (int s = 0; s < MAX_INPUTS; s++) T->ws[i].args[s] = -1;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < MAX_WS; i++) {
|
||||||
|
const TbBpBlock* o = &B->blocks[i];
|
||||||
|
if (!o->used) continue;
|
||||||
|
EdBlock* b = &T->ws[i];
|
||||||
|
b->used = true;
|
||||||
|
snprintf(b->type_name, sizeof(b->type_name), "%s", o->type);
|
||||||
|
b->type = b->type_name[0] ? tb_type_block_find(ed->rt, b->type_name) : NULL;
|
||||||
|
b->x = o->x; b->y = o->y;
|
||||||
|
b->parent = o->parent; b->prel = o->prel; b->next = o->next;
|
||||||
|
for (int k = 0; k < 2; k++) b->sub[k] = o->sub[k];
|
||||||
|
for (int s = 0; s < MAX_INPUTS; s++) {
|
||||||
|
b->args[s] = o->args[s];
|
||||||
|
snprintf(b->in_text[s], sizeof(b->in_text[s]), "%s", o->in_text[s]);
|
||||||
|
}
|
||||||
|
snprintf(b->lit_text, sizeof(b->lit_text), "%s", o->lit);
|
||||||
|
}
|
||||||
|
T->top_n = B->top_n < MAX_WS ? B->top_n : MAX_WS;
|
||||||
|
for (int i = 0; i < T->top_n; i++) T->top[i] = B->top[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int u = 0; u < ed->user_block_n; u++) {
|
||||||
|
UserBlockDef* d = &ed->user_blocks[u];
|
||||||
|
int ti = -1;
|
||||||
|
for (int t = 0; t < ed->tab_n; t++)
|
||||||
|
if (ed->tabs[t].comp_id == u && ed->tabs[t].is_composite) { ti = t; break; }
|
||||||
|
if (ti >= 0) comp_register(ed, d, &ed->tabs[ti]);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < bp->var_n; i++) {
|
||||||
|
const TbBpVar* v = &bp->vars[i];
|
||||||
|
char buf[160];
|
||||||
|
if (v->kind == TB_BP_VAL_INT) snprintf(buf, sizeof(buf), "%lld", (long long)v->num);
|
||||||
|
else if (v->kind == TB_BP_VAL_REAL) snprintf(buf, sizeof(buf), "%g", v->num);
|
||||||
|
else snprintf(buf, sizeof(buf), "%s", v->text);
|
||||||
|
tb_variables_set_text(v->name, buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
ed->cur_tab = (bp->cur_tab >= 0 && bp->cur_tab < ed->tab_n) ? bp->cur_tab : 0;
|
||||||
|
palette_rebuild(ed);
|
||||||
|
tab_select(ed, ed->cur_tab);
|
||||||
|
ed->stage_buf[0] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool project_load(Ed* ed, const char* path) {
|
||||||
|
char err[160] = "";
|
||||||
|
TbBlueprint* bp = tb_blueprint_load_file(path, err, sizeof(err));
|
||||||
|
if (!bp) {
|
||||||
|
snprintf(ed->hot_status, sizeof(ed->hot_status), "Falha ao abrir: %.200s", err[0] ? err : path);
|
||||||
|
ed->hot_status_ok = false;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
blueprint_apply(ed, bp);
|
||||||
|
tb_blueprint_free(bp);
|
||||||
|
snprintf(ed->hot_status, sizeof(ed->hot_status), "Projeto aberto: %.200s", path);
|
||||||
|
ed->hot_status_ok = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool project_save(Ed* ed, const char* path) {
|
||||||
|
TbBlueprint* bp = ed_to_blueprint(ed);
|
||||||
|
bool ok = bp && tb_blueprint_save_file(bp, path, TB_BP_FMT_JSON, true);
|
||||||
|
tb_blueprint_free(bp);
|
||||||
|
snprintf(ed->hot_status, sizeof(ed->hot_status),
|
||||||
|
ok ? "Projeto salvo: %.200s" : "Falha ao salvar: %.200s", path);
|
||||||
|
ed->hot_status_ok = ok;
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool project_export(Ed* ed, const char* path, int fmt) {
|
||||||
|
TbBlueprint* bp = ed_to_blueprint(ed);
|
||||||
|
bool ok = bp && tb_blueprint_save_file(bp, path, fmt, true);
|
||||||
|
tb_blueprint_free(bp);
|
||||||
|
snprintf(ed->hot_status, sizeof(ed->hot_status),
|
||||||
|
ok ? "Exportado %s: %.200s" : "Falha ao exportar %s: %.200s",
|
||||||
|
tb_blueprint_format_name(fmt), path);
|
||||||
|
ed->hot_status_ok = ok;
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
/* ===
|
/* ===
|
||||||
* Diálogo modal "Criar um Bloco" (estilo Scratch)
|
* Diálogo modal "Criar um Bloco" (estilo Scratch)
|
||||||
* === */
|
* === */
|
||||||
@@ -2339,18 +2558,43 @@ static void hotlib_check(Ed* ed) {
|
|||||||
/* ===
|
/* ===
|
||||||
* Renderização da interface
|
* Renderização da interface
|
||||||
* === */
|
* === */
|
||||||
|
static bool hit_open_btn(float mx, float my);
|
||||||
|
static bool hit_save_btn(float mx, float my);
|
||||||
|
static bool hit_exp_btn(float mx, float my, int fmt);
|
||||||
|
|
||||||
|
static void menu_button(TinyBlocks_RenderableBlock* rb, float x, float w, const char* label, bool active) {
|
||||||
|
rb_fill_rrect(rb, x, 7, w, MENU_H - 14, 6, active ? COL_MENU_DARK : COLA(255, 255, 255, 34));
|
||||||
|
rb_text_c(rb, x + (w - tw(label, FS_UI)) * 0.5f, MENU_H * 0.5f, label, COL_WHITE, FS_UI);
|
||||||
|
}
|
||||||
|
|
||||||
static void render_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) {
|
static void render_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) {
|
||||||
rb_fill_rect(rb, 0, 0, WIN_W, MENU_H, COL_MENU);
|
rb_fill_rect(rb, 0, 0, WIN_W, MENU_H, COL_MENU);
|
||||||
rb_text_c(rb, 18, MENU_H*0.5f, "TinyBlocks", COL_WHITE, 20);
|
rb_text_c(rb, 18, MENU_H*0.5f, "TinyBlocks", COL_WHITE, 20);
|
||||||
|
float mx = ed->mouse_x, my = ed->mouse_y;
|
||||||
|
bool active = ed->path_input_active;
|
||||||
|
|
||||||
if (ed->lib_hover || ed->path_input_active)
|
menu_button(rb, OPEN_BTN_X, OPEN_BTN_W, "Abrir", (active && ed->path_mode == PM_LOAD) || hit_open_btn(mx, my));
|
||||||
|
menu_button(rb, SAVE_BTN_X, SAVE_BTN_W, "Salvar", (active && ed->path_mode == PM_SAVE) || hit_save_btn(mx, my));
|
||||||
|
rb_text_c(rb, EXP_LBL_X, MENU_H*0.5f, "Exportar:", COL_WHITE, FS_UI);
|
||||||
|
menu_button(rb, EXP_JSON_X, EXP_JSON_W, "JSON", (active && ed->path_mode == PM_EXP_JSON) || hit_exp_btn(mx, my, EX_JSON));
|
||||||
|
menu_button(rb, EXP_XML_X, EXP_XML_W, "XML", (active && ed->path_mode == PM_EXP_XML) || hit_exp_btn(mx, my, EX_XML));
|
||||||
|
menu_button(rb, EXP_CSV_X, EXP_CSV_W, "CSV", (active && ed->path_mode == PM_EXP_CSV) || hit_exp_btn(mx, my, EX_CSV));
|
||||||
|
|
||||||
|
if (ed->lib_hover || (active && ed->path_mode == PM_LIB))
|
||||||
rb_fill_rect(rb, LIB_BTN_X, 0, LIB_BTN_W, MENU_H, COL_MENU_DARK);
|
rb_fill_rect(rb, LIB_BTN_X, 0, LIB_BTN_W, MENU_H, COL_MENU_DARK);
|
||||||
rb_text_c(rb, LIB_BTN_X + 14, MENU_H*0.5f, "Carregar library=", COL_WHITE, FS_UI);
|
rb_text_c(rb, LIB_BTN_X + 14, MENU_H*0.5f, "Carregar library=", COL_WHITE, FS_UI);
|
||||||
|
|
||||||
if (ed->path_input_active) {
|
if (ed->path_input_active) {
|
||||||
float bx = LIB_BTN_X + LIB_BTN_W + 10, bw = WIN_W - bx - 16;
|
float bx = LIB_BTN_X + LIB_BTN_W + 10, bw = WIN_W - bx - 16;
|
||||||
rb_fill_rrect(rb, bx, 7, bw, MENU_H-14, 6, COL_WHITE);
|
rb_fill_rrect(rb, bx, 7, bw, MENU_H-14, 6, COL_WHITE);
|
||||||
const char* t = ed->path_input_buf[0] ? ed->path_input_buf : "caminho do .so (Enter carrega, Esc cancela)";
|
const char* prompt =
|
||||||
|
ed->path_mode == PM_LOAD ? "caminho do projeto .json (Enter abre, Esc cancela)" :
|
||||||
|
ed->path_mode == PM_SAVE ? "caminho para salvar o projeto .json" :
|
||||||
|
ed->path_mode == PM_EXP_JSON ? "caminho para exportar .json" :
|
||||||
|
ed->path_mode == PM_EXP_XML ? "caminho para exportar .xml" :
|
||||||
|
ed->path_mode == PM_EXP_CSV ? "caminho para exportar .csv" :
|
||||||
|
"caminho do .so (Enter carrega, Esc cancela)";
|
||||||
|
const char* t = ed->path_input_buf[0] ? ed->path_input_buf : prompt;
|
||||||
rb_text_c(rb, bx + 10, MENU_H*0.5f, t, ed->path_input_buf[0] ? COL_TEXT : COL_TEXT_DIM, FS_UI);
|
rb_text_c(rb, bx + 10, MENU_H*0.5f, t, ed->path_input_buf[0] ? COL_TEXT : COL_TEXT_DIM, FS_UI);
|
||||||
float cw = tw(ed->path_input_buf, FS_UI);
|
float cw = tw(ed->path_input_buf, FS_UI);
|
||||||
rb_fill_rect(rb, bx + 11 + cw, MENU_H*0.5f - 8, 1.5f, 16, COL_TEXT);
|
rb_fill_rect(rb, bx + 11 + cw, MENU_H*0.5f - 8, 1.5f, 16, COL_TEXT);
|
||||||
@@ -2795,6 +3039,22 @@ static bool hit_detach(Ed* ed, float mx, float my) {
|
|||||||
return ed->stage && in_rect(mx, my, WIN_W-50, MENU_H+6, 40, 32);
|
return ed->stage && in_rect(mx, my, WIN_W-50, MENU_H+6, 40, 32);
|
||||||
}
|
}
|
||||||
static bool hit_lib_btn(float mx, float my) { return in_rect(mx, my, LIB_BTN_X, 0, LIB_BTN_W, MENU_H); }
|
static bool hit_lib_btn(float mx, float my) { return in_rect(mx, my, LIB_BTN_X, 0, LIB_BTN_W, MENU_H); }
|
||||||
|
static bool hit_open_btn(float mx, float my) { return in_rect(mx, my, OPEN_BTN_X, 0, OPEN_BTN_W, MENU_H); }
|
||||||
|
static bool hit_save_btn(float mx, float my) { return in_rect(mx, my, SAVE_BTN_X, 0, SAVE_BTN_W, MENU_H); }
|
||||||
|
static bool hit_exp_btn(float mx, float my, int fmt) {
|
||||||
|
switch (fmt) {
|
||||||
|
case EX_JSON: return in_rect(mx, my, EXP_JSON_X, 0, EXP_JSON_W, MENU_H);
|
||||||
|
case EX_XML: return in_rect(mx, my, EXP_XML_X, 0, EXP_XML_W, MENU_H);
|
||||||
|
default: return in_rect(mx, my, EXP_CSV_X, 0, EXP_CSV_W, MENU_H);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void start_path(Ed* ed, int mode, const char* def) {
|
||||||
|
ed->path_input_active = true;
|
||||||
|
ed->path_mode = mode;
|
||||||
|
snprintf(ed->path_input_buf, sizeof(ed->path_input_buf), "%s", def ? def : "");
|
||||||
|
ed->path_input_len = (int)strlen(ed->path_input_buf);
|
||||||
|
}
|
||||||
|
|
||||||
static int hit_fly(Ed* ed, float mx, float my) {
|
static int hit_fly(Ed* ed, float mx, float my) {
|
||||||
float fx = mx - CAT_W, fy = my - PAL_Y + ed->fly_scroll;
|
float fx = mx - CAT_W, fy = my - PAL_Y + ed->fly_scroll;
|
||||||
@@ -2890,12 +3150,13 @@ static void on_lmb_down(Ed* ed, float mx, float my) {
|
|||||||
|
|
||||||
/* Barra de menu */
|
/* Barra de menu */
|
||||||
if (my < MENU_H) {
|
if (my < MENU_H) {
|
||||||
if (hit_lib_btn(mx, my)) {
|
if (hit_lib_btn(mx, my)) start_path(ed, PM_LIB, "");
|
||||||
ed->path_input_active = true;
|
else if (hit_open_btn(mx, my)) start_path(ed, PM_LOAD, "projeto.json");
|
||||||
ed->path_input_buf[0] = 0; ed->path_input_len = 0;
|
else if (hit_save_btn(mx, my)) start_path(ed, PM_SAVE, "projeto.json");
|
||||||
} else if (mx < LIB_BTN_X + LIB_BTN_W) {
|
else if (hit_exp_btn(mx, my, EX_JSON)) start_path(ed, PM_EXP_JSON, "projeto.json");
|
||||||
ed->path_input_active = false;
|
else if (hit_exp_btn(mx, my, EX_XML)) start_path(ed, PM_EXP_XML, "projeto.xml");
|
||||||
}
|
else if (hit_exp_btn(mx, my, EX_CSV)) start_path(ed, PM_EXP_CSV, "projeto.csv");
|
||||||
|
else ed->path_input_active = false;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
ed->path_input_active = false;
|
ed->path_input_active = false;
|
||||||
@@ -3021,10 +3282,21 @@ static void on_key(Ed* ed, int sc, bool ctrl) {
|
|||||||
if (ed->ctx_menu_open) { if (sc == TB_KEY_ESCAPE) ed->ctx_menu_open = false; return; }
|
if (ed->ctx_menu_open) { if (sc == TB_KEY_ESCAPE) ed->ctx_menu_open = false; return; }
|
||||||
|
|
||||||
if (ed->path_input_active) {
|
if (ed->path_input_active) {
|
||||||
if (sc == TB_KEY_ESCAPE) ed->path_input_active = false;
|
if (sc == TB_KEY_ESCAPE) { ed->path_input_active = false; ed->path_mode = PM_NONE; }
|
||||||
else if (enter) {
|
else if (enter) {
|
||||||
if (ed->path_input_buf[0]) hotlib_load(ed, ed->path_input_buf);
|
const char* p = ed->path_input_buf;
|
||||||
|
if (p[0]) {
|
||||||
|
switch (ed->path_mode) {
|
||||||
|
case PM_LOAD: project_load(ed, p); break;
|
||||||
|
case PM_SAVE: project_save(ed, p); break;
|
||||||
|
case PM_EXP_JSON: project_export(ed, p, EX_JSON); break;
|
||||||
|
case PM_EXP_XML: project_export(ed, p, EX_XML); break;
|
||||||
|
case PM_EXP_CSV: project_export(ed, p, EX_CSV); break;
|
||||||
|
default: hotlib_load(ed, p); break;
|
||||||
|
}
|
||||||
|
}
|
||||||
ed->path_input_active = false;
|
ed->path_input_active = false;
|
||||||
|
ed->path_mode = PM_NONE;
|
||||||
} else if (sc == TB_KEY_BACKSPACE) {
|
} else if (sc == TB_KEY_BACKSPACE) {
|
||||||
utf8_pop(ed->path_input_buf);
|
utf8_pop(ed->path_input_buf);
|
||||||
ed->path_input_len = (int)strlen(ed->path_input_buf);
|
ed->path_input_len = (int)strlen(ed->path_input_buf);
|
||||||
@@ -3040,8 +3312,7 @@ static void on_key(Ed* ed, int sc, bool ctrl) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (ctrl && sc == (TB_KEY_A + ('o' - 'a'))) {
|
if (ctrl && sc == (TB_KEY_A + ('o' - 'a'))) {
|
||||||
ed->path_input_active = true;
|
start_path(ed, PM_LIB, "");
|
||||||
ed->path_input_buf[0] = 0; ed->path_input_len = 0;
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (sc == TB_KEY_DELETE && ed->state == ES_IDLE) {
|
if (sc == TB_KEY_DELETE && ed->state == ES_IDLE) {
|
||||||
@@ -3132,6 +3403,7 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|||||||
if (dropped[0]) {
|
if (dropped[0]) {
|
||||||
size_t len = strlen(dropped);
|
size_t len = strlen(dropped);
|
||||||
if (len > 3 && strcmp(dropped + len - 3, ".so") == 0) hotlib_load(ed, dropped);
|
if (len > 3 && strcmp(dropped + len - 3, ".so") == 0) hotlib_load(ed, dropped);
|
||||||
|
else if (len > 5 && strcmp(dropped + len - 5, ".json") == 0) project_load(ed, dropped);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ev_int(evb, GFX_IN_MOUSE_L_DOWN)) on_lmb_down(ed, mx, my);
|
if (ev_int(evb, GFX_IN_MOUSE_L_DOWN)) on_lmb_down(ed, mx, my);
|
||||||
@@ -3232,6 +3504,7 @@ static bool editor_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|||||||
ed->edit_bi = -1;
|
ed->edit_bi = -1;
|
||||||
ed->bubble_bi = -1;
|
ed->bubble_bi = -1;
|
||||||
ed->ctx_menu_bi = -1;
|
ed->ctx_menu_bi = -1;
|
||||||
|
ed->path_mode = PM_NONE;
|
||||||
|
|
||||||
ed->tab_n = 1;
|
ed->tab_n = 1;
|
||||||
ed->cur_tab = 0;
|
ed->cur_tab = 0;
|
||||||
@@ -3240,7 +3513,7 @@ static bool editor_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|||||||
strcpy(ed->stage_buf,
|
strcpy(ed->stage_buf,
|
||||||
"Clique na bandeira verde (ou F5) para executar.\n"
|
"Clique na bandeira verde (ou F5) para executar.\n"
|
||||||
"Clique num bloco para executá-lo sozinho.\n");
|
"Clique num bloco para executá-lo sozinho.\n");
|
||||||
strcpy(ed->hot_status, "Ctrl+O ou arraste um .so para carregar uma library");
|
strcpy(ed->hot_status, "Abrir/Salvar projeto no menu; Ctrl+O ou arraste um .so");
|
||||||
ed->hot_status_ok = true;
|
ed->hot_status_ok = true;
|
||||||
|
|
||||||
*(Ed**)self->userdata = ed;
|
*(Ed**)self->userdata = ed;
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Makefile da library json (lexer + parser + emissor)
|
||||||
|
CC := gcc
|
||||||
|
BUILD := build
|
||||||
|
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||||
|
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude
|
||||||
|
|
||||||
|
OBJS := $(BUILD)/lexer.o $(BUILD)/parser.o $(BUILD)/tb_json.o
|
||||||
|
LIB_A := $(BUILD)/libtinyblocks-json.a
|
||||||
|
LIB_SO := $(BUILD)/libtinyblocks-json.so
|
||||||
|
|
||||||
|
.PHONY: all static shared clean
|
||||||
|
all: static shared
|
||||||
|
static: $(LIB_A)
|
||||||
|
shared: $(LIB_SO)
|
||||||
|
|
||||||
|
$(BUILD)/lexer.o: src/lexer.c include/lexeme.h
|
||||||
|
@mkdir -p $(BUILD)
|
||||||
|
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||||
|
$(BUILD)/parser.o: src/parser.c include/ast.h include/lexeme.h
|
||||||
|
@mkdir -p $(BUILD)
|
||||||
|
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||||
|
$(BUILD)/tb_json.o: src/tb_json.c include/tb_json.h include/ast.h include/lexeme.h
|
||||||
|
@mkdir -p $(BUILD)
|
||||||
|
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||||
|
|
||||||
|
$(LIB_A): $(OBJS)
|
||||||
|
ar rcs $@ $^
|
||||||
|
$(LIB_SO): $(OBJS)
|
||||||
|
$(CC) -shared -o $@ $^
|
||||||
|
|
||||||
|
clean:
|
||||||
|
$(RM) -r $(BUILD)
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-json / include/ast.h
|
||||||
|
* Arvore de valores JSON e API de parse/construcao/emissao.
|
||||||
|
*/
|
||||||
|
#ifndef TB_JSON_AST_H
|
||||||
|
#define TB_JSON_AST_H
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include "lexeme.h"
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
JSON_NULL, JSON_BOOL, JSON_INT, JSON_REAL, JSON_STR, JSON_ARR, JSON_OBJ
|
||||||
|
} JsonKind;
|
||||||
|
|
||||||
|
typedef struct JsonValue JsonValue;
|
||||||
|
struct JsonValue {
|
||||||
|
JsonKind kind;
|
||||||
|
bool bval;
|
||||||
|
long long ival;
|
||||||
|
double fval;
|
||||||
|
char* str; /* JSON_STR */
|
||||||
|
JsonValue** items; /* JSON_ARR / JSON_OBJ (valores) */
|
||||||
|
char** keys; /* JSON_OBJ (chaves, alinhado a items) */
|
||||||
|
size_t count, cap;
|
||||||
|
};
|
||||||
|
|
||||||
|
/* -- Parse --- */
|
||||||
|
JsonValue* json_parse(const char* text, JsonLexError* err);
|
||||||
|
JsonValue* json_parse_file(const char* path, JsonLexError* err);
|
||||||
|
void json_free(JsonValue* v);
|
||||||
|
|
||||||
|
/* -- Construcao (assumem a posse dos filhos) --- */
|
||||||
|
JsonValue* json_null(void);
|
||||||
|
JsonValue* json_bool(bool b);
|
||||||
|
JsonValue* json_int(long long i);
|
||||||
|
JsonValue* json_real(double d);
|
||||||
|
JsonValue* json_str(const char* s);
|
||||||
|
JsonValue* json_arr(void);
|
||||||
|
JsonValue* json_obj(void);
|
||||||
|
void json_arr_add(JsonValue* arr, JsonValue* v);
|
||||||
|
void json_obj_put(JsonValue* obj, const char* key, JsonValue* v); /* ultimo vence */
|
||||||
|
|
||||||
|
/* -- Navegacao --- */
|
||||||
|
JsonValue* json_obj_get(const JsonValue* obj, const char* key);
|
||||||
|
JsonValue* json_arr_at(const JsonValue* arr, size_t i);
|
||||||
|
size_t json_size(const JsonValue* v);
|
||||||
|
const char* json_as_str (const JsonValue* v, const char* def);
|
||||||
|
long long json_as_int (const JsonValue* v, long long def);
|
||||||
|
double json_as_real(const JsonValue* v, double def);
|
||||||
|
bool json_as_bool(const JsonValue* v, bool def);
|
||||||
|
|
||||||
|
/* -- Emissao (json_to_string devolve malloc; libere com free) --- */
|
||||||
|
char* json_to_string(const JsonValue* v, bool pretty);
|
||||||
|
bool json_write_file(const JsonValue* v, const char* path, bool pretty);
|
||||||
|
|
||||||
|
#endif /* TB_JSON_AST_H */
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-json / include/lexeme.h
|
||||||
|
* Lexer de JSON: transforma o texto em uma lista de lexemas.
|
||||||
|
*/
|
||||||
|
#ifndef TB_JSON_LEXEME_H
|
||||||
|
#define TB_JSON_LEXEME_H
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
JL_EOF, JL_ERROR,
|
||||||
|
JL_LBRACE, JL_RBRACE, JL_LBRACKET, JL_RBRACKET,
|
||||||
|
JL_COLON, JL_COMMA,
|
||||||
|
JL_STRING, JL_NUMBER, JL_TRUE, JL_FALSE, JL_NULL
|
||||||
|
} JsonLexKind;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
JsonLexKind kind;
|
||||||
|
const char* start; /* inicio no texto original */
|
||||||
|
size_t len;
|
||||||
|
int line, col;
|
||||||
|
char* text; /* string decodificada (JL_STRING) */
|
||||||
|
bool is_int;
|
||||||
|
long long ival;
|
||||||
|
double num;
|
||||||
|
} JsonLexeme;
|
||||||
|
|
||||||
|
typedef struct { JsonLexeme* items; size_t count, cap; } JsonLexemeList;
|
||||||
|
|
||||||
|
typedef struct { bool ok; char msg[128]; int line, col; } JsonLexError;
|
||||||
|
|
||||||
|
/* Tokeniza 'src'; em sucesso devolve true e preenche 'out'. */
|
||||||
|
bool json_lex(const char* src, JsonLexemeList* out, JsonLexError* err);
|
||||||
|
void json_lexemes_free(JsonLexemeList* l);
|
||||||
|
const char* json_lexeme_name(JsonLexKind k);
|
||||||
|
|
||||||
|
#endif /* TB_JSON_LEXEME_H */
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tb_json.h
|
||||||
|
* Library tinyblocks-json: parser/emissor de JSON e blocos de consulta.
|
||||||
|
*/
|
||||||
|
#ifndef TINYBLOCKS_JSON_H
|
||||||
|
#define TINYBLOCKS_JSON_H
|
||||||
|
|
||||||
|
#include <tinyblocks/tinyblocks.h>
|
||||||
|
#include "ast.h"
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
TB_API const TinyBlocks_LibraryDescriptor* tb_json_get_library(void);
|
||||||
|
|
||||||
|
/* Le um valor escalar de um texto JSON (caminho "a.b[0].c").
|
||||||
|
* Devolve em buffer estatico; util para metadados/UI. */
|
||||||
|
TB_API const char* tb_json_get_path(const char* text, const char* dotted, const char* def);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* TINYBLOCKS_JSON_H */
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Metadados da library json. Lido pela UI/build sem recompilar o .so.
|
||||||
|
[library]
|
||||||
|
name = "tinyblocks-json"
|
||||||
|
version = "1.0.0"
|
||||||
|
category = "JSON"
|
||||||
|
description = "Parser e emissor de JSON"
|
||||||
|
color = [240, 173, 78, 255]
|
||||||
|
dark = [211, 132, 27, 255]
|
||||||
|
|
||||||
|
[build]
|
||||||
|
sources = ["src/lexer.c", "src/parser.c", "src/tb_json.c"]
|
||||||
|
includes = ["include"]
|
||||||
|
shared = "build/libtinyblocks-json.so"
|
||||||
|
static = "build/libtinyblocks-json.a"
|
||||||
|
depends = []
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-json / src/lexer.c
|
||||||
|
*/
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include "lexeme.h"
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
const char* p;
|
||||||
|
int line, col;
|
||||||
|
JsonLexemeList* out;
|
||||||
|
JsonLexError* err;
|
||||||
|
} Lexer;
|
||||||
|
|
||||||
|
static bool fail(Lexer* L, const char* msg) {
|
||||||
|
if (L->err) {
|
||||||
|
L->err->ok = false;
|
||||||
|
snprintf(L->err->msg, sizeof(L->err->msg), "%s", msg);
|
||||||
|
L->err->line = L->line; L->err->col = L->col;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int adv(Lexer* L) {
|
||||||
|
int c = (unsigned char)*L->p++;
|
||||||
|
if (c == '\n') { L->line++; L->col = 1; } else L->col++;
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool push(Lexer* L, JsonLexKind k, const char* start, size_t len) {
|
||||||
|
if (L->out->count >= L->out->cap) {
|
||||||
|
size_t nc = L->out->cap ? L->out->cap * 2 : 64;
|
||||||
|
JsonLexeme* p = (JsonLexeme*)realloc(L->out->items, nc * sizeof(JsonLexeme));
|
||||||
|
if (!p) return fail(L, "sem memoria");
|
||||||
|
L->out->items = p; L->out->cap = nc;
|
||||||
|
}
|
||||||
|
JsonLexeme* t = &L->out->items[L->out->count++];
|
||||||
|
memset(t, 0, sizeof(*t));
|
||||||
|
t->kind = k; t->start = start; t->len = len; t->line = L->line; t->col = L->col;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void skip_ws(Lexer* L) {
|
||||||
|
for (;;) {
|
||||||
|
char c = *L->p;
|
||||||
|
if (c == ' ' || c == '\t' || c == '\r' || c == '\n') adv(L);
|
||||||
|
else break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static int hexval(int c) {
|
||||||
|
if (c >= '0' && c <= '9') return c - '0';
|
||||||
|
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||||
|
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool utf8_put(char* b, size_t* n, unsigned cp) {
|
||||||
|
if (cp < 0x80) { b[(*n)++] = (char)cp; }
|
||||||
|
else if (cp < 0x800) {
|
||||||
|
b[(*n)++] = (char)(0xC0 | (cp >> 6));
|
||||||
|
b[(*n)++] = (char)(0x80 | (cp & 0x3F));
|
||||||
|
} else if (cp < 0x10000) {
|
||||||
|
b[(*n)++] = (char)(0xE0 | (cp >> 12));
|
||||||
|
b[(*n)++] = (char)(0x80 | ((cp >> 6) & 0x3F));
|
||||||
|
b[(*n)++] = (char)(0x80 | (cp & 0x3F));
|
||||||
|
} else {
|
||||||
|
b[(*n)++] = (char)(0xF0 | (cp >> 18));
|
||||||
|
b[(*n)++] = (char)(0x80 | ((cp >> 12) & 0x3F));
|
||||||
|
b[(*n)++] = (char)(0x80 | ((cp >> 6) & 0x3F));
|
||||||
|
b[(*n)++] = (char)(0x80 | (cp & 0x3F));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool lex_string(Lexer* L) {
|
||||||
|
const char* start = L->p;
|
||||||
|
adv(L); /* " */
|
||||||
|
size_t cap = 32, n = 0;
|
||||||
|
char* b = (char*)malloc(cap);
|
||||||
|
if (!b) return fail(L, "sem memoria");
|
||||||
|
for (;;) {
|
||||||
|
char c = *L->p;
|
||||||
|
if (c == 0) { free(b); return fail(L, "string nao terminada"); }
|
||||||
|
if (c == '"') { adv(L); break; }
|
||||||
|
if (c == '\\') {
|
||||||
|
adv(L);
|
||||||
|
char e = *L->p;
|
||||||
|
if (e == 0) { free(b); return fail(L, "escape incompleto"); }
|
||||||
|
adv(L);
|
||||||
|
char decoded = 0; bool simple = true;
|
||||||
|
switch (e) {
|
||||||
|
case '"': decoded = '"'; break;
|
||||||
|
case '\\': decoded = '\\'; break;
|
||||||
|
case '/': decoded = '/'; break;
|
||||||
|
case 'b': decoded = '\b'; break;
|
||||||
|
case 'f': decoded = '\f'; break;
|
||||||
|
case 'n': decoded = '\n'; break;
|
||||||
|
case 'r': decoded = '\r'; break;
|
||||||
|
case 't': decoded = '\t'; break;
|
||||||
|
case 'u': {
|
||||||
|
simple = false;
|
||||||
|
unsigned cp = 0;
|
||||||
|
for (int i = 0; i < 4; i++) {
|
||||||
|
int h = hexval((unsigned char)*L->p);
|
||||||
|
if (h < 0) { free(b); return fail(L, "\\u invalido"); }
|
||||||
|
cp = cp * 16 + (unsigned)h; adv(L);
|
||||||
|
}
|
||||||
|
if (cp >= 0xD800 && cp <= 0xDBFF && L->p[0] == '\\' && L->p[1] == 'u') {
|
||||||
|
adv(L); adv(L);
|
||||||
|
unsigned lo = 0;
|
||||||
|
for (int i = 0; i < 4; i++) {
|
||||||
|
int h = hexval((unsigned char)*L->p);
|
||||||
|
if (h < 0) { free(b); return fail(L, "\\u invalido"); }
|
||||||
|
lo = lo * 16 + (unsigned)h; adv(L);
|
||||||
|
}
|
||||||
|
cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
|
||||||
|
}
|
||||||
|
if (n + 4 > cap) { cap *= 2; char* nb = realloc(b, cap); if (!nb) { free(b); return fail(L, "sem memoria"); } b = nb; }
|
||||||
|
utf8_put(b, &n, cp);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default: free(b); return fail(L, "escape invalido");
|
||||||
|
}
|
||||||
|
if (simple) {
|
||||||
|
if (n + 1 >= cap) { cap *= 2; char* nb = realloc(b, cap); if (!nb) { free(b); return fail(L, "sem memoria"); } b = nb; }
|
||||||
|
b[n++] = decoded;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (n + 1 >= cap) { cap *= 2; char* nb = realloc(b, cap); if (!nb) { free(b); return fail(L, "sem memoria"); } b = nb; }
|
||||||
|
b[n++] = c; adv(L);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b[n] = 0;
|
||||||
|
if (!push(L, JL_STRING, start, (size_t)(L->p - start))) { free(b); return false; }
|
||||||
|
L->out->items[L->out->count - 1].text = b;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool lex_number(Lexer* L) {
|
||||||
|
const char* start = L->p;
|
||||||
|
bool is_int = true;
|
||||||
|
if (*L->p == '-') adv(L);
|
||||||
|
while (*L->p >= '0' && *L->p <= '9') adv(L);
|
||||||
|
if (*L->p == '.') { is_int = false; adv(L); while (*L->p >= '0' && *L->p <= '9') adv(L); }
|
||||||
|
if (*L->p == 'e' || *L->p == 'E') {
|
||||||
|
is_int = false; adv(L);
|
||||||
|
if (*L->p == '+' || *L->p == '-') adv(L);
|
||||||
|
while (*L->p >= '0' && *L->p <= '9') adv(L);
|
||||||
|
}
|
||||||
|
char tmp[64];
|
||||||
|
size_t n = (size_t)(L->p - start);
|
||||||
|
if (n >= sizeof(tmp)) return fail(L, "numero longo demais");
|
||||||
|
memcpy(tmp, start, n); tmp[n] = 0;
|
||||||
|
if (!push(L, JL_NUMBER, start, n)) return false;
|
||||||
|
JsonLexeme* t = &L->out->items[L->out->count - 1];
|
||||||
|
if (is_int) { t->is_int = true; t->ival = strtoll(tmp, NULL, 10); t->num = (double)t->ival; }
|
||||||
|
else { t->is_int = false; t->num = strtod(tmp, NULL); t->ival = (long long)t->num; }
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool lex_word(Lexer* L) {
|
||||||
|
const char* start = L->p;
|
||||||
|
while (*L->p >= 'a' && *L->p <= 'z') adv(L);
|
||||||
|
size_t n = (size_t)(L->p - start);
|
||||||
|
JsonLexKind k;
|
||||||
|
if (n == 4 && strncmp(start, "true", 4) == 0) k = JL_TRUE;
|
||||||
|
else if (n == 5 && strncmp(start, "false", 5) == 0) k = JL_FALSE;
|
||||||
|
else if (n == 4 && strncmp(start, "null", 4) == 0) k = JL_NULL;
|
||||||
|
else return fail(L, "literal invalido");
|
||||||
|
return push(L, k, start, n);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool json_lex(const char* src, JsonLexemeList* out, JsonLexError* err) {
|
||||||
|
Lexer L = { src, 1, 1, out, err };
|
||||||
|
if (err) { err->ok = true; err->msg[0] = 0; err->line = err->col = 0; }
|
||||||
|
for (;;) {
|
||||||
|
skip_ws(&L);
|
||||||
|
char c = *L.p;
|
||||||
|
if (c == 0) { push(&L, JL_EOF, L.p, 0); return true; }
|
||||||
|
switch (c) {
|
||||||
|
case '{': adv(&L); if (!push(&L, JL_LBRACE, L.p-1, 1)) return false; break;
|
||||||
|
case '}': adv(&L); if (!push(&L, JL_RBRACE, L.p-1, 1)) return false; break;
|
||||||
|
case '[': adv(&L); if (!push(&L, JL_LBRACKET, L.p-1, 1)) return false; break;
|
||||||
|
case ']': adv(&L); if (!push(&L, JL_RBRACKET, L.p-1, 1)) return false; break;
|
||||||
|
case ':': adv(&L); if (!push(&L, JL_COLON, L.p-1, 1)) return false; break;
|
||||||
|
case ',': adv(&L); if (!push(&L, JL_COMMA, L.p-1, 1)) return false; break;
|
||||||
|
case '"': if (!lex_string(&L)) return false; break;
|
||||||
|
default:
|
||||||
|
if (c == '-' || (c >= '0' && c <= '9')) { if (!lex_number(&L)) return false; }
|
||||||
|
else if (c >= 'a' && c <= 'z') { if (!lex_word(&L)) return false; }
|
||||||
|
else return fail(&L, "caractere inesperado");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void json_lexemes_free(JsonLexemeList* l) {
|
||||||
|
if (!l) return;
|
||||||
|
for (size_t i = 0; i < l->count; i++) free(l->items[i].text);
|
||||||
|
free(l->items);
|
||||||
|
l->items = NULL; l->count = l->cap = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* json_lexeme_name(JsonLexKind k) {
|
||||||
|
switch (k) {
|
||||||
|
case JL_EOF: return "fim";
|
||||||
|
case JL_ERROR: return "erro";
|
||||||
|
case JL_LBRACE: return "{";
|
||||||
|
case JL_RBRACE: return "}";
|
||||||
|
case JL_LBRACKET: return "[";
|
||||||
|
case JL_RBRACKET: return "]";
|
||||||
|
case JL_COLON: return ":";
|
||||||
|
case JL_COMMA: return ",";
|
||||||
|
case JL_STRING: return "string";
|
||||||
|
case JL_NUMBER: return "numero";
|
||||||
|
case JL_TRUE: return "true";
|
||||||
|
case JL_FALSE: return "false";
|
||||||
|
case JL_NULL: return "null";
|
||||||
|
}
|
||||||
|
return "?";
|
||||||
|
}
|
||||||
@@ -0,0 +1,330 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-json / src/parser.c
|
||||||
|
* Parser descendente recursivo + construtores + emissao.
|
||||||
|
*/
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
#include "ast.h"
|
||||||
|
|
||||||
|
/* -- utilitarios --- */
|
||||||
|
static char* dup_str(const char* s) {
|
||||||
|
size_t n = strlen(s);
|
||||||
|
char* p = (char*)malloc(n + 1);
|
||||||
|
if (!p) return NULL;
|
||||||
|
memcpy(p, s, n + 1);
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
static JsonValue* vnew(JsonKind k) {
|
||||||
|
JsonValue* v = (JsonValue*)calloc(1, sizeof(JsonValue));
|
||||||
|
if (v) v->kind = k;
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -- construtores --- */
|
||||||
|
JsonValue* json_null(void) { return vnew(JSON_NULL); }
|
||||||
|
JsonValue* json_arr(void) { return vnew(JSON_ARR); }
|
||||||
|
JsonValue* json_obj(void) { return vnew(JSON_OBJ); }
|
||||||
|
JsonValue* json_bool(bool b) { JsonValue* v = vnew(JSON_BOOL); if (v) v->bval = b; return v; }
|
||||||
|
JsonValue* json_int(long long i) { JsonValue* v = vnew(JSON_INT); if (v) v->ival = i; return v; }
|
||||||
|
JsonValue* json_real(double d) { JsonValue* v = vnew(JSON_REAL); if (v) v->fval = d; return v; }
|
||||||
|
JsonValue* json_str(const char* s) {
|
||||||
|
JsonValue* v = vnew(JSON_STR);
|
||||||
|
if (v) v->str = dup_str(s ? s : "");
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool arr_grow(JsonValue* a) {
|
||||||
|
if (a->count < a->cap) return true;
|
||||||
|
size_t nc = a->cap ? a->cap * 2 : 8;
|
||||||
|
JsonValue** ni = (JsonValue**)realloc(a->items, nc * sizeof(JsonValue*));
|
||||||
|
if (!ni) return false;
|
||||||
|
a->items = ni;
|
||||||
|
if (a->kind == JSON_OBJ) {
|
||||||
|
char** nk = (char**)realloc(a->keys, nc * sizeof(char*));
|
||||||
|
if (!nk) return false;
|
||||||
|
a->keys = nk;
|
||||||
|
}
|
||||||
|
a->cap = nc;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void json_arr_add(JsonValue* arr, JsonValue* v) {
|
||||||
|
if (!arr || arr->kind != JSON_ARR || !v) { json_free(v); return; }
|
||||||
|
if (!arr_grow(arr)) { json_free(v); return; }
|
||||||
|
arr->items[arr->count++] = v;
|
||||||
|
}
|
||||||
|
|
||||||
|
void json_obj_put(JsonValue* obj, const char* key, JsonValue* v) {
|
||||||
|
if (!obj || obj->kind != JSON_OBJ || !key) { json_free(v); return; }
|
||||||
|
for (size_t i = 0; i < obj->count; i++) {
|
||||||
|
if (strcmp(obj->keys[i], key) == 0) { json_free(obj->items[i]); obj->items[i] = v; return; }
|
||||||
|
}
|
||||||
|
if (!arr_grow(obj)) { json_free(v); return; }
|
||||||
|
obj->keys[obj->count] = dup_str(key);
|
||||||
|
obj->items[obj->count] = v;
|
||||||
|
obj->count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -- navegacao --- */
|
||||||
|
JsonValue* json_obj_get(const JsonValue* obj, const char* key) {
|
||||||
|
if (!obj || obj->kind != JSON_OBJ || !key) return NULL;
|
||||||
|
for (size_t i = 0; i < obj->count; i++)
|
||||||
|
if (strcmp(obj->keys[i], key) == 0) return obj->items[i];
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
JsonValue* json_arr_at(const JsonValue* arr, size_t i) {
|
||||||
|
if (!arr || arr->kind != JSON_ARR || i >= arr->count) return NULL;
|
||||||
|
return arr->items[i];
|
||||||
|
}
|
||||||
|
size_t json_size(const JsonValue* v) {
|
||||||
|
if (!v) return 0;
|
||||||
|
if (v->kind == JSON_ARR || v->kind == JSON_OBJ) return v->count;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const char* json_as_str(const JsonValue* v, const char* def) {
|
||||||
|
if (!v) return def;
|
||||||
|
if (v->kind == JSON_STR) return v->str ? v->str : def;
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
long long json_as_int(const JsonValue* v, long long def) {
|
||||||
|
if (!v) return def;
|
||||||
|
if (v->kind == JSON_INT) return v->ival;
|
||||||
|
if (v->kind == JSON_REAL) return (long long)v->fval;
|
||||||
|
if (v->kind == JSON_BOOL) return v->bval ? 1 : 0;
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
double json_as_real(const JsonValue* v, double def) {
|
||||||
|
if (!v) return def;
|
||||||
|
if (v->kind == JSON_REAL) return v->fval;
|
||||||
|
if (v->kind == JSON_INT) return (double)v->ival;
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
bool json_as_bool(const JsonValue* v, bool def) {
|
||||||
|
if (!v) return def;
|
||||||
|
if (v->kind == JSON_BOOL) return v->bval;
|
||||||
|
if (v->kind == JSON_INT) return v->ival != 0;
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
|
||||||
|
void json_free(JsonValue* v) {
|
||||||
|
if (!v) return;
|
||||||
|
if (v->kind == JSON_STR) free(v->str);
|
||||||
|
for (size_t i = 0; i < v->count; i++) {
|
||||||
|
if (v->kind == JSON_OBJ && v->keys) free(v->keys[i]);
|
||||||
|
json_free(v->items[i]);
|
||||||
|
}
|
||||||
|
free(v->items);
|
||||||
|
free(v->keys);
|
||||||
|
free(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -- parser --- */
|
||||||
|
typedef struct {
|
||||||
|
const JsonLexeme* t;
|
||||||
|
size_t n, i;
|
||||||
|
JsonLexError* err;
|
||||||
|
int depth;
|
||||||
|
} Parser;
|
||||||
|
|
||||||
|
#define MAX_DEPTH 256
|
||||||
|
|
||||||
|
static const JsonLexeme* cur(Parser* P) { return &P->t[P->i]; }
|
||||||
|
static void next(Parser* P) { if (P->i + 1 < P->n) P->i++; }
|
||||||
|
|
||||||
|
static bool fail(Parser* P, const char* msg) {
|
||||||
|
if (P->err) {
|
||||||
|
P->err->ok = false;
|
||||||
|
snprintf(P->err->msg, sizeof(P->err->msg), "%s", msg);
|
||||||
|
P->err->line = cur(P)->line; P->err->col = cur(P)->col;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static JsonValue* parse_value(Parser* P);
|
||||||
|
|
||||||
|
static JsonValue* parse_array(Parser* P) {
|
||||||
|
next(P); /* [ */
|
||||||
|
JsonValue* a = json_arr();
|
||||||
|
if (!a) return NULL;
|
||||||
|
if (cur(P)->kind == JL_RBRACKET) { next(P); return a; }
|
||||||
|
for (;;) {
|
||||||
|
JsonValue* v = parse_value(P);
|
||||||
|
if (!v) { json_free(a); return NULL; }
|
||||||
|
json_arr_add(a, v);
|
||||||
|
if (cur(P)->kind == JL_COMMA) { next(P); continue; }
|
||||||
|
if (cur(P)->kind == JL_RBRACKET) { next(P); return a; }
|
||||||
|
fail(P, "esperado , ou ]");
|
||||||
|
json_free(a); return NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static JsonValue* parse_object(Parser* P) {
|
||||||
|
next(P); /* { */
|
||||||
|
JsonValue* o = json_obj();
|
||||||
|
if (!o) return NULL;
|
||||||
|
if (cur(P)->kind == JL_RBRACE) { next(P); return o; }
|
||||||
|
for (;;) {
|
||||||
|
if (cur(P)->kind != JL_STRING) { fail(P, "chave (string) esperada"); json_free(o); return NULL; }
|
||||||
|
char* key = dup_str(cur(P)->text ? cur(P)->text : "");
|
||||||
|
next(P);
|
||||||
|
if (cur(P)->kind != JL_COLON) { free(key); fail(P, "esperado :"); json_free(o); return NULL; }
|
||||||
|
next(P);
|
||||||
|
JsonValue* v = parse_value(P);
|
||||||
|
if (!v) { free(key); json_free(o); return NULL; }
|
||||||
|
json_obj_put(o, key, v);
|
||||||
|
free(key);
|
||||||
|
if (cur(P)->kind == JL_COMMA) { next(P); continue; }
|
||||||
|
if (cur(P)->kind == JL_RBRACE) { next(P); return o; }
|
||||||
|
fail(P, "esperado , ou }");
|
||||||
|
json_free(o); return NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static JsonValue* parse_value(Parser* P) {
|
||||||
|
if (P->depth >= MAX_DEPTH) { fail(P, "aninhamento profundo demais"); return NULL; }
|
||||||
|
const JsonLexeme* t = cur(P);
|
||||||
|
switch (t->kind) {
|
||||||
|
case JL_STRING: next(P); return json_str(t->text ? t->text : "");
|
||||||
|
case JL_NUMBER:
|
||||||
|
next(P);
|
||||||
|
return t->is_int ? json_int(t->ival) : json_real(t->num);
|
||||||
|
case JL_TRUE: next(P); return json_bool(true);
|
||||||
|
case JL_FALSE: next(P); return json_bool(false);
|
||||||
|
case JL_NULL: next(P); return json_null();
|
||||||
|
case JL_LBRACKET: P->depth++; { JsonValue* v = parse_array(P); P->depth--; return v; }
|
||||||
|
case JL_LBRACE: P->depth++; { JsonValue* v = parse_object(P); P->depth--; return v; }
|
||||||
|
default: fail(P, "valor esperado"); return NULL;
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonValue* json_parse(const char* text, JsonLexError* err) {
|
||||||
|
JsonLexemeList toks = {0};
|
||||||
|
if (!json_lex(text, &toks, err)) { json_lexemes_free(&toks); return NULL; }
|
||||||
|
Parser P = { toks.items, toks.count, 0, err, 0 };
|
||||||
|
JsonValue* v = parse_value(&P);
|
||||||
|
if (v && cur(&P)->kind != JL_EOF) {
|
||||||
|
fail(&P, "conteudo extra apos o valor");
|
||||||
|
json_free(v); v = NULL;
|
||||||
|
}
|
||||||
|
json_lexemes_free(&toks);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonValue* json_parse_file(const char* path, JsonLexError* err) {
|
||||||
|
FILE* f = fopen(path, "rb");
|
||||||
|
if (!f) {
|
||||||
|
if (err) { err->ok = false; snprintf(err->msg, sizeof(err->msg), "nao abriu %s", path); err->line = err->col = 0; }
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
fseek(f, 0, SEEK_END);
|
||||||
|
long sz = ftell(f);
|
||||||
|
fseek(f, 0, SEEK_SET);
|
||||||
|
if (sz < 0 || sz > (long)(256 * 1024 * 1024)) { fclose(f); return NULL; }
|
||||||
|
char* buf = (char*)malloc((size_t)sz + 1);
|
||||||
|
if (!buf) { fclose(f); return NULL; }
|
||||||
|
size_t rd = fread(buf, 1, (size_t)sz, f);
|
||||||
|
buf[rd] = 0;
|
||||||
|
fclose(f);
|
||||||
|
JsonValue* v = json_parse(buf, err);
|
||||||
|
free(buf);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -- emissao --- */
|
||||||
|
typedef struct { char* p; size_t len, cap; bool ok; } Buf;
|
||||||
|
|
||||||
|
static void bput(Buf* b, const char* s, size_t n) {
|
||||||
|
if (!b->ok) return;
|
||||||
|
if (b->len + n + 1 > b->cap) {
|
||||||
|
size_t nc = b->cap ? b->cap : 128;
|
||||||
|
while (nc < b->len + n + 1) nc *= 2;
|
||||||
|
char* p = (char*)realloc(b->p, nc);
|
||||||
|
if (!p) { b->ok = false; return; }
|
||||||
|
b->p = p; b->cap = nc;
|
||||||
|
}
|
||||||
|
memcpy(b->p + b->len, s, n);
|
||||||
|
b->len += n; b->p[b->len] = 0;
|
||||||
|
}
|
||||||
|
static void bs(Buf* b, const char* s) { bput(b, s, strlen(s)); }
|
||||||
|
static void bc(Buf* b, char c) { bput(b, &c, 1); }
|
||||||
|
|
||||||
|
static void emit_string(Buf* b, const char* s) {
|
||||||
|
bc(b, '"');
|
||||||
|
for (const unsigned char* p = (const unsigned char*)s; *p; p++) {
|
||||||
|
switch (*p) {
|
||||||
|
case '"': bs(b, "\\\""); break;
|
||||||
|
case '\\': bs(b, "\\\\"); break;
|
||||||
|
case '\b': bs(b, "\\b"); break;
|
||||||
|
case '\f': bs(b, "\\f"); break;
|
||||||
|
case '\n': bs(b, "\\n"); break;
|
||||||
|
case '\r': bs(b, "\\r"); break;
|
||||||
|
case '\t': bs(b, "\\t"); break;
|
||||||
|
default:
|
||||||
|
if (*p < 0x20) { char tmp[8]; snprintf(tmp, sizeof(tmp), "\\u%04x", *p); bs(b, tmp); }
|
||||||
|
else bc(b, (char)*p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bc(b, '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
static void emit_value(Buf* b, const JsonValue* v, bool pretty, int depth) {
|
||||||
|
if (!v) { bs(b, "null"); return; }
|
||||||
|
switch (v->kind) {
|
||||||
|
case JSON_NULL: bs(b, "null"); break;
|
||||||
|
case JSON_BOOL: bs(b, v->bval ? "true" : "false"); break;
|
||||||
|
case JSON_INT: { char tmp[32]; snprintf(tmp, sizeof(tmp), "%lld", v->ival); bs(b, tmp); break; }
|
||||||
|
case JSON_REAL: { char tmp[64]; snprintf(tmp, sizeof(tmp), "%.17g", v->fval); bs(b, tmp); break; }
|
||||||
|
case JSON_STR: emit_string(b, v->str ? v->str : ""); break;
|
||||||
|
case JSON_ARR: {
|
||||||
|
if (v->count == 0) { bs(b, "[]"); break; }
|
||||||
|
bc(b, '[');
|
||||||
|
for (size_t i = 0; i < v->count; i++) {
|
||||||
|
if (i) bc(b, ',');
|
||||||
|
if (pretty) { bc(b, '\n'); for (int k = 0; k <= depth; k++) bs(b, " "); }
|
||||||
|
emit_value(b, v->items[i], pretty, depth + 1);
|
||||||
|
}
|
||||||
|
if (pretty) { bc(b, '\n'); for (int k = 0; k < depth; k++) bs(b, " "); }
|
||||||
|
bc(b, ']');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case JSON_OBJ: {
|
||||||
|
if (v->count == 0) { bs(b, "{}"); break; }
|
||||||
|
bc(b, '{');
|
||||||
|
for (size_t i = 0; i < v->count; i++) {
|
||||||
|
if (i) bc(b, ',');
|
||||||
|
if (pretty) { bc(b, '\n'); for (int k = 0; k <= depth; k++) bs(b, " "); }
|
||||||
|
emit_string(b, v->keys[i]);
|
||||||
|
bc(b, ':');
|
||||||
|
if (pretty) bc(b, ' ');
|
||||||
|
emit_value(b, v->items[i], pretty, depth + 1);
|
||||||
|
}
|
||||||
|
if (pretty) { bc(b, '\n'); for (int k = 0; k < depth; k++) bs(b, " "); }
|
||||||
|
bc(b, '}');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
char* json_to_string(const JsonValue* v, bool pretty) {
|
||||||
|
Buf b = {0};
|
||||||
|
b.ok = true;
|
||||||
|
emit_value(&b, v, pretty, 0);
|
||||||
|
if (!b.p) { b.p = (char*)malloc(1); if (b.p) b.p[0] = 0; }
|
||||||
|
return b.p;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool json_write_file(const JsonValue* v, const char* path, bool pretty) {
|
||||||
|
char* s = json_to_string(v, pretty);
|
||||||
|
if (!s) return false;
|
||||||
|
FILE* f = fopen(path, "wb");
|
||||||
|
if (!f) { free(s); return false; }
|
||||||
|
size_t n = strlen(s);
|
||||||
|
size_t w = fwrite(s, 1, n, f);
|
||||||
|
fclose(f);
|
||||||
|
free(s);
|
||||||
|
return w == n;
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tb_json.c
|
||||||
|
* Library tinyblocks-json: blocos Json.Get (consulta) e Json.Valid.
|
||||||
|
*/
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include <tinyblocks/tinyblocks.h>
|
||||||
|
#include "tb_json.h"
|
||||||
|
|
||||||
|
#define CAT_COLOR 240/255.f, 173/255.f, 78/255.f, 1.f
|
||||||
|
#define CAT_DARK 211/255.f, 132/255.f, 27/255.f, 1.f
|
||||||
|
|
||||||
|
/* Caminho "a.b[0].c" ou "a.0.c" sobre a arvore. */
|
||||||
|
static const JsonValue* path_walk(const JsonValue* root, const char* dotted) {
|
||||||
|
const JsonValue* v = root;
|
||||||
|
const char* p = dotted;
|
||||||
|
char part[128];
|
||||||
|
while (*p && v) {
|
||||||
|
size_t n = 0;
|
||||||
|
while (*p && *p != '.' && *p != '[' && n < sizeof(part) - 1) part[n++] = *p++;
|
||||||
|
part[n] = 0;
|
||||||
|
if (n) {
|
||||||
|
if (v->kind == JSON_OBJ) v = json_obj_get(v, part);
|
||||||
|
else if (v->kind == JSON_ARR) v = json_arr_at(v, (size_t)strtoul(part, NULL, 10));
|
||||||
|
else v = NULL;
|
||||||
|
}
|
||||||
|
if (v && *p == '[') {
|
||||||
|
p++;
|
||||||
|
size_t idx = 0;
|
||||||
|
while (*p >= '0' && *p <= '9') idx = idx * 10 + (size_t)(*p++ - '0');
|
||||||
|
if (*p == ']') p++;
|
||||||
|
v = json_arr_at(v, idx);
|
||||||
|
}
|
||||||
|
if (*p == '.') p++;
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
static const char* value_to_text(const JsonValue* v, char* buf, size_t cap) {
|
||||||
|
if (!v) { buf[0] = 0; return buf; }
|
||||||
|
switch (v->kind) {
|
||||||
|
case JSON_STR: snprintf(buf, cap, "%s", v->str ? v->str : ""); break;
|
||||||
|
case JSON_INT: snprintf(buf, cap, "%lld", v->ival); break;
|
||||||
|
case JSON_REAL: snprintf(buf, cap, "%g", v->fval); break;
|
||||||
|
case JSON_BOOL: snprintf(buf, cap, "%s", v->bval ? "true" : "false"); break;
|
||||||
|
case JSON_NULL: snprintf(buf, cap, "null"); break;
|
||||||
|
default: buf[0] = 0; break;
|
||||||
|
}
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void eval_get(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||||
|
TinyBlocks_Value text = tb_block_get_input(self, rt, 0);
|
||||||
|
TinyBlocks_Value key = tb_block_get_input(self, rt, 1);
|
||||||
|
const char* src = (text.kind == TB_VALUE_TEXT && text.as.text) ? text.as.text : "";
|
||||||
|
const char* dotted = (key.kind == TB_VALUE_TEXT && key.as.text) ? key.as.text : "";
|
||||||
|
JsonLexError err;
|
||||||
|
JsonValue* doc = json_parse(src, &err);
|
||||||
|
char out[512] = "";
|
||||||
|
if (doc) {
|
||||||
|
value_to_text(path_walk(doc, dotted), out, sizeof(out));
|
||||||
|
json_free(doc);
|
||||||
|
}
|
||||||
|
tb_block_set_output(self, 0, tb_value_text(out));
|
||||||
|
self->dirty = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void eval_valid(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||||
|
TinyBlocks_Value text = tb_block_get_input(self, rt, 0);
|
||||||
|
const char* src = (text.kind == TB_VALUE_TEXT && text.as.text) ? text.as.text : "";
|
||||||
|
JsonLexError err;
|
||||||
|
JsonValue* doc = json_parse(src, &err);
|
||||||
|
bool ok = doc != NULL;
|
||||||
|
json_free(doc);
|
||||||
|
tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0));
|
||||||
|
self->dirty = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool json_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||||
|
static const TinyBlocks_Category cat = { "JSON", {CAT_COLOR}, {CAT_DARK} };
|
||||||
|
tb_library_set_category(lib, &cat);
|
||||||
|
|
||||||
|
static const TinyBlocks_SlotDesc get_in[] = {{"texto", TB_VALUE_TEXT}, {"chave", TB_VALUE_TEXT}};
|
||||||
|
static const TinyBlocks_SlotDesc valid_in[] = {{"texto", TB_VALUE_TEXT}};
|
||||||
|
static const TinyBlocks_SlotDesc out_val[] = {{"valor", TB_VALUE_TEXT}};
|
||||||
|
static const TinyBlocks_SlotDesc out_bool[] = {{"valido", TB_VALUE_INTEGER}};
|
||||||
|
|
||||||
|
TinyBlocks_TypeBlock* a = tb_type_block_create(rt, "Json.Get", get_in, 2, out_val, 1, eval_get);
|
||||||
|
TinyBlocks_TypeBlock* b = tb_type_block_create(rt, "Json.Valid", valid_in, 1, out_bool, 1, eval_valid);
|
||||||
|
return a && b && tb_library_add(lib, &a->base) && tb_library_add(lib, &b->base);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void json_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { (void)rt; (void)lib; }
|
||||||
|
|
||||||
|
TINYBLOCKS_DEFINE_LIBRARY(json,
|
||||||
|
"tinyblocks-json",
|
||||||
|
"1.0.0",
|
||||||
|
json_init,
|
||||||
|
json_deinit)
|
||||||
|
|
||||||
|
const TinyBlocks_LibraryDescriptor* tb_json_get_library(void) {
|
||||||
|
return &_tb_lib_desc_json;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* tb_json_get_path(const char* text, const char* dotted, const char* def) {
|
||||||
|
static char buf[256];
|
||||||
|
JsonLexError err;
|
||||||
|
JsonValue* doc = json_parse(text, &err);
|
||||||
|
if (!doc) return def;
|
||||||
|
const JsonValue* v = path_walk(doc, dotted);
|
||||||
|
if (!v) { json_free(doc); return def; }
|
||||||
|
value_to_text(v, buf, sizeof(buf));
|
||||||
|
json_free(doc);
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
@@ -18,4 +18,10 @@ TB_API const TinyBlocks_Value* tb_variables_value(int i); /* emprestado */
|
|||||||
/* Zera variáveis que guardam blocos (chamado antes de uma nova execução) */
|
/* Zera variáveis que guardam blocos (chamado antes de uma nova execução) */
|
||||||
TB_API void tb_variables_reset_blocks(void);
|
TB_API void tb_variables_reset_blocks(void);
|
||||||
|
|
||||||
|
/* Remove todas as variáveis. */
|
||||||
|
TB_API void tb_variables_clear(void);
|
||||||
|
|
||||||
|
/* Define uma variável a partir de texto (interpreta inteiro/real; senão texto). */
|
||||||
|
TB_API void tb_variables_set_text(const char* name, const char* value);
|
||||||
|
|
||||||
#endif /* TINYBLOCKS_VARIABLES_H */
|
#endif /* TINYBLOCKS_VARIABLES_H */
|
||||||
@@ -99,6 +99,25 @@ void tb_variables_reset_blocks(void) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void tb_variables_clear(void) {
|
||||||
|
for (int i = 0; i < s_n; i++) tb_value_free(&s_vars[i].val);
|
||||||
|
s_n = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void tb_variables_set_text(const char* name, const char* value) {
|
||||||
|
if (!name || !name[0]) return;
|
||||||
|
int i = var_find(name, true);
|
||||||
|
if (i < 0) return;
|
||||||
|
tb_value_free(&s_vars[i].val);
|
||||||
|
const char* s = value ? value : "";
|
||||||
|
char* end = NULL;
|
||||||
|
long long iv = strtoll(s, &end, 10);
|
||||||
|
if (end && *end == 0 && end != s) { s_vars[i].val = tb_value_integer(iv); return; }
|
||||||
|
double dv = strtod(s, &end);
|
||||||
|
if (end && *end == 0 && end != s) { s_vars[i].val = tb_value_real(dv); return; }
|
||||||
|
s_vars[i].val = tb_value_text(s);
|
||||||
|
}
|
||||||
|
|
||||||
/* == Registro === */
|
/* == Registro === */
|
||||||
static bool variables_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
static bool variables_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||||
static const TinyBlocks_Category cat = {
|
static const TinyBlocks_Category cat = {
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Makefile da library xml (lexer + parser + emissor sobre a AST JSON do core)
|
||||||
|
CC := gcc
|
||||||
|
BUILD := build
|
||||||
|
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||||
|
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude
|
||||||
|
|
||||||
|
OBJS := $(BUILD)/lexer.o $(BUILD)/parser.o $(BUILD)/tb_xml.o
|
||||||
|
LIB_A := $(BUILD)/libtinyblocks-xml.a
|
||||||
|
LIB_SO := $(BUILD)/libtinyblocks-xml.so
|
||||||
|
|
||||||
|
.PHONY: all static shared clean
|
||||||
|
all: static shared
|
||||||
|
static: $(LIB_A)
|
||||||
|
shared: $(LIB_SO)
|
||||||
|
|
||||||
|
$(BUILD)/lexer.o: src/lexer.c include/lexeme.h
|
||||||
|
@mkdir -p $(BUILD)
|
||||||
|
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||||
|
$(BUILD)/parser.o: src/parser.c include/ast.h include/lexeme.h
|
||||||
|
@mkdir -p $(BUILD)
|
||||||
|
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||||
|
$(BUILD)/tb_xml.o: src/tb_xml.c include/tb_xml.h include/ast.h include/lexeme.h
|
||||||
|
@mkdir -p $(BUILD)
|
||||||
|
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||||
|
|
||||||
|
$(LIB_A): $(OBJS)
|
||||||
|
ar rcs $@ $^
|
||||||
|
$(LIB_SO): $(OBJS)
|
||||||
|
$(CC) -shared -o $@ $^
|
||||||
|
|
||||||
|
clean:
|
||||||
|
$(RM) -r $(BUILD)
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-xml / include/ast.h
|
||||||
|
*
|
||||||
|
* A AST do XML e a arvore JSON do core (TinyBlocks_JsonValue), usando uma
|
||||||
|
* convencao explicita e sem perdas:
|
||||||
|
*
|
||||||
|
* elemento -> { "tag": "nome",
|
||||||
|
* "attrs": { "k": "v", ... },
|
||||||
|
* "children": [ "texto", {elemento}, ... ] }
|
||||||
|
*
|
||||||
|
* Assim o XML pode ser convertido de/para JSON e reemitido.
|
||||||
|
*/
|
||||||
|
#ifndef TB_XML_AST_H
|
||||||
|
#define TB_XML_AST_H
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <tinyblocks/tb_json_block.h>
|
||||||
|
#include "lexeme.h"
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* xml_parse(const char* text, char* err, size_t errcap);
|
||||||
|
TinyBlocks_JsonValue* xml_parse_file(const char* path, char* err, size_t errcap);
|
||||||
|
char* xml_to_string(const TinyBlocks_JsonValue* root, bool pretty);
|
||||||
|
bool xml_write_file(const TinyBlocks_JsonValue* root, const char* path, bool pretty);
|
||||||
|
|
||||||
|
#endif /* TB_XML_AST_H */
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-xml / include/lexeme.h
|
||||||
|
* Lexer de XML: emit tokens de texto, tags, comentarios, CDATA e PI.
|
||||||
|
*/
|
||||||
|
#ifndef TB_XML_LEXEME_H
|
||||||
|
#define TB_XML_LEXEME_H
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
XT_EOF, XT_ERROR,
|
||||||
|
XT_TEXT, /* texto entre tags (entidades decodificadas) */
|
||||||
|
XT_START, /* <tag attrs...> */
|
||||||
|
XT_EMPTY, /* <tag attrs.../> */
|
||||||
|
XT_END, /* </tag> */
|
||||||
|
XT_COMMENT, /* <!-- ... --> */
|
||||||
|
XT_CDATA, /* <![CDATA[ ... ]]> */
|
||||||
|
XT_PI, /* <? ... ?> */
|
||||||
|
XT_DOCTYPE /* <! ... > */
|
||||||
|
} XmlTokKind;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
XmlTokKind kind;
|
||||||
|
int line, col;
|
||||||
|
char* name; /* XT_START/XT_EMPTY/XT_END */
|
||||||
|
char** attr_names; /* XT_START/XT_EMPTY */
|
||||||
|
char** attr_vals;
|
||||||
|
int attr_n, attr_cap;
|
||||||
|
char* text; /* XT_TEXT/XT_COMMENT/XT_CDATA/XT_PI/XT_DOCTYPE */
|
||||||
|
} XmlToken;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
const char* p;
|
||||||
|
int line, col;
|
||||||
|
char* err; size_t errcap;
|
||||||
|
bool failed;
|
||||||
|
} XmlLexer;
|
||||||
|
|
||||||
|
typedef struct { bool ok; char msg[160]; int line, col; } XmlError;
|
||||||
|
|
||||||
|
void xml_lexer_init(XmlLexer* L, const char* src, char* err, size_t errcap);
|
||||||
|
bool xml_lexer_next(XmlLexer* L, XmlToken* t); /* false = fim/erro */
|
||||||
|
void xml_token_free(XmlToken* t);
|
||||||
|
const char* xml_tok_name(XmlTokKind k);
|
||||||
|
|
||||||
|
/* Decodifica entidades XML (< &#NN; ...) em 'dst'. */
|
||||||
|
void xml_decode_entities(const char* src, char* dst, size_t cap);
|
||||||
|
|
||||||
|
#endif /* TB_XML_LEXEME_H */
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tb_xml.h
|
||||||
|
* Library tinyblocks-xml: parser/emissor de XML (AST = JSON do core).
|
||||||
|
*/
|
||||||
|
#ifndef TINYBLOCKS_XML_H
|
||||||
|
#define TINYBLOCKS_XML_H
|
||||||
|
|
||||||
|
#include <tinyblocks/tinyblocks.h>
|
||||||
|
#include "ast.h"
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
TB_API const TinyBlocks_LibraryDescriptor* tb_xml_get_library(void);
|
||||||
|
|
||||||
|
/* Consulta um caminho "raiz/filho/@atributo" no texto XML. */
|
||||||
|
TB_API const char* tb_xml_get_path(const char* text, const char* path, const char* def);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* TINYBLOCKS_XML_H */
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Metadados da library xml.
|
||||||
|
[library]
|
||||||
|
name = "tinyblocks-xml"
|
||||||
|
version = "1.0.0"
|
||||||
|
category = "XML"
|
||||||
|
description = "Parser e emissor de XML (AST JSON do core)"
|
||||||
|
color = [200, 120, 80, 255]
|
||||||
|
dark = [150, 84, 50, 255]
|
||||||
|
|
||||||
|
[build]
|
||||||
|
sources = ["src/lexer.c", "src/parser.c", "src/tb_xml.c"]
|
||||||
|
includes = ["include"]
|
||||||
|
shared = "build/libtinyblocks-xml.so"
|
||||||
|
static = "build/libtinyblocks-xml.a"
|
||||||
|
depends = []
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-xml / src/lexer.c
|
||||||
|
*/
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
#include "lexeme.h"
|
||||||
|
|
||||||
|
static char* dup_range(const char* s, size_t n) {
|
||||||
|
char* p = (char*)malloc(n + 1);
|
||||||
|
if (!p) return NULL;
|
||||||
|
memcpy(p, s, n); p[n] = 0;
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* xml_tok_name(XmlTokKind k) {
|
||||||
|
switch (k) {
|
||||||
|
case XT_EOF: return "fim";
|
||||||
|
case XT_ERROR: return "erro";
|
||||||
|
case XT_TEXT: return "texto";
|
||||||
|
case XT_START: return "inicio";
|
||||||
|
case XT_EMPTY: return "vazio";
|
||||||
|
case XT_END: return "fim-tag";
|
||||||
|
case XT_COMMENT: return "comentario";
|
||||||
|
case XT_CDATA: return "cdata";
|
||||||
|
case XT_PI: return "pi";
|
||||||
|
case XT_DOCTYPE: return "doctype";
|
||||||
|
}
|
||||||
|
return "?";
|
||||||
|
}
|
||||||
|
|
||||||
|
void xml_lexer_init(XmlLexer* L, const char* src, char* err, size_t errcap) {
|
||||||
|
L->p = src;
|
||||||
|
L->line = 1; L->col = 1;
|
||||||
|
L->err = err; L->errcap = errcap; L->failed = false;
|
||||||
|
if (err && errcap) err[0] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void xfail(XmlLexer* L, const char* msg) {
|
||||||
|
if (L->failed) return;
|
||||||
|
L->failed = true;
|
||||||
|
if (L->err && L->errcap)
|
||||||
|
snprintf(L->err, L->errcap, "XML %d:%d: %s", L->line, L->col, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int xadv(XmlLexer* L) {
|
||||||
|
int c = (unsigned char)*L->p++;
|
||||||
|
if (c == '\n') { L->line++; L->col = 1; } else L->col++;
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
void xml_decode_entities(const char* src, char* dst, size_t cap) {
|
||||||
|
size_t n = 0;
|
||||||
|
while (*src && n + 1 < cap) {
|
||||||
|
if (*src == '&') {
|
||||||
|
const char* semi = strchr(src, ';');
|
||||||
|
if (semi) {
|
||||||
|
size_t len = (size_t)(semi - src);
|
||||||
|
char ent[16];
|
||||||
|
if (len < sizeof(ent)) {
|
||||||
|
memcpy(ent, src + 1, len - 1); ent[len - 1] = 0;
|
||||||
|
int out = -1;
|
||||||
|
if (strcmp(ent, "lt") == 0) out = '<';
|
||||||
|
else if (strcmp(ent, "gt") == 0) out = '>';
|
||||||
|
else if (strcmp(ent, "amp") == 0) out = '&';
|
||||||
|
else if (strcmp(ent, "quot") == 0) out = '"';
|
||||||
|
else if (strcmp(ent, "apos") == 0) out = '\'';
|
||||||
|
else if (ent[0] == '#') {
|
||||||
|
long cp = 0;
|
||||||
|
if (ent[1] == 'x' || ent[1] == 'X') cp = strtol(ent + 2, NULL, 16);
|
||||||
|
else cp = strtol(ent + 1, NULL, 10);
|
||||||
|
if (cp > 0 && cp < 0x80) out = (int)cp;
|
||||||
|
else if (cp >= 0x80 && n + 4 < cap) {
|
||||||
|
if (cp < 0x800) {
|
||||||
|
dst[n++] = (char)(0xC0 | (cp >> 6));
|
||||||
|
dst[n++] = (char)(0x80 | (cp & 0x3F));
|
||||||
|
} else if (cp < 0x10000) {
|
||||||
|
dst[n++] = (char)(0xE0 | (cp >> 12));
|
||||||
|
dst[n++] = (char)(0x80 | ((cp >> 6) & 0x3F));
|
||||||
|
dst[n++] = (char)(0x80 | (cp & 0x3F));
|
||||||
|
} else {
|
||||||
|
dst[n++] = (char)(0xF0 | (cp >> 18));
|
||||||
|
dst[n++] = (char)(0x80 | ((cp >> 12) & 0x3F));
|
||||||
|
dst[n++] = (char)(0x80 | ((cp >> 6) & 0x3F));
|
||||||
|
dst[n++] = (char)(0x80 | (cp & 0x3F));
|
||||||
|
}
|
||||||
|
src = semi + 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (out >= 0) { dst[n++] = (char)out; src = semi + 1; continue; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dst[n++] = *src++;
|
||||||
|
}
|
||||||
|
dst[n] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool is_name_start(int c) {
|
||||||
|
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == ':' || c >= 0x80;
|
||||||
|
}
|
||||||
|
static bool is_name_char(int c) {
|
||||||
|
return is_name_start(c) || (c >= '0' && c <= '9') || c == '-' || c == '.';
|
||||||
|
}
|
||||||
|
|
||||||
|
static char* read_name(XmlLexer* L) {
|
||||||
|
const char* s = L->p;
|
||||||
|
if (!is_name_start((unsigned char)*L->p)) { xfail(L, "nome esperado"); return NULL; }
|
||||||
|
while (is_name_char((unsigned char)*L->p)) xadv(L);
|
||||||
|
return dup_range(s, (size_t)(L->p - s));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void skip_ws(XmlLexer* L) {
|
||||||
|
while (*L->p == ' ' || *L->p == '\t' || *L->p == '\r' || *L->p == '\n') xadv(L);
|
||||||
|
}
|
||||||
|
|
||||||
|
static char* read_quoted_value(XmlLexer* L) {
|
||||||
|
int q = xadv(L);
|
||||||
|
const char* s = L->p;
|
||||||
|
char raw[1024];
|
||||||
|
size_t n = 0;
|
||||||
|
while (*L->p && *L->p != q) {
|
||||||
|
if (n + 1 < sizeof(raw)) raw[n++] = (char)*L->p;
|
||||||
|
xadv(L);
|
||||||
|
}
|
||||||
|
raw[n] = 0;
|
||||||
|
if (*L->p != q) { xfail(L, "string de atributo nao terminada"); return NULL; }
|
||||||
|
xadv(L);
|
||||||
|
char* out = (char*)malloc(3 * n + 4);
|
||||||
|
if (!out) return NULL;
|
||||||
|
xml_decode_entities(raw, out, 3 * n + 4);
|
||||||
|
(void)s;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool tok_push_attr(XmlToken* t, char* name, char* val) {
|
||||||
|
if (t->attr_n >= t->attr_cap) {
|
||||||
|
int nc = t->attr_cap ? t->attr_cap * 2 : 8;
|
||||||
|
char** nn = (char**)realloc(t->attr_names, (size_t)nc * sizeof(char*));
|
||||||
|
char** nv = (char**)realloc(t->attr_vals, (size_t)nc * sizeof(char*));
|
||||||
|
if (!nn || !nv) { free(nn); free(nv); free(name); free(val); return false; }
|
||||||
|
t->attr_names = nn; t->attr_vals = nv; t->attr_cap = nc;
|
||||||
|
}
|
||||||
|
t->attr_names[t->attr_n] = name;
|
||||||
|
t->attr_vals[t->attr_n] = val;
|
||||||
|
t->attr_n++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void xml_token_free(XmlToken* t) {
|
||||||
|
if (!t) return;
|
||||||
|
free(t->name);
|
||||||
|
for (int i = 0; i < t->attr_n; i++) { free(t->attr_names[i]); free(t->attr_vals[i]); }
|
||||||
|
free(t->attr_names);
|
||||||
|
free(t->attr_vals);
|
||||||
|
free(t->text);
|
||||||
|
memset(t, 0, sizeof(*t));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool xml_lexer_next(XmlLexer* L, XmlToken* t) {
|
||||||
|
memset(t, 0, sizeof(*t));
|
||||||
|
if (L->failed || *L->p == 0) { t->kind = XT_EOF; return false; }
|
||||||
|
|
||||||
|
if (*L->p != '<') {
|
||||||
|
/* texto */
|
||||||
|
const char* s = L->p;
|
||||||
|
while (*L->p && *L->p != '<') xadv(L);
|
||||||
|
char* raw = dup_range(s, (size_t)(L->p - s));
|
||||||
|
if (!raw) { xfail(L, "sem memoria"); t->kind = XT_ERROR; return false; }
|
||||||
|
size_t cap = strlen(raw) * 3 + 4;
|
||||||
|
char* dec = (char*)malloc(cap);
|
||||||
|
if (!dec) { free(raw); xfail(L, "sem memoria"); t->kind = XT_ERROR; return false; }
|
||||||
|
xml_decode_entities(raw, dec, cap);
|
||||||
|
free(raw);
|
||||||
|
t->kind = XT_TEXT; t->text = dec; t->line = L->line; t->col = L->col;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
int line = L->line, col = L->col;
|
||||||
|
xadv(L); /* < */
|
||||||
|
if (*L->p == '!') {
|
||||||
|
xadv(L);
|
||||||
|
if (L->p[0] == '-' && L->p[1] == '-') {
|
||||||
|
xadv(L); xadv(L);
|
||||||
|
const char* s = L->p;
|
||||||
|
while (*L->p && !(L->p[0] == '-' && L->p[1] == '-' && L->p[2] == '>')) xadv(L);
|
||||||
|
if (!*L->p) { xfail(L, "comentario nao terminado"); t->kind = XT_ERROR; return false; }
|
||||||
|
t->text = dup_range(s, (size_t)(L->p - s));
|
||||||
|
xadv(L); xadv(L); xadv(L);
|
||||||
|
t->kind = XT_COMMENT; t->line = line; t->col = col;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (strncmp(L->p, "[CDATA[", 7) == 0) {
|
||||||
|
for (int i = 0; i < 7; i++) xadv(L);
|
||||||
|
const char* s = L->p;
|
||||||
|
while (*L->p && !(L->p[0] == ']' && L->p[1] == ']' && L->p[2] == '>')) xadv(L);
|
||||||
|
if (!*L->p) { xfail(L, "CDATA nao terminado"); t->kind = XT_ERROR; return false; }
|
||||||
|
t->text = dup_range(s, (size_t)(L->p - s));
|
||||||
|
xadv(L); xadv(L); xadv(L);
|
||||||
|
t->kind = XT_CDATA; t->line = line; t->col = col;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const char* s = L->p;
|
||||||
|
int depth = 1;
|
||||||
|
while (*L->p && depth > 0) {
|
||||||
|
if (*L->p == '<') depth++;
|
||||||
|
else if (*L->p == '>') depth--;
|
||||||
|
if (depth > 0) xadv(L);
|
||||||
|
}
|
||||||
|
t->text = dup_range(s, (size_t)(L->p - s));
|
||||||
|
if (*L->p == '>') xadv(L);
|
||||||
|
t->kind = XT_DOCTYPE; t->line = line; t->col = col;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (*L->p == '?') {
|
||||||
|
xadv(L);
|
||||||
|
const char* s = L->p;
|
||||||
|
while (*L->p && !(L->p[0] == '?' && L->p[1] == '>')) xadv(L);
|
||||||
|
t->text = dup_range(s, (size_t)(L->p - s));
|
||||||
|
if (*L->p == '?') xadv(L);
|
||||||
|
if (*L->p == '>') xadv(L);
|
||||||
|
t->kind = XT_PI; t->line = line; t->col = col;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (*L->p == '/') {
|
||||||
|
xadv(L);
|
||||||
|
t->name = read_name(L);
|
||||||
|
if (!t->name) { t->kind = XT_ERROR; return false; }
|
||||||
|
skip_ws(L);
|
||||||
|
if (*L->p == '>') xadv(L);
|
||||||
|
t->kind = XT_END; t->line = line; t->col = col;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
/* start / empty tag */
|
||||||
|
t->name = read_name(L);
|
||||||
|
if (!t->name) { t->kind = XT_ERROR; return false; }
|
||||||
|
for (;;) {
|
||||||
|
skip_ws(L);
|
||||||
|
if (*L->p == 0) { xfail(L, "tag nao terminada"); xml_token_free(t); t->kind = XT_ERROR; return false; }
|
||||||
|
if (*L->p == '/') { xadv(L); if (*L->p == '>') xadv(L); t->kind = XT_EMPTY; break; }
|
||||||
|
if (*L->p == '>') { xadv(L); t->kind = XT_START; break; }
|
||||||
|
char* an = read_name(L);
|
||||||
|
if (!an) { xml_token_free(t); t->kind = XT_ERROR; return false; }
|
||||||
|
skip_ws(L);
|
||||||
|
char* av = NULL;
|
||||||
|
if (*L->p == '=') { xadv(L); skip_ws(L); av = read_quoted_value(L); }
|
||||||
|
else av = dup_range("", 0);
|
||||||
|
if (!av || !tok_push_attr(t, an, av)) { free(an); free(av); xml_token_free(t); xfail(L, "sem memoria"); t->kind = XT_ERROR; return false; }
|
||||||
|
}
|
||||||
|
t->line = line; t->col = col;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tinyblocks-xml / src/parser.c
|
||||||
|
* Constroi a arvore JSON a partir do XML e reemite XML a partir dela.
|
||||||
|
*/
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
#include "ast.h"
|
||||||
|
|
||||||
|
/* === Parser === */
|
||||||
|
typedef struct { XmlLexer* L; XmlToken cur; bool ok; } Reader;
|
||||||
|
|
||||||
|
static bool rnext(Reader* R) {
|
||||||
|
xml_token_free(&R->cur);
|
||||||
|
R->ok = xml_lexer_next(R->L, &R->cur);
|
||||||
|
return R->ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void set_err(char* err, size_t cap, const char* msg) {
|
||||||
|
if (err && cap) snprintf(err, cap, "%s", msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
static TinyBlocks_JsonValue* parse_element(Reader* R, char* err, size_t cap, int depth) {
|
||||||
|
if (depth > 256) { set_err(err, cap, "XML aninhado demais"); return NULL; }
|
||||||
|
char* name;
|
||||||
|
if (R->cur.kind == XT_START || R->cur.kind == XT_EMPTY) {
|
||||||
|
name = R->cur.name ? (char*)malloc(strlen(R->cur.name) + 1) : NULL;
|
||||||
|
if (name) strcpy(name, R->cur.name);
|
||||||
|
} else { set_err(err, cap, "elemento esperado"); return NULL; }
|
||||||
|
if (!name) { set_err(err, cap, "sem memoria"); return NULL; }
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* obj = tb_json_object();
|
||||||
|
if (!obj) { free(name); return NULL; }
|
||||||
|
TinyBlocks_JsonValue* jn = tb_json_string(name);
|
||||||
|
tb_json_object_set(obj, "tag", jn);
|
||||||
|
tb_json_release(jn);
|
||||||
|
free(name);
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* attrs = tb_json_object();
|
||||||
|
TinyBlocks_JsonValue* children = tb_json_array();
|
||||||
|
tb_json_object_set(obj, "attrs", attrs);
|
||||||
|
tb_json_object_set(obj, "children", children);
|
||||||
|
tb_json_release(attrs);
|
||||||
|
tb_json_release(children);
|
||||||
|
|
||||||
|
for (int i = 0; i < R->cur.attr_n; i++) {
|
||||||
|
TinyBlocks_JsonValue* v = tb_json_string(R->cur.attr_vals[i]);
|
||||||
|
tb_json_object_set(attrs, R->cur.attr_names[i], v);
|
||||||
|
tb_json_release(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool empty = R->cur.kind == XT_EMPTY;
|
||||||
|
if (empty) return obj;
|
||||||
|
|
||||||
|
for (;;) {
|
||||||
|
rnext(R);
|
||||||
|
if (R->cur.kind == XT_START || R->cur.kind == XT_EMPTY) {
|
||||||
|
TinyBlocks_JsonValue* child = parse_element(R, err, cap, depth + 1);
|
||||||
|
if (!child) { tb_json_release(obj); return NULL; }
|
||||||
|
tb_json_array_push(children, child);
|
||||||
|
tb_json_release(child);
|
||||||
|
} else if (R->cur.kind == XT_END) {
|
||||||
|
TinyBlocks_JsonValue* t = tb_json_object_get(obj, "tag");
|
||||||
|
const char* nm = t ? tb_json_as_string(t) : NULL;
|
||||||
|
if (nm && R->cur.name && strcmp(nm, R->cur.name) != 0) {
|
||||||
|
set_err(err, cap, "tag de fechamento nao corresponde");
|
||||||
|
tb_json_release(t);
|
||||||
|
tb_json_release(obj); return NULL;
|
||||||
|
}
|
||||||
|
tb_json_release(t);
|
||||||
|
break;
|
||||||
|
} else if (R->cur.kind == XT_TEXT || R->cur.kind == XT_CDATA) {
|
||||||
|
if (R->cur.text && R->cur.text[0]) {
|
||||||
|
TinyBlocks_JsonValue* v = tb_json_string(R->cur.text);
|
||||||
|
tb_json_array_push(children, v);
|
||||||
|
tb_json_release(v);
|
||||||
|
}
|
||||||
|
} else if (R->cur.kind == XT_COMMENT || R->cur.kind == XT_PI || R->cur.kind == XT_DOCTYPE) {
|
||||||
|
/* ignora */
|
||||||
|
} else {
|
||||||
|
set_err(err, cap, "fim inesperado dentro do elemento");
|
||||||
|
tb_json_release(obj); return NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* xml_parse(const char* text, char* err, size_t errcap) {
|
||||||
|
XmlLexer L; xml_lexer_init(&L, text, err, errcap);
|
||||||
|
Reader R = { .L = &L, .ok = true };
|
||||||
|
memset(&R.cur, 0, sizeof(R.cur));
|
||||||
|
TinyBlocks_JsonValue* root = NULL;
|
||||||
|
for (;;) {
|
||||||
|
if (!rnext(&R)) {
|
||||||
|
if (L.failed) { set_err(err, errcap, L.err ? L.err : "erro de XML"); }
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (R.cur.kind == XT_START || R.cur.kind == XT_EMPTY) {
|
||||||
|
root = parse_element(&R, err, errcap, 0);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (R.cur.kind == XT_ERROR) { set_err(err, errcap, L.err ? L.err : "erro de XML"); break; }
|
||||||
|
if (R.cur.kind == XT_TEXT && R.cur.text) {
|
||||||
|
bool ws = true;
|
||||||
|
for (const char* q = R.cur.text; *q; q++) if (*q != ' ' && *q != '\t' && *q != '\r' && *q != '\n') ws = false;
|
||||||
|
if (!ws) { set_err(err, errcap, "texto fora do elemento raiz"); break; }
|
||||||
|
}
|
||||||
|
/* PI, DOCTYPE, COMMENT: ignora */
|
||||||
|
}
|
||||||
|
xml_token_free(&R.cur);
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* xml_parse_file(const char* path, char* err, size_t errcap) {
|
||||||
|
FILE* f = fopen(path, "rb");
|
||||||
|
if (!f) { set_err(err, errcap, "nao abriu o arquivo"); return NULL; }
|
||||||
|
fseek(f, 0, SEEK_END); long sz = ftell(f); fseek(f, 0, SEEK_SET);
|
||||||
|
if (sz < 0 || sz > 256L * 1024 * 1024) { fclose(f); set_err(err, errcap, "arquivo grande demais"); return NULL; }
|
||||||
|
char* buf = (char*)malloc((size_t)sz + 1);
|
||||||
|
if (!buf) { fclose(f); return NULL; }
|
||||||
|
size_t rd = fread(buf, 1, (size_t)sz, f);
|
||||||
|
buf[rd] = 0; fclose(f);
|
||||||
|
TinyBlocks_JsonValue* v = xml_parse(buf, err, errcap);
|
||||||
|
free(buf);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* === Emissor === */
|
||||||
|
typedef struct { char* p; size_t len, cap; } Buf;
|
||||||
|
|
||||||
|
static void bput(Buf* b, const char* s, size_t n) {
|
||||||
|
if (b->len + n + 1 > b->cap) {
|
||||||
|
size_t nc = b->cap ? b->cap : 128;
|
||||||
|
while (nc < b->len + n + 1) nc *= 2;
|
||||||
|
char* p = (char*)realloc(b->p, nc);
|
||||||
|
if (!p) return;
|
||||||
|
b->p = p; b->cap = nc;
|
||||||
|
}
|
||||||
|
memcpy(b->p + b->len, s, n); b->len += n; b->p[b->len] = 0;
|
||||||
|
}
|
||||||
|
static void bs(Buf* b, const char* s) { bput(b, s, strlen(s)); }
|
||||||
|
static void bc(Buf* b, char c) { bput(b, &c, 1); }
|
||||||
|
|
||||||
|
static void esc(Buf* b, const char* s) {
|
||||||
|
for (const char* q = s; *q; q++) {
|
||||||
|
switch (*q) {
|
||||||
|
case '<': bs(b, "<"); break;
|
||||||
|
case '>': bs(b, ">"); break;
|
||||||
|
case '&': bs(b, "&"); break;
|
||||||
|
case '"': bs(b, """); break;
|
||||||
|
case '\'': bs(b, "'"); break;
|
||||||
|
default: bc(b, *q);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void emit_json(Buf* b, const TinyBlocks_JsonValue* j, bool pretty, int depth) {
|
||||||
|
if (!j) return;
|
||||||
|
if (tb_json_kind(j) == TB_JSON_STRING) {
|
||||||
|
esc(b, tb_json_as_string(j));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (tb_json_kind(j) == TB_JSON_ARRAY) {
|
||||||
|
for (uint32_t i = 0; i < tb_json_array_length(j); i++) {
|
||||||
|
TinyBlocks_JsonValue* it = tb_json_array_get(j, i);
|
||||||
|
emit_json(b, it, pretty, depth);
|
||||||
|
tb_json_release(it);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (tb_json_kind(j) != TB_JSON_OBJECT) {
|
||||||
|
const char* s = tb_json_as_string(j);
|
||||||
|
if (s) esc(b, s);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
TinyBlocks_JsonValue* tagv = tb_json_object_get(j, "tag");
|
||||||
|
const char* tag = tagv ? tb_json_as_string(tagv) : NULL;
|
||||||
|
tb_json_release(tagv);
|
||||||
|
if (!tag) tag = "item";
|
||||||
|
bc(b, '<'); bs(b, tag);
|
||||||
|
TinyBlocks_JsonValue* attrs = tb_json_object_get(j, "attrs");
|
||||||
|
for (uint32_t i = 0; attrs && i < tb_json_object_length(attrs); i++) {
|
||||||
|
const char* k = tb_json_object_key_at(attrs, i);
|
||||||
|
TinyBlocks_JsonValue* v = tb_json_object_get(attrs, k);
|
||||||
|
bc(b, ' '); bs(b, k); bs(b, "=\"");
|
||||||
|
esc(b, v ? tb_json_as_string(v) : "");
|
||||||
|
bc(b, '"');
|
||||||
|
tb_json_release(v);
|
||||||
|
}
|
||||||
|
tb_json_release(attrs);
|
||||||
|
|
||||||
|
TinyBlocks_JsonValue* ch = tb_json_object_get(j, "children");
|
||||||
|
bool has = ch && tb_json_array_length(ch) > 0;
|
||||||
|
if (!has) { bs(b, "/>"); tb_json_release(ch); return; }
|
||||||
|
bc(b, '>');
|
||||||
|
for (uint32_t i = 0; i < tb_json_array_length(ch); i++) {
|
||||||
|
TinyBlocks_JsonValue* c = tb_json_array_get(ch, i);
|
||||||
|
emit_json(b, c, pretty, depth + 1);
|
||||||
|
tb_json_release(c);
|
||||||
|
}
|
||||||
|
bs(b, "</"); bs(b, tag); bc(b, '>');
|
||||||
|
tb_json_release(ch);
|
||||||
|
}
|
||||||
|
|
||||||
|
char* xml_to_string(const TinyBlocks_JsonValue* root, bool pretty) {
|
||||||
|
Buf b = {0};
|
||||||
|
if (pretty) bs(&b, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
|
||||||
|
emit_json(&b, root, pretty, 0);
|
||||||
|
if (!b.p) { b.p = (char*)malloc(1); if (b.p) b.p[0] = 0; }
|
||||||
|
return b.p;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool xml_write_file(const TinyBlocks_JsonValue* root, const char* path, bool pretty) {
|
||||||
|
char* s = xml_to_string(root, pretty);
|
||||||
|
if (!s) return false;
|
||||||
|
FILE* f = fopen(path, "wb");
|
||||||
|
if (!f) { free(s); return false; }
|
||||||
|
size_t n = strlen(s);
|
||||||
|
size_t w = fwrite(s, 1, n, f);
|
||||||
|
fclose(f);
|
||||||
|
free(s);
|
||||||
|
return w == n;
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tb_xml.c
|
||||||
|
*/
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include <tinyblocks/tinyblocks.h>
|
||||||
|
#include "tb_xml.h"
|
||||||
|
|
||||||
|
#define CAT_COLOR 200/255.f, 120/255.f, 80/255.f, 1.f
|
||||||
|
#define CAT_DARK 150/255.f, 84/255.f, 50/255.f, 1.f
|
||||||
|
|
||||||
|
/* Primeiro elemento filho com a tag dada (nova ref) ou NULL. */
|
||||||
|
static TinyBlocks_JsonValue* find_child(const TinyBlocks_JsonValue* el, const char* tag) {
|
||||||
|
TinyBlocks_JsonValue* ch = tb_json_object_get(el, "children");
|
||||||
|
TinyBlocks_JsonValue* found = NULL;
|
||||||
|
for (uint32_t i = 0; ch && i < tb_json_array_length(ch); i++) {
|
||||||
|
TinyBlocks_JsonValue* it = tb_json_array_get(ch, i);
|
||||||
|
if (tb_json_kind(it) == TB_JSON_OBJECT) {
|
||||||
|
TinyBlocks_JsonValue* t = tb_json_object_get(it, "tag");
|
||||||
|
const char* nm = t ? tb_json_as_string(t) : NULL;
|
||||||
|
bool match = nm && strcmp(nm, tag) == 0;
|
||||||
|
tb_json_release(t);
|
||||||
|
if (match) { found = it; it = NULL; break; }
|
||||||
|
}
|
||||||
|
tb_json_release(it);
|
||||||
|
}
|
||||||
|
tb_json_release(ch);
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Concatena os filhos de texto de um elemento em 'buf'. */
|
||||||
|
static const char* element_text(const TinyBlocks_JsonValue* el, char* buf, size_t cap) {
|
||||||
|
buf[0] = 0;
|
||||||
|
TinyBlocks_JsonValue* ch = tb_json_object_get(el, "children");
|
||||||
|
size_t n = 0;
|
||||||
|
for (uint32_t i = 0; ch && i < tb_json_array_length(ch); i++) {
|
||||||
|
TinyBlocks_JsonValue* it = tb_json_array_get(ch, i);
|
||||||
|
if (tb_json_kind(it) == TB_JSON_STRING) {
|
||||||
|
const char* s = tb_json_as_string(it);
|
||||||
|
size_t l = strlen(s);
|
||||||
|
if (n + l + 1 < cap) { memcpy(buf + n, s, l); n += l; buf[n] = 0; }
|
||||||
|
}
|
||||||
|
tb_json_release(it);
|
||||||
|
}
|
||||||
|
tb_json_release(ch);
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
static const char* xml_lookup(const TinyBlocks_JsonValue* root, const char* path,
|
||||||
|
char* buf, size_t cap, const char* def) {
|
||||||
|
const TinyBlocks_JsonValue* cur = root;
|
||||||
|
const char* p = path;
|
||||||
|
char seg[128];
|
||||||
|
TinyBlocks_JsonValue* owned = NULL;
|
||||||
|
while (*p) {
|
||||||
|
size_t n = 0;
|
||||||
|
while (*p && *p != '/' && n < sizeof(seg) - 1) seg[n++] = *p++;
|
||||||
|
seg[n] = 0;
|
||||||
|
if (*p == '/') p++;
|
||||||
|
if (seg[0] == '@') {
|
||||||
|
TinyBlocks_JsonValue* attrs = tb_json_object_get(cur, "attrs");
|
||||||
|
TinyBlocks_JsonValue* v = tb_json_object_get(attrs, seg + 1);
|
||||||
|
const char* s = v ? tb_json_as_string(v) : def;
|
||||||
|
snprintf(buf, cap, "%s", s ? s : "");
|
||||||
|
tb_json_release(v);
|
||||||
|
tb_json_release(attrs);
|
||||||
|
tb_json_release(owned);
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
TinyBlocks_JsonValue* child = find_child(cur, seg);
|
||||||
|
if (!child) {
|
||||||
|
if (owned) tb_json_release(owned);
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
if (owned) tb_json_release(owned);
|
||||||
|
owned = child;
|
||||||
|
cur = owned;
|
||||||
|
}
|
||||||
|
const char* r = element_text(cur, buf, cap);
|
||||||
|
if (owned) tb_json_release(owned);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void eval_valid(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||||
|
TinyBlocks_Value text = tb_block_get_input(self, rt, 0);
|
||||||
|
const char* src = (text.kind == TB_VALUE_TEXT && text.as.text) ? text.as.text : "";
|
||||||
|
char err[160];
|
||||||
|
TinyBlocks_JsonValue* doc = xml_parse(src, err, sizeof(err));
|
||||||
|
tb_block_set_output(self, 0, tb_value_integer(doc ? 1 : 0));
|
||||||
|
tb_json_release(doc);
|
||||||
|
self->dirty = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void eval_get(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||||
|
TinyBlocks_Value text = tb_block_get_input(self, rt, 0);
|
||||||
|
TinyBlocks_Value path = tb_block_get_input(self, rt, 1);
|
||||||
|
const char* src = (text.kind == TB_VALUE_TEXT && text.as.text) ? text.as.text : "";
|
||||||
|
const char* pth = (path.kind == TB_VALUE_TEXT && path.as.text) ? path.as.text : "";
|
||||||
|
char err[160];
|
||||||
|
TinyBlocks_JsonValue* doc = xml_parse(src, err, sizeof(err));
|
||||||
|
char buf[512] = "";
|
||||||
|
if (doc) {
|
||||||
|
xml_lookup(doc, pth, buf, sizeof(buf), "");
|
||||||
|
tb_json_release(doc);
|
||||||
|
}
|
||||||
|
tb_block_set_output(self, 0, tb_value_text(buf));
|
||||||
|
self->dirty = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool xml_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||||
|
static const TinyBlocks_Category cat = { "XML", {CAT_COLOR}, {CAT_DARK} };
|
||||||
|
tb_library_set_category(lib, &cat);
|
||||||
|
static const TinyBlocks_SlotDesc valid_in[] = {{"texto", TB_VALUE_TEXT}};
|
||||||
|
static const TinyBlocks_SlotDesc get_in[] = {{"texto", TB_VALUE_TEXT}, {"caminho", TB_VALUE_TEXT}};
|
||||||
|
static const TinyBlocks_SlotDesc out_i[] = {{"valido", TB_VALUE_INTEGER}};
|
||||||
|
static const TinyBlocks_SlotDesc out_t[] = {{"valor", TB_VALUE_TEXT}};
|
||||||
|
TinyBlocks_TypeBlock* a = tb_type_block_create(rt, "Xml.Valid", valid_in, 1, out_i, 1, eval_valid);
|
||||||
|
TinyBlocks_TypeBlock* b = tb_type_block_create(rt, "Xml.Get", get_in, 2, out_t, 1, eval_get);
|
||||||
|
return a && b && tb_library_add(lib, &a->base) && tb_library_add(lib, &b->base);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void xml_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { (void)rt; (void)lib; }
|
||||||
|
|
||||||
|
TINYBLOCKS_DEFINE_LIBRARY(xml,
|
||||||
|
"tinyblocks-xml",
|
||||||
|
"1.0.0",
|
||||||
|
xml_init,
|
||||||
|
xml_deinit)
|
||||||
|
|
||||||
|
const TinyBlocks_LibraryDescriptor* tb_xml_get_library(void) {
|
||||||
|
return &_tb_lib_desc_xml;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* tb_xml_get_path(const char* text, const char* path, const char* def) {
|
||||||
|
static char buf[512];
|
||||||
|
char err[160];
|
||||||
|
TinyBlocks_JsonValue* doc = xml_parse(text, err, sizeof(err));
|
||||||
|
if (!doc) return def;
|
||||||
|
const char* r = xml_lookup(doc, path, buf, sizeof(buf), def);
|
||||||
|
tb_json_release(doc);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
/*
|
||||||
|
* Teste da tinyblocks-blueprint: modelo + serializacao JSON nativa e export
|
||||||
|
* XML/CSV.
|
||||||
|
*/
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <blueprint.h>
|
||||||
|
|
||||||
|
static int fails = 0;
|
||||||
|
#define CHECK(cond, msg) do { if (cond) printf("ok %s\n", msg); else { printf("FAIL %s\n", msg); fails++; } } while (0)
|
||||||
|
|
||||||
|
static TbBlueprint* make_example(void) {
|
||||||
|
TbBlueprint* bp = tb_blueprint_new();
|
||||||
|
int t0 = tb_blueprint_add_tab(bp, "Codigo", false);
|
||||||
|
TbBpTab* T = tb_blueprint_tab(bp, t0);
|
||||||
|
|
||||||
|
int hat = tb_blueprint_alloc_block(T);
|
||||||
|
snprintf(T->blocks[hat].type, sizeof(T->blocks[hat].type), "Events.WhenRun");
|
||||||
|
T->blocks[hat].x = 40; T->blocks[hat].y = 40;
|
||||||
|
tb_blueprint_top_add(T, hat);
|
||||||
|
|
||||||
|
int set = tb_blueprint_alloc_block(T);
|
||||||
|
snprintf(T->blocks[set].type, sizeof(T->blocks[set].type), "Variables.Set");
|
||||||
|
snprintf(T->blocks[set].in_text[0], 64, "x");
|
||||||
|
snprintf(T->blocks[set].in_text[1], 64, "10");
|
||||||
|
tb_blueprint_link(T, hat, TB_BP_REL_NEXT, set);
|
||||||
|
|
||||||
|
int rep = tb_blueprint_alloc_block(T);
|
||||||
|
snprintf(T->blocks[rep].type, sizeof(T->blocks[rep].type), "Control.Repeat");
|
||||||
|
snprintf(T->blocks[rep].in_text[0], 64, "5");
|
||||||
|
tb_blueprint_link(T, set, TB_BP_REL_NEXT, rep);
|
||||||
|
|
||||||
|
int chg = tb_blueprint_alloc_block(T);
|
||||||
|
snprintf(T->blocks[chg].type, sizeof(T->blocks[chg].type), "Variables.Change");
|
||||||
|
snprintf(T->blocks[chg].in_text[0], 64, "x");
|
||||||
|
snprintf(T->blocks[chg].in_text[1], 64, "1");
|
||||||
|
tb_blueprint_link(T, rep, TB_BP_REL_SUB0, chg);
|
||||||
|
|
||||||
|
/* bloco composto */
|
||||||
|
TbBpUserBlock* d = &bp->user_blocks[bp->user_block_n++];
|
||||||
|
memset(d, 0, sizeof(*d));
|
||||||
|
snprintf(d->name, sizeof(d->name), "dobro");
|
||||||
|
d->color_idx = 2;
|
||||||
|
d->input_count = 1;
|
||||||
|
snprintf(d->input_names[0], 32, "n");
|
||||||
|
d->output_count = 1;
|
||||||
|
snprintf(d->output_names[0], 32, "resultado");
|
||||||
|
d->part_n = 2;
|
||||||
|
d->parts[0].kind = TB_BP_PARAM_NUM; snprintf(d->parts[0].name, 32, "n");
|
||||||
|
d->parts[1].kind = TB_BP_PARAM_LABEL; snprintf(d->parts[1].name, 32, "vezes 2");
|
||||||
|
d->tab_idx = -1;
|
||||||
|
|
||||||
|
tb_blueprint_var_set_text(bp, "x", "42");
|
||||||
|
tb_blueprint_var_set_text(bp, "nome", "mundo");
|
||||||
|
return bp;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
TbBlueprint* bp = make_example();
|
||||||
|
|
||||||
|
/* JSON nativo round-trip */
|
||||||
|
char* json = tb_blueprint_serialize(bp, TB_BP_FMT_JSON, true);
|
||||||
|
CHECK(json && strstr(json, "\"format\": \"tinyblocks-project\""), "JSON contem o formato");
|
||||||
|
CHECK(json && strstr(json, "Events.WhenRun"), "JSON contem o tipo do bloco");
|
||||||
|
|
||||||
|
char err[160] = "";
|
||||||
|
TbBlueprint* bp2 = tb_blueprint_parse(json, TB_BP_FMT_JSON, err, sizeof(err));
|
||||||
|
CHECK(bp2 != NULL, "JSON e carregavel");
|
||||||
|
if (bp2) {
|
||||||
|
CHECK(bp2->tab_count == 1, "uma aba preservada");
|
||||||
|
TbBpTab* T = &bp2->tabs[0];
|
||||||
|
CHECK(T->top_n == 1 && T->top[0] == 0, "topo da pilha preservado");
|
||||||
|
CHECK(strcmp(T->blocks[0].type, "Events.WhenRun") == 0, "tipo do bloco 0");
|
||||||
|
CHECK(T->blocks[0].next == 1, "vinculo next preservado");
|
||||||
|
CHECK(T->blocks[2].sub[0] == 3, "boca do repita preservada");
|
||||||
|
CHECK(strcmp(T->blocks[3].in_text[1], "1") == 0, "texto de campo preservado");
|
||||||
|
CHECK(bp2->user_block_n == 1 && strcmp(bp2->user_blocks[0].name, "dobro") == 0,
|
||||||
|
"bloco composto preservado");
|
||||||
|
CHECK(bp2->user_blocks[0].part_n == 2 &&
|
||||||
|
bp2->user_blocks[0].parts[1].kind == TB_BP_PARAM_LABEL, "partes do prototipo");
|
||||||
|
CHECK(bp2->var_n == 2 && strcmp(bp2->vars[0].name, "x") == 0 &&
|
||||||
|
bp2->vars[0].kind == TB_BP_VAL_INT && bp2->vars[0].num == 42, "variavel inteira");
|
||||||
|
CHECK(bp2->vars[1].kind == TB_BP_VAL_TEXT && strcmp(bp2->vars[1].text, "mundo") == 0,
|
||||||
|
"variavel de texto");
|
||||||
|
tb_blueprint_free(bp2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* export XML */
|
||||||
|
char* xml = tb_blueprint_serialize(bp, TB_BP_FMT_XML, true);
|
||||||
|
CHECK(xml && strstr(xml, "<?xml"), "XML tem cabecalho");
|
||||||
|
CHECK(xml && strstr(xml, "<tab"), "XML tem <tab>");
|
||||||
|
CHECK(xml && strstr(xml, "Events.WhenRun"), "XML contem o tipo do bloco");
|
||||||
|
|
||||||
|
/* export CSV (tabela de blocos) */
|
||||||
|
char* csv = tb_blueprint_serialize(bp, TB_BP_FMT_CSV, false);
|
||||||
|
CHECK(csv && strstr(csv, "aba,tipo,x,y,texto"), "CSV tem cabecalho de colunas");
|
||||||
|
CHECK(csv && strstr(csv, "Events.WhenRun"), "CSV lista o bloco");
|
||||||
|
CHECK(csv && strstr(csv, ",40,40,"), "CSV preserva as coordenadas");
|
||||||
|
|
||||||
|
free(json);
|
||||||
|
free(xml);
|
||||||
|
free(csv);
|
||||||
|
tb_blueprint_free(bp);
|
||||||
|
|
||||||
|
printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails);
|
||||||
|
return fails != 0;
|
||||||
|
}
|
||||||
@@ -290,6 +290,24 @@ int main(void) {
|
|||||||
click(1280 - 50 + 20, 44 + 22);
|
click(1280 - 50 + 20, 44 + 22);
|
||||||
CHECK(!any_has("Palco aberto em outra janela"), "palco recolhido volta ao painel");
|
CHECK(!any_has("Palco aberto em outra janela"), "palco recolhido volta ao painel");
|
||||||
|
|
||||||
|
/* 12. Salvar e abrir projeto (.json) via tinyblocks-blueprint */
|
||||||
|
const char* proj = "/tmp/tb_harness_proj.json";
|
||||||
|
remove(proj);
|
||||||
|
if (need("Salvar", R_FLY, 0, &x, &y)) click(x, y);
|
||||||
|
for (int i = 0; i < 16; i++) key(TB_KEY_BACKSPACE, 0, 0);
|
||||||
|
type(proj);
|
||||||
|
key(TB_KEY_RETURN, 0, 0);
|
||||||
|
CHECK(any_has("Projeto salvo"), "salvar projeto escreve o .json");
|
||||||
|
if (need("Abrir", R_FLY, 0, &x, &y)) click(x, y);
|
||||||
|
for (int i = 0; i < 40; i++) key(TB_KEY_BACKSPACE, 0, 0);
|
||||||
|
type(proj);
|
||||||
|
key(TB_KEY_RETURN, 0, 0);
|
||||||
|
frame(0, 0, 0, 0, 0, 0, NULL);
|
||||||
|
CHECK(any_has("Projeto aberto"), "abrir projeto le o .json");
|
||||||
|
CHECK(find("quando a bandeira for clicado", R_WS, 0, &x, &y),
|
||||||
|
"estado restaurado apos abrir (chapéu de exemplo de volta)");
|
||||||
|
remove(proj);
|
||||||
|
|
||||||
printf("comandos de desenho no último frame: %u\n", ncmd);
|
printf("comandos de desenho no último frame: %u\n", ncmd);
|
||||||
tinyblocks_deinit(&rt);
|
tinyblocks_deinit(&rt);
|
||||||
printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails);
|
printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails);
|
||||||
|
|||||||
Reference in new issue
Block a user