Libraries os, string, number e vector (listas); pastas e booleanos no fs
- tinyblocks-fs: itens da pasta (lista), quantidade/item N da pasta e os booleanos "é arquivo?", "é pasta?" e "existe?". - tinyblocks-os (categoria Sistema): sistema operacional, distribuição, versão do kernel, arquitetura, computador, usuário, pastas, CPUs, memória, tempo ligado e "o sistema é [ ]?". - tinyblocks-string (Texto): maiúsculas/minúsculas, trecho, letra N, posição, troca, apara, repete, inverte, divide em lista e testes; conta letras UTF-8. - tinyblocks-number (Números): reais, potência, raiz, arredondamentos, trigonometria em graus, logaritmos, pi, aleatório, limite, formatação, par/primo/inteiro. - tinyblocks-vector (Listas, blocos List.*): listas JSON imutáveis com adicionar, inserir, remover, trocar, item N, posição, fatia, ordenar, juntar, soma; campos aceitam "[1,2]" ou "a, b". O exemplo de desenho vetorial passa a se chamar tinyblocks-vector-draw. - Editor: saída única cujo nome termina em '?' vira bloco booleano (hexágono); listas JSON aparecem como texto no "escreva"; rótulos PT. - Testes: make test-os e make test-stdlib. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f0abc7593a
commit
33705b2903
25 files changed
+2262
-9
No files matched your search
@@ -302,6 +302,84 @@ static const BlockSpec s_specs[] = {
|
||||
{"Stage.ImageByName", "desenhe imagem nome %1 em x %2 y %3", "|0|0"},
|
||||
{"Stage.ImageByNumber", "desenhe imagem número %1 em x %2 y %3", "1|0|0"},
|
||||
{"Stage.Text", "escreva %1 no palco em x %2 y %3", "Olá!|-40|0"},
|
||||
/* Arquivos: pastas e testes (tinyblocks-fs) */
|
||||
{"FS.ListDir", "itens da pasta %1", ".|"},
|
||||
{"FS.ListCount", "quantidade de itens na pasta %1", ".|"},
|
||||
{"FS.ListItem", "item %2 da pasta %1", ".|1"},
|
||||
{"FS.IsFile", "%1 é arquivo?", "projeto.json"},
|
||||
{"FS.IsDir", "%1 é pasta?", "."},
|
||||
{"FS.Exists", "%1 existe?", "projeto.json"},
|
||||
/* Sistema (tinyblocks-os) */
|
||||
{"OS.Name", "sistema operacional", NULL},
|
||||
{"OS.Distro", "distribuição", NULL},
|
||||
{"OS.Version", "versão do kernel", NULL},
|
||||
{"OS.Arch", "arquitetura", NULL},
|
||||
{"OS.Hostname", "nome do computador", NULL},
|
||||
{"OS.User", "usuário", NULL},
|
||||
{"OS.Home", "pasta pessoal", NULL},
|
||||
{"OS.Cwd", "pasta atual", NULL},
|
||||
{"OS.Cpus", "número de processadores", NULL},
|
||||
{"OS.MemoryMB", "memória total (MB)", NULL},
|
||||
{"OS.UptimeS", "tempo ligado (segundos)", NULL},
|
||||
{"OS.Is", "o sistema é %1?", "Linux"},
|
||||
/* Números (tinyblocks-number) */
|
||||
{"Number.Div", "%1 ÷ %2", "10|4"},
|
||||
{"Number.Pow", "%1 elevado a %2", "2|10"},
|
||||
{"Number.Sqrt", "raiz quadrada de %1", "16"},
|
||||
{"Number.Round", "arredonde %1", "2.5"},
|
||||
{"Number.Floor", "arredonde %1 para baixo", "2.7"},
|
||||
{"Number.Ceil", "arredonde %1 para cima", "2.1"},
|
||||
{"Number.RoundTo", "arredonde %1 com %2 casas", "3.14159|2"},
|
||||
{"Number.Sin", "seno de %1", "90"},
|
||||
{"Number.Cos", "cosseno de %1", "0"},
|
||||
{"Number.Tan", "tangente de %1", "45"},
|
||||
{"Number.Asin", "arco-seno de %1", "1"},
|
||||
{"Number.Acos", "arco-cosseno de %1", "1"},
|
||||
{"Number.Atan", "arco-tangente de %1", "1"},
|
||||
{"Number.Log10", "log de %1", "100"},
|
||||
{"Number.Ln", "ln de %1", "1"},
|
||||
{"Number.Exp", "e elevado a %1", "1"},
|
||||
{"Number.Pi", "pi", NULL},
|
||||
{"Number.Random", "aleatório real entre %1 e %2", "0|1"},
|
||||
{"Number.Clamp", "limite %1 entre %2 e %3", "150|0|100"},
|
||||
{"Number.Format", "%1 com %2 casas decimais", "3.14159|2"},
|
||||
{"Number.IsEven", "%1 é par?", "4"},
|
||||
{"Number.IsPrime", "%1 é primo?", "7"},
|
||||
{"Number.IsInteger", "%1 é inteiro?", "2.5"},
|
||||
/* Texto (tinyblocks-string) */
|
||||
{"String.Upper", "maiúsculas de %1", "maçã"},
|
||||
{"String.Lower", "minúsculas de %1", "MAÇÃ"},
|
||||
{"String.Sub", "letras %2 a %3 de %1", "TinyBlocks|1|4"},
|
||||
{"String.Letter", "letra %2 de %1", "maçã|3"},
|
||||
{"String.Length", "número de letras de %1", "maçã"},
|
||||
{"String.Find", "posição de %2 em %1", "banana|na"},
|
||||
{"String.Replace", "troque %2 por %3 em %1", "olá mundo|mundo|TinyBlocks"},
|
||||
{"String.Trim", "sem espaços nas pontas %1", " olá "},
|
||||
{"String.Repeat", "repita %1 %2 vezes", "ab|3"},
|
||||
{"String.Reverse", "inverta %1", "maçã"},
|
||||
{"String.Split", "divida %1 por %2", "maçã,banana,uva|,"},
|
||||
{"String.Contains", "%1 contém %2?", "maçã|Ç"},
|
||||
{"String.StartsWith", "%1 começa com %2?", "TinyBlocks|Tiny"},
|
||||
{"String.EndsWith", "%1 termina com %2?", "foto.png|.png"},
|
||||
{"String.IsNumber", "%1 é número?", "3.14"},
|
||||
{"String.IsEmpty", "%1 está vazio?", ""},
|
||||
/* Listas (tinyblocks-vector) */
|
||||
{"List.Empty", "lista vazia", NULL},
|
||||
{"List.Of", "lista com %1 %2 %3", "maçã|banana|uva"},
|
||||
{"List.Range", "números de %1 até %2", "1|10"},
|
||||
{"List.Add", "adicione %2 ao fim de %1", "1, 2, 3|4"},
|
||||
{"List.Insert", "insira %2 na posição %3 de %1", "a, c|b|2"},
|
||||
{"List.Remove", "remova o item %2 de %1", "a, b, c|2"},
|
||||
{"List.Replace", "troque o item %2 de %1 por %3", "a, b, c|2|B"},
|
||||
{"List.Item", "item %2 de %1", "maçã, banana, uva|2"},
|
||||
{"List.Length", "tamanho da lista %1", "maçã, banana, uva"},
|
||||
{"List.IndexOf", "posição de %2 na lista %1", "maçã, banana, uva|uva"},
|
||||
{"List.Contains", "%1 contém o item %2?", "maçã, banana, uva|banana"},
|
||||
{"List.Slice", "itens %2 a %3 de %1", "1, 2, 3, 4, 5|2|4"},
|
||||
{"List.Reverse", "inverta a lista %1", "1, 2, 3"},
|
||||
{"List.Sort", "ordene %1", "3, 1, 2"},
|
||||
{"List.Join", "junte os itens de %1 com %2", "a, b, c| - "},
|
||||
{"List.Sum", "soma dos itens de %1", "1, 2, 3"},
|
||||
/* Curvas (lista de pontos [x,y]) */
|
||||
{"Curves.Line", "reta de x %1 y %2 até x %3 y %4 com %5 passos", "0|0|100|0|20"},
|
||||
{"Curves.Bezier", "bezier de x %1 y %2 controles (%3,%4) (%5,%6) até x %7 y %8 com %9 passos", "0|0|0|80|100|80|100|0|20"},
|
||||
|
||||
@@ -124,7 +124,12 @@ static void value_to_str(const TinyBlocks_Value* v, char* buf, size_t cap) {
|
||||
case TB_VALUE_TEXT: snprintf(buf, cap, "%s", v->as.text ? v->as.text : ""); break;
|
||||
case TB_VALUE_BLOCK: snprintf(buf, cap, "[bloco]"); break;
|
||||
case TB_VALUE_VECTOR: snprintf(buf, cap, "[vetor]"); break;
|
||||
case TB_VALUE_JSON: snprintf(buf, cap, "[json]"); break;
|
||||
case TB_VALUE_JSON: {
|
||||
char* js = v->as.json ? tb_json_stringify(v->as.json) : NULL;
|
||||
snprintf(buf, cap, "%s", js ? js : "[json]");
|
||||
free(js);
|
||||
break;
|
||||
}
|
||||
case TB_VALUE_IMAGE: snprintf(buf, cap, "[imagem %dx%d]",
|
||||
tb_image_width(v->as.image), tb_image_height(v->as.image)); break;
|
||||
default: buf[0] = 0; break;
|
||||
@@ -218,6 +223,13 @@ static Shape shape_of(const TinyBlocks_TypeBlock* t) {
|
||||
strcmp(n, "Operators.Gt") == 0 || strcmp(n, "Operators.And") == 0 ||
|
||||
strcmp(n, "Operators.Or") == 0 || strcmp(n, "Operators.Not") == 0)
|
||||
return SH_BOOL;
|
||||
/* Convencao para as libraries: uma unica saida cujo nome termina em '?'
|
||||
(ex.: "é pasta?") e um bloco booleano. */
|
||||
if (t->output_desc_count == 1 && t->output_descs && t->output_descs[0].name) {
|
||||
const char* on = t->output_descs[0].name;
|
||||
size_t ol = strlen(on);
|
||||
if (ol > 0 && on[ol - 1] == '?') return SH_BOOL;
|
||||
}
|
||||
return t->output_desc_count > 0 ? SH_REPORTER : SH_STACK;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
name = "tinyblocks-fs"
|
||||
version = "1.0.0"
|
||||
category = "Arquivos"
|
||||
description = "Abra, leia, escreva, anexe e posicao de arquivo"
|
||||
description = "Abra, leia, escreva e anexe arquivos; liste pastas; teste arquivo/pasta"
|
||||
color = [0, 188, 212, 255]
|
||||
dark = [0, 151, 167, 255]
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/*
|
||||
* TinyBlocks - tb_fs.c
|
||||
* Categoria "Arquivos": abra / leia / escreva / anexe / posicao.
|
||||
* Categoria "Arquivos": abra / leia / escreva / anexe / posicao, listar
|
||||
* pasta (FS.ListDir/ListCount/ListItem) e testes FS.IsFile/IsDir/Exists.
|
||||
* Mantem uma pequena tabela de arquivos abertos (handle inteiro >= 1).
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
@@ -8,8 +9,12 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include <strings.h>
|
||||
#include <dirent.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include <tinyblocks/tb_json_block.h>
|
||||
#include "tb_fs.h"
|
||||
|
||||
#define FS_MAX_FILES 64
|
||||
@@ -107,6 +112,104 @@ static void eval_close(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* -- Pastas --------------------------------------------------------------- */
|
||||
|
||||
static int cmp_name(const void* a, const void* b) {
|
||||
return strcasecmp(*(char* const*)a, *(char* const*)b);
|
||||
}
|
||||
|
||||
/* Nomes da pasta (sem "." e ".."), em ordem alfabetica. Vazio = pasta
|
||||
atual. Devolve um vetor alocado (libere com free_names) e o total. */
|
||||
static char** list_names(const char* path, int* count) {
|
||||
*count = 0;
|
||||
DIR* d = opendir(path[0] ? path : ".");
|
||||
if (!d) return NULL;
|
||||
char** v = NULL;
|
||||
int n = 0, cap = 0;
|
||||
struct dirent* de;
|
||||
while ((de = readdir(d)) != NULL) {
|
||||
if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue;
|
||||
if (n == cap) {
|
||||
int nc = cap ? cap * 2 : 32;
|
||||
char** nv = realloc(v, (size_t)nc * sizeof(char*));
|
||||
if (!nv) break;
|
||||
v = nv;
|
||||
cap = nc;
|
||||
}
|
||||
size_t len = strlen(de->d_name);
|
||||
char* copy = malloc(len + 1);
|
||||
if (!copy) break;
|
||||
memcpy(copy, de->d_name, len + 1);
|
||||
v[n++] = copy;
|
||||
}
|
||||
closedir(d);
|
||||
if (n > 1) qsort(v, (size_t)n, sizeof(char*), cmp_name);
|
||||
*count = n;
|
||||
return v;
|
||||
}
|
||||
|
||||
static void free_names(char** v, int n) {
|
||||
for (int i = 0; i < n; i++) free(v[i]);
|
||||
free(v);
|
||||
}
|
||||
|
||||
static void eval_listdir(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
int n = 0;
|
||||
char** names = list_names(in_text(self, rt, 0), &n);
|
||||
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||
for (int i = 0; arr && i < n; i++) {
|
||||
TinyBlocks_JsonValue* s = tb_json_string(names[i]);
|
||||
if (s) { tb_json_array_push(arr, s); tb_json_release(s); }
|
||||
}
|
||||
free_names(names, n);
|
||||
tb_block_set_output(self, 0, tb_value_json(arr));
|
||||
tb_json_release(arr);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_listcount(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
int n = 0;
|
||||
char** names = list_names(in_text(self, rt, 0), &n);
|
||||
free_names(names, n);
|
||||
tb_block_set_output(self, 0, tb_value_integer(n));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* item N (1..total) da pasta, em ordem alfabetica; fora da faixa = "" */
|
||||
static void eval_listitem(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
int n = 0;
|
||||
char** names = list_names(in_text(self, rt, 0), &n);
|
||||
int64_t k = in_int(self, rt, 1);
|
||||
const char* item = (k >= 1 && k <= n) ? names[k - 1] : "";
|
||||
tb_block_set_output(self, 0, tb_value_text(item));
|
||||
free_names(names, n);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_isfile(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
struct stat st;
|
||||
const char* p = in_text(self, rt, 0);
|
||||
bool ok = p[0] && stat(p, &st) == 0 && S_ISREG(st.st_mode);
|
||||
tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_isdir(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
struct stat st;
|
||||
const char* p = in_text(self, rt, 0);
|
||||
bool ok = p[0] && stat(p, &st) == 0 && S_ISDIR(st.st_mode);
|
||||
tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_exists(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
struct stat st;
|
||||
const char* p = in_text(self, rt, 0);
|
||||
bool ok = p[0] && stat(p, &st) == 0;
|
||||
tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* -- Registro ------------------------------------------------------------ */
|
||||
|
||||
static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name,
|
||||
@@ -134,13 +237,42 @@ static bool fs_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
static const TinyBlocks_SlotDesc handle_out[]= {{"handle", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc text_out[] = {{"texto", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc pos_out[] = {{"posicao",TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc dir_in[] = {{"pasta", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc item_in[] = {{"pasta", TB_VALUE_TEXT}, {"numero", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc path_in[] = {{"caminho", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc list_out[] = {{"lista", TB_VALUE_JSON}};
|
||||
static const TinyBlocks_SlotDesc count_out[] = {{"quantidade", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc name_out[] = {{"nome", TB_VALUE_TEXT}};
|
||||
/* saida terminada em '?' = bloco booleano (hexagonal no editor) */
|
||||
static const TinyBlocks_SlotDesc file_out[] = {{"é arquivo?", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc isdir_out[] = {{"é pasta?", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc exist_out[] = {{"existe?", TB_VALUE_INTEGER}};
|
||||
|
||||
TB_BLOCK_META("FS.ListDir", "eval_listdir",
|
||||
"Lista com os nomes dos itens da pasta (ordem alfabetica)");
|
||||
TB_BLOCK_META("FS.ListCount", "eval_listcount",
|
||||
"Quantos itens (arquivos e pastas) a pasta tem");
|
||||
TB_BLOCK_META("FS.ListItem", "eval_listitem",
|
||||
"Nome do item N da pasta (1 = primeiro, ordem alfabetica)");
|
||||
TB_BLOCK_META("FS.IsFile", "eval_isfile",
|
||||
"Verdadeiro se o caminho for um arquivo");
|
||||
TB_BLOCK_META("FS.IsDir", "eval_isdir",
|
||||
"Verdadeiro se o caminho for uma pasta");
|
||||
TB_BLOCK_META("FS.Exists", "eval_exists",
|
||||
"Verdadeiro se o caminho existir (arquivo ou pasta)");
|
||||
|
||||
return reg(rt, lib, "FS.Open", open_in, 1, handle_out, 1, eval_open)
|
||||
&& reg(rt, lib, "FS.Read", read_in, 2, text_out, 1, eval_read)
|
||||
&& reg(rt, lib, "FS.Write", write_in, 2, NULL, 0, eval_write)
|
||||
&& reg(rt, lib, "FS.Append", append_in, 2, NULL, 0, eval_append)
|
||||
&& reg(rt, lib, "FS.Tell", tell_in, 1, pos_out, 1, eval_tell)
|
||||
&& reg(rt, lib, "FS.Close", close_in, 1, NULL, 0, eval_close);
|
||||
&& reg(rt, lib, "FS.Close", close_in, 1, NULL, 0, eval_close)
|
||||
&& reg(rt, lib, "FS.ListDir", dir_in, 1, list_out, 1, eval_listdir)
|
||||
&& reg(rt, lib, "FS.ListCount", dir_in, 1, count_out, 1, eval_listcount)
|
||||
&& reg(rt, lib, "FS.ListItem", item_in, 2, name_out, 1, eval_listitem)
|
||||
&& reg(rt, lib, "FS.IsFile", path_in, 1, file_out, 1, eval_isfile)
|
||||
&& reg(rt, lib, "FS.IsDir", path_in, 1, isdir_out, 1, eval_isdir)
|
||||
&& reg(rt, lib, "FS.Exists", path_in, 1, exist_out, 1, eval_exists);
|
||||
}
|
||||
|
||||
static void fs_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Makefile da library number (categoria "Números")
|
||||
# Constroi build/libtinyblocks-number.a e build/libtinyblocks-number.so
|
||||
CC := gcc
|
||||
BUILD := build
|
||||
|
||||
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||
-I../../include -Iinclude
|
||||
|
||||
OBJ := $(BUILD)/tb_number.o
|
||||
LIB_A := $(BUILD)/libtinyblocks-number.a
|
||||
LIB_SO := $(BUILD)/libtinyblocks-number.so
|
||||
|
||||
.PHONY: all static shared clean
|
||||
all: static shared
|
||||
static: $(LIB_A)
|
||||
shared: $(LIB_SO)
|
||||
|
||||
$(OBJ): src/tb_number.c include/tb_number.h
|
||||
@mkdir -p $(BUILD)
|
||||
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||
|
||||
$(LIB_A): $(OBJ)
|
||||
ar rcs $@ $^
|
||||
|
||||
$(LIB_SO): $(OBJ)
|
||||
$(CC) -shared -o $@ $^ -lm
|
||||
|
||||
clean:
|
||||
$(RM) -r $(BUILD)
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* TinyBlocks - tb_number.h
|
||||
* Library tinyblocks-number: matematica com numeros reais (divisao,
|
||||
* potencia, raiz, arredondamentos, trigonometria em graus, logaritmos, pi,
|
||||
* aleatorio real, limite, formatacao) e testes par/primo/inteiro.
|
||||
* Registra a categoria "Números".
|
||||
*/
|
||||
#ifndef TINYBLOCKS_NUMBER_H
|
||||
#define TINYBLOCKS_NUMBER_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
|
||||
TB_API const TinyBlocks_LibraryDescriptor* tb_number_get_library(void);
|
||||
|
||||
/* Funcoes usadas pelos blocos (uteis tambem direto de C) */
|
||||
TB_API double tb_number_round_to(double x, int places);
|
||||
TB_API bool tb_number_is_prime(long long n);
|
||||
/* Formata com `places` casas, sem zeros a direita se places < 0 */
|
||||
TB_API void tb_number_format (double x, int places, char* out, size_t cap);
|
||||
|
||||
#endif /* TINYBLOCKS_NUMBER_H */
|
||||
@@ -0,0 +1,15 @@
|
||||
# Metadados da library number. Lido pela UI/build sem recompilar o .so.
|
||||
[library]
|
||||
name = "tinyblocks-number"
|
||||
version = "1.0.0"
|
||||
category = "Números"
|
||||
description = "Numeros reais - divisao, potencia, raiz, arredondar, trigonometria, primo"
|
||||
color = [139, 195, 74, 255]
|
||||
dark = [104, 159, 56, 255]
|
||||
|
||||
[build]
|
||||
sources = ["src/tb_number.c"]
|
||||
includes = ["include"]
|
||||
shared = "build/libtinyblocks-number.so"
|
||||
static = "build/libtinyblocks-number.a"
|
||||
depends = []
|
||||
@@ -0,0 +1,247 @@
|
||||
/*
|
||||
* TinyBlocks - tb_number.c
|
||||
* Categoria "Números": matematica com numeros reais. Number.Div / Pow /
|
||||
* Sqrt / Round / Floor / Ceil / RoundTo / Sin / Cos / Tan / Asin / Acos /
|
||||
* Atan / Log10 / Ln / Exp / Pi / Random / Clamp / Format e os booleanos
|
||||
* Number.IsEven / IsPrime / IsInteger.
|
||||
*
|
||||
* Angulos em GRAUS, como no Scratch. Resultados inteiros saem como inteiro
|
||||
* ("3", nao "3.0"); trigonometria e arredondada em 10 casas (sen 180 = 0).
|
||||
*/
|
||||
#define _DEFAULT_SOURCE
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include <math.h>
|
||||
#include <time.h>
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include "tb_number.h"
|
||||
|
||||
#ifndef M_PI
|
||||
#define M_PI 3.14159265358979323846
|
||||
#endif
|
||||
#define DEG (M_PI / 180.0)
|
||||
|
||||
/* -- API ------------------------------------------------------------------ */
|
||||
|
||||
TB_API double tb_number_round_to(double x, int places) {
|
||||
if (places < 0) places = 0;
|
||||
if (places > 12) places = 12;
|
||||
double k = pow(10.0, places);
|
||||
return round(x * k) / k;
|
||||
}
|
||||
|
||||
TB_API bool tb_number_is_prime(long long n) {
|
||||
if (n < 2) return false;
|
||||
if (n < 4) return true;
|
||||
if (n % 2 == 0 || n % 3 == 0) return false;
|
||||
for (long long i = 5; i <= n / i; i += 6)
|
||||
if (n % i == 0 || n % (i + 2) == 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
TB_API void tb_number_format(double x, int places, char* out, size_t cap) {
|
||||
if (!out || !cap) return;
|
||||
if (places >= 0) {
|
||||
if (places > 12) places = 12;
|
||||
snprintf(out, cap, "%.*f", places, x);
|
||||
return;
|
||||
}
|
||||
snprintf(out, cap, "%.10f", x); /* sem zeros a direita */
|
||||
char* dot = strchr(out, '.');
|
||||
if (dot) {
|
||||
char* e = out + strlen(out) - 1;
|
||||
while (e > dot && *e == '0') *e-- = 0;
|
||||
if (e == dot) *e = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* -- Entradas/saidas ------------------------------------------------------ */
|
||||
|
||||
static double num(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
||||
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
||||
if (v.kind == TB_VALUE_INTEGER) return (double)v.as.integer;
|
||||
if (v.kind == TB_VALUE_REAL) return v.as.real;
|
||||
if (v.kind == TB_VALUE_TEXT && v.as.text) return strtod(v.as.text, NULL);
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
/* Inteiro quando o resultado for exato (e couber), senao real */
|
||||
static void out_num(TinyBlocks_Block* self, double x) {
|
||||
if (isfinite(x) && x == floor(x) && fabs(x) < 1e15)
|
||||
tb_block_set_output(self, 0, tb_value_integer((int64_t)x));
|
||||
else
|
||||
tb_block_set_output(self, 0, tb_value_real(isfinite(x) ? x : 0.0));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void out_bool(TinyBlocks_Block* self, bool b) {
|
||||
tb_block_set_output(self, 0, tb_value_integer(b ? 1 : 0));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* trigonometria: corta o ruido de ponto flutuante (sen 180 = 0, nao 1e-16) */
|
||||
static double trig(double x) { return tb_number_round_to(x, 10); }
|
||||
|
||||
/* -- Blocos --------------------------------------------------------------- */
|
||||
|
||||
#define N(i) num(self, rt, (i))
|
||||
|
||||
static void eval_div(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
double b = N(1);
|
||||
out_num(self, b == 0.0 ? 0.0 : N(0) / b);
|
||||
}
|
||||
static void eval_pow(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, pow(N(0), N(1))); }
|
||||
static void eval_sqrt(TinyBlocks_Block* self, TinyBlocks* rt) { double x = N(0); out_num(self, x < 0 ? 0.0 : sqrt(x)); }
|
||||
static void eval_round(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, round(N(0))); }
|
||||
static void eval_floor(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, floor(N(0))); }
|
||||
static void eval_ceil(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, ceil(N(0))); }
|
||||
static void eval_round_to(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
out_num(self, tb_number_round_to(N(0), (int)N(1)));
|
||||
}
|
||||
static void eval_sin(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(sin(N(0) * DEG))); }
|
||||
static void eval_cos(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(cos(N(0) * DEG))); }
|
||||
static void eval_tan(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(tan(N(0) * DEG))); }
|
||||
static void eval_asin(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
double x = N(0);
|
||||
out_num(self, (x < -1 || x > 1) ? 0.0 : trig(asin(x) / DEG));
|
||||
}
|
||||
static void eval_acos(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
double x = N(0);
|
||||
out_num(self, (x < -1 || x > 1) ? 0.0 : trig(acos(x) / DEG));
|
||||
}
|
||||
static void eval_atan(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(atan(N(0)) / DEG)); }
|
||||
static void eval_log10(TinyBlocks_Block* self, TinyBlocks* rt) { double x = N(0); out_num(self, x > 0 ? log10(x) : 0.0); }
|
||||
static void eval_ln(TinyBlocks_Block* self, TinyBlocks* rt) { double x = N(0); out_num(self, x > 0 ? log(x) : 0.0); }
|
||||
static void eval_exp(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, exp(N(0))); }
|
||||
static void eval_pi(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_num(self, M_PI); }
|
||||
|
||||
static void eval_random(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
double a = N(0), b = N(1);
|
||||
if (a > b) { double t = a; a = b; b = t; }
|
||||
double r = a + (b - a) * ((double)rand() / ((double)RAND_MAX + 1.0));
|
||||
tb_block_set_output(self, 0, tb_value_real(r)); /* sempre real */
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_clamp(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
double x = N(0), lo = N(1), hi = N(2);
|
||||
if (lo > hi) { double t = lo; lo = hi; hi = t; }
|
||||
out_num(self, x < lo ? lo : x > hi ? hi : x);
|
||||
}
|
||||
|
||||
static void eval_format(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char buf[64];
|
||||
tb_number_format(N(0), (int)N(1), buf, sizeof(buf));
|
||||
tb_block_set_output(self, 0, tb_value_text(buf));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_is_even(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
double x = N(0);
|
||||
out_bool(self, x == floor(x) && fmod(fabs(x), 2.0) == 0.0);
|
||||
}
|
||||
static void eval_is_prime(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
double x = N(0);
|
||||
out_bool(self, x == floor(x) && x < 9e15 && tb_number_is_prime((long long)x));
|
||||
}
|
||||
static void eval_is_int(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
double x = N(0);
|
||||
out_bool(self, isfinite(x) && x == floor(x));
|
||||
}
|
||||
|
||||
/* -- Registro ------------------------------------------------------------- */
|
||||
|
||||
static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name,
|
||||
const TinyBlocks_SlotDesc* in, uint32_t ni,
|
||||
const TinyBlocks_SlotDesc* out, uint32_t no,
|
||||
void (*fn)(TinyBlocks_Block*, TinyBlocks*)) {
|
||||
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn);
|
||||
return t && tb_library_add(lib, &t->base);
|
||||
}
|
||||
|
||||
static bool number_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
srand((unsigned)time(NULL) ^ 0x5bd1e995u);
|
||||
static const TinyBlocks_Category cat = {
|
||||
"Números",
|
||||
{139/255.f, 195/255.f, 74/255.f, 1.f},
|
||||
{104/255.f, 159/255.f, 56/255.f, 1.f},
|
||||
};
|
||||
tb_library_set_category(lib, &cat);
|
||||
|
||||
TB_BLOCK_META("Number.Div", "eval_div", "Divisao com casas decimais (por 0 da 0)");
|
||||
TB_BLOCK_META("Number.Pow", "eval_pow", "A elevado a B");
|
||||
TB_BLOCK_META("Number.Sqrt", "eval_sqrt", "Raiz quadrada");
|
||||
TB_BLOCK_META("Number.Round", "eval_round", "Arredonda para o inteiro mais proximo");
|
||||
TB_BLOCK_META("Number.Floor", "eval_floor", "Arredonda para baixo");
|
||||
TB_BLOCK_META("Number.Ceil", "eval_ceil", "Arredonda para cima");
|
||||
TB_BLOCK_META("Number.RoundTo", "tb_number_round_to", "Arredonda mantendo N casas decimais");
|
||||
TB_BLOCK_META("Number.Sin", "eval_sin", "Seno (angulo em graus)");
|
||||
TB_BLOCK_META("Number.Cos", "eval_cos", "Cosseno (angulo em graus)");
|
||||
TB_BLOCK_META("Number.Tan", "eval_tan", "Tangente (angulo em graus)");
|
||||
TB_BLOCK_META("Number.Asin", "eval_asin", "Arco-seno, em graus");
|
||||
TB_BLOCK_META("Number.Acos", "eval_acos", "Arco-cosseno, em graus");
|
||||
TB_BLOCK_META("Number.Atan", "eval_atan", "Arco-tangente, em graus");
|
||||
TB_BLOCK_META("Number.Log10", "eval_log10", "Logaritmo na base 10");
|
||||
TB_BLOCK_META("Number.Ln", "eval_ln", "Logaritmo natural (base e)");
|
||||
TB_BLOCK_META("Number.Exp", "eval_exp", "e elevado a X");
|
||||
TB_BLOCK_META("Number.Pi", "eval_pi", "O numero pi (3,14159...)");
|
||||
TB_BLOCK_META("Number.Random", "eval_random", "Numero real aleatorio entre A e B");
|
||||
TB_BLOCK_META("Number.Clamp", "eval_clamp", "Prende o numero entre o minimo e o maximo");
|
||||
TB_BLOCK_META("Number.Format", "tb_number_format", "Texto do numero com N casas decimais");
|
||||
TB_BLOCK_META("Number.IsEven", "eval_is_even", "Verdadeiro se o numero for par");
|
||||
TB_BLOCK_META("Number.IsPrime", "tb_number_is_prime", "Verdadeiro se o numero for primo");
|
||||
TB_BLOCK_META("Number.IsInteger", "eval_is_int", "Verdadeiro se o numero nao tiver casas decimais");
|
||||
|
||||
static const TinyBlocks_SlotDesc n1[] = {{"x", TB_VALUE_REAL}};
|
||||
static const TinyBlocks_SlotDesc n2[] = {{"a", TB_VALUE_REAL}, {"b", TB_VALUE_REAL}};
|
||||
static const TinyBlocks_SlotDesc n3[] = {{"x", TB_VALUE_REAL}, {"min", TB_VALUE_REAL}, {"max", TB_VALUE_REAL}};
|
||||
static const TinyBlocks_SlotDesc nk[] = {{"x", TB_VALUE_REAL}, {"casas", TB_VALUE_INTEGER}};
|
||||
/* saida "qualquer": inteiro quando exato, senao real */
|
||||
static const TinyBlocks_SlotDesc out[] = {{"numero", TB_VALUE_NONE}};
|
||||
static const TinyBlocks_SlotDesc text_out[] = {{"texto", TB_VALUE_TEXT}};
|
||||
/* saidas terminadas em '?' = blocos booleanos (hexagonais no editor) */
|
||||
static const TinyBlocks_SlotDesc even_out[] = {{"é par?", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc prime_out[] = {{"é primo?", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc int_out[] = {{"é inteiro?", TB_VALUE_INTEGER}};
|
||||
|
||||
return reg(rt, lib, "Number.Div", n2, 2, out, 1, eval_div)
|
||||
&& reg(rt, lib, "Number.Pow", n2, 2, out, 1, eval_pow)
|
||||
&& reg(rt, lib, "Number.Sqrt", n1, 1, out, 1, eval_sqrt)
|
||||
&& reg(rt, lib, "Number.Round", n1, 1, out, 1, eval_round)
|
||||
&& reg(rt, lib, "Number.Floor", n1, 1, out, 1, eval_floor)
|
||||
&& reg(rt, lib, "Number.Ceil", n1, 1, out, 1, eval_ceil)
|
||||
&& reg(rt, lib, "Number.RoundTo", nk, 2, out, 1, eval_round_to)
|
||||
&& reg(rt, lib, "Number.Sin", n1, 1, out, 1, eval_sin)
|
||||
&& reg(rt, lib, "Number.Cos", n1, 1, out, 1, eval_cos)
|
||||
&& reg(rt, lib, "Number.Tan", n1, 1, out, 1, eval_tan)
|
||||
&& reg(rt, lib, "Number.Asin", n1, 1, out, 1, eval_asin)
|
||||
&& reg(rt, lib, "Number.Acos", n1, 1, out, 1, eval_acos)
|
||||
&& reg(rt, lib, "Number.Atan", n1, 1, out, 1, eval_atan)
|
||||
&& reg(rt, lib, "Number.Log10", n1, 1, out, 1, eval_log10)
|
||||
&& reg(rt, lib, "Number.Ln", n1, 1, out, 1, eval_ln)
|
||||
&& reg(rt, lib, "Number.Exp", n1, 1, out, 1, eval_exp)
|
||||
&& reg(rt, lib, "Number.Pi", NULL, 0, out, 1, eval_pi)
|
||||
&& reg(rt, lib, "Number.Random", n2, 2, out, 1, eval_random)
|
||||
&& reg(rt, lib, "Number.Clamp", n3, 3, out, 1, eval_clamp)
|
||||
&& reg(rt, lib, "Number.Format", nk, 2, text_out, 1, eval_format)
|
||||
&& reg(rt, lib, "Number.IsEven", n1, 1, even_out, 1, eval_is_even)
|
||||
&& reg(rt, lib, "Number.IsPrime", n1, 1, prime_out, 1, eval_is_prime)
|
||||
&& reg(rt, lib, "Number.IsInteger", n1, 1, int_out, 1, eval_is_int);
|
||||
}
|
||||
|
||||
static void number_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
(void)rt; (void)lib;
|
||||
}
|
||||
|
||||
TINYBLOCKS_DEFINE_LIBRARY(number,
|
||||
"tinyblocks-number",
|
||||
"1.0.0",
|
||||
number_init,
|
||||
number_deinit)
|
||||
|
||||
const TinyBlocks_LibraryDescriptor* tb_number_get_library(void) {
|
||||
return &_tb_lib_desc_number;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
# Makefile da library os (categoria "Sistema")
|
||||
# Constroi build/libtinyblocks-os.a e build/libtinyblocks-os.so
|
||||
CC := gcc
|
||||
BUILD := build
|
||||
|
||||
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||
-I../../include -Iinclude
|
||||
|
||||
OBJ := $(BUILD)/tb_os.o
|
||||
LIB_A := $(BUILD)/libtinyblocks-os.a
|
||||
LIB_SO := $(BUILD)/libtinyblocks-os.so
|
||||
|
||||
.PHONY: all static shared clean
|
||||
all: static shared
|
||||
static: $(LIB_A)
|
||||
shared: $(LIB_SO)
|
||||
|
||||
$(OBJ): src/tb_os.c include/tb_os.h
|
||||
@mkdir -p $(BUILD)
|
||||
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||
|
||||
$(LIB_A): $(OBJ)
|
||||
ar rcs $@ $^
|
||||
|
||||
$(LIB_SO): $(OBJ)
|
||||
$(CC) -shared -o $@ $^
|
||||
|
||||
clean:
|
||||
$(RM) -r $(BUILD)
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* TinyBlocks - tb_os.h
|
||||
* Library tinyblocks-os: blocos que informam sobre o sistema (nome do SO,
|
||||
* distribuicao, versao do kernel, arquitetura, computador, usuario, CPUs,
|
||||
* memoria, tempo ligado). Registra a categoria "Sistema".
|
||||
*/
|
||||
#ifndef TINYBLOCKS_OS_H
|
||||
#define TINYBLOCKS_OS_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
|
||||
TB_API const TinyBlocks_LibraryDescriptor* tb_os_get_library(void);
|
||||
|
||||
/* Funcoes usadas pelos blocos (uteis tambem direto de C).
|
||||
As de texto escrevem em out (sempre terminado em 0). */
|
||||
TB_API void tb_os_name (char* out, size_t cap); /* "Linux", "Windows", "macOS" */
|
||||
TB_API void tb_os_distro (char* out, size_t cap); /* "Ubuntu 26.04 LTS" */
|
||||
TB_API void tb_os_version (char* out, size_t cap); /* versao do kernel */
|
||||
TB_API void tb_os_arch (char* out, size_t cap); /* "x86_64", "aarch64" */
|
||||
TB_API void tb_os_hostname(char* out, size_t cap);
|
||||
TB_API void tb_os_user (char* out, size_t cap);
|
||||
TB_API int tb_os_cpus (void);
|
||||
TB_API long long tb_os_memory_mb(void);
|
||||
TB_API long long tb_os_uptime_s(void);
|
||||
|
||||
#endif /* TINYBLOCKS_OS_H */
|
||||
@@ -0,0 +1,15 @@
|
||||
# Metadados da library os. Lido pela UI/build sem recompilar o .so.
|
||||
[library]
|
||||
name = "tinyblocks-os"
|
||||
version = "1.0.0"
|
||||
category = "Sistema"
|
||||
description = "Sistema operacional, versao, arquitetura, computador, usuario e recursos"
|
||||
color = [92, 107, 192, 255]
|
||||
dark = [57, 73, 171, 255]
|
||||
|
||||
[build]
|
||||
sources = ["src/tb_os.c"]
|
||||
includes = ["include"]
|
||||
shared = "build/libtinyblocks-os.so"
|
||||
static = "build/libtinyblocks-os.a"
|
||||
depends = []
|
||||
@@ -0,0 +1,236 @@
|
||||
/*
|
||||
* TinyBlocks - tb_os.c
|
||||
* Categoria "Sistema": OS.Name / Distro / Version / Arch / Hostname / User /
|
||||
* Home / Cwd / Cpus / MemoryMB / UptimeS e o booleano OS.Is ("o sistema e
|
||||
* Linux?"). Le uname(), /etc/os-release, sysconf() e /proc/uptime.
|
||||
*/
|
||||
#define _DEFAULT_SOURCE
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <stdint.h>
|
||||
#include <unistd.h>
|
||||
#include <pwd.h>
|
||||
#include <sys/utsname.h>
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include "tb_os.h"
|
||||
|
||||
static void copy(char* out, size_t cap, const char* s) {
|
||||
if (!out || !cap) return;
|
||||
snprintf(out, cap, "%s", s ? s : "");
|
||||
}
|
||||
|
||||
/* -- Consultas ------------------------------------------------------------ */
|
||||
|
||||
TB_API void tb_os_name(char* out, size_t cap) {
|
||||
#if defined(__APPLE__)
|
||||
copy(out, cap, "macOS");
|
||||
#elif defined(_WIN32)
|
||||
copy(out, cap, "Windows");
|
||||
#else
|
||||
struct utsname u;
|
||||
copy(out, cap, uname(&u) == 0 ? u.sysname : "desconhecido");
|
||||
#endif
|
||||
}
|
||||
|
||||
/* PRETTY_NAME do /etc/os-release (ex: "Ubuntu 26.04 LTS"); sem o arquivo,
|
||||
cai no nome do sistema. */
|
||||
TB_API void tb_os_distro(char* out, size_t cap) {
|
||||
const char* files[2] = { "/etc/os-release", "/usr/lib/os-release" };
|
||||
for (int f = 0; f < 2; f++) {
|
||||
FILE* fp = fopen(files[f], "r");
|
||||
if (!fp) continue;
|
||||
char line[512];
|
||||
while (fgets(line, sizeof(line), fp)) {
|
||||
if (strncmp(line, "PRETTY_NAME=", 12) != 0) continue;
|
||||
char* v = line + 12;
|
||||
v[strcspn(v, "\r\n")] = 0;
|
||||
size_t n = strlen(v);
|
||||
if (n >= 2 && (v[0] == '"' || v[0] == '\'') && v[n - 1] == v[0]) {
|
||||
v[n - 1] = 0;
|
||||
v++;
|
||||
}
|
||||
copy(out, cap, v);
|
||||
fclose(fp);
|
||||
return;
|
||||
}
|
||||
fclose(fp);
|
||||
}
|
||||
tb_os_name(out, cap);
|
||||
}
|
||||
|
||||
TB_API void tb_os_version(char* out, size_t cap) {
|
||||
struct utsname u;
|
||||
copy(out, cap, uname(&u) == 0 ? u.release : "");
|
||||
}
|
||||
|
||||
TB_API void tb_os_arch(char* out, size_t cap) {
|
||||
struct utsname u;
|
||||
copy(out, cap, uname(&u) == 0 ? u.machine : "");
|
||||
}
|
||||
|
||||
TB_API void tb_os_hostname(char* out, size_t cap) {
|
||||
char h[256];
|
||||
if (gethostname(h, sizeof(h)) == 0) { h[sizeof(h) - 1] = 0; copy(out, cap, h); }
|
||||
else copy(out, cap, "");
|
||||
}
|
||||
|
||||
TB_API void tb_os_user(char* out, size_t cap) {
|
||||
struct passwd* pw = getpwuid(getuid());
|
||||
if (pw && pw->pw_name) { copy(out, cap, pw->pw_name); return; }
|
||||
copy(out, cap, getenv("USER"));
|
||||
}
|
||||
|
||||
TB_API int tb_os_cpus(void) {
|
||||
long n = sysconf(_SC_NPROCESSORS_ONLN);
|
||||
return n > 0 ? (int)n : 1;
|
||||
}
|
||||
|
||||
TB_API long long tb_os_memory_mb(void) {
|
||||
long pages = sysconf(_SC_PHYS_PAGES);
|
||||
long psize = sysconf(_SC_PAGESIZE);
|
||||
if (pages <= 0 || psize <= 0) return 0;
|
||||
return (long long)pages * (long long)psize / (1024LL * 1024LL);
|
||||
}
|
||||
|
||||
TB_API long long tb_os_uptime_s(void) {
|
||||
FILE* fp = fopen("/proc/uptime", "r");
|
||||
if (!fp) return 0;
|
||||
double up = 0;
|
||||
if (fscanf(fp, "%lf", &up) != 1) up = 0;
|
||||
fclose(fp);
|
||||
return (long long)up;
|
||||
}
|
||||
|
||||
/* -- Blocos --------------------------------------------------------------- */
|
||||
|
||||
static void out_text(TinyBlocks_Block* self, void (*fn)(char*, size_t)) {
|
||||
char buf[512];
|
||||
fn(buf, sizeof(buf));
|
||||
tb_block_set_output(self, 0, tb_value_text(buf));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_name(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_text(self, tb_os_name); }
|
||||
static void eval_distro(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_text(self, tb_os_distro); }
|
||||
static void eval_version(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_text(self, tb_os_version); }
|
||||
static void eval_arch(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_text(self, tb_os_arch); }
|
||||
static void eval_hostname(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_text(self, tb_os_hostname); }
|
||||
static void eval_user(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_text(self, tb_os_user); }
|
||||
|
||||
static void eval_home(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
const char* h = getenv("HOME");
|
||||
if (!h || !h[0]) {
|
||||
struct passwd* pw = getpwuid(getuid());
|
||||
h = pw ? pw->pw_dir : "";
|
||||
}
|
||||
tb_block_set_output(self, 0, tb_value_text(h ? h : ""));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_cwd(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
char buf[1024];
|
||||
tb_block_set_output(self, 0, tb_value_text(getcwd(buf, sizeof(buf)) ? buf : ""));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_cpus(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
tb_block_set_output(self, 0, tb_value_integer(tb_os_cpus()));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_memory(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
tb_block_set_output(self, 0, tb_value_integer(tb_os_memory_mb()));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_uptime(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
tb_block_set_output(self, 0, tb_value_integer(tb_os_uptime_s()));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* "o sistema e [Linux]?" - compara com o nome do SO e com a distribuicao
|
||||
(aceita "Linux", "macOS", "Ubuntu", ...), sem diferenciar maiusculas. */
|
||||
static void eval_is(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
|
||||
const char* want = (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : "";
|
||||
char name[128], distro[256];
|
||||
tb_os_name(name, sizeof(name));
|
||||
tb_os_distro(distro, sizeof(distro));
|
||||
size_t wl = strlen(want);
|
||||
bool ok = wl > 0 && (strcasecmp(name, want) == 0 || strncasecmp(distro, want, wl) == 0);
|
||||
tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* -- Registro ------------------------------------------------------------- */
|
||||
|
||||
static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name,
|
||||
const TinyBlocks_SlotDesc* in, uint32_t ni,
|
||||
const TinyBlocks_SlotDesc* out, uint32_t no,
|
||||
void (*fn)(TinyBlocks_Block*, TinyBlocks*)) {
|
||||
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn);
|
||||
return t && tb_library_add(lib, &t->base);
|
||||
}
|
||||
|
||||
static bool os_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
static const TinyBlocks_Category cat = {
|
||||
"Sistema",
|
||||
{ 92/255.f, 107/255.f, 192/255.f, 1.f},
|
||||
{ 57/255.f, 73/255.f, 171/255.f, 1.f},
|
||||
};
|
||||
tb_library_set_category(lib, &cat);
|
||||
|
||||
TB_BLOCK_META("OS.Name", "tb_os_name", "Nome do sistema operacional (Linux, macOS, ...)");
|
||||
TB_BLOCK_META("OS.Distro", "tb_os_distro", "Distribuicao/versao do sistema (os-release)");
|
||||
TB_BLOCK_META("OS.Version", "tb_os_version", "Versao do kernel");
|
||||
TB_BLOCK_META("OS.Arch", "tb_os_arch", "Arquitetura do processador (x86_64, aarch64, ...)");
|
||||
TB_BLOCK_META("OS.Hostname", "tb_os_hostname", "Nome do computador na rede");
|
||||
TB_BLOCK_META("OS.User", "tb_os_user", "Usuario que esta rodando o programa");
|
||||
TB_BLOCK_META("OS.Home", "eval_home", "Pasta pessoal do usuario");
|
||||
TB_BLOCK_META("OS.Cwd", "eval_cwd", "Pasta de trabalho atual");
|
||||
TB_BLOCK_META("OS.Cpus", "tb_os_cpus", "Quantos processadores (nucleos) estao ativos");
|
||||
TB_BLOCK_META("OS.MemoryMB", "tb_os_memory_mb", "Memoria RAM total, em MB");
|
||||
TB_BLOCK_META("OS.UptimeS", "tb_os_uptime_s", "Ha quantos segundos o computador esta ligado");
|
||||
TB_BLOCK_META("OS.Is", "eval_is", "Verdadeiro se o sistema (ou a distribuicao) tiver esse nome");
|
||||
|
||||
static const TinyBlocks_SlotDesc text_out[] = {{"texto", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc num_out[] = {{"numero", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc is_in[] = {{"nome", TB_VALUE_TEXT}};
|
||||
/* saida terminada em '?' = bloco booleano (hexagonal no editor) */
|
||||
static const TinyBlocks_SlotDesc is_out[] = {{"é?", TB_VALUE_INTEGER}};
|
||||
|
||||
return reg(rt, lib, "OS.Name", NULL, 0, text_out, 1, eval_name)
|
||||
&& reg(rt, lib, "OS.Distro", NULL, 0, text_out, 1, eval_distro)
|
||||
&& reg(rt, lib, "OS.Version", NULL, 0, text_out, 1, eval_version)
|
||||
&& reg(rt, lib, "OS.Arch", NULL, 0, text_out, 1, eval_arch)
|
||||
&& reg(rt, lib, "OS.Hostname", NULL, 0, text_out, 1, eval_hostname)
|
||||
&& reg(rt, lib, "OS.User", NULL, 0, text_out, 1, eval_user)
|
||||
&& reg(rt, lib, "OS.Home", NULL, 0, text_out, 1, eval_home)
|
||||
&& reg(rt, lib, "OS.Cwd", NULL, 0, text_out, 1, eval_cwd)
|
||||
&& reg(rt, lib, "OS.Cpus", NULL, 0, num_out, 1, eval_cpus)
|
||||
&& reg(rt, lib, "OS.MemoryMB", NULL, 0, num_out, 1, eval_memory)
|
||||
&& reg(rt, lib, "OS.UptimeS", NULL, 0, num_out, 1, eval_uptime)
|
||||
&& reg(rt, lib, "OS.Is", is_in, 1, is_out, 1, eval_is);
|
||||
}
|
||||
|
||||
static void os_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
(void)rt; (void)lib;
|
||||
}
|
||||
|
||||
TINYBLOCKS_DEFINE_LIBRARY(os,
|
||||
"tinyblocks-os",
|
||||
"1.0.0",
|
||||
os_init,
|
||||
os_deinit)
|
||||
|
||||
const TinyBlocks_LibraryDescriptor* tb_os_get_library(void) {
|
||||
return &_tb_lib_desc_os;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
# Makefile da library string (categoria "Texto")
|
||||
# Constroi build/libtinyblocks-string.a e build/libtinyblocks-string.so
|
||||
CC := gcc
|
||||
BUILD := build
|
||||
|
||||
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||
-I../../include -Iinclude
|
||||
|
||||
OBJ := $(BUILD)/tb_string.o
|
||||
LIB_A := $(BUILD)/libtinyblocks-string.a
|
||||
LIB_SO := $(BUILD)/libtinyblocks-string.so
|
||||
|
||||
.PHONY: all static shared clean
|
||||
all: static shared
|
||||
static: $(LIB_A)
|
||||
shared: $(LIB_SO)
|
||||
|
||||
$(OBJ): src/tb_string.c include/tb_string.h
|
||||
@mkdir -p $(BUILD)
|
||||
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||
|
||||
$(LIB_A): $(OBJ)
|
||||
ar rcs $@ $^
|
||||
|
||||
$(LIB_SO): $(OBJ)
|
||||
$(CC) -shared -o $@ $^
|
||||
|
||||
clean:
|
||||
$(RM) -r $(BUILD)
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* TinyBlocks - tb_string.h
|
||||
* Library tinyblocks-string: blocos de texto (maiusculas/minusculas, trecho,
|
||||
* letra N, contem/comeca/termina, posicao, troca, apara, repete, inverte,
|
||||
* divide em lista, testes de numero/vazio). Ciente de UTF-8: posicoes e
|
||||
* tamanhos contam letras, nao bytes. Registra a categoria "Texto".
|
||||
*/
|
||||
#ifndef TINYBLOCKS_STRING_H
|
||||
#define TINYBLOCKS_STRING_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdbool.h>
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
|
||||
TB_API const TinyBlocks_LibraryDescriptor* tb_string_get_library(void);
|
||||
|
||||
/* Funcoes usadas pelos blocos (uteis tambem direto de C). As que devolvem
|
||||
char* alocam com malloc (libere com free). Posicoes comecam em 1. */
|
||||
TB_API size_t tb_string_length (const char* s); /* em letras */
|
||||
TB_API char* tb_string_upper (const char* s);
|
||||
TB_API char* tb_string_lower (const char* s);
|
||||
TB_API char* tb_string_sub (const char* s, long long from, long long to);
|
||||
TB_API long long tb_string_find(const char* s, const char* what); /* 0 = nao achou */
|
||||
TB_API char* tb_string_replace(const char* s, const char* what, const char* with);
|
||||
TB_API char* tb_string_trim (const char* s);
|
||||
TB_API char* tb_string_reverse(const char* s);
|
||||
TB_API bool tb_string_is_number(const char* s);
|
||||
|
||||
#endif /* TINYBLOCKS_STRING_H */
|
||||
@@ -0,0 +1,15 @@
|
||||
# Metadados da library string. Lido pela UI/build sem recompilar o .so.
|
||||
[library]
|
||||
name = "tinyblocks-string"
|
||||
version = "1.0.0"
|
||||
category = "Texto"
|
||||
description = "Texto - maiusculas, trecho, letra N, contem, troca, divide em lista"
|
||||
color = [207, 99, 207, 255]
|
||||
dark = [170, 68, 170, 255]
|
||||
|
||||
[build]
|
||||
sources = ["src/tb_string.c"]
|
||||
includes = ["include"]
|
||||
shared = "build/libtinyblocks-string.so"
|
||||
static = "build/libtinyblocks-string.a"
|
||||
depends = []
|
||||
@@ -0,0 +1,396 @@
|
||||
/*
|
||||
* TinyBlocks - tb_string.c
|
||||
* Categoria "Texto": String.Upper / Lower / Sub / Letter / Length / Find /
|
||||
* Replace / Trim / Repeat / Reverse / Split e os booleanos String.Contains /
|
||||
* StartsWith / EndsWith / IsNumber / IsEmpty.
|
||||
*
|
||||
* Tudo conta LETRAS (pontos de codigo UTF-8), nao bytes: "maçã" tem 4.
|
||||
* Maiusculas/minusculas cobrem ASCII e Latin-1 (á, ç, õ, ...), o que basta
|
||||
* para portugues. "contém" ignora maiusculas, como no Scratch.
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include <ctype.h>
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include <tinyblocks/tb_json_block.h>
|
||||
#include "tb_string.h"
|
||||
|
||||
#define STR_MAX_OUT (1u << 20) /* teto de 1 MB para "repita" */
|
||||
|
||||
/* -- UTF-8 ---------------------------------------------------------------- */
|
||||
|
||||
static size_t u8_len(unsigned char c) {
|
||||
if (c < 0x80) return 1;
|
||||
if ((c & 0xE0) == 0xC0) return 2;
|
||||
if ((c & 0xF0) == 0xE0) return 3;
|
||||
if ((c & 0xF8) == 0xF0) return 4;
|
||||
return 1; /* byte invalido: conta 1 */
|
||||
}
|
||||
|
||||
/* Byte onde comeca a letra `idx` (0-based); strlen se passar do fim */
|
||||
static size_t u8_offset(const char* s, size_t idx) {
|
||||
size_t o = 0, n = strlen(s);
|
||||
while (idx > 0 && o < n) {
|
||||
size_t l = u8_len((unsigned char)s[o]);
|
||||
o = o + l > n ? n : o + l;
|
||||
idx--;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
static char* dup_n(const char* s, size_t n) {
|
||||
char* r = malloc(n + 1);
|
||||
if (!r) return NULL;
|
||||
memcpy(r, s, n);
|
||||
r[n] = 0;
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Muda a caixa: up = maiusculas. ASCII + Latin-1 (C3 80..9E <-> C3 A0..BE) */
|
||||
static char* change_case(const char* s, bool up) {
|
||||
size_t n = strlen(s);
|
||||
char* r = dup_n(s, n);
|
||||
if (!r) return NULL;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
unsigned char c = (unsigned char)r[i];
|
||||
if (c < 0x80) {
|
||||
r[i] = (char)(up ? toupper(c) : tolower(c));
|
||||
} else if (c == 0xC3 && i + 1 < n) {
|
||||
unsigned char d = (unsigned char)r[i + 1];
|
||||
if (up && d >= 0xA0 && d <= 0xBE && d != 0xB7) r[i + 1] = (char)(d - 0x20);
|
||||
else if (!up && d >= 0x80 && d <= 0x9E && d != 0x97) r[i + 1] = (char)(d + 0x20);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Quantas letras ha nos primeiros `nbytes` bytes */
|
||||
static size_t u8_count(const char* s, size_t nbytes) {
|
||||
size_t n = 0, o = 0;
|
||||
while (o < nbytes && s[o]) { o += u8_len((unsigned char)s[o]); n++; }
|
||||
return n;
|
||||
}
|
||||
|
||||
/* -- API ------------------------------------------------------------------ */
|
||||
|
||||
TB_API size_t tb_string_length(const char* s) {
|
||||
return u8_count(s, strlen(s));
|
||||
}
|
||||
|
||||
TB_API char* tb_string_upper(const char* s) { return change_case(s, true); }
|
||||
TB_API char* tb_string_lower(const char* s) { return change_case(s, false); }
|
||||
|
||||
/* Letras `from` ate `to` (1-based, inclusivo), cortadas aos limites */
|
||||
TB_API char* tb_string_sub(const char* s, long long from, long long to) {
|
||||
long long n = (long long)tb_string_length(s);
|
||||
if (from < 1) from = 1;
|
||||
if (to > n) to = n;
|
||||
if (from > to) return dup_n("", 0);
|
||||
size_t a = u8_offset(s, (size_t)(from - 1));
|
||||
size_t b = u8_offset(s, (size_t)to);
|
||||
return dup_n(s + a, b - a);
|
||||
}
|
||||
|
||||
TB_API long long tb_string_find(const char* s, const char* what) {
|
||||
if (!what[0]) return 0;
|
||||
const char* p = strstr(s, what);
|
||||
if (!p) return 0;
|
||||
return (long long)u8_count(s, (size_t)(p - s)) + 1;
|
||||
}
|
||||
|
||||
TB_API char* tb_string_replace(const char* s, const char* what, const char* with) {
|
||||
size_t wl = strlen(what), rl = strlen(with), n = strlen(s);
|
||||
if (!wl) return dup_n(s, n);
|
||||
size_t count = 0;
|
||||
for (const char* p = strstr(s, what); p; p = strstr(p + wl, what)) count++;
|
||||
size_t out = n + count * rl - count * wl;
|
||||
char* r = malloc(out + 1);
|
||||
if (!r) return NULL;
|
||||
char* o = r;
|
||||
const char* cur = s;
|
||||
for (const char* p = strstr(s, what); p; p = strstr(cur, what)) {
|
||||
memcpy(o, cur, (size_t)(p - cur)); o += p - cur;
|
||||
memcpy(o, with, rl); o += rl;
|
||||
cur = p + wl;
|
||||
}
|
||||
strcpy(o, cur);
|
||||
return r;
|
||||
}
|
||||
|
||||
TB_API char* tb_string_trim(const char* s) {
|
||||
const char* a = s;
|
||||
while (*a && isspace((unsigned char)*a)) a++;
|
||||
const char* b = a + strlen(a);
|
||||
while (b > a && isspace((unsigned char)b[-1])) b--;
|
||||
return dup_n(a, (size_t)(b - a));
|
||||
}
|
||||
|
||||
TB_API char* tb_string_reverse(const char* s) {
|
||||
size_t n = strlen(s);
|
||||
char* r = malloc(n + 1);
|
||||
if (!r) return NULL;
|
||||
size_t o = 0;
|
||||
while (o < n) {
|
||||
size_t l = u8_len((unsigned char)s[o]);
|
||||
if (o + l > n) l = n - o;
|
||||
memcpy(r + (n - o - l), s + o, l); /* letra inteira, de tras pra frente */
|
||||
o += l;
|
||||
}
|
||||
r[n] = 0;
|
||||
return r;
|
||||
}
|
||||
|
||||
TB_API bool tb_string_is_number(const char* s) {
|
||||
while (isspace((unsigned char)*s)) s++;
|
||||
if (!*s) return false;
|
||||
char* e;
|
||||
strtod(s, &e);
|
||||
if (e == s) return false;
|
||||
while (isspace((unsigned char)*e)) e++;
|
||||
return *e == 0;
|
||||
}
|
||||
|
||||
/* -- Entradas ------------------------------------------------------------- */
|
||||
|
||||
/* Texto da entrada i (numeros viram texto). Fica valido ate o proximo uso. */
|
||||
static const char* in_text(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i, char* buf, size_t cap) {
|
||||
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
||||
switch (v.kind) {
|
||||
case TB_VALUE_TEXT: return v.as.text ? v.as.text : "";
|
||||
case TB_VALUE_INTEGER: snprintf(buf, cap, "%lld", (long long)v.as.integer); return buf;
|
||||
case TB_VALUE_REAL: snprintf(buf, cap, "%g", v.as.real); return buf;
|
||||
default: return "";
|
||||
}
|
||||
}
|
||||
|
||||
static long long in_int(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
||||
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
||||
if (v.kind == TB_VALUE_INTEGER) return v.as.integer;
|
||||
if (v.kind == TB_VALUE_REAL) return (long long)v.as.real;
|
||||
if (v.kind == TB_VALUE_TEXT && v.as.text) return strtoll(v.as.text, NULL, 10);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void out_owned(TinyBlocks_Block* self, char* s) {
|
||||
tb_block_set_output(self, 0, tb_value_text(s ? s : ""));
|
||||
free(s);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void out_bool(TinyBlocks_Block* self, bool b) {
|
||||
tb_block_set_output(self, 0, tb_value_integer(b ? 1 : 0));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
#define TXT(i) in_text(self, rt, (i), b##i, sizeof(b##i))
|
||||
|
||||
/* -- Blocos --------------------------------------------------------------- */
|
||||
|
||||
static void eval_upper(TinyBlocks_Block* self, TinyBlocks* rt) { char b0[64]; out_owned(self, tb_string_upper(TXT(0))); }
|
||||
static void eval_lower(TinyBlocks_Block* self, TinyBlocks* rt) { char b0[64]; out_owned(self, tb_string_lower(TXT(0))); }
|
||||
static void eval_trim(TinyBlocks_Block* self, TinyBlocks* rt) { char b0[64]; out_owned(self, tb_string_trim(TXT(0))); }
|
||||
static void eval_reverse(TinyBlocks_Block* self, TinyBlocks* rt) { char b0[64]; out_owned(self, tb_string_reverse(TXT(0))); }
|
||||
|
||||
static void eval_sub(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char b0[64];
|
||||
out_owned(self, tb_string_sub(TXT(0), in_int(self, rt, 1), in_int(self, rt, 2)));
|
||||
}
|
||||
|
||||
static void eval_letter(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char b0[64];
|
||||
long long k = in_int(self, rt, 1);
|
||||
out_owned(self, tb_string_sub(TXT(0), k, k));
|
||||
}
|
||||
|
||||
static void eval_length(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char b0[64];
|
||||
tb_block_set_output(self, 0, tb_value_integer((int64_t)tb_string_length(TXT(0))));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_find(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char b0[64], b1[64];
|
||||
tb_block_set_output(self, 0, tb_value_integer(tb_string_find(TXT(0), TXT(1))));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_replace(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char b0[64], b1[64], b2[64];
|
||||
out_owned(self, tb_string_replace(TXT(0), TXT(1), TXT(2)));
|
||||
}
|
||||
|
||||
static void eval_repeat(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char b0[64];
|
||||
const char* s = TXT(0);
|
||||
long long k = in_int(self, rt, 1);
|
||||
size_t n = strlen(s);
|
||||
if (k < 0) k = 0;
|
||||
if (n && (size_t)k > STR_MAX_OUT / n) k = (long long)(STR_MAX_OUT / n);
|
||||
char* r = malloc(n * (size_t)k + 1);
|
||||
if (r) {
|
||||
for (long long i = 0; i < k; i++) memcpy(r + (size_t)i * n, s, n);
|
||||
r[n * (size_t)k] = 0;
|
||||
}
|
||||
out_owned(self, r);
|
||||
}
|
||||
|
||||
static void push_piece(TinyBlocks_JsonValue* arr, const char* s, size_t n) {
|
||||
char* piece = dup_n(s, n);
|
||||
TinyBlocks_JsonValue* item = piece ? tb_json_string(piece) : NULL;
|
||||
free(piece);
|
||||
if (item) { tb_json_array_push(arr, item); tb_json_release(item); }
|
||||
}
|
||||
|
||||
/* Divide em lista JSON; separador vazio = uma letra por item.
|
||||
"a,,b" -> ["a","","b"]; "a," -> ["a",""]; "" -> [] */
|
||||
static void eval_split(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char b0[64], b1[64];
|
||||
const char* s = TXT(0);
|
||||
const char* sep = TXT(1);
|
||||
size_t sl = strlen(sep), n = strlen(s);
|
||||
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||
if (arr && n) {
|
||||
if (!sl) {
|
||||
for (size_t o = 0; o < n; ) {
|
||||
size_t l = u8_len((unsigned char)s[o]);
|
||||
if (o + l > n) l = n - o;
|
||||
push_piece(arr, s + o, l);
|
||||
o += l;
|
||||
}
|
||||
} else {
|
||||
const char* cur = s;
|
||||
for (;;) {
|
||||
const char* p = strstr(cur, sep);
|
||||
push_piece(arr, cur, p ? (size_t)(p - cur) : strlen(cur));
|
||||
if (!p) break;
|
||||
cur = p + sl;
|
||||
}
|
||||
}
|
||||
}
|
||||
tb_block_set_output(self, 0, tb_value_json(arr));
|
||||
tb_json_release(arr);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_contains(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char b0[64], b1[64];
|
||||
char* a = tb_string_lower(TXT(0));
|
||||
char* w = tb_string_lower(TXT(1));
|
||||
out_bool(self, a && w && strstr(a, w) != NULL);
|
||||
free(a); free(w);
|
||||
}
|
||||
|
||||
static void eval_starts(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char b0[64], b1[64];
|
||||
const char* s = TXT(0);
|
||||
const char* w = TXT(1);
|
||||
out_bool(self, strncmp(s, w, strlen(w)) == 0);
|
||||
}
|
||||
|
||||
static void eval_ends(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char b0[64], b1[64];
|
||||
const char* s = TXT(0);
|
||||
const char* w = TXT(1);
|
||||
size_t n = strlen(s), m = strlen(w);
|
||||
out_bool(self, m <= n && strcmp(s + n - m, w) == 0);
|
||||
}
|
||||
|
||||
static void eval_isnum(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char b0[64];
|
||||
out_bool(self, tb_string_is_number(TXT(0)));
|
||||
}
|
||||
|
||||
static void eval_isempty(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char b0[64];
|
||||
char* t = tb_string_trim(TXT(0));
|
||||
out_bool(self, !t || !t[0]);
|
||||
free(t);
|
||||
}
|
||||
|
||||
/* -- Registro ------------------------------------------------------------- */
|
||||
|
||||
static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name,
|
||||
const TinyBlocks_SlotDesc* in, uint32_t ni,
|
||||
const TinyBlocks_SlotDesc* out, uint32_t no,
|
||||
void (*fn)(TinyBlocks_Block*, TinyBlocks*)) {
|
||||
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn);
|
||||
return t && tb_library_add(lib, &t->base);
|
||||
}
|
||||
|
||||
static bool string_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
static const TinyBlocks_Category cat = {
|
||||
"Texto",
|
||||
{207/255.f, 99/255.f, 207/255.f, 1.f},
|
||||
{170/255.f, 68/255.f, 170/255.f, 1.f},
|
||||
};
|
||||
tb_library_set_category(lib, &cat);
|
||||
|
||||
TB_BLOCK_META("String.Upper", "tb_string_upper", "Texto em letras maiusculas");
|
||||
TB_BLOCK_META("String.Lower", "tb_string_lower", "Texto em letras minusculas");
|
||||
TB_BLOCK_META("String.Sub", "tb_string_sub", "Pedaco do texto da letra A ate a letra B");
|
||||
TB_BLOCK_META("String.Letter", "eval_letter", "A letra N do texto (1 = primeira)");
|
||||
TB_BLOCK_META("String.Length", "tb_string_length", "Quantas letras o texto tem");
|
||||
TB_BLOCK_META("String.Find", "tb_string_find", "Posicao do trecho no texto (0 = nao tem)");
|
||||
TB_BLOCK_META("String.Replace", "tb_string_replace", "Troca todas as ocorrencias de um trecho");
|
||||
TB_BLOCK_META("String.Trim", "tb_string_trim", "Tira os espacos do comeco e do fim");
|
||||
TB_BLOCK_META("String.Repeat", "eval_repeat", "Repete o texto N vezes");
|
||||
TB_BLOCK_META("String.Reverse", "tb_string_reverse", "Texto de tras para frente");
|
||||
TB_BLOCK_META("String.Split", "eval_split", "Divide o texto em uma lista pelo separador");
|
||||
TB_BLOCK_META("String.Contains", "eval_contains", "Verdadeiro se o texto contem o trecho (ignora maiusculas)");
|
||||
TB_BLOCK_META("String.StartsWith", "eval_starts", "Verdadeiro se o texto comeca com o trecho");
|
||||
TB_BLOCK_META("String.EndsWith", "eval_ends", "Verdadeiro se o texto termina com o trecho");
|
||||
TB_BLOCK_META("String.IsNumber", "tb_string_is_number", "Verdadeiro se o texto for um numero");
|
||||
TB_BLOCK_META("String.IsEmpty", "eval_isempty", "Verdadeiro se o texto estiver vazio (ou so espacos)");
|
||||
|
||||
static const TinyBlocks_SlotDesc t1[] = {{"texto", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc t2[] = {{"texto", TB_VALUE_TEXT}, {"trecho", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc t3[] = {{"texto", TB_VALUE_TEXT}, {"trecho", TB_VALUE_TEXT}, {"por", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc sub[] = {{"texto", TB_VALUE_TEXT}, {"de", TB_VALUE_INTEGER}, {"ate", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc tn[] = {{"texto", TB_VALUE_TEXT}, {"n", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc split[]= {{"texto", TB_VALUE_TEXT}, {"separador", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc text_out[] = {{"texto", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc int_out[] = {{"numero", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc list_out[] = {{"lista", TB_VALUE_JSON}};
|
||||
/* saidas terminadas em '?' = blocos booleanos (hexagonais no editor) */
|
||||
static const TinyBlocks_SlotDesc has_out[] = {{"contém?", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc beg_out[] = {{"começa?", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc end_out[] = {{"termina?", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc num_out[] = {{"é número?", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc emp_out[] = {{"vazio?", TB_VALUE_INTEGER}};
|
||||
|
||||
return reg(rt, lib, "String.Upper", t1, 1, text_out, 1, eval_upper)
|
||||
&& reg(rt, lib, "String.Lower", t1, 1, text_out, 1, eval_lower)
|
||||
&& reg(rt, lib, "String.Sub", sub, 3, text_out, 1, eval_sub)
|
||||
&& reg(rt, lib, "String.Letter", tn, 2, text_out, 1, eval_letter)
|
||||
&& reg(rt, lib, "String.Length", t1, 1, int_out, 1, eval_length)
|
||||
&& reg(rt, lib, "String.Find", t2, 2, int_out, 1, eval_find)
|
||||
&& reg(rt, lib, "String.Replace", t3, 3, text_out, 1, eval_replace)
|
||||
&& reg(rt, lib, "String.Trim", t1, 1, text_out, 1, eval_trim)
|
||||
&& reg(rt, lib, "String.Repeat", tn, 2, text_out, 1, eval_repeat)
|
||||
&& reg(rt, lib, "String.Reverse", t1, 1, text_out, 1, eval_reverse)
|
||||
&& reg(rt, lib, "String.Split", split, 2, list_out, 1, eval_split)
|
||||
&& reg(rt, lib, "String.Contains", t2, 2, has_out, 1, eval_contains)
|
||||
&& reg(rt, lib, "String.StartsWith", t2, 2, beg_out, 1, eval_starts)
|
||||
&& reg(rt, lib, "String.EndsWith", t2, 2, end_out, 1, eval_ends)
|
||||
&& reg(rt, lib, "String.IsNumber", t1, 1, num_out, 1, eval_isnum)
|
||||
&& reg(rt, lib, "String.IsEmpty", t1, 1, emp_out, 1, eval_isempty);
|
||||
}
|
||||
|
||||
static void string_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
(void)rt; (void)lib;
|
||||
}
|
||||
|
||||
TINYBLOCKS_DEFINE_LIBRARY(string,
|
||||
"tinyblocks-string",
|
||||
"1.0.0",
|
||||
string_init,
|
||||
string_deinit)
|
||||
|
||||
const TinyBlocks_LibraryDescriptor* tb_string_get_library(void) {
|
||||
return &_tb_lib_desc_string;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
# Makefile da library vector (categoria "Listas")
|
||||
# Constroi build/libtinyblocks-vector.a e build/libtinyblocks-vector.so
|
||||
CC := gcc
|
||||
BUILD := build
|
||||
|
||||
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||
-I../../include -Iinclude
|
||||
|
||||
OBJ := $(BUILD)/tb_vector.o
|
||||
LIB_A := $(BUILD)/libtinyblocks-vector.a
|
||||
LIB_SO := $(BUILD)/libtinyblocks-vector.so
|
||||
|
||||
.PHONY: all static shared clean
|
||||
all: static shared
|
||||
static: $(LIB_A)
|
||||
shared: $(LIB_SO)
|
||||
|
||||
$(OBJ): src/tb_vector.c include/tb_vector.h
|
||||
@mkdir -p $(BUILD)
|
||||
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||
|
||||
$(LIB_A): $(OBJ)
|
||||
ar rcs $@ $^
|
||||
|
||||
$(LIB_SO): $(OBJ)
|
||||
$(CC) -shared -o $@ $^ -lm
|
||||
|
||||
clean:
|
||||
$(RM) -r $(BUILD)
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* TinyBlocks - tb_vector.h
|
||||
* Library tinyblocks-vector: listas dinamicas (como std::vector / as listas
|
||||
* do Scratch). Registra a categoria "Listas"; os blocos se chamam List.*
|
||||
* (Vector.* ja e o desenho vetorial do exemplo examples/vector).
|
||||
*
|
||||
* Uma lista e um array JSON (TB_VALUE_JSON), o mesmo formato de
|
||||
* "itens da pasta" e Regex.Split. Os blocos sao funcionais: devolvem uma
|
||||
* lista NOVA, e o programa guarda o resultado numa variavel:
|
||||
* mude L para (adicione 5 ao fim de L)
|
||||
* Um campo digitado tambem vira lista: "[1, 2, 3]" ou "maçã, banana".
|
||||
* Posicoes comecam em 1.
|
||||
*/
|
||||
#ifndef TINYBLOCKS_VECTOR_H
|
||||
#define TINYBLOCKS_VECTOR_H
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include <tinyblocks/tb_json_block.h>
|
||||
|
||||
TB_API const TinyBlocks_LibraryDescriptor* tb_vector_get_library(void);
|
||||
|
||||
/* Converte um valor em lista (ref nova; libere com tb_json_release).
|
||||
JSON array -> ele mesmo; texto "[...]" -> parse; "a, b" -> ["a","b"];
|
||||
numero -> [n]; vazio/outros -> []. */
|
||||
TB_API TinyBlocks_JsonValue* tb_vector_from_value(TinyBlocks_Value v);
|
||||
|
||||
#endif /* TINYBLOCKS_VECTOR_H */
|
||||
@@ -0,0 +1,15 @@
|
||||
# Metadados da library vector. Lido pela UI/build sem recompilar o .so.
|
||||
[library]
|
||||
name = "tinyblocks-vector"
|
||||
version = "1.0.0"
|
||||
category = "Listas"
|
||||
description = "Listas (std::vector) - adicionar, inserir, remover, item N, ordenar, juntar"
|
||||
color = [255, 102, 26, 255]
|
||||
dark = [230, 77, 0, 255]
|
||||
|
||||
[build]
|
||||
sources = ["src/tb_vector.c"]
|
||||
includes = ["include"]
|
||||
shared = "build/libtinyblocks-vector.so"
|
||||
static = "build/libtinyblocks-vector.a"
|
||||
depends = []
|
||||
@@ -0,0 +1,516 @@
|
||||
/*
|
||||
* TinyBlocks - tb_vector.c
|
||||
* Categoria "Listas": List.Empty / Of / Range / Add / Insert / Remove /
|
||||
* Replace / Item / Length / IndexOf / Slice / Reverse / Sort / Join / Sum e
|
||||
* o booleano List.Contains. Listas sao arrays JSON imutaveis: cada bloco
|
||||
* monta uma lista nova (ver tb_vector.h).
|
||||
*
|
||||
* Comparacao de itens como no Scratch: numeros pelo valor ("2" == 2.0) e
|
||||
* textos sem diferenciar maiusculas.
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <stdint.h>
|
||||
#include <ctype.h>
|
||||
#include <math.h>
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include <tinyblocks/tb_json_block.h>
|
||||
#include "tb_vector.h"
|
||||
|
||||
#define LIST_MAX_RANGE 100000
|
||||
|
||||
/* -- Itens ---------------------------------------------------------------- */
|
||||
|
||||
static bool text_number(const char* s, double* out) {
|
||||
while (isspace((unsigned char)*s)) s++;
|
||||
if (!*s) return false;
|
||||
char* e;
|
||||
double d = strtod(s, &e);
|
||||
if (e == s) return false;
|
||||
while (isspace((unsigned char)*e)) e++;
|
||||
if (*e) return false;
|
||||
*out = d;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Item JSON a partir de um texto digitado: numero vira numero */
|
||||
static TinyBlocks_JsonValue* item_from_text(const char* s) {
|
||||
double d;
|
||||
if (text_number(s, &d)) return tb_json_number(d);
|
||||
return tb_json_string(s);
|
||||
}
|
||||
|
||||
/* Item JSON a partir de um valor de entrada (ref nova; NULL = sem valor) */
|
||||
static TinyBlocks_JsonValue* item_from_value(TinyBlocks_Value v) {
|
||||
switch (v.kind) {
|
||||
case TB_VALUE_INTEGER: return tb_json_number((double)v.as.integer);
|
||||
case TB_VALUE_REAL: return tb_json_number(v.as.real);
|
||||
case TB_VALUE_TEXT: return tb_json_string(v.as.text ? v.as.text : "");
|
||||
case TB_VALUE_JSON: if (v.as.json) tb_json_retain(v.as.json); return v.as.json;
|
||||
default: return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
/* Valor de saida a partir de um item JSON */
|
||||
static TinyBlocks_Value value_from_item(const TinyBlocks_JsonValue* j) {
|
||||
if (!j) return tb_value_text("");
|
||||
switch (tb_json_kind(j)) {
|
||||
case TB_JSON_NUMBER: {
|
||||
double d = tb_json_as_number(j, 0);
|
||||
if (d == floor(d) && fabs(d) < 1e15) return tb_value_integer((int64_t)d);
|
||||
return tb_value_real(d);
|
||||
}
|
||||
case TB_JSON_STRING: return tb_value_text(tb_json_as_string(j));
|
||||
case TB_JSON_BOOL: return tb_value_integer(tb_json_as_bool(j, false) ? 1 : 0);
|
||||
case TB_JSON_NULL: return tb_value_text("");
|
||||
default: {
|
||||
TinyBlocks_JsonValue* c = tb_json_clone(j);
|
||||
TinyBlocks_Value v = tb_value_json(c);
|
||||
tb_json_release(c);
|
||||
return v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Texto do item (para juntar/comparar) */
|
||||
static void item_text(const TinyBlocks_JsonValue* j, char* out, size_t cap) {
|
||||
out[0] = 0;
|
||||
if (!j) return;
|
||||
switch (tb_json_kind(j)) {
|
||||
case TB_JSON_NUMBER: {
|
||||
double d = tb_json_as_number(j, 0);
|
||||
if (d == floor(d) && fabs(d) < 1e15) snprintf(out, cap, "%lld", (long long)d);
|
||||
else snprintf(out, cap, "%g", d);
|
||||
break;
|
||||
}
|
||||
case TB_JSON_STRING: snprintf(out, cap, "%s", tb_json_as_string(j)); break;
|
||||
case TB_JSON_BOOL: snprintf(out, cap, "%s", tb_json_as_bool(j, false) ? "1" : "0"); break;
|
||||
case TB_JSON_NULL: break;
|
||||
default: {
|
||||
char* s = tb_json_stringify(j);
|
||||
snprintf(out, cap, "%s", s ? s : "");
|
||||
free(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static bool item_number(const TinyBlocks_JsonValue* j, double* d) {
|
||||
if (!j) return false;
|
||||
if (tb_json_kind(j) == TB_JSON_NUMBER) { *d = tb_json_as_number(j, 0); return true; }
|
||||
if (tb_json_kind(j) == TB_JSON_STRING) return text_number(tb_json_as_string(j), d);
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool item_equal(const TinyBlocks_JsonValue* a, const TinyBlocks_JsonValue* b) {
|
||||
double x, y;
|
||||
if (item_number(a, &x) && item_number(b, &y)) return x == y;
|
||||
char sa[512], sb[512];
|
||||
item_text(a, sa, sizeof(sa));
|
||||
item_text(b, sb, sizeof(sb));
|
||||
return strcasecmp(sa, sb) == 0;
|
||||
}
|
||||
|
||||
/* -- Listas --------------------------------------------------------------- */
|
||||
|
||||
static void push_owned(TinyBlocks_JsonValue* arr, TinyBlocks_JsonValue* item) {
|
||||
if (!item) return;
|
||||
tb_json_array_push(arr, item);
|
||||
tb_json_release(item);
|
||||
}
|
||||
|
||||
/* "maçã, banana" -> ["maçã", "banana"]; itens numericos viram numero */
|
||||
static TinyBlocks_JsonValue* list_from_csv(const char* s) {
|
||||
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||
if (!arr) return NULL;
|
||||
while (*s) {
|
||||
const char* e = strchr(s, ',');
|
||||
size_t n = e ? (size_t)(e - s) : strlen(s);
|
||||
while (n && isspace((unsigned char)*s)) { s++; n--; }
|
||||
while (n && isspace((unsigned char)s[n - 1])) n--;
|
||||
char* piece = malloc(n + 1);
|
||||
if (piece) {
|
||||
memcpy(piece, s, n);
|
||||
piece[n] = 0;
|
||||
push_owned(arr, item_from_text(piece));
|
||||
free(piece);
|
||||
}
|
||||
if (!e) break;
|
||||
s = e + 1;
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
TB_API TinyBlocks_JsonValue* tb_vector_from_value(TinyBlocks_Value v) {
|
||||
if (v.kind == TB_VALUE_JSON && v.as.json && tb_json_kind(v.as.json) == TB_JSON_ARRAY) {
|
||||
tb_json_retain(v.as.json);
|
||||
return v.as.json;
|
||||
}
|
||||
if (v.kind == TB_VALUE_TEXT && v.as.text) {
|
||||
const char* s = v.as.text;
|
||||
while (isspace((unsigned char)*s)) s++;
|
||||
if (!*s) return tb_json_array();
|
||||
if (*s == '[') {
|
||||
TinyBlocks_JsonValue* j = tb_json_parse(s, NULL, 0);
|
||||
if (j && tb_json_kind(j) == TB_JSON_ARRAY) return j;
|
||||
if (j) tb_json_release(j);
|
||||
}
|
||||
return list_from_csv(s);
|
||||
}
|
||||
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||
if (arr && (v.kind == TB_VALUE_INTEGER || v.kind == TB_VALUE_REAL ||
|
||||
(v.kind == TB_VALUE_JSON && v.as.json)))
|
||||
push_owned(arr, item_from_value(v));
|
||||
return arr;
|
||||
}
|
||||
|
||||
/* Copia os itens [from, to) de src para uma lista nova */
|
||||
static TinyBlocks_JsonValue* list_copy(const TinyBlocks_JsonValue* src, uint32_t from, uint32_t to) {
|
||||
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||
uint32_t n = src ? tb_json_array_length(src) : 0;
|
||||
if (to > n) to = n;
|
||||
for (uint32_t i = from; arr && i < to; i++) push_owned(arr, tb_json_array_get(src, i));
|
||||
return arr;
|
||||
}
|
||||
|
||||
/* -- Entradas/saidas ------------------------------------------------------ */
|
||||
|
||||
static TinyBlocks_JsonValue* in_list(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
||||
return tb_vector_from_value(tb_block_get_input(self, rt, i));
|
||||
}
|
||||
|
||||
static long long in_int(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
||||
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
||||
if (v.kind == TB_VALUE_INTEGER) return v.as.integer;
|
||||
if (v.kind == TB_VALUE_REAL) return (long long)llround(v.as.real);
|
||||
if (v.kind == TB_VALUE_TEXT && v.as.text) return strtoll(v.as.text, NULL, 10);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static TinyBlocks_JsonValue* in_item(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
||||
TinyBlocks_JsonValue* it = item_from_value(tb_block_get_input(self, rt, i));
|
||||
return it ? it : tb_json_string("");
|
||||
}
|
||||
|
||||
/* Toma a referencia de arr */
|
||||
static void out_list(TinyBlocks_Block* self, TinyBlocks_JsonValue* arr) {
|
||||
if (!arr) arr = tb_json_array();
|
||||
tb_block_set_output(self, 0, tb_value_json(arr));
|
||||
tb_json_release(arr);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void out_int(TinyBlocks_Block* self, long long n) {
|
||||
tb_block_set_output(self, 0, tb_value_integer(n));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* -- Blocos --------------------------------------------------------------- */
|
||||
|
||||
static void eval_empty(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
out_list(self, tb_json_array());
|
||||
}
|
||||
|
||||
/* "lista com A B C": campos vazios ficam de fora */
|
||||
static void eval_of(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||
for (uint32_t i = 0; arr && i < 3; i++) {
|
||||
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
||||
if (v.kind == TB_VALUE_NONE || (v.kind == TB_VALUE_TEXT && (!v.as.text || !v.as.text[0])))
|
||||
continue;
|
||||
push_owned(arr, item_from_value(v));
|
||||
}
|
||||
out_list(self, arr);
|
||||
}
|
||||
|
||||
/* "números de A até B" (inclusivo, passo 1 ou -1) */
|
||||
static void eval_range(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
long long a = in_int(self, rt, 0), b = in_int(self, rt, 1);
|
||||
long long step = a <= b ? 1 : -1;
|
||||
long long n = (b - a) * step + 1;
|
||||
if (n > LIST_MAX_RANGE) n = LIST_MAX_RANGE;
|
||||
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||
for (long long i = 0; arr && i < n; i++) push_owned(arr, tb_json_number((double)(a + i * step)));
|
||||
out_list(self, arr);
|
||||
}
|
||||
|
||||
static void eval_add(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_JsonValue* src = in_list(self, rt, 0);
|
||||
TinyBlocks_JsonValue* arr = list_copy(src, 0, UINT32_MAX);
|
||||
if (arr) push_owned(arr, in_item(self, rt, 1));
|
||||
tb_json_release(src);
|
||||
out_list(self, arr);
|
||||
}
|
||||
|
||||
/* "insira X na posição N de L": N fora da faixa encaixa no comeco/fim */
|
||||
static void eval_insert(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_JsonValue* src = in_list(self, rt, 0);
|
||||
uint32_t n = src ? tb_json_array_length(src) : 0;
|
||||
long long pos = in_int(self, rt, 2);
|
||||
if (pos < 1) pos = 1;
|
||||
if (pos > (long long)n + 1) pos = (long long)n + 1;
|
||||
TinyBlocks_JsonValue* arr = list_copy(src, 0, (uint32_t)(pos - 1));
|
||||
if (arr) {
|
||||
push_owned(arr, in_item(self, rt, 1));
|
||||
for (uint32_t i = (uint32_t)(pos - 1); i < n; i++) push_owned(arr, tb_json_array_get(src, i));
|
||||
}
|
||||
tb_json_release(src);
|
||||
out_list(self, arr);
|
||||
}
|
||||
|
||||
static void eval_remove(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_JsonValue* src = in_list(self, rt, 0);
|
||||
uint32_t n = src ? tb_json_array_length(src) : 0;
|
||||
long long k = in_int(self, rt, 1);
|
||||
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||
for (uint32_t i = 0; arr && i < n; i++)
|
||||
if ((long long)i + 1 != k) push_owned(arr, tb_json_array_get(src, i));
|
||||
tb_json_release(src);
|
||||
out_list(self, arr);
|
||||
}
|
||||
|
||||
static void eval_replace(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_JsonValue* src = in_list(self, rt, 0);
|
||||
uint32_t n = src ? tb_json_array_length(src) : 0;
|
||||
long long k = in_int(self, rt, 1);
|
||||
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||
for (uint32_t i = 0; arr && i < n; i++) {
|
||||
if ((long long)i + 1 == k) push_owned(arr, in_item(self, rt, 2));
|
||||
else push_owned(arr, tb_json_array_get(src, i));
|
||||
}
|
||||
tb_json_release(src);
|
||||
out_list(self, arr);
|
||||
}
|
||||
|
||||
static void eval_item(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_JsonValue* src = in_list(self, rt, 0);
|
||||
long long k = in_int(self, rt, 1);
|
||||
uint32_t n = src ? tb_json_array_length(src) : 0;
|
||||
TinyBlocks_JsonValue* it = (k >= 1 && k <= (long long)n) ? tb_json_array_get(src, (uint32_t)(k - 1)) : NULL;
|
||||
tb_block_set_output(self, 0, value_from_item(it));
|
||||
if (it) tb_json_release(it);
|
||||
tb_json_release(src);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_length(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_JsonValue* src = in_list(self, rt, 0);
|
||||
out_int(self, src ? tb_json_array_length(src) : 0);
|
||||
tb_json_release(src);
|
||||
}
|
||||
|
||||
/* posicao do item (1..n), 0 se nao estiver na lista */
|
||||
static long long find_item(const TinyBlocks_JsonValue* src, const TinyBlocks_JsonValue* want) {
|
||||
uint32_t n = src ? tb_json_array_length(src) : 0;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
TinyBlocks_JsonValue* it = tb_json_array_get(src, i);
|
||||
bool eq = item_equal(it, want);
|
||||
if (it) tb_json_release(it);
|
||||
if (eq) return (long long)i + 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void eval_index_of(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_JsonValue* src = in_list(self, rt, 0);
|
||||
TinyBlocks_JsonValue* want = in_item(self, rt, 1);
|
||||
out_int(self, find_item(src, want));
|
||||
tb_json_release(want);
|
||||
tb_json_release(src);
|
||||
}
|
||||
|
||||
static void eval_contains(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_JsonValue* src = in_list(self, rt, 0);
|
||||
TinyBlocks_JsonValue* want = in_item(self, rt, 1);
|
||||
out_int(self, find_item(src, want) > 0 ? 1 : 0);
|
||||
tb_json_release(want);
|
||||
tb_json_release(src);
|
||||
}
|
||||
|
||||
/* "itens A a B de L" (inclusivo, cortado aos limites) */
|
||||
static void eval_slice(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_JsonValue* src = in_list(self, rt, 0);
|
||||
long long a = in_int(self, rt, 1), b = in_int(self, rt, 2);
|
||||
if (a < 1) a = 1;
|
||||
TinyBlocks_JsonValue* arr = (b >= a) ? list_copy(src, (uint32_t)(a - 1), (uint32_t)(b > UINT32_MAX ? UINT32_MAX : b))
|
||||
: tb_json_array();
|
||||
tb_json_release(src);
|
||||
out_list(self, arr);
|
||||
}
|
||||
|
||||
static void eval_reverse(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_JsonValue* src = in_list(self, rt, 0);
|
||||
uint32_t n = src ? tb_json_array_length(src) : 0;
|
||||
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||
for (uint32_t i = n; arr && i > 0; i--) push_owned(arr, tb_json_array_get(src, i - 1));
|
||||
tb_json_release(src);
|
||||
out_list(self, arr);
|
||||
}
|
||||
|
||||
/* Ordem: numeros (pelo valor) antes de textos (sem diferenciar maiusculas) */
|
||||
static int cmp_items(const void* pa, const void* pb) {
|
||||
const TinyBlocks_JsonValue* a = *(TinyBlocks_JsonValue* const*)pa;
|
||||
const TinyBlocks_JsonValue* b = *(TinyBlocks_JsonValue* const*)pb;
|
||||
double x, y;
|
||||
bool na = item_number(a, &x), nb = item_number(b, &y);
|
||||
if (na && nb) return x < y ? -1 : x > y ? 1 : 0;
|
||||
if (na != nb) return na ? -1 : 1;
|
||||
char sa[512], sb[512];
|
||||
item_text(a, sa, sizeof(sa));
|
||||
item_text(b, sb, sizeof(sb));
|
||||
return strcasecmp(sa, sb);
|
||||
}
|
||||
|
||||
static void eval_sort(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_JsonValue* src = in_list(self, rt, 0);
|
||||
uint32_t n = src ? tb_json_array_length(src) : 0;
|
||||
TinyBlocks_JsonValue** items = n ? malloc(n * sizeof(*items)) : NULL;
|
||||
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||
if (items) {
|
||||
for (uint32_t i = 0; i < n; i++) items[i] = tb_json_array_get(src, i);
|
||||
qsort(items, n, sizeof(*items), cmp_items);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
if (arr) push_owned(arr, items[i]);
|
||||
else if (items[i]) tb_json_release(items[i]);
|
||||
}
|
||||
free(items);
|
||||
}
|
||||
tb_json_release(src);
|
||||
out_list(self, arr);
|
||||
}
|
||||
|
||||
static void eval_join(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_JsonValue* src = in_list(self, rt, 0);
|
||||
TinyBlocks_Value sv = tb_block_get_input(self, rt, 1);
|
||||
const char* sep = (sv.kind == TB_VALUE_TEXT && sv.as.text) ? sv.as.text : "";
|
||||
uint32_t n = src ? tb_json_array_length(src) : 0;
|
||||
size_t cap = 256, len = 0, sl = strlen(sep);
|
||||
char* out = malloc(cap);
|
||||
if (out) out[0] = 0;
|
||||
for (uint32_t i = 0; out && i < n; i++) {
|
||||
char t[512];
|
||||
TinyBlocks_JsonValue* it = tb_json_array_get(src, i);
|
||||
item_text(it, t, sizeof(t));
|
||||
if (it) tb_json_release(it);
|
||||
size_t tl = strlen(t), need = len + (i ? sl : 0) + tl + 1;
|
||||
if (need > cap) {
|
||||
while (cap < need) cap *= 2;
|
||||
char* no = realloc(out, cap);
|
||||
if (!no) break;
|
||||
out = no;
|
||||
}
|
||||
if (i) { memcpy(out + len, sep, sl); len += sl; }
|
||||
memcpy(out + len, t, tl + 1);
|
||||
len += tl;
|
||||
}
|
||||
tb_block_set_output(self, 0, tb_value_text(out ? out : ""));
|
||||
free(out);
|
||||
tb_json_release(src);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_sum(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_JsonValue* src = in_list(self, rt, 0);
|
||||
uint32_t n = src ? tb_json_array_length(src) : 0;
|
||||
double s = 0;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
TinyBlocks_JsonValue* it = tb_json_array_get(src, i);
|
||||
double d;
|
||||
if (item_number(it, &d)) s += d;
|
||||
if (it) tb_json_release(it);
|
||||
}
|
||||
tb_json_release(src);
|
||||
if (s == floor(s) && fabs(s) < 1e15) tb_block_set_output(self, 0, tb_value_integer((int64_t)s));
|
||||
else tb_block_set_output(self, 0, tb_value_real(s));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* -- Registro ------------------------------------------------------------- */
|
||||
|
||||
static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name,
|
||||
const TinyBlocks_SlotDesc* in, uint32_t ni,
|
||||
const TinyBlocks_SlotDesc* out, uint32_t no,
|
||||
void (*fn)(TinyBlocks_Block*, TinyBlocks*)) {
|
||||
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn);
|
||||
return t && tb_library_add(lib, &t->base);
|
||||
}
|
||||
|
||||
static bool vector_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
static const TinyBlocks_Category cat = {
|
||||
"Listas",
|
||||
{255/255.f, 102/255.f, 26/255.f, 1.f},
|
||||
{230/255.f, 77/255.f, 0/255.f, 1.f},
|
||||
};
|
||||
tb_library_set_category(lib, &cat);
|
||||
|
||||
TB_BLOCK_META("List.Empty", "eval_empty", "Uma lista sem itens");
|
||||
TB_BLOCK_META("List.Of", "eval_of", "Lista com ate 3 itens (campos vazios ficam de fora)");
|
||||
TB_BLOCK_META("List.Range", "eval_range", "Lista com os numeros de A ate B");
|
||||
TB_BLOCK_META("List.Add", "eval_add", "Nova lista com o item no fim");
|
||||
TB_BLOCK_META("List.Insert", "eval_insert", "Nova lista com o item na posicao N");
|
||||
TB_BLOCK_META("List.Remove", "eval_remove", "Nova lista sem o item N");
|
||||
TB_BLOCK_META("List.Replace", "eval_replace", "Nova lista com o item N trocado");
|
||||
TB_BLOCK_META("List.Item", "eval_item", "O item N da lista (1 = primeiro)");
|
||||
TB_BLOCK_META("List.Length", "eval_length", "Quantos itens a lista tem");
|
||||
TB_BLOCK_META("List.IndexOf", "eval_index_of", "Posicao do item na lista (0 = nao tem)");
|
||||
TB_BLOCK_META("List.Contains", "eval_contains", "Verdadeiro se a lista tiver o item");
|
||||
TB_BLOCK_META("List.Slice", "eval_slice", "Pedaco da lista do item A ao item B");
|
||||
TB_BLOCK_META("List.Reverse", "eval_reverse", "Lista de tras para frente");
|
||||
TB_BLOCK_META("List.Sort", "eval_sort", "Lista em ordem (numeros, depois textos)");
|
||||
TB_BLOCK_META("List.Join", "eval_join", "Texto com os itens separados pelo separador");
|
||||
TB_BLOCK_META("List.Sum", "eval_sum", "Soma dos itens numericos");
|
||||
|
||||
/* listas e itens chegam como "qualquer" (TB_VALUE_NONE): o campo
|
||||
digitado vira numero ou texto, e o texto pode ser "[1,2]" ou "a, b" */
|
||||
static const TinyBlocks_SlotDesc l1[] = {{"lista", TB_VALUE_NONE}};
|
||||
static const TinyBlocks_SlotDesc li[] = {{"lista", TB_VALUE_NONE}, {"item", TB_VALUE_NONE}};
|
||||
static const TinyBlocks_SlotDesc ln[] = {{"lista", TB_VALUE_NONE}, {"n", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc lin[] = {{"lista", TB_VALUE_NONE}, {"item", TB_VALUE_NONE}, {"n", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc lni[] = {{"lista", TB_VALUE_NONE}, {"n", TB_VALUE_INTEGER}, {"item", TB_VALUE_NONE}};
|
||||
static const TinyBlocks_SlotDesc lab[] = {{"lista", TB_VALUE_NONE}, {"de", TB_VALUE_INTEGER}, {"ate", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc lsep[] = {{"lista", TB_VALUE_NONE}, {"separador", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc of_in[] = {{"a", TB_VALUE_NONE}, {"b", TB_VALUE_NONE}, {"c", TB_VALUE_NONE}};
|
||||
static const TinyBlocks_SlotDesc rng[] = {{"de", TB_VALUE_INTEGER}, {"ate", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc list_out[] = {{"lista", TB_VALUE_JSON}};
|
||||
static const TinyBlocks_SlotDesc item_out[] = {{"item", TB_VALUE_NONE}};
|
||||
static const TinyBlocks_SlotDesc int_out[] = {{"numero", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc num_out[] = {{"numero", TB_VALUE_NONE}};
|
||||
static const TinyBlocks_SlotDesc text_out[] = {{"texto", TB_VALUE_TEXT}};
|
||||
/* saida terminada em '?' = bloco booleano (hexagonal no editor) */
|
||||
static const TinyBlocks_SlotDesc has_out[] = {{"contém?", TB_VALUE_INTEGER}};
|
||||
|
||||
return reg(rt, lib, "List.Empty", NULL, 0, list_out, 1, eval_empty)
|
||||
&& reg(rt, lib, "List.Of", of_in, 3, list_out, 1, eval_of)
|
||||
&& reg(rt, lib, "List.Range", rng, 2, list_out, 1, eval_range)
|
||||
&& reg(rt, lib, "List.Add", li, 2, list_out, 1, eval_add)
|
||||
&& reg(rt, lib, "List.Insert", lin, 3, list_out, 1, eval_insert)
|
||||
&& reg(rt, lib, "List.Remove", ln, 2, list_out, 1, eval_remove)
|
||||
&& reg(rt, lib, "List.Replace", lni, 3, list_out, 1, eval_replace)
|
||||
&& reg(rt, lib, "List.Item", ln, 2, item_out, 1, eval_item)
|
||||
&& reg(rt, lib, "List.Length", l1, 1, int_out, 1, eval_length)
|
||||
&& reg(rt, lib, "List.IndexOf", li, 2, int_out, 1, eval_index_of)
|
||||
&& reg(rt, lib, "List.Contains", li, 2, has_out, 1, eval_contains)
|
||||
&& reg(rt, lib, "List.Slice", lab, 3, list_out, 1, eval_slice)
|
||||
&& reg(rt, lib, "List.Reverse", l1, 1, list_out, 1, eval_reverse)
|
||||
&& reg(rt, lib, "List.Sort", l1, 1, list_out, 1, eval_sort)
|
||||
&& reg(rt, lib, "List.Join", lsep, 2, text_out, 1, eval_join)
|
||||
&& reg(rt, lib, "List.Sum", l1, 1, num_out, 1, eval_sum);
|
||||
}
|
||||
|
||||
static void vector_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
(void)rt; (void)lib;
|
||||
}
|
||||
|
||||
TINYBLOCKS_DEFINE_LIBRARY(vector,
|
||||
"tinyblocks-vector",
|
||||
"1.0.0",
|
||||
vector_init,
|
||||
vector_deinit)
|
||||
|
||||
const TinyBlocks_LibraryDescriptor* tb_vector_get_library(void) {
|
||||
return &_tb_lib_desc_vector;
|
||||
}
|
||||
Reference in new issue
Block a user