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:
mguinhosandClaude Opus 5.5 committed 2026-10-22 13:10:09 -03:00
1 parent f0abc7593a
commit 33705b2903
25 files changed
+2262 -9

No files matched your search

+236
View File
@@ -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;
}