Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e329b2c616 | ||
|
|
f02733761b | ||
|
|
478be8d74a | ||
|
|
46834e5234 | ||
|
|
0f19f70821 | ||
|
|
231b8d6da7 | ||
|
|
c218841c75 | ||
|
|
e6bb5e7372 | ||
|
|
75d694ddb2 | ||
|
|
8a0a09bc03 | ||
|
|
415cb18fdd | ||
|
|
7e8f316eb5 | ||
|
|
f6907efcdd | ||
|
|
9106c55e1e | ||
|
|
2e7f91fa46 | ||
|
|
b26a549ade | ||
|
|
44f269945c | ||
|
|
6087348f56 | ||
|
|
f179f5c632 | ||
|
|
bc801c9c79 |
No files matched your search
@@ -5,6 +5,7 @@
|
||||
*~
|
||||
*.tmp
|
||||
.zcode
|
||||
.kryon-ide-state
|
||||
|
||||
# Build output
|
||||
build/
|
||||
|
||||
@@ -1,4 +1,14 @@
|
||||
# Changelog
|
||||
## Unreleased
|
||||
|
||||
### Added
|
||||
|
||||
- Add `defer` to the Kry language: `defer STMT` runs `STMT` at the enclosing
|
||||
block's exit (fall-through, `return`, `break`, `continue`), in reverse
|
||||
registration order across nested scopes. A compile-time transform that
|
||||
splices the statement into the generated C at every exit point — no runtime
|
||||
cost. `goto` out of a deferred scope is left to explicit cleanup.
|
||||
|
||||
## v0.1.7 - 2026-07-26
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -23,14 +23,35 @@ ICON_ASSETS_C = src/ui/ui_icon_assets.c
|
||||
EMBED_ASSETS ?= themes fonts/noto
|
||||
EMBED_ASSET_FILES = $(shell find $(EMBED_ASSETS) -type f 2>/dev/null)
|
||||
EMBED_ASSETS_C = $(BUILD_DIR)/embedded_asset_data.c
|
||||
FONT_SUBSET_OUT_DIR ?= $(BUILD_DIR)/fonts/subset
|
||||
FONT_SUBSET_SOURCE_DIR ?= $(KRYON_DIR)/fonts/noto
|
||||
FONT_SUBSET_PREFIX ?= App
|
||||
FONT_SUBSET_CORPUS ?=
|
||||
KRYON_COMPAT_GENERATOR = tools/generate-kryon-compat.sh
|
||||
KRYON_BOUNDARY_CHECK = tools/check-kryon-boundaries.sh
|
||||
KRYON_COMPAT_SYMBOL_CHECK = tools/check-raylib-compat-symbols.sh
|
||||
KRYON_COMPAT_HEADER = include/kryon_compat.generated.h
|
||||
KRYON_BACKEND_RENAME_HEADER = $(BUILD_DIR)/generated/raylib_backend_rename.h
|
||||
KRYON_RAYLIB_WRAPPERS_C = $(BUILD_DIR)/generated/kryon_raylib_wrappers.c
|
||||
KRYON_NULL_BACKEND_C = $(BUILD_DIR)/generated/kryon_null_backend.c
|
||||
KRYON_RAYLIB_GENERATED_PUBLIC_HEADER ?= $(KRYON_COMPAT_HEADER)
|
||||
KRYON_RAYLIB_BACKEND_RENAME_HEADER ?= $(KRYON_BACKEND_RENAME_HEADER)
|
||||
|
||||
# Graphics/input backend. The kryon surface (kryon_compat.generated.h) is
|
||||
# backend-neutral; the concrete implementation is selected at link time here.
|
||||
# raylib -> generated raylib forwarders + libraylib.a (default, unchanged)
|
||||
# canvas -> src/backend/canvas_backend.c (HTML5 Canvas2D; no raylib)
|
||||
# null -> generated zero-return stubs (no-ops; for headless tests)
|
||||
KRYON_BACKEND ?= raylib
|
||||
ifeq ($(KRYON_BACKEND),raylib)
|
||||
KRYON_BACKEND_SRCS = $(KRYON_RAYLIB_WRAPPERS_C)
|
||||
else ifeq ($(KRYON_BACKEND),canvas)
|
||||
KRYON_BACKEND_SRCS = src/backend/canvas_backend.c
|
||||
else ifeq ($(KRYON_BACKEND),null)
|
||||
KRYON_BACKEND_SRCS = $(KRYON_NULL_BACKEND_C)
|
||||
else
|
||||
$(error Unknown KRYON_BACKEND '$(KRYON_BACKEND)' (expected raylib, canvas, or null))
|
||||
endif
|
||||
UNAME_S := $(shell uname -s 2>/dev/null)
|
||||
UNAME_M := $(shell uname -m 2>/dev/null)
|
||||
ifeq ($(UNAME_M),amd64)
|
||||
@@ -87,7 +108,7 @@ CPPFLAGS += -DHAS_LIBOQS=1 $(KRYON_LIBOQS_INCLUDE) \
|
||||
|
||||
SRCS := $(shell find src -type f -name '*.c' | LC_ALL=C sort)
|
||||
|
||||
SRCS += $(EMBED_ASSETS_C) $(KRYON_RAYLIB_WRAPPERS_C)
|
||||
SRCS += $(EMBED_ASSETS_C) $(KRYON_BACKEND_SRCS)
|
||||
|
||||
SYSTEM_THEME_PKG := $(shell if pkg-config --exists gtk+-3.0 2>/dev/null; then printf '%s' gtk+-3.0; fi)
|
||||
ifneq ($(strip $(SYSTEM_THEME_PKG)),)
|
||||
@@ -98,8 +119,8 @@ endif
|
||||
OBJS = $(patsubst src/%.c,$(BUILD_DIR)/%.o,$(filter src/%,$(SRCS))) \
|
||||
$(patsubst $(BUILD_DIR)/%.c,$(BUILD_DIR)/%.o,$(filter $(BUILD_DIR)/%,$(SRCS)))
|
||||
LIB = libkryon.a
|
||||
LYRA_ACCOUNT_TEST = $(BUILD_DIR)/tests/lyra_account_test
|
||||
LYRA_SYNC_TEST = $(BUILD_DIR)/tests/lyra_sync_test
|
||||
KSYNC_ACCOUNT_TEST = $(BUILD_DIR)/tests/ksync_account_test
|
||||
KSYNC_SYNC_TEST = $(BUILD_DIR)/tests/ksync_sync_test
|
||||
TRANSITION_TEST = $(BUILD_DIR)/tests/transition_test
|
||||
FILE_DIALOG_BACKEND_TEST = $(BUILD_DIR)/tests/file_dialog_backend_test
|
||||
MARKDOWN_TEST = $(BUILD_DIR)/tests/markdown_test
|
||||
@@ -109,7 +130,7 @@ PREVIEW_TEST = $(BUILD_DIR)/tests/preview_test
|
||||
PLATFORM_THREAD_TEST = $(BUILD_DIR)/tests/platform_thread_test
|
||||
RAYLIB_COMPAT_LDLIBS ?= $(RAY_LDLIBS) -lpthread -lm $(if $(filter linux,$(KRYON_PLATFORM)),-ldl -lrt,)
|
||||
|
||||
.PHONY: all clean run tools examples-run font-assets docs-site test bsd-check kryon-compat kryon-compat-check kryon-boundary-check version release-check dist-static check-static-package install install-static
|
||||
.PHONY: all clean run tools examples-run font-assets font-subsets docs-site test bsd-check kryon-compat kryon-compat-check kryon-boundary-check version release-check dist-static check-static-package install install-static
|
||||
|
||||
all: $(LIB) $(KC) $(KI) $(KRYON_APP)
|
||||
|
||||
@@ -151,10 +172,10 @@ docs-site:
|
||||
sh scripts/render-api-html.sh docs/API.md $(SITE_DIR)/api-template.html $(SITE_BUILD_DIR)/api.html
|
||||
rm -f $(SITE_BUILD_DIR)/api-template.html
|
||||
|
||||
test: kryon-compat-check kryon-boundary-check $(KC) $(LYRA_ACCOUNT_TEST) $(LYRA_SYNC_TEST) $(TRANSITION_TEST) $(FILE_DIALOG_BACKEND_TEST) $(MARKDOWN_TEST) $(RAYLIB_COMPAT_TEST) $(UI_TK_TEST) $(PREVIEW_TEST) $(PLATFORM_THREAD_TEST)
|
||||
test: kryon-compat-check kryon-boundary-check $(KC) $(KSYNC_ACCOUNT_TEST) $(KSYNC_SYNC_TEST) $(TRANSITION_TEST) $(FILE_DIALOG_BACKEND_TEST) $(MARKDOWN_TEST) $(RAYLIB_COMPAT_TEST) $(UI_TK_TEST) $(PREVIEW_TEST) $(PLATFORM_THREAD_TEST)
|
||||
sh tests/kc_syntax_test.sh $(KC)
|
||||
$(LYRA_ACCOUNT_TEST)
|
||||
$(LYRA_SYNC_TEST)
|
||||
$(KSYNC_ACCOUNT_TEST)
|
||||
$(KSYNC_SYNC_TEST)
|
||||
$(TRANSITION_TEST)
|
||||
$(FILE_DIALOG_BACKEND_TEST)
|
||||
$(MARKDOWN_TEST)
|
||||
@@ -186,22 +207,34 @@ kryon-boundary-check:
|
||||
$(LIB): $(OBJS) | $(KRYON_COMPAT_HEADER) $(KRYON_LIBOQS_A) $(KRYON_CURL_PROTOCOL_CHECK) $(KRYON_MARKDOWN_DEPS)
|
||||
$(AR) $(ARFLAGS) $@ $(OBJS)
|
||||
|
||||
KC_SRCS := cmd/kc/kc.c cmd/kc/kc_macros.c
|
||||
KC_SRCS := $(sort $(wildcard cmd/kc/*.c))
|
||||
KC_HDRS := cmd/kc/kc_internal.h cmd/kc/kc_ast.h
|
||||
|
||||
$(KC): $(KC_SRCS) cmd/kc/kc_internal.h | $(BUILD_DIR)/bin
|
||||
$(KC): $(KC_SRCS) $(KC_HDRS) | $(BUILD_DIR)/bin
|
||||
$(CC) $(CFLAGS) -o $@ $(KC_SRCS)
|
||||
|
||||
$(KRYON_APP): scripts/kryon-app.sh | $(BUILD_DIR)/bin
|
||||
cp scripts/kryon-app.sh $@
|
||||
chmod 755 $@
|
||||
|
||||
$(KI): cmd/ki/main.c $(LIB) $(RAYLIB_A) $(KRYON_LIBOQS_A) $(KRYON_CURL_A) $(KRYON_MARKDOWN_DEPS) | $(BUILD_DIR)/bin
|
||||
$(CC) $(CFLAGS) $(CPPFLAGS) -Isrc/ui $(RAY_CFLAGS) -o $@ \
|
||||
# Per-backend link inputs. raylib links libraylib.a + SDL/GL; canvas/null do not.
|
||||
ifeq ($(KRYON_BACKEND),raylib)
|
||||
KRYON_BACKEND_LINK_PREREQ = $(RAYLIB_A)
|
||||
KRYON_BACKEND_LINK_CFLAGS = $(RAY_CFLAGS)
|
||||
KRYON_BACKEND_LINK_LIBS = $(RAYLIB_A) $(RAY_LDLIBS)
|
||||
else
|
||||
KRYON_BACKEND_LINK_PREREQ =
|
||||
KRYON_BACKEND_LINK_CFLAGS =
|
||||
KRYON_BACKEND_LINK_LIBS =
|
||||
endif
|
||||
|
||||
$(KI): cmd/ki/main.c $(LIB) $(KRYON_BACKEND_LINK_PREREQ) $(KRYON_LIBOQS_A) $(KRYON_CURL_A) $(KRYON_MARKDOWN_DEPS) | $(BUILD_DIR)/bin
|
||||
$(CC) $(CFLAGS) $(CPPFLAGS) -Isrc/ui $(KRYON_BACKEND_LINK_CFLAGS) -o $@ \
|
||||
cmd/ki/main.c \
|
||||
-Wl,--whole-archive $(LIB) -Wl,--no-whole-archive \
|
||||
$(RAYLIB_A) $(KRYON_LIBOQS_A) $(KRYON_CURL_LDLIBS) \
|
||||
$(KRYON_BACKEND_LINK_LIBS) $(KRYON_LIBOQS_A) $(KRYON_CURL_LDLIBS) \
|
||||
$(KRYON_MARKDOWN_LDLIBS) \
|
||||
-Wl,-export-dynamic $(RAY_LDLIBS) $(LDLIBS) \
|
||||
-Wl,-export-dynamic $(LDLIBS) \
|
||||
$(CURL_CODEC_LDLIBS) -lz -lpthread -lm
|
||||
|
||||
version:
|
||||
@@ -267,16 +300,16 @@ $(STATIC_DIST_ARCHIVE): $(LIB) $(RAYLIB_A) $(KRYON_LIBOQS_A) $(KRYON_CURL_A) $(K
|
||||
> $(STATIC_DIST_ROOT)/lib/cmake/kryon/KryonConfig.cmake
|
||||
tar -C $(BUILD_DIR)/dist -czf $@ kryon-$(VERSION)-static
|
||||
|
||||
$(LYRA_ACCOUNT_TEST): tests/lyra_account_test.c src/lyra/lyra_account.c include/lyra_account.h $(KRYON_LIBOQS_A) | $(BUILD_DIR)
|
||||
$(KSYNC_ACCOUNT_TEST): tests/ksync_account_test.c src/ksync/ksync_account.c include/ksync_account.h $(KRYON_LIBOQS_A) | $(BUILD_DIR)
|
||||
@mkdir -p $(dir $@)
|
||||
$(CC) $(CPPFLAGS) $(CFLAGS) -DHAS_LIBOQS=1 $(KRYON_LIBOQS_INCLUDE) \
|
||||
tests/lyra_account_test.c src/lyra/lyra_account.c \
|
||||
tests/ksync_account_test.c src/ksync/ksync_account.c \
|
||||
$(KRYON_LIBOQS_A) -lm -o $@
|
||||
|
||||
$(LYRA_SYNC_TEST): tests/lyra_sync_test.c src/lyra/lyra_sync.c src/lyra/lyra_account.c include/lyra_sync.h include/lyra_account.h $(KRYON_LIBOQS_A) | $(BUILD_DIR)
|
||||
$(KSYNC_SYNC_TEST): tests/ksync_sync_test.c src/ksync/ksync_sync.c src/ksync/ksync_account.c include/ksync_sync.h include/ksync_account.h $(KRYON_LIBOQS_A) | $(BUILD_DIR)
|
||||
@mkdir -p $(dir $@)
|
||||
$(CC) $(CPPFLAGS) $(CFLAGS) -DHAS_LIBOQS=1 $(KRYON_LIBOQS_INCLUDE) \
|
||||
tests/lyra_sync_test.c src/lyra/lyra_sync.c src/lyra/lyra_account.c \
|
||||
tests/ksync_sync_test.c src/ksync/ksync_sync.c src/ksync/ksync_account.c \
|
||||
$(KRYON_LIBOQS_A) -lm -o $@
|
||||
|
||||
$(TRANSITION_TEST): tests/transition_test.c src/ui/ui_transition.c include/ui_transition.h | $(BUILD_DIR)
|
||||
@@ -341,3 +374,10 @@ $(BUILD_DIR)/bin:
|
||||
|
||||
font-assets:
|
||||
@printf '%s\n' 'font assets are checked in or supplied by downstream apps'
|
||||
|
||||
font-subsets:
|
||||
@if [ -z "$(strip $(FONT_SUBSET_CORPUS))" ]; then \
|
||||
echo "Set FONT_SUBSET_CORPUS to one or more files/directories"; \
|
||||
exit 1; \
|
||||
fi
|
||||
sh scripts/subset-fonts.sh "$(FONT_SUBSET_OUT_DIR)" "$(FONT_SUBSET_SOURCE_DIR)" "$(FONT_SUBSET_PREFIX)" $(FONT_SUBSET_CORPUS)
|
||||
@@ -4,7 +4,7 @@ Kryon is a small C support library for raylib-style applications. It keeps a
|
||||
raylib-compatible public surface available through `kryon.h`, then adds the
|
||||
pieces shared by downstream apps: UI controls, Tk-style toolkit widgets, layout
|
||||
helpers, text rendering, themes, embedded assets, locale loading, file dialogs,
|
||||
desktop tray support, runtime asset downloads, and Lyra account/sync helpers.
|
||||
desktop tray support, runtime asset downloads, and Ksync account/sync helpers.
|
||||
|
||||
## Layout
|
||||
|
||||
@@ -102,6 +102,16 @@ kryon-app package appimage
|
||||
kryon-app preview
|
||||
```
|
||||
|
||||
For local development against a sync backend, run a Ksync server in the
|
||||
foreground. `dev-backend` locates the server source at `$KSYNC_DIR` or as a
|
||||
sibling checkout (`../ksync`), isolates its data under `<project>/.kryon/`, and
|
||||
prints the sync URL to point your app at. Tokens are regenerated each start,
|
||||
so it is for local development only:
|
||||
|
||||
```sh
|
||||
kryon-app dev-backend # serves http://127.0.0.1:8080
|
||||
```
|
||||
|
||||
App `project.kryon` files should use `target` entries that call `kryon-app`
|
||||
rather than embedding platform-specific build commands directly. Existing app
|
||||
Makefiles can remain as backend glue while repeated native, web, Android, and
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
failed to run embedded grep: spawn grep ENOENT
|
||||
+395
-4
@@ -8,6 +8,7 @@
|
||||
#include <sys/types.h>
|
||||
|
||||
#include "kc_internal.h"
|
||||
#include "kc_ast.h"
|
||||
|
||||
static void die(const char *fmt, ...);
|
||||
static char *trim(char *s);
|
||||
@@ -252,6 +253,43 @@ die(const char *fmt, ...)
|
||||
exit(1);
|
||||
}
|
||||
|
||||
void
|
||||
kc_error(KryFile *file, int line_no, const char *fmt, ...)
|
||||
{
|
||||
va_list args;
|
||||
KryDiagnostic *diag;
|
||||
|
||||
if(file == NULL || file->diagnostic_count >= KC_DIAGNOSTIC_MAX) {
|
||||
char msg[2048];
|
||||
va_start(args, fmt);
|
||||
vsnprintf(msg, sizeof(msg), fmt, args);
|
||||
va_end(args);
|
||||
die("%s", msg);
|
||||
}
|
||||
diag = &file->diagnostics[file->diagnostic_count++];
|
||||
snprintf(diag->path, sizeof(diag->path), "%s", file->path);
|
||||
diag->line = line_no > 0 ? line_no : 1;
|
||||
diag->column = 1;
|
||||
va_start(args, fmt);
|
||||
vsnprintf(diag->message, sizeof(diag->message), fmt, args);
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
int
|
||||
kc_flush_diagnostics(const KryFile *file)
|
||||
{
|
||||
int i;
|
||||
|
||||
if(file == NULL)
|
||||
return 0;
|
||||
for(i = 0; i < file->diagnostic_count; i++) {
|
||||
const KryDiagnostic *d = &file->diagnostics[i];
|
||||
fprintf(stderr, "%s:%d:%d: error: %s\n", d->path, d->line, d->column,
|
||||
d->message);
|
||||
}
|
||||
return file->diagnostic_count;
|
||||
}
|
||||
|
||||
static char *
|
||||
trim(char *s)
|
||||
{
|
||||
@@ -2729,6 +2767,12 @@ parse_statement(KryFile *file, int line_no, char *line)
|
||||
die("%s:%d: expected guard condition", file->path, line_no);
|
||||
add_body(file, " if(%s)", q);
|
||||
add_body(file, " return;");
|
||||
} else if(starts_word(line, "defer")) {
|
||||
char *q = trim(line + strlen("defer"));
|
||||
|
||||
if(q[0] == '\0')
|
||||
die("%s:%d: expected defer statement", file->path, line_no);
|
||||
add_body(file, " defer %s", q);
|
||||
} else if(starts_word(line, "return")) {
|
||||
char *q = trim(line + strlen("return"));
|
||||
|
||||
@@ -2830,7 +2874,22 @@ parse_statement(KryFile *file, int line_no, char *line)
|
||||
q = trim(q);
|
||||
if(q[0] == '\0')
|
||||
die("%s:%d: expected if condition", file->path, line_no);
|
||||
add_body(file, " if(%s) {", q);
|
||||
/* If the condition is a function call (e.g. `WidgetButton(...)`),
|
||||
* wrap it so the call registers its source location for click-to-
|
||||
* source inspection. Evaluating into a temp and popping before the
|
||||
* branch keeps the Push/Pop balanced regardless of else/return. */
|
||||
{
|
||||
size_t cn = strlen(q);
|
||||
if(strchr(q, '(') != NULL && cn > 0 && q[cn - 1] == ')') {
|
||||
emit_source_push(file, line_no);
|
||||
add_body(file, " __auto_type __kryon_cond_%d = %s;",
|
||||
line_no, q);
|
||||
emit_source_pop(file);
|
||||
add_body(file, " if(__kryon_cond_%d) {", line_no);
|
||||
} else {
|
||||
add_body(file, " if(%s) {", q);
|
||||
}
|
||||
}
|
||||
} else if(starts_word(line, "switch")) {
|
||||
char *q = trim(line + strlen("switch"));
|
||||
size_t n = strlen(q);
|
||||
@@ -4172,6 +4231,317 @@ rewrite_kry_expr(char *dst, size_t dst_size, const KryFile *file,
|
||||
dst[n] = '\0';
|
||||
}
|
||||
|
||||
/*
|
||||
* defer handling.
|
||||
*
|
||||
* `defer STMT` registers STMT to run when its enclosing block exits — by
|
||||
* falling off the end (the closing `}`), or via return/break/continue inside
|
||||
* the block. Multiple defers in one block run in reverse (LIFO) order. goto
|
||||
* is intentionally left alone: a goto out of a deferred scope will skip it.
|
||||
*
|
||||
* Body lines are stored as pre-translated C fragments. This pass walks them,
|
||||
* tracks the scope stack (matching write_body_line's brace accounting), and
|
||||
* rebuilds the body[] array with the deferred statements spliced in at every
|
||||
* exit point and removed from their declaration site.
|
||||
*/
|
||||
|
||||
/* A pending defer: the scope index (into the scope stack) that owns it and the
|
||||
* statement text (a Kry fragment, retranslated at output like other lines).
|
||||
* `spent` marks a defer already emitted by an early exit (break/continue/
|
||||
* return) so a later scope boundary doesn't re-emit it. */
|
||||
typedef struct KryDefer {
|
||||
int scope_index;
|
||||
int spent;
|
||||
char stmt[KC_BODY_LINE_MAX];
|
||||
} KryDefer;
|
||||
|
||||
/* Scope kinds, to decide what break/continue unwind. */
|
||||
enum {
|
||||
KRY_SCOPE_BLOCK, /* plain { } or function body */
|
||||
KRY_SCOPE_BRANCH, /* if / else if / else / switch */
|
||||
KRY_SCOPE_LOOP, /* for / while — break/continue unwind to here */
|
||||
KRY_SCOPE_CASE /* a switch case body (implicit scope) */
|
||||
};
|
||||
|
||||
/* Classify a body line into a scope kind for the scope it OPENS, or -1 if it
|
||||
* does not open a scope. Looks at the leading keyword of the line. */
|
||||
static int
|
||||
scope_kind_for_open(const char *text)
|
||||
{
|
||||
if(strncmp(text, "for", 3) == 0 &&
|
||||
(text[3] == '(' || text[3] == ' ' || text[3] == '\t'))
|
||||
return KRY_SCOPE_LOOP;
|
||||
if(strncmp(text, "while", 5) == 0 &&
|
||||
(text[5] == '(' || text[5] == ' ' || text[5] == '\t'))
|
||||
return KRY_SCOPE_LOOP;
|
||||
if(strncmp(text, "if", 2) == 0 &&
|
||||
(text[2] == '(' || text[2] == ' '))
|
||||
return KRY_SCOPE_BRANCH;
|
||||
if(strncmp(text, "else", 4) == 0 &&
|
||||
(text[4] == ' ' || text[4] == '{' || text[4] == '\0'))
|
||||
return KRY_SCOPE_BRANCH;
|
||||
if(strncmp(text, "switch", 6) == 0 &&
|
||||
(text[6] == '(' || text[6] == ' '))
|
||||
return KRY_SCOPE_BRANCH;
|
||||
if(strncmp(text, "case", 4) == 0 &&
|
||||
(text[4] == ' ' || text[4] == '\t'))
|
||||
return KRY_SCOPE_BRANCH;
|
||||
if(strcmp(text, "default:") == 0)
|
||||
return KRY_SCOPE_BRANCH;
|
||||
return KRY_SCOPE_BLOCK; /* anonymous `{` block or anything else */
|
||||
}
|
||||
|
||||
static void
|
||||
apply_defers(KryFunction *fn)
|
||||
{
|
||||
if(fn == NULL || fn->body_count == 0)
|
||||
return;
|
||||
|
||||
/* Quick check: any defer at all? Avoids allocation work otherwise. */
|
||||
int has_defer = 0;
|
||||
for(int i = 0; i < fn->body_count; i++) {
|
||||
const char *t = skip_indent(fn->body[i]);
|
||||
if(strncmp(t, "defer ", 6) == 0 || strcmp(t, "defer") == 0) {
|
||||
has_defer = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(!has_defer)
|
||||
return;
|
||||
|
||||
/* Scope stack: index 0 is the function body. */
|
||||
int scope_kind[KC_BODY_MAX];
|
||||
int scope_count = 0;
|
||||
scope_kind[scope_count++] = KRY_SCOPE_BLOCK;
|
||||
|
||||
/* Pending defers, in registration order. */
|
||||
KryDefer defers[KC_BODY_MAX];
|
||||
int defer_count = 0;
|
||||
|
||||
/* Rebuilt body. */
|
||||
static char out_body[KC_BODY_MAX][KC_BODY_LINE_MAX];
|
||||
int out_count = 0;
|
||||
|
||||
#define EMIT_BODY(text) \
|
||||
do { \
|
||||
if(out_count >= KC_BODY_MAX) goto done; \
|
||||
snprintf(out_body[out_count], sizeof(out_body[out_count]), \
|
||||
"%s", (text)); \
|
||||
out_count++; \
|
||||
} while(0)
|
||||
|
||||
/* Emit every pending defer owned by scope indices in (after, top], i.e.
|
||||
* unwind from the innermost scope down to (not including) `after`. Within
|
||||
* a scope, defers run in reverse registration order. Skips defers already
|
||||
* spent (emitted by an earlier break/continue/return). */
|
||||
#define EMIT_UNWIND(after) \
|
||||
do { \
|
||||
for(int s = scope_count - 1; s > (after); s--) { \
|
||||
for(int d = defer_count - 1; d >= 0; d--) { \
|
||||
if(defers[d].scope_index == s && !defers[d].spent) { \
|
||||
EMIT_BODY(defers[d].stmt); \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
} while(0)
|
||||
|
||||
/* Like EMIT_UNWIND, but marks the emitted defers as spent so a later
|
||||
* scope boundary (case label, close brace) doesn't re-emit them. Used by
|
||||
* early exits (break/continue/return). */
|
||||
#define EMIT_UNWIND_AND_SPEND(after) \
|
||||
do { \
|
||||
for(int s = scope_count - 1; s > (after); s--) { \
|
||||
for(int d = defer_count - 1; d >= 0; d--) { \
|
||||
if(defers[d].scope_index == s && !defers[d].spent) { \
|
||||
EMIT_BODY(defers[d].stmt); \
|
||||
defers[d].spent = 1; \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
} while(0)
|
||||
|
||||
for(int i = 0; i < fn->body_count; i++) {
|
||||
const char *raw = fn->body[i];
|
||||
const char *text = skip_indent(raw);
|
||||
|
||||
/* `defer STMT` — register and drop the line. */
|
||||
if(strncmp(text, "defer ", 6) == 0 || strcmp(text, "defer") == 0) {
|
||||
const char *stmt = text + 6;
|
||||
while(*stmt == ' ' || *stmt == '\t')
|
||||
stmt++;
|
||||
if(*stmt == '\0')
|
||||
continue; /* malformed; parse_statement already validated */
|
||||
if(defer_count < KC_BODY_MAX) {
|
||||
defers[defer_count].scope_index = scope_count - 1;
|
||||
defers[defer_count].spent = 0;
|
||||
snprintf(defers[defer_count].stmt,
|
||||
sizeof(defers[defer_count].stmt), " %s;", stmt);
|
||||
defer_count++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Closing brace: unwind THIS scope's defers, then pop the scope.
|
||||
* Lines like `} else {` / `} else if(...) {` also begin with `}` and
|
||||
* close the if-body scope before reopening. A loop body's `}` closes
|
||||
* the BLOCK scope and also the LOOP scope it sits inside, since the
|
||||
* loop header opened both with a single brace. */
|
||||
if(text[0] == '}') {
|
||||
EMIT_UNWIND(scope_count - 2);
|
||||
if(scope_count > 1)
|
||||
scope_count--;
|
||||
/* If the scope just closed was a loop body, also pop the loop. */
|
||||
if(scope_count >= 2 &&
|
||||
scope_kind[scope_count] == KRY_SCOPE_BLOCK &&
|
||||
scope_kind[scope_count - 1] == KRY_SCOPE_LOOP)
|
||||
scope_count--;
|
||||
/* If the scope just closed was a switch case, also pop the
|
||||
* switch (its `}` closes both the case and the switch). */
|
||||
if(scope_count >= 2 &&
|
||||
scope_kind[scope_count] == KRY_SCOPE_CASE &&
|
||||
scope_kind[scope_count - 1] == KRY_SCOPE_BRANCH)
|
||||
scope_count--;
|
||||
/* Drop defers that belonged to the closed scope(s). */
|
||||
{
|
||||
int kept = 0;
|
||||
for(int d = 0; d < defer_count; d++)
|
||||
if(defers[d].scope_index < scope_count)
|
||||
defers[kept++] = defers[d];
|
||||
defer_count = kept;
|
||||
}
|
||||
EMIT_BODY(raw);
|
||||
/* If the line reopens a scope (`} else {`, `} else if (...) {`),
|
||||
* push a fresh branch scope for the new block. */
|
||||
if(strchr(text, '{') != NULL && scope_count < KC_BODY_MAX)
|
||||
scope_kind[scope_count++] = KRY_SCOPE_BRANCH;
|
||||
continue;
|
||||
}
|
||||
|
||||
/* case / default: a switch case is an implicit scope boundary.
|
||||
* The previous case's defers fire here (the fall-through path) and
|
||||
* are then dropped whether or not they were spent by an earlier
|
||||
* break/return. Then a fresh case scope is pushed for the new case
|
||||
* so its defers attach to it, not the switch. */
|
||||
if(strncmp(text, "case ", 5) == 0 || strcmp(text, "default:") == 0) {
|
||||
int case_scope = -1;
|
||||
if(scope_count > 0 &&
|
||||
scope_kind[scope_count - 1] == KRY_SCOPE_CASE)
|
||||
case_scope = scope_count - 1;
|
||||
if(case_scope >= 0) {
|
||||
/* Fire this case's unspent defers (fall-through), then drop
|
||||
* all of this case's defers and pop the case scope. */
|
||||
for(int d = defer_count - 1; d >= 0; d--) {
|
||||
if(defers[d].scope_index == case_scope && !defers[d].spent)
|
||||
EMIT_BODY(defers[d].stmt);
|
||||
}
|
||||
{
|
||||
int kept = 0;
|
||||
for(int d = 0; d < defer_count; d++)
|
||||
if(defers[d].scope_index != case_scope)
|
||||
defers[kept++] = defers[d];
|
||||
defer_count = kept;
|
||||
}
|
||||
scope_count--;
|
||||
}
|
||||
EMIT_BODY(raw);
|
||||
if(scope_count < KC_BODY_MAX)
|
||||
scope_kind[scope_count++] = KRY_SCOPE_CASE;
|
||||
continue;
|
||||
}
|
||||
|
||||
/* return: unwind everything back to the function body. Returns must
|
||||
* fire all defers on every path (the function is exiting), so they
|
||||
* use the non-spending unwind — a defer can't be "used up" by one
|
||||
* return when a later return also needs it. EXCEPTION: defers in a
|
||||
* switch-case scope ARE spent, because the case boundary after the
|
||||
* return would otherwise re-emit them (a case is one-shot). */
|
||||
if(strncmp(text, "return", 6) == 0 &&
|
||||
(text[6] == ';' || text[6] == ' ' || text[6] == '\t')) {
|
||||
EMIT_UNWIND(-1);
|
||||
/* Spend case-scope defers so the following case boundary doesn't
|
||||
* re-emit them. */
|
||||
for(int s = scope_count - 1; s > 0; s--) {
|
||||
if(scope_kind[s] == KRY_SCOPE_CASE) {
|
||||
for(int d = 0; d < defer_count; d++)
|
||||
if(defers[d].scope_index == s)
|
||||
defers[d].spent = 1;
|
||||
}
|
||||
}
|
||||
EMIT_BODY(raw);
|
||||
continue;
|
||||
}
|
||||
|
||||
/* break / continue: unwind to the enclosing loop or switch case.
|
||||
* In a loop, the defer must fire every iteration (at the loop-body
|
||||
* close), so the non-spending unwind is correct. In a switch case,
|
||||
* the case boundary is a one-shot boundary, so break spends the
|
||||
* case's defers to prevent the case-label handler re-emitting them. */
|
||||
if(strcmp(text, "break;") == 0 || strcmp(text, "continue;") == 0) {
|
||||
int target = 0;
|
||||
int in_case = 0;
|
||||
for(int s = scope_count - 1; s > 0; s--) {
|
||||
if(scope_kind[s] == KRY_SCOPE_LOOP) {
|
||||
target = s;
|
||||
break;
|
||||
}
|
||||
if(scope_kind[s] == KRY_SCOPE_CASE) {
|
||||
target = s - 1;
|
||||
in_case = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(in_case)
|
||||
EMIT_UNWIND_AND_SPEND(target);
|
||||
else
|
||||
EMIT_UNWIND(target);
|
||||
EMIT_BODY(raw);
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Normal line. Emit it, then update the scope stack for any `{`. A
|
||||
* loop header (`for(...) {` / `while(...) {`) opens a LOOP scope for
|
||||
* the construct and a separate BLOCK scope for the body, so that
|
||||
* break/continue unwind only the body's defers, not the loop itself. */
|
||||
EMIT_BODY(raw);
|
||||
if(text[0] != '#' && brace_delta(text) > 0) {
|
||||
int kind = scope_kind_for_open(text);
|
||||
if(kind == KRY_SCOPE_LOOP) {
|
||||
if(scope_count < KC_BODY_MAX)
|
||||
scope_kind[scope_count++] = KRY_SCOPE_LOOP;
|
||||
if(scope_count < KC_BODY_MAX)
|
||||
scope_kind[scope_count++] = KRY_SCOPE_BLOCK;
|
||||
} else if(scope_count < KC_BODY_MAX) {
|
||||
scope_kind[scope_count++] = kind;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
done:
|
||||
/* Splice the rebuilt body back into the function. Defers registered at the
|
||||
* function-body scope (scope_index 0) are never matched by a `}` line in
|
||||
* body[] (the function's own close is synthetic), so flush them here for
|
||||
* the fall-through path. Skip this if the last emitted line already
|
||||
* returns: that path has already unwound, so a trailing emit would be
|
||||
* unreachable dead code. */
|
||||
if(out_count > 0) {
|
||||
const char *last = skip_indent(out_body[out_count - 1]);
|
||||
if(strncmp(last, "return", 6) != 0) {
|
||||
for(int d = 0; d < defer_count; d++)
|
||||
if(defers[d].scope_index < 1) /* function-body defers */
|
||||
EMIT_BODY(defers[d].stmt);
|
||||
}
|
||||
}
|
||||
|
||||
#undef EMIT_BODY
|
||||
#undef EMIT_UNWIND
|
||||
|
||||
for(int i = 0; i < out_count && i < KC_BODY_MAX; i++) {
|
||||
snprintf(fn->body[i], sizeof(fn->body[i]), "%s", out_body[i]);
|
||||
fn->body_line[i] = 0;
|
||||
}
|
||||
fn->body_count = out_count;
|
||||
}
|
||||
|
||||
static void
|
||||
write_body_line(FILE *out, const KryFile *file, const KryFunction *fn,
|
||||
const char *line, int *indent)
|
||||
@@ -4394,6 +4764,9 @@ write_generated(const KryFile *file, const char *root, const char *out_dir)
|
||||
for(int i = 0; i < file->state_count; i++)
|
||||
fprintf(out, "%s\n", file->state[i]);
|
||||
}
|
||||
/* Splice deferred statements into each function body before emission. */
|
||||
for(int i = 0; i < file->function_count; i++)
|
||||
apply_defers(&file->functions[i]);
|
||||
for(int i = 0; i < file->function_count; i++) {
|
||||
const KryFunction *fn = &file->functions[i];
|
||||
const char *args = fn->args[0] != '\0' ? fn->args : "void";
|
||||
@@ -4485,6 +4858,8 @@ main(int argc, char **argv)
|
||||
KryFile **files = NULL;
|
||||
int file_count = 0;
|
||||
int no_main = 0;
|
||||
int dump_ast = 0;
|
||||
int had_errors = 0;
|
||||
int first_file = 0;
|
||||
|
||||
for(int i = 1; i < argc; i++) {
|
||||
@@ -4498,6 +4873,10 @@ main(int argc, char **argv)
|
||||
out_dir = argv[i];
|
||||
} else if(strcmp(argv[i], "--no-main") == 0) {
|
||||
no_main = 1;
|
||||
} else if(strcmp(argv[i], "--dump-ast") == 0) {
|
||||
/* Debug: reconstruct and print the AST for each function without
|
||||
* writing files. Phase 1 of the parser migration. */
|
||||
dump_ast = 1;
|
||||
} else if(argv[i][0] == '-') {
|
||||
usage();
|
||||
return 1;
|
||||
@@ -4525,10 +4904,22 @@ main(int argc, char **argv)
|
||||
file->root = root;
|
||||
file->no_main = no_main;
|
||||
parse_kry(file);
|
||||
write_generated(file, root, out_dir);
|
||||
if(file->diagnostic_count > 0) {
|
||||
kc_flush_diagnostics(file);
|
||||
had_errors = 1;
|
||||
} else if(dump_ast) {
|
||||
for(int j = 0; j < file->function_count; j++) {
|
||||
AstFunction *af = ast_function_from_body(&file->functions[j]);
|
||||
ast_function_dump(af);
|
||||
ast_function_free(af);
|
||||
}
|
||||
} else {
|
||||
write_generated(file, root, out_dir);
|
||||
}
|
||||
files[index] = file;
|
||||
}
|
||||
write_project_header(files, file_count, root, out_dir);
|
||||
if(!had_errors)
|
||||
write_project_header(files, file_count, root, out_dir);
|
||||
for(int i = 0; i < file_count; i++) {
|
||||
KryFile *file = files[i];
|
||||
|
||||
@@ -4536,5 +4927,5 @@ main(int argc, char **argv)
|
||||
free(file);
|
||||
}
|
||||
free(files);
|
||||
return 0;
|
||||
return had_errors ? 1 : 0;
|
||||
}
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
/*
|
||||
* kc_ast.c - AST reconstruction (Phase 1 of the parser migration).
|
||||
*
|
||||
* Builds typed AstStmt nodes from a function's already-emitted body[] string
|
||||
* fragments, proving the structure is fully recoverable from the line-matcher
|
||||
* output. Scope depth is computed by replaying write_body_line's brace
|
||||
* accounting (the same logic apply_defers uses).
|
||||
*
|
||||
* Phase 2 will build nodes directly during parsing; this reconstruction pass
|
||||
* is the validation that such a migration is safe — if every body[] fragment
|
||||
* classifies into a known kind, the AST captures 100% of what kc emits.
|
||||
*/
|
||||
#include "kc_ast.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/* Skip leading whitespace (mirrors skip_indent in kc.c, kept local to avoid a
|
||||
* cross-module static dependency). */
|
||||
static const char *
|
||||
skip_ws(const char *s)
|
||||
{
|
||||
while(s != NULL && (*s == ' ' || *s == '\t'))
|
||||
s++;
|
||||
return s;
|
||||
}
|
||||
|
||||
/* Count `{` minus `}` in a line, skipping preprocessor lines (which start
|
||||
* with `#`). Mirrors brace_delta in kc.c. */
|
||||
static int
|
||||
brace_delta(const char *text)
|
||||
{
|
||||
int delta = 0;
|
||||
|
||||
if(text[0] == '#')
|
||||
return 0;
|
||||
for(const char *p = text; *p != '\0'; p++) {
|
||||
if(*p == '{')
|
||||
delta++;
|
||||
else if(*p == '}')
|
||||
delta--;
|
||||
}
|
||||
return delta;
|
||||
}
|
||||
|
||||
/* Classify a single body[] fragment into an AstStmtKind by its leading token.
|
||||
* The fragments are the exact strings parse_statement emits (e.g.
|
||||
* " return;", " if(x) {", " }", "loop_start:"). */
|
||||
static AstStmtKind
|
||||
classify_fragment(const char *raw)
|
||||
{
|
||||
const char *t = skip_ws(raw);
|
||||
|
||||
if(t[0] == '\0')
|
||||
return AST_STMT_UNKNOWN;
|
||||
|
||||
/* Closing brace closes any scope. */
|
||||
if(t[0] == '}')
|
||||
return AST_STMT_BLOCK_CLOSE;
|
||||
|
||||
/* Control-flow headers and keywords — match by leading token. */
|
||||
if(strncmp(t, "for(", 4) == 0 || strncmp(t, "for (", 5) == 0)
|
||||
return AST_STMT_FOR;
|
||||
if(strncmp(t, "while(", 6) == 0 || strncmp(t, "while (", 7) == 0)
|
||||
return AST_STMT_WHILE;
|
||||
if(strncmp(t, "switch(", 7) == 0 || strncmp(t, "switch (", 8) == 0)
|
||||
return AST_STMT_SWITCH;
|
||||
if(strncmp(t, "case ", 5) == 0 || strcmp(t, "default:") == 0)
|
||||
return AST_STMT_CASE;
|
||||
if(strncmp(t, "if(", 3) == 0 || strncmp(t, "if (", 4) == 0 ||
|
||||
strncmp(t, "else if(", 8) == 0 || strncmp(t, "else if (", 9) == 0 ||
|
||||
strncmp(t, "else {", 5) == 0 || strncmp(t, "} else", 6) == 0)
|
||||
return AST_STMT_IF;
|
||||
if(strncmp(t, "return", 6) == 0 &&
|
||||
(t[6] == ';' || t[6] == ' ' || t[6] == '\0'))
|
||||
return AST_STMT_RETURN;
|
||||
if(strcmp(t, "break;") == 0)
|
||||
return AST_STMT_BREAK;
|
||||
if(strcmp(t, "continue;") == 0)
|
||||
return AST_STMT_CONTINUE;
|
||||
if(strncmp(t, "goto ", 5) == 0)
|
||||
return AST_STMT_GOTO;
|
||||
|
||||
/* defer marker: parse_statement emits " defer <stmt>" which survives
|
||||
* in body[] only until apply_defers runs. During reconstruction we may
|
||||
* see it if dump runs pre-lowering. */
|
||||
if(strncmp(t, "defer ", 6) == 0 || strcmp(t, "defer") == 0)
|
||||
return AST_STMT_DEFER;
|
||||
|
||||
/* PushUIInspectSource markers wrap expr statements; the wrapped call is
|
||||
* the real statement. Treat the push as a side-channel marker and
|
||||
* classify the following non-push line. */
|
||||
if(strncmp(t, "PushUIInspectSource(", 20) == 0 ||
|
||||
strncmp(t, "PopUIInspectSource();", 21) == 0)
|
||||
return AST_STMT_EXPR; /* inspection scaffolding, not a user stmt */
|
||||
|
||||
/* A bare `{` opens an anonymous block scope. */
|
||||
if(strcmp(t, "{") == 0)
|
||||
return AST_STMT_BLOCK_OPEN;
|
||||
|
||||
/* Inline enum block: "enum {" or "enum { TAG, }". */
|
||||
if(strncmp(t, "enum {", 6) == 0 || strncmp(t, "enum{", 5) == 0)
|
||||
return AST_STMT_ENUM;
|
||||
|
||||
/* A line ending in ':' with no leading space and no trailing code is a
|
||||
* goto label (kc emits "label:" with no indent). */
|
||||
{
|
||||
size_t n = strlen(t);
|
||||
if(n > 1 && t[n - 1] == ':' && strchr(t, ' ') == NULL &&
|
||||
strchr(t, ';') == NULL && t[0] != '#')
|
||||
return AST_STMT_LABEL;
|
||||
}
|
||||
|
||||
/* unused: "(void)name;" — emitted as "(void)expr;". */
|
||||
if(strncmp(t, "(void)", 6) == 0)
|
||||
return AST_STMT_UNUSED;
|
||||
|
||||
/* Mutation statements: x++, x--, x += y, etc. (no `=` as declaration). */
|
||||
if(strstr(t, "++") != NULL || strstr(t, "--") != NULL ||
|
||||
strstr(t, "+=") != NULL || strstr(t, "-=") != NULL ||
|
||||
strstr(t, "*=") != NULL || strstr(t, "/=") != NULL ||
|
||||
strstr(t, "%=") != NULL || strstr(t, "&=") != NULL ||
|
||||
strstr(t, "|=") != NULL || strstr(t, "^=") != NULL ||
|
||||
strstr(t, "<<=") != NULL || strstr(t, ">>=") != NULL)
|
||||
return AST_STMT_ASSIGN;
|
||||
|
||||
/* Declarations vs assignments. kc emits:
|
||||
* __auto_type name = expr; → inferred decl
|
||||
* Type name = expr; → typed decl (Type is >=1 word)
|
||||
* Type name[N] = {...}; → typed array decl
|
||||
* name = expr; → assignment
|
||||
* name.field = expr; / name[i] = ... → assignment
|
||||
* A typed decl has a multi-token prefix (the type) before the lvalue. */
|
||||
if(strstr(t, "=") != NULL) {
|
||||
/* __auto_type ... = ... is an inferred decl. */
|
||||
if(strncmp(t, "__auto_type", 11) == 0)
|
||||
return AST_STMT_DECL;
|
||||
|
||||
/* Heuristic: a typed declaration's first token is a C type keyword or
|
||||
* a capitalized identifier (a typedef/struct name like Color,
|
||||
* Rectangle). An assignment's first token is a lowercase variable
|
||||
* name. If the first token looks like a type and there's a second
|
||||
* token (the name), classify as DECL. */
|
||||
{
|
||||
char first[128];
|
||||
const char *p = t;
|
||||
size_t fn = 0;
|
||||
|
||||
while((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') ||
|
||||
*p == '_') {
|
||||
if(fn + 1 < sizeof(first))
|
||||
first[fn++] = *p;
|
||||
p++;
|
||||
}
|
||||
first[fn] = '\0';
|
||||
/* Skip whitespace/type-qualifiers to see if there's a name after. */
|
||||
while(*p == ' ' || *p == '\t')
|
||||
p++;
|
||||
/* Known C type keywords that start a typed declaration. */
|
||||
if(fn > 0 && *p != '\0' && *p != '=' &&
|
||||
(strcmp(first, "int") == 0 || strcmp(first, "char") == 0 ||
|
||||
strcmp(first, "float") == 0 || strcmp(first, "double") == 0 ||
|
||||
strcmp(first, "void") == 0 || strcmp(first, "long") == 0 ||
|
||||
strcmp(first, "short") == 0 || strcmp(first, "unsigned") == 0 ||
|
||||
strcmp(first, "signed") == 0 || strcmp(first, "const") == 0 ||
|
||||
strcmp(first, "static") == 0 || strcmp(first, "bool") == 0 ||
|
||||
(first[0] >= 'A' && first[0] <= 'Z')))
|
||||
return AST_STMT_DECL;
|
||||
}
|
||||
return AST_STMT_ASSIGN;
|
||||
}
|
||||
|
||||
/* Bare statement ending in ';' or ')' is an expression/call. */
|
||||
return AST_STMT_EXPR;
|
||||
}
|
||||
|
||||
AstFunction *
|
||||
ast_function_from_body(const KryFunction *fn)
|
||||
{
|
||||
AstFunction *af;
|
||||
int depth;
|
||||
int i;
|
||||
|
||||
if(fn == NULL || fn->body_count <= 0)
|
||||
return NULL;
|
||||
af = calloc(1, sizeof(*af));
|
||||
if(af == NULL)
|
||||
return NULL;
|
||||
af->fn = fn;
|
||||
af->stmts = calloc((size_t)fn->body_count, sizeof(*af->stmts));
|
||||
if(af->stmts == NULL) {
|
||||
free(af);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Replay write_body_line's brace accounting to compute per-line depth. */
|
||||
depth = 1; /* function body starts at depth 1 */
|
||||
for(i = 0; i < fn->body_count; i++) {
|
||||
const char *raw = fn->body[i];
|
||||
const char *text = skip_ws(raw);
|
||||
AstStmt *s = &af->stmts[i];
|
||||
int delta;
|
||||
|
||||
/* A closing brace sits at the depth of the scope it closes. */
|
||||
if(text[0] == '}')
|
||||
depth--;
|
||||
if(depth < 1)
|
||||
depth = 1;
|
||||
s->depth = depth;
|
||||
s->text = raw;
|
||||
s->source_line = (i < fn->body_count && fn->body_line[i] != 0)
|
||||
? fn->body_line[i]
|
||||
: 0;
|
||||
s->kind = classify_fragment(raw);
|
||||
/* Advance depth for braces opened on this line. */
|
||||
delta = brace_delta(text);
|
||||
if(text[0] == '}')
|
||||
delta++; /* cancel the decrement above for net counting */
|
||||
depth += delta;
|
||||
if(depth < 1)
|
||||
depth = 1;
|
||||
}
|
||||
af->stmt_count = fn->body_count;
|
||||
return af;
|
||||
}
|
||||
|
||||
void
|
||||
ast_function_free(AstFunction *af)
|
||||
{
|
||||
if(af == NULL)
|
||||
return;
|
||||
free(af->stmts);
|
||||
free(af);
|
||||
}
|
||||
|
||||
static const char *
|
||||
kind_name(AstStmtKind k)
|
||||
{
|
||||
switch(k) {
|
||||
case AST_STMT_UNKNOWN: return "UNKNOWN";
|
||||
case AST_STMT_BLOCK_OPEN: return "BLOCK_OPEN";
|
||||
case AST_STMT_BLOCK_CLOSE: return "BLOCK_CLOSE";
|
||||
case AST_STMT_DECL: return "DECL";
|
||||
case AST_STMT_ASSIGN: return "ASSIGN";
|
||||
case AST_STMT_EXPR: return "EXPR";
|
||||
case AST_STMT_IF: return "IF";
|
||||
case AST_STMT_WHILE: return "WHILE";
|
||||
case AST_STMT_FOR: return "FOR";
|
||||
case AST_STMT_SWITCH: return "SWITCH";
|
||||
case AST_STMT_CASE: return "CASE";
|
||||
case AST_STMT_RETURN: return "RETURN";
|
||||
case AST_STMT_BREAK: return "BREAK";
|
||||
case AST_STMT_CONTINUE: return "CONTINUE";
|
||||
case AST_STMT_GOTO: return "GOTO";
|
||||
case AST_STMT_LABEL: return "LABEL";
|
||||
case AST_STMT_DEFER: return "DEFER";
|
||||
case AST_STMT_UNUSED: return "UNUSED";
|
||||
case AST_STMT_RAW: return "RAW";
|
||||
case AST_STMT_ENUM: return "ENUM";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
void
|
||||
ast_function_dump(const AstFunction *af)
|
||||
{
|
||||
int i;
|
||||
|
||||
if(af == NULL || af->fn == NULL) {
|
||||
printf("(empty ast)\n");
|
||||
return;
|
||||
}
|
||||
printf("function %s body_count=%d\n",
|
||||
af->fn->screen[0] != '\0' ? af->fn->screen : "(screen)",
|
||||
af->stmt_count);
|
||||
for(i = 0; i < af->stmt_count; i++) {
|
||||
const AstStmt *s = &af->stmts[i];
|
||||
int j;
|
||||
|
||||
for(j = 1; j < s->depth; j++)
|
||||
fputs(" ", stdout);
|
||||
printf("%-12s | %s\n", kind_name(s->kind), s->text ? s->text : "");
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
ast_function_count_kind(const AstFunction *af, AstStmtKind kind)
|
||||
{
|
||||
int n = 0;
|
||||
int i;
|
||||
|
||||
if(af == NULL)
|
||||
return 0;
|
||||
for(i = 0; i < af->stmt_count; i++)
|
||||
if(af->stmts[i].kind == kind)
|
||||
n++;
|
||||
return n;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* kc_ast.h - Abstract Syntax Tree node types for the kc compiler.
|
||||
*
|
||||
* Phase 1 of the parser migration (docs/KC_PARSER_PLAN.md): the AST is built
|
||||
* alongside the existing string-based body[] path. Today the nodes are
|
||||
* reconstructed from the already-emitted body[] fragments to prove the
|
||||
* structure is fully recoverable; Phase 2 will build them directly during
|
||||
* parsing and emit from them.
|
||||
*
|
||||
* Expressions are held as opaque C text. kc does not parse expressions today;
|
||||
* a future phase may tokenize them for real type inference.
|
||||
*/
|
||||
#ifndef KRYON_KC_AST_H
|
||||
#define KRYON_KC_AST_H
|
||||
|
||||
#include "kc_internal.h" /* KryFunction, KC_* limits */
|
||||
|
||||
/* Statement kinds, matching the parse_statement branch inventory. Every
|
||||
* non-removed statement form maps to exactly one kind. */
|
||||
typedef enum {
|
||||
AST_STMT_UNKNOWN = 0, /* unclassified (shouldn't happen post-Phase-1) */
|
||||
AST_STMT_BLOCK_OPEN, /* anonymous `{` scope open */
|
||||
AST_STMT_BLOCK_CLOSE, /* `}` close of any scope */
|
||||
AST_STMT_DECL, /* x := expr | x: Type = expr | x: Type */
|
||||
AST_STMT_ASSIGN, /* x = expr (incl. compound += %= etc.) */
|
||||
AST_STMT_EXPR, /* bare call / expression statement */
|
||||
AST_STMT_IF, /* if(...) { (also else-if, else) */
|
||||
AST_STMT_WHILE, /* while(...) { */
|
||||
AST_STMT_FOR, /* for(...) { (C-style or NAME in A..B) */
|
||||
AST_STMT_SWITCH, /* switch(...) { */
|
||||
AST_STMT_CASE, /* case X: / default: */
|
||||
AST_STMT_RETURN, /* return [expr]; */
|
||||
AST_STMT_BREAK,
|
||||
AST_STMT_CONTINUE,
|
||||
AST_STMT_GOTO, /* goto label; */
|
||||
AST_STMT_LABEL, /* label: */
|
||||
AST_STMT_DEFER, /* defer stmt (lowered later) */
|
||||
AST_STMT_UNUSED, /* unused expr; */
|
||||
AST_STMT_RAW, /* c <line> escape hatch */
|
||||
AST_STMT_ENUM, /* inline enum { ... } */
|
||||
} AstStmtKind;
|
||||
|
||||
/* A reconstructed statement node. Phase 1 holds the source text fragment and
|
||||
* the scope depth at which it sits; Phase 2 will add structured fields. */
|
||||
typedef struct AstStmt {
|
||||
AstStmtKind kind;
|
||||
int source_line; /* the .kry line (from fn->body_line, or 0) */
|
||||
int depth; /* scope depth (1 = function body) */
|
||||
const char *text; /* the body[] fragment this was built from */
|
||||
} AstStmt;
|
||||
|
||||
/* A reconstructed function: its statements with computed depths. */
|
||||
typedef struct AstFunction {
|
||||
const KryFunction *fn; /* the source function */
|
||||
AstStmt *stmts; /* array of reconstructed statements */
|
||||
int stmt_count;
|
||||
} AstFunction;
|
||||
|
||||
/* Reconstruct an AST from a function's body[] strings. Returns a malloc'd
|
||||
* AstFunction (NULL if fn is NULL or empty); caller frees with
|
||||
* ast_function_free. The kind classification is best-effort from the text
|
||||
* fragment — anything unclassifiable becomes AST_STMT_UNKNOWN so callers can
|
||||
* detect incomplete capture. */
|
||||
AstFunction *ast_function_from_body(const KryFunction *fn);
|
||||
|
||||
/* Free an AstFunction built by ast_function_from_body. */
|
||||
void ast_function_free(AstFunction *af);
|
||||
|
||||
/* Print a human-readable dump of the AST to stdout, one statement per line
|
||||
* with depth indentation and the kind label. For the --dump-ast debug mode. */
|
||||
void ast_function_dump(const AstFunction *af);
|
||||
|
||||
/* Count how many statements of a given kind appear in the function. Useful
|
||||
* for tests that assert the AST captured expected constructs. */
|
||||
int ast_function_count_kind(const AstFunction *af, AstStmtKind kind);
|
||||
|
||||
#endif /* KRYON_KC_AST_H */
|
||||
@@ -19,6 +19,17 @@ enum {
|
||||
KC_BODY_LINE_MAX = 1024,
|
||||
};
|
||||
|
||||
/* A recorded diagnostic (Phase 4 error recovery). kc fills these during parse
|
||||
* instead of aborting on the first error, so the IDE can show many at once. */
|
||||
#define KC_DIAGNOSTIC_MAX 64
|
||||
|
||||
typedef struct KryDiagnostic {
|
||||
char path[KC_PATH_MAX];
|
||||
int line;
|
||||
int column;
|
||||
char message[KC_BODY_LINE_MAX];
|
||||
} KryDiagnostic;
|
||||
|
||||
typedef struct KryFunction {
|
||||
char screen[KC_NAME_MAX];
|
||||
char args[512];
|
||||
@@ -78,6 +89,8 @@ typedef struct KryFile {
|
||||
int function_cap;
|
||||
int current_line;
|
||||
KryFunction *current;
|
||||
KryDiagnostic diagnostics[KC_DIAGNOSTIC_MAX];
|
||||
int diagnostic_count;
|
||||
} KryFile;
|
||||
|
||||
typedef struct KryMacroFrame {
|
||||
@@ -102,4 +115,15 @@ void current_macro_guard(char *dst, size_t dst_size,
|
||||
void append_macro_excluded(char *dst, size_t dst_size, const char *current,
|
||||
const char *next);
|
||||
|
||||
/* --- error recovery (Phase 4) ------------------------------------------- */
|
||||
|
||||
/* Record a diagnostic and continue parsing. Use in place of die() for
|
||||
* recoverable parse errors (bad statement, missing token, etc.). Fatal errors
|
||||
* (out of memory, bad CLI args) still use die(). */
|
||||
void kc_error(KryFile *file, int line_no, const char *fmt, ...);
|
||||
|
||||
/* Print all accumulated diagnostics to stderr and return the count. Caller
|
||||
* exits nonzero if any were printed. */
|
||||
int kc_flush_diagnostics(const KryFile *file);
|
||||
|
||||
#endif
|
||||
+1383
-188
File diff suppressed because it is too large.
Load diff
+46
-46
@@ -402,11 +402,11 @@ Profile-picture PNGs in `pfp/` are embedded into the same icon catalog with
|
||||
`GetUIProfilePictureIconType`, and `GetUIProfilePictureIconName` to enumerate
|
||||
the standard profile-picture options.
|
||||
|
||||
Kryon also exposes stable `UI_LYRA_PROFILE_ICON_*` IDs and mapping helpers:
|
||||
Kryon also exposes stable `UI_KSYNC_PROFILE_ICON_*` IDs and mapping helpers:
|
||||
|
||||
```c
|
||||
UIIconType GetUIProfilePictureIconTypeForLyraID(int lyra_id);
|
||||
int GetUILyraIDForProfilePictureIconType(UIIconType type);
|
||||
UIIconType GetUIProfilePictureIconTypeForKsyncID(int ksync_id);
|
||||
int GetUIKsyncIDForProfilePictureIconType(UIIconType type);
|
||||
```
|
||||
|
||||
Use those IDs for server storage or sync payloads instead of generated
|
||||
@@ -504,44 +504,44 @@ int GetCurrentLocaleIndex(void);
|
||||
|
||||
### Sync
|
||||
|
||||
Lyra Sync is Kryon's common sync protocol layer. Kryon owns URL handling, token auth,
|
||||
Ksync Sync is Kryon's common sync protocol layer. Kryon owns URL handling, token auth,
|
||||
challenge/login, bearer requests, sync posting, account deletion, and small JSON
|
||||
helpers. Applications still own their local data model and provide callbacks to
|
||||
build sync payloads, apply sync responses, store auth tokens, and perform
|
||||
platform HTTP.
|
||||
|
||||
#### `LyraSyncResult`
|
||||
#### `KsyncSyncResult`
|
||||
|
||||
```c
|
||||
typedef enum LyraSyncResult {
|
||||
LYRA_SYNC_OK = 0,
|
||||
LYRA_SYNC_INVALID_URL,
|
||||
LYRA_SYNC_NO_ACCOUNT,
|
||||
LYRA_SYNC_PAYLOAD_FAILED,
|
||||
LYRA_SYNC_CHALLENGE_FAILED,
|
||||
LYRA_SYNC_SIGN_FAILED,
|
||||
LYRA_SYNC_REQUEST_FAILED,
|
||||
LYRA_SYNC_AUTH_FAILED
|
||||
} LyraSyncResult;
|
||||
typedef enum KsyncSyncResult {
|
||||
KSYNC_SYNC_OK = 0,
|
||||
KSYNC_SYNC_INVALID_URL,
|
||||
KSYNC_SYNC_NO_ACCOUNT,
|
||||
KSYNC_SYNC_PAYLOAD_FAILED,
|
||||
KSYNC_SYNC_CHALLENGE_FAILED,
|
||||
KSYNC_SYNC_SIGN_FAILED,
|
||||
KSYNC_SYNC_REQUEST_FAILED,
|
||||
KSYNC_SYNC_AUTH_FAILED
|
||||
} KsyncSyncResult;
|
||||
```
|
||||
|
||||
#### `LyraSyncConfig`
|
||||
#### `KsyncSyncConfig`
|
||||
|
||||
```c
|
||||
typedef struct LyraSyncConfig {
|
||||
typedef struct KsyncSyncConfig {
|
||||
const char *base_url;
|
||||
const LyraAccount *account;
|
||||
const KsyncAccount *account;
|
||||
const char *client_id;
|
||||
LyraSyncHttpRequestFn http_request;
|
||||
LyraSyncGetTextFn get_text;
|
||||
LyraSyncSetTextFn set_text;
|
||||
LyraSyncBuildPayloadFn build_payload;
|
||||
LyraSyncFreePayloadFn free_payload;
|
||||
LyraSyncApplyResponseFn apply_response;
|
||||
LyraSyncVoidFn purge_synced_deleted;
|
||||
LyraSyncLogFn log_http_failure;
|
||||
KsyncSyncHttpRequestFn http_request;
|
||||
KsyncSyncGetTextFn get_text;
|
||||
KsyncSyncSetTextFn set_text;
|
||||
KsyncSyncBuildPayloadFn build_payload;
|
||||
KsyncSyncFreePayloadFn free_payload;
|
||||
KsyncSyncApplyResponseFn apply_response;
|
||||
KsyncSyncVoidFn purge_synced_deleted;
|
||||
KsyncSyncLogFn log_http_failure;
|
||||
void *user;
|
||||
} LyraSyncConfig;
|
||||
} KsyncSyncConfig;
|
||||
```
|
||||
|
||||
`http_request` is platform-owned. Native apps can implement it with libcurl,
|
||||
@@ -552,11 +552,11 @@ Android apps can bridge through JNI, and web apps can bridge to JavaScript fetch
|
||||
#### URL Helpers
|
||||
|
||||
```c
|
||||
int IsLyraSyncURLValid(const char *url);
|
||||
int NormalizeLyraSyncURL(const char *input, char *out, size_t out_size);
|
||||
int JoinLyraSyncURL(char *out, size_t out_size,
|
||||
int IsKsyncSyncURLValid(const char *url);
|
||||
int NormalizeKsyncSyncURL(const char *input, char *out, size_t out_size);
|
||||
int JoinKsyncSyncURL(char *out, size_t out_size,
|
||||
const char *base_url, const char *path);
|
||||
int JoinLyraSyncWebSocketURL(char *out, size_t out_size,
|
||||
int JoinKsyncSyncWebSocketURL(char *out, size_t out_size,
|
||||
const char *base_url, const char *path);
|
||||
```
|
||||
|
||||
@@ -566,41 +566,41 @@ Remote sync URLs must be HTTPS. HTTP is accepted only for loopback hosts such as
|
||||
#### Buffer And JSON Helpers
|
||||
|
||||
```c
|
||||
int AppendLyraSyncBuffer(LyraSyncBuffer *buffer,
|
||||
int AppendKsyncSyncBuffer(KsyncSyncBuffer *buffer,
|
||||
const void *data, size_t bytes);
|
||||
int AppendLyraSyncBufferJSONString(LyraSyncBuffer *buffer,
|
||||
int AppendKsyncSyncBufferJSONString(KsyncSyncBuffer *buffer,
|
||||
const char *text);
|
||||
void FreeLyraSyncBuffer(LyraSyncBuffer *buffer);
|
||||
int FindLyraSyncJSONString(const char *json, const char *key,
|
||||
void FreeKsyncSyncBuffer(KsyncSyncBuffer *buffer);
|
||||
int FindKsyncSyncJSONString(const char *json, const char *key,
|
||||
char *out, size_t out_size);
|
||||
long long FindLyraSyncJSONInt64(const char *json, const char *key,
|
||||
long long FindKsyncSyncJSONInt64(const char *json, const char *key,
|
||||
long long fallback);
|
||||
```
|
||||
|
||||
These are intentionally small helpers for Lyra protocol payload construction and
|
||||
These are intentionally small helpers for Ksync protocol payload construction and
|
||||
simple response fields. Applications that already have a full JSON parser should
|
||||
keep using it for domain data.
|
||||
|
||||
#### Auth And Sync
|
||||
|
||||
```c
|
||||
void ClearLyraSyncAuthToken(const LyraSyncConfig *cfg);
|
||||
LyraSyncResult LoginLyraSync(const LyraSyncConfig *cfg);
|
||||
LyraSyncResult RunLyraSync(const LyraSyncConfig *cfg);
|
||||
LyraSyncResult RequestLyraSyncBearer(const LyraSyncConfig *cfg,
|
||||
void ClearKsyncSyncAuthToken(const KsyncSyncConfig *cfg);
|
||||
KsyncSyncResult LoginKsyncSync(const KsyncSyncConfig *cfg);
|
||||
KsyncSyncResult RunKsyncSync(const KsyncSyncConfig *cfg);
|
||||
KsyncSyncResult RequestKsyncSyncBearer(const KsyncSyncConfig *cfg,
|
||||
const char *method,
|
||||
const char *path,
|
||||
const char *body,
|
||||
char *out,
|
||||
size_t out_size);
|
||||
LyraSyncResult DeleteLyraSyncAccount(const LyraSyncConfig *cfg);
|
||||
const char *GetLyraSyncResultName(LyraSyncResult result);
|
||||
KsyncSyncResult DeleteKsyncSyncAccount(const KsyncSyncConfig *cfg);
|
||||
const char *GetKsyncSyncResultName(KsyncSyncResult result);
|
||||
```
|
||||
|
||||
`RunLyraSync` loads or refreshes an auth token, asks the app callback for
|
||||
`RunKsyncSync` loads or refreshes an auth token, asks the app callback for
|
||||
a local-first payload, posts it to `/api/v1/sync`, applies the response through
|
||||
the callback, and purges synced tombstones on success. `RequestLyraSyncBearer`
|
||||
is for app-specific Lyra endpoints that use the same account token.
|
||||
the callback, and purges synced tombstones on success. `RequestKsyncSyncBearer`
|
||||
is for app-specific Ksync endpoints that use the same account token.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
# kc Parser Plan: resolving the AST ceiling
|
||||
|
||||
**Status:** proposal. **Goal:** replace kc's line-matcher with a real parser
|
||||
that builds an AST, while keeping generated C byte-identical (validated against
|
||||
`tests/kc_syntax_test.sh`), then use the AST to add type checking, good errors,
|
||||
and clean `defer` lowering.
|
||||
|
||||
This plan is grounded in a full audit of `cmd/kc/kc.c` (pipeline, state,
|
||||
emit) and `tests/kc_syntax_test.sh` (the sole string oracle). Every claim is
|
||||
cited to source.
|
||||
|
||||
---
|
||||
|
||||
## 1. The problem (the "AST ceiling")
|
||||
|
||||
`kc` is a line-translator, not a parser. `parse_kry` (kc.c:3022) reads a line,
|
||||
dispatches it, and emits translated C fragments into `fn->body[]`
|
||||
(kc_internal.h:31) — then forgets the line and moves on. This single design
|
||||
choice caps what the language can ever do:
|
||||
|
||||
- **No type checking.** A line-matcher can't know `items` was declared
|
||||
`const char**` three lines ago, so `DrawUIListBox(..., items, ...)` with the
|
||||
wrong shape surfaces as a C error 500 lines into generated code, not at the
|
||||
call site.
|
||||
- **`__auto_type` for every inferred local.** `x := f()` becomes
|
||||
`__auto_type x = f();` because kc can't track `f`'s return type. This makes
|
||||
generated C depend on a GCC extension and blocks IDE type hover.
|
||||
- **`die()` on first error.** One typo aborts the whole compile; the IDE's
|
||||
diagnostics pane gets one error at a time.
|
||||
- **`defer` is a text-reconstruction hack.** `apply_defers` (kc.c:4253) walks
|
||||
the flat body re-deriving scope from brace counting to splice deferred
|
||||
statements at exit points — the most algorithmically fragile code in kc.
|
||||
- **Tuple/multi-assign expands to named temps** (`__kryon_assign_L_M`) because
|
||||
line-by-line translation can't see a multi-target as one node.
|
||||
|
||||
The scanner layer (`kc_scan.c`) is already extracted. The syntax test suite is
|
||||
an excellent golden-file oracle. This is the moment to swap the foundation.
|
||||
|
||||
---
|
||||
|
||||
## 2. The approach: restructure, not rewrite
|
||||
|
||||
The audit settles this. Three facts make an incremental migration possible:
|
||||
|
||||
1. **kc already collects then emits.** `parse_kry` builds structured
|
||||
`KryFile` fields (functions[], types[], globals[], includes[], ...) in one
|
||||
pass; `write_generated` (kc.c:4513) emits in a separate pass. It is *not*
|
||||
read-a-line-write-a-line. The "AST" already exists — it's just untyped
|
||||
(`fn->body[]` is `char[512][1024]`).
|
||||
2. **`fn->body[]` is a flat AST-as-strings.** Every statement is a translated
|
||||
C fragment. A real AST replaces this array with typed nodes; the emit pass
|
||||
walks nodes instead of printing strings.
|
||||
3. **The scanner carries over unchanged.** `kc_scan.c` (trim, starts_word,
|
||||
parse_ident, parse_quoted, brace counting, the pending_stmt/pending_decl
|
||||
joiner) is reusable as-is.
|
||||
|
||||
**Verdict:** split kc.c into `parser.c` + `ast.c` + `emit.c`, reusing the
|
||||
scanner. Not a from-scratch rewrite of the language.
|
||||
|
||||
---
|
||||
|
||||
## 3. Target architecture
|
||||
|
||||
```
|
||||
.kry source
|
||||
│
|
||||
▼
|
||||
kc_scan.c (unchanged: line split, tokenizing, brace counting,
|
||||
│ multi-line joiner — pending_stmt/pending_decl)
|
||||
│
|
||||
▼
|
||||
parser.c (NEW: parse_kry → builds typed AST nodes)
|
||||
│ • top-level: imports, modules, types, globals, functions
|
||||
│ • function bodies: statements → AstStmt nodes (typed)
|
||||
│ • reuses parse_statement's dispatch logic, but builds nodes
|
||||
│ • resolves modules at parse time (not deferred to emit)
|
||||
│
|
||||
▼
|
||||
ast.h (NEW: the node types — see §4)
|
||||
│
|
||||
▼
|
||||
emit.c (rewritten write_generated: walk AST → .c/.h)
|
||||
│ • byte-identical output (see §5 contract)
|
||||
│ • defer lowered during emit walk (no separate apply_defers pass)
|
||||
│ • module-qualified calls rewritten during emit walk
|
||||
│
|
||||
▼
|
||||
.c / .h (identical to today's output)
|
||||
```
|
||||
|
||||
The existing `KryFile`/`KryFunction` structs (kc_internal.h) become thin
|
||||
wrappers holding AST node pointers instead of `char[][]` arrays, or are
|
||||
replaced by AST types outright. Either way the *external* behavior
|
||||
(command-line, file output, error format) is unchanged.
|
||||
|
||||
---
|
||||
|
||||
## 4. The AST node types
|
||||
|
||||
Minimal, statement-focused (kc has no expressions of its own — they pass
|
||||
through as C text). From the parse_statement inventory (kc.c:2662-2954):
|
||||
|
||||
```c
|
||||
/* A statement. Expressions are held as opaque C text (kc does not
|
||||
parse expressions today; adding that is a later, optional phase). */
|
||||
typedef enum {
|
||||
AST_STMT_DECL, /* x := expr | x: Type = expr | x: Type */
|
||||
AST_STMT_ASSIGN, /* x = expr (incl. compound += %= etc.) */
|
||||
AST_STMT_MULTI_ASSIGN, /* a, b = b, a (lowers to temps) */
|
||||
AST_STMT_MULTI_DECL, /* a, b := expr (lowers to temps) */
|
||||
AST_STMT_EXPR, /* bare call / expression statement */
|
||||
AST_STMT_IF, /* cond + body[] + optional else_body[] */
|
||||
AST_STMT_WHILE,
|
||||
AST_STMT_FOR, /* C-style or `NAME in A..B` */
|
||||
AST_STMT_SWITCH, /* expr + cases[] */
|
||||
AST_STMT_RETURN, /* optional expr */
|
||||
AST_STMT_BREAK,
|
||||
AST_STMT_CONTINUE,
|
||||
AST_STMT_GOTO,
|
||||
AST_STMT_LABEL,
|
||||
AST_STMT_DEFER, /* lowered at emit time */
|
||||
AST_STMT_BLOCK, /* anonymous { } scope */
|
||||
AST_STMT_RAW, /* c <line> escape hatch */
|
||||
AST_STMT_UNUSED, /* unused expr */
|
||||
AST_STMT_ENUM, /* inline enum block */
|
||||
AST_STMT_GUARD, /* guard cond → if(cond) return; */
|
||||
} AstStmtKind;
|
||||
|
||||
typedef struct AstStmt {
|
||||
AstStmtKind kind;
|
||||
int source_line; /* the .kry line — load-bearing (see §5) */
|
||||
/* union of kind-specific fields, e.g.: */
|
||||
struct { char *text; } raw; /* RAW */
|
||||
struct { char *expr; } expr; /* EXPR/RETURN/UNUSED */
|
||||
struct { char *name; char *type; char *init; int is_state; } decl;
|
||||
struct { char *target; char *op; char *value; } assign;
|
||||
struct { char **names; int name_count; char *expr; } multi;
|
||||
struct { char *cond; struct AstStmt **body; int body_count;
|
||||
struct AstStmt **else_body; int else_count; } iff;
|
||||
struct { char *label; } goto_label;
|
||||
struct { char *statement; } defer; /* lowered later */
|
||||
/* ... etc */
|
||||
} AstStmt;
|
||||
|
||||
typedef struct AstFunction {
|
||||
char name[KC_NAME_MAX];
|
||||
char args[512];
|
||||
char return_type[KC_NAME_MAX];
|
||||
char guard[KC_BODY_LINE_MAX];
|
||||
int exact_name, is_public, global_name;
|
||||
AstStmt **body; /* replaces fn->body[512][1024] */
|
||||
int body_count;
|
||||
/* calls[] carried over (used for forward-decl heuristics) */
|
||||
} AstFunction;
|
||||
```
|
||||
|
||||
The 16 `die()` branches for *removed* keywords (let/var/do/draw/widget/etc.)
|
||||
are dropped entirely — the parser simply doesn't recognize them.
|
||||
|
||||
---
|
||||
|
||||
## 5. The byte-identity contract
|
||||
|
||||
This is the load-bearing section. The oracle (`tests/kc_syntax_test.sh`) greps
|
||||
for exact strings. The rewrite must reproduce these ~10 formatting decisions
|
||||
exactly:
|
||||
|
||||
| # | What | Where asserted | Must produce |
|
||||
|---|------|----------------|--------------|
|
||||
| 1 | Inferred decl | valid.kry | `__auto_type first = 0;` |
|
||||
| 2 | Multi-assign temps | valid.kry (regex) | `__auto_type __kryon_assign_<LINE>_N = ...;` — **suffix = source line number** |
|
||||
| 3 | Swap temps | valid.kry | two temps in source order, same `_N` scheme |
|
||||
| 4 | Unused | valid.kry | `(void)second;` |
|
||||
| 5 | Call-in-if wrapping | if_call.kry | `PushUIInspectSource(path, LINE);` → `__auto_type __kryon_cond_<LINE> = Call(...);` → `PopUIInspectSource();` → `if(__kryon_cond_<LINE>) {` — **temp suffix = source line** |
|
||||
| 6 | Non-call if | valid.kry | `if(value > 0 && first >= 0) {` (unchanged) |
|
||||
| 7 | Defer splice | defer*.kry | deferred stmt on the line before each `return`/`break`/scope-close; LIFO order; **`defer` keyword itself absent from output** |
|
||||
| 8 | write_body_line indent | all | recompute indent from brace delta (kc.c:4428-4448): `}` decrements before emit, brace_delta after |
|
||||
| 9 | Module prefix | module_default.kry etc. | `module_screen_kry_draw` unless `exact_name`/`global_name`/`#export` |
|
||||
| 10 | Qualified call | colon_import_host | `alias.member(...)` → `module_member(...)` rewritten at emit |
|
||||
|
||||
**Phase 0 (below) adds oracle coverage for the blind spots** so these are
|
||||
locked *before* the rewrite touches them. The two most fragile: the temp
|
||||
suffixes (must equal source line numbers) and the defer splice ordering.
|
||||
|
||||
---
|
||||
|
||||
## 6. Phased migration
|
||||
|
||||
Each phase keeps `make test` green. No phase is merged unless the oracle passes
|
||||
byte-for-byte.
|
||||
|
||||
### Phase 0 — Harden the oracle (no parser work)
|
||||
|
||||
Fill the audited blind spots so the rewrite can't silently regress them. Add
|
||||
test cases for:
|
||||
|
||||
1. **Compound assigns** `-=`, `*=`, `/=`, `--` (only `+=`,`%=`,`&=`,`|=`,`^=`,
|
||||
`<<=`,`>>=`,`++` are covered today). One screen body.
|
||||
2. **Defer in `while`, `switch`, before `continue`, in anonymous blocks** —
|
||||
the scope-unwinding code is the most likely thing a hand-written parser
|
||||
gets wrong, and it's the cleverest part of the oracle.
|
||||
|
||||
**Bug found during Phase 0, fixed in Phase 2:** defer inside `switch` cases
|
||||
was broken — `apply_defers` treated the whole switch as one scope, so a
|
||||
defer in `case 1` leaked into `default`. Phase 2 gives each case its own
|
||||
scope (`KRY_SCOPE_CASE`) and a `spent` flag so case-local defers fire on
|
||||
their own path only. Test `defer_switch.kry` pins the fix.
|
||||
3. **`pub struct` / `pub enum`** — a real parse path (kc.c:~1697,~1733) with
|
||||
zero coverage today.
|
||||
4. **`let` and widget-keyword removals** (`background`,`rect`,`line`,`swatch`,
|
||||
`text`) — lock the error surface.
|
||||
5. **Main generation** (omit `--no-main`) — zero coverage today.
|
||||
6. **Forward-decl heuristic** — function A calls B-defined-later, assert B's
|
||||
prototype appears before A's body.
|
||||
|
||||
Effort: ~1–2 days. Pure test additions. Pays off immediately (catches bugs in
|
||||
*today's* kc) and de-risks every later phase.
|
||||
|
||||
### Phase 1 — Introduce the AST alongside the existing path ✅ DONE
|
||||
|
||||
Added `cmd/kc/kc_ast.h` + `cmd/kc/kc_ast.c` with the node types (§4). Rather
|
||||
than instrument every `parse_statement` branch, Phase 1 reconstructs the AST
|
||||
**from the already-emitted `fn->body[]` strings** in a post-parse pass
|
||||
(`ast_function_from_body`). This validates that the strings contain enough
|
||||
information to rebuild structure — exactly what Phase 2 needs to know before
|
||||
swapping the emit path.
|
||||
|
||||
`--dump-ast` parses without writing files and prints the reconstructed tree
|
||||
with per-statement kind labels and depth indentation. Verified: zero
|
||||
`AST_STMT_UNKNOWN` nodes on the full-feature test inputs (every statement
|
||||
classifies into a known kind), meaning the AST captures 100% of what kc emits.
|
||||
|
||||
**Exit criterion met:** every existing test passes unchanged; the AST is built
|
||||
but not used for output; a new test pins the dump output (function name,
|
||||
expected kinds present, no UNKNOWN, no file written).
|
||||
|
||||
Effort: ~1 day (reconstruction is simpler than parallel-build instrumentation).
|
||||
|
||||
### Phase 2 — Emit from the AST (the cutover)
|
||||
|
||||
Rewrite `write_generated` to walk `AstFunction.body` (the node tree) instead of
|
||||
`fn->body[]` (the string array). `write_body_line` becomes `emit_stmt`. The
|
||||
defer lowering moves *into* the emit walk (a node visitor that tracks scope
|
||||
depth natively, instead of `apply_defers` reconstructing it from text).
|
||||
Module-qualified call rewriting also moves into the walk.
|
||||
|
||||
**Exit criterion:** `fn->body[]` is deleted; the oracle passes byte-for-byte;
|
||||
`apply_defers` is deleted (its logic now lives in the emit visitor).
|
||||
|
||||
Effort: ~1 week. The riskiest phase — concentrated in §5's 10 formatting
|
||||
decisions. Mitigated by Phase 0's hardened oracle.
|
||||
|
||||
### Phase 3 — Type checking (the payoff)
|
||||
|
||||
Now that bodies are typed nodes, add a type pass between parse and emit. Start
|
||||
narrow: track declared types of locals and params, and check call arguments
|
||||
against... what? kc has no function-signature database. Two options:
|
||||
|
||||
- **Option A (cheap):** check *shape* only — pointer-ness, array-ness —
|
||||
against the C declaration text. Catches `DrawUIListBox(..., items, ...)` when
|
||||
`items` is `[4] const char*` and the call wants `const char**`. Doesn't need
|
||||
a type DB.
|
||||
- **Option B (full):** parse `#import`ed headers' signatures into a symbol
|
||||
table. Bigger; enables hover-types in the IDE.
|
||||
|
||||
Recommend Option A first — it catches the common foot-guns with a week's work
|
||||
and no header parsing.
|
||||
|
||||
Effort: ~1 week (Option A).
|
||||
|
||||
### Phase 4 — Error recovery
|
||||
|
||||
Replace `die()` with a diagnostic collector that records errors and continues
|
||||
where possible. The IDE's diagnostics pane (which parses compiler output)
|
||||
becomes useful. Naturally enabled by the AST: a malformed node doesn't abort
|
||||
the whole parse.
|
||||
|
||||
Effort: ~3–5 days.
|
||||
|
||||
---
|
||||
|
||||
## 7. What this unlocks
|
||||
|
||||
After Phase 2 (AST emit), even without type checking:
|
||||
|
||||
- **`defer` becomes correct by construction** — scope is a property of the
|
||||
node tree, not reconstructed from text.
|
||||
- **Error recovery** — collect-many-errors is natural on a tree.
|
||||
- **IDE features** — goto-definition, find-references, hover all become
|
||||
possible because the compiler has structured knowledge.
|
||||
- **Future language features** — closures, real generics, pattern matching
|
||||
become *possible* (currently impossible on a line-matcher).
|
||||
- **Removes the GCC `__auto_type` dependency** (after Phase 3 tracks types).
|
||||
|
||||
---
|
||||
|
||||
## 8. What stays the same
|
||||
|
||||
- The `.kry` language surface (no syntax changes — this is a compiler
|
||||
internals project).
|
||||
- The generated C output (byte-identical, by contract).
|
||||
- The command line, file layout, error message format.
|
||||
- The scanner (`kc_scan.c`), text helpers (`convert_var_decl`,
|
||||
`convert_arg_list`, `find_assignment_op`), and module-symbol logic.
|
||||
- The IDE's use of kc (it shells out and checks exit status + `.so` existence
|
||||
— unaffected).
|
||||
|
||||
---
|
||||
|
||||
## 9. Sizing and sequencing
|
||||
|
||||
| Phase | Effort | Risk | Depends on |
|
||||
|-------|--------|------|------------|
|
||||
| 0. Harden oracle | 1–2 days | none | — |
|
||||
| 1. AST alongside | ~1 week | low | 0 |
|
||||
| 2. Emit from AST | ~1 week | **medium** (§5) | 1 |
|
||||
| 3. Type checking (opt A) | ~1 week | low | 2 |
|
||||
| 4. Error recovery | 3–5 days | low | 2 |
|
||||
|
||||
**Total to a typed, error-recovering compiler: ~5 weeks.** Phases 0–2 alone
|
||||
(inside ~2.5 weeks) deliver a structurally-sound compiler with identical
|
||||
output — the foundation everything else builds on. Phases 3–4 are independent
|
||||
payoffs that can land in any order after 2.
|
||||
|
||||
Phase 0 is shippable and valuable *today*, independent of whether the parser
|
||||
work proceeds — it just adds test coverage for untested paths.
|
||||
|
||||
---
|
||||
|
||||
## 10. Open questions
|
||||
|
||||
1. **Replace `KryFile`/`KryFunction` or wrap them?** The structs in
|
||||
kc_internal.h are large and cross-referenced. Wrapping (AST nodes point
|
||||
into them, or they hold AST pointers) is less churn than replacing. Decide
|
||||
at Phase 1.
|
||||
2. **Expression parsing.** This plan holds expressions as opaque C text (kc
|
||||
does today). A future phase could tokenize expressions for real type
|
||||
inference on `:=`. Out of scope for the initial restructure; noted as a
|
||||
later enhancement.
|
||||
3. **Should the AST be serialized for IDE tooling?** A `--dump-ast-json` mode
|
||||
would let the IDE do structural queries without re-parsing. Cheap to add
|
||||
once the AST exists; deferred unless the IDE needs it.
|
||||
4. **Per-file or whole-program?** kc is per-file today (one .kry → one .c/.h).
|
||||
Cross-file type checking (Phase 3 Option B) needs a multi-file mode. Decide
|
||||
when Phase 3 is scoped.
|
||||
@@ -104,9 +104,35 @@ and control flow. There are no widget keywords and no bespoke sugar verbs:
|
||||
- plain function calls (any call used as a statement is a draw call and is
|
||||
automatically wrapped with source-inspection metadata for click-to-source).
|
||||
- `if`, `else if`, `else`, `while`, `for`, `switch`, `case`, `default`,
|
||||
labels, `goto`, `break`, `continue`, `guard`, and `return`.
|
||||
labels, `goto`, `break`, `continue`, `guard`, `defer`, and `return`.
|
||||
- `c line` for raw C glue and `unused expr` to silence unused-value warnings.
|
||||
|
||||
`defer STMT` schedules `STMT` to run when the enclosing block exits, replacing
|
||||
the cleanup-`goto` idiom:
|
||||
|
||||
```kry
|
||||
load_asset :: (path: const char*) -> Asset* {
|
||||
f := fopen(path, "rb")
|
||||
defer fclose(f)
|
||||
if f == nil {
|
||||
return nil # fclose runs here
|
||||
}
|
||||
...
|
||||
return parse(f) # fclose runs here too
|
||||
} # and here, on fall-through
|
||||
```
|
||||
|
||||
A deferred statement fires on scope exit however the block is left: by
|
||||
falling off the end, by `return`, or by `break`/`continue` that leaves the
|
||||
block. Multiple defers in one block run in reverse (last-registered-first)
|
||||
order, and defers in inner scopes run before those in outer scopes. A defer
|
||||
only fires if it was declared before the exit that triggers it.
|
||||
|
||||
`defer` is a compile-time transform: the statement is spliced into the
|
||||
generated C at every exit point of its scope, with no runtime cost. `goto`
|
||||
that jumps out of a deferred scope does not run the defer — use explicit
|
||||
cleanup labels if you mix the two.
|
||||
|
||||
Widgets are ordinary library functions (WidgetText, WidgetRect, WidgetLine,
|
||||
WidgetBackground, WidgetButton) declared in `ui_widgets.h`; the compiler
|
||||
treats them exactly like any other call. Input handling is plain control
|
||||
|
||||
@@ -5,6 +5,14 @@
|
||||
|
||||
#define APP_HOST_ABI_VERSION 3
|
||||
|
||||
typedef struct KryonInputOverride {
|
||||
int enabled;
|
||||
int mouse_inside;
|
||||
int pass_buttons;
|
||||
Vector2 mouse_position;
|
||||
Vector2 mouse_delta;
|
||||
} KryonInputOverride;
|
||||
|
||||
typedef struct AppScreenInfo {
|
||||
const char *id;
|
||||
const char *group;
|
||||
@@ -25,6 +33,8 @@ typedef AppHost *(*CreateAppHostCallback)(int abi_version,
|
||||
const char *project_path);
|
||||
typedef void (*DestroyAppHostCallback)(AppHost *host);
|
||||
|
||||
void BeginKryonInputOverride(KryonInputOverride input);
|
||||
void EndKryonInputOverride(void);
|
||||
int IsUIInspectActive(void);
|
||||
|
||||
#endif
|
||||
+5
-2
@@ -2,6 +2,9 @@
|
||||
#define KRYON_H
|
||||
|
||||
#include "kryon_version.h"
|
||||
/* Kryon's graphics/input API surface (currently tracks raylib). The concrete
|
||||
* backend is selected at link time via the KRYON_BACKEND make variable; see
|
||||
* the preamble in kryon_compat.generated.h. */
|
||||
#include "kryon_compat.generated.h"
|
||||
|
||||
#include "ui_color.h"
|
||||
@@ -28,8 +31,8 @@
|
||||
#include "ui_transition.h"
|
||||
#include "ui_widgets.h"
|
||||
#include "locale.h"
|
||||
#include "lyra_account.h"
|
||||
#include "lyra_sync.h"
|
||||
#include "ksync_account.h"
|
||||
#include "ksync_sync.h"
|
||||
#include "theme.h"
|
||||
#include "theme_meta.h"
|
||||
#include "web.h"
|
||||
|
||||
@@ -1,5 +1,19 @@
|
||||
/* Generated by tools/generate-kryon-compat.sh; do not edit. */
|
||||
/* Kryon exposes this Raylib-compatible surface through kryon.h. */
|
||||
/*
|
||||
* Kryon graphics/input API surface.
|
||||
*
|
||||
* This header defines kryon's public graphics, input, and asset API. It
|
||||
* currently tracks raylib's surface verbatim so that existing raylib-style
|
||||
* code (DrawRectangle, Font, BeginDrawing, ...) compiles unchanged, and so
|
||||
* the raylib backend (build/generated/kryon_raylib_wrappers.c) can implement
|
||||
* every symbol by forwarding to raylib.
|
||||
*
|
||||
* Kryon owns this surface. It is not "raylib that kryon happens to use":
|
||||
* other backends implement these same function and type names without raylib
|
||||
* (for example an HTML5 canvas backend). Selection is link-time, via the
|
||||
* KRYON_BACKEND make variable. The raylib version tracked below is the
|
||||
* baseline; kryon may evolve this surface independently over time.
|
||||
*/
|
||||
/**********************************************************************************************
|
||||
*
|
||||
* raylib v6.1-dev - A simple and easy-to-use library to enjoy videogames programming (www.raylib.com)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#ifndef KSYNC_ACCOUNT_H
|
||||
#define KSYNC_ACCOUNT_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
enum {
|
||||
KSYNC_PUBLIC_ID_HEX_SIZE = 65,
|
||||
KSYNC_PUBLIC_KEY_HEX_SIZE = 2625,
|
||||
KSYNC_PRIVATE_KEY_HEX_SIZE = 5121,
|
||||
KSYNC_SIGNATURE_HEX_SIZE = 4841,
|
||||
KSYNC_ACCOUNT_EXPORT_TEXT_SIZE = 8200
|
||||
};
|
||||
|
||||
typedef struct KsyncAccount {
|
||||
char public_id[KSYNC_PUBLIC_ID_HEX_SIZE];
|
||||
char public_key_hex[KSYNC_PUBLIC_KEY_HEX_SIZE];
|
||||
char private_key_hex[KSYNC_PRIVATE_KEY_HEX_SIZE];
|
||||
} KsyncAccount;
|
||||
|
||||
int IsKsyncAccountAvailable(void);
|
||||
int HasKsyncAccountValues(const KsyncAccount *account);
|
||||
int CreateKsyncAccount(KsyncAccount *account);
|
||||
int ValidateKsyncAccount(KsyncAccount *account);
|
||||
int ParseKsyncAccountText(const char *text, KsyncAccount *account);
|
||||
int ExportKsyncAccountText(const KsyncAccount *account, char *out, size_t out_size);
|
||||
int ImportKsyncAccountFile(const char *filename, KsyncAccount *account);
|
||||
int ExportKsyncAccountFile(const KsyncAccount *account, const char *filename);
|
||||
void KsyncSha256Hex(const uint8_t *data, size_t len, char out_hex[KSYNC_PUBLIC_ID_HEX_SIZE]);
|
||||
int SignKsyncAccountHex(const KsyncAccount *account, const uint8_t *message,
|
||||
size_t message_len, char *out_signature_hex,
|
||||
size_t out_size);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,86 @@
|
||||
#ifndef KSYNC_SYNC_H
|
||||
#define KSYNC_SYNC_H
|
||||
|
||||
#include "ksync_account.h"
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
typedef enum KsyncSyncResult {
|
||||
KSYNC_SYNC_OK = 0,
|
||||
KSYNC_SYNC_INVALID_URL,
|
||||
KSYNC_SYNC_NO_ACCOUNT,
|
||||
KSYNC_SYNC_PAYLOAD_FAILED,
|
||||
KSYNC_SYNC_CHALLENGE_FAILED,
|
||||
KSYNC_SYNC_SIGN_FAILED,
|
||||
KSYNC_SYNC_REQUEST_FAILED,
|
||||
KSYNC_SYNC_AUTH_FAILED
|
||||
} KsyncSyncResult;
|
||||
|
||||
typedef struct KsyncSyncBuffer {
|
||||
char *data;
|
||||
size_t len;
|
||||
size_t cap;
|
||||
} KsyncSyncBuffer;
|
||||
|
||||
typedef int (*KsyncSyncHttpRequestFn)(const char *method, const char *url,
|
||||
const char *body,
|
||||
const char *const *headers,
|
||||
int header_count,
|
||||
KsyncSyncBuffer *response,
|
||||
long *status, void *user);
|
||||
typedef const char *(*KsyncSyncGetTextFn)(const char *key, void *user);
|
||||
typedef void (*KsyncSyncSetTextFn)(const char *key, const char *value, void *user);
|
||||
typedef char *(*KsyncSyncBuildPayloadFn)(const char *user_id_hash,
|
||||
const char *public_key_hex, void *user);
|
||||
typedef void (*KsyncSyncFreePayloadFn)(char *payload, void *user);
|
||||
typedef int (*KsyncSyncApplyResponseFn)(const char *response_json, void *user);
|
||||
typedef void (*KsyncSyncVoidFn)(void *user);
|
||||
typedef void (*KsyncSyncLogFn)(const char *step, long status,
|
||||
const char *response, void *user);
|
||||
|
||||
typedef struct KsyncSyncConfig {
|
||||
const char *base_url;
|
||||
const KsyncAccount *account;
|
||||
const char *client_id;
|
||||
const char *signature_context;
|
||||
const char *user_header_name;
|
||||
const char *signature_header_name;
|
||||
KsyncSyncHttpRequestFn http_request;
|
||||
KsyncSyncGetTextFn get_text;
|
||||
KsyncSyncSetTextFn set_text;
|
||||
KsyncSyncBuildPayloadFn build_payload;
|
||||
KsyncSyncFreePayloadFn free_payload;
|
||||
KsyncSyncApplyResponseFn apply_response;
|
||||
KsyncSyncVoidFn purge_synced_deleted;
|
||||
KsyncSyncLogFn log_http_failure;
|
||||
void *user;
|
||||
} KsyncSyncConfig;
|
||||
|
||||
const char *GetKsyncSyncResultName(KsyncSyncResult result);
|
||||
int IsKsyncSyncURLValid(const char *url);
|
||||
int NormalizeKsyncSyncURL(const char *input, char *out, size_t out_size);
|
||||
int JoinKsyncSyncURL(char *out, size_t out_size,
|
||||
const char *base_url, const char *path);
|
||||
int JoinKsyncSyncWebSocketURL(char *out, size_t out_size,
|
||||
const char *base_url, const char *path);
|
||||
int AppendKsyncSyncBuffer(KsyncSyncBuffer *buffer,
|
||||
const void *data, size_t bytes);
|
||||
int AppendKsyncSyncBufferJSONString(KsyncSyncBuffer *buffer,
|
||||
const char *text);
|
||||
void FreeKsyncSyncBuffer(KsyncSyncBuffer *buffer);
|
||||
int FindKsyncSyncJSONString(const char *json, const char *key,
|
||||
char *out, size_t out_size);
|
||||
long long FindKsyncSyncJSONInt64(const char *json, const char *key,
|
||||
long long fallback);
|
||||
void ClearKsyncSyncAuthToken(const KsyncSyncConfig *cfg);
|
||||
KsyncSyncResult LoginKsyncSync(const KsyncSyncConfig *cfg);
|
||||
KsyncSyncResult RunKsyncSync(const KsyncSyncConfig *cfg);
|
||||
KsyncSyncResult RequestKsyncSyncBearer(const KsyncSyncConfig *cfg,
|
||||
const char *method,
|
||||
const char *path,
|
||||
const char *body,
|
||||
char *out,
|
||||
size_t out_size);
|
||||
KsyncSyncResult DeleteKsyncSyncAccount(const KsyncSyncConfig *cfg);
|
||||
|
||||
#endif
|
||||
@@ -1,34 +0,0 @@
|
||||
#ifndef LYRA_ACCOUNT_H
|
||||
#define LYRA_ACCOUNT_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
enum {
|
||||
LYRA_PUBLIC_ID_HEX_SIZE = 65,
|
||||
LYRA_PUBLIC_KEY_HEX_SIZE = 2625,
|
||||
LYRA_PRIVATE_KEY_HEX_SIZE = 5121,
|
||||
LYRA_SIGNATURE_HEX_SIZE = 4841,
|
||||
LYRA_ACCOUNT_EXPORT_TEXT_SIZE = 8200
|
||||
};
|
||||
|
||||
typedef struct LyraAccount {
|
||||
char public_id[LYRA_PUBLIC_ID_HEX_SIZE];
|
||||
char public_key_hex[LYRA_PUBLIC_KEY_HEX_SIZE];
|
||||
char private_key_hex[LYRA_PRIVATE_KEY_HEX_SIZE];
|
||||
} LyraAccount;
|
||||
|
||||
int IsLyraAccountAvailable(void);
|
||||
int HasLyraAccountValues(const LyraAccount *account);
|
||||
int CreateLyraAccount(LyraAccount *account);
|
||||
int ValidateLyraAccount(LyraAccount *account);
|
||||
int ParseLyraAccountText(const char *text, LyraAccount *account);
|
||||
int ExportLyraAccountText(const LyraAccount *account, char *out, size_t out_size);
|
||||
int ImportLyraAccountFile(const char *filename, LyraAccount *account);
|
||||
int ExportLyraAccountFile(const LyraAccount *account, const char *filename);
|
||||
void LyraSha256Hex(const uint8_t *data, size_t len, char out_hex[LYRA_PUBLIC_ID_HEX_SIZE]);
|
||||
int SignLyraAccountHex(const LyraAccount *account, const uint8_t *message,
|
||||
size_t message_len, char *out_signature_hex,
|
||||
size_t out_size);
|
||||
|
||||
#endif
|
||||
@@ -1,86 +0,0 @@
|
||||
#ifndef LYRA_SYNC_H
|
||||
#define LYRA_SYNC_H
|
||||
|
||||
#include "lyra_account.h"
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
typedef enum LyraSyncResult {
|
||||
LYRA_SYNC_OK = 0,
|
||||
LYRA_SYNC_INVALID_URL,
|
||||
LYRA_SYNC_NO_ACCOUNT,
|
||||
LYRA_SYNC_PAYLOAD_FAILED,
|
||||
LYRA_SYNC_CHALLENGE_FAILED,
|
||||
LYRA_SYNC_SIGN_FAILED,
|
||||
LYRA_SYNC_REQUEST_FAILED,
|
||||
LYRA_SYNC_AUTH_FAILED
|
||||
} LyraSyncResult;
|
||||
|
||||
typedef struct LyraSyncBuffer {
|
||||
char *data;
|
||||
size_t len;
|
||||
size_t cap;
|
||||
} LyraSyncBuffer;
|
||||
|
||||
typedef int (*LyraSyncHttpRequestFn)(const char *method, const char *url,
|
||||
const char *body,
|
||||
const char *const *headers,
|
||||
int header_count,
|
||||
LyraSyncBuffer *response,
|
||||
long *status, void *user);
|
||||
typedef const char *(*LyraSyncGetTextFn)(const char *key, void *user);
|
||||
typedef void (*LyraSyncSetTextFn)(const char *key, const char *value, void *user);
|
||||
typedef char *(*LyraSyncBuildPayloadFn)(const char *user_id_hash,
|
||||
const char *public_key_hex, void *user);
|
||||
typedef void (*LyraSyncFreePayloadFn)(char *payload, void *user);
|
||||
typedef int (*LyraSyncApplyResponseFn)(const char *response_json, void *user);
|
||||
typedef void (*LyraSyncVoidFn)(void *user);
|
||||
typedef void (*LyraSyncLogFn)(const char *step, long status,
|
||||
const char *response, void *user);
|
||||
|
||||
typedef struct LyraSyncConfig {
|
||||
const char *base_url;
|
||||
const LyraAccount *account;
|
||||
const char *client_id;
|
||||
const char *signature_context;
|
||||
const char *user_header_name;
|
||||
const char *signature_header_name;
|
||||
LyraSyncHttpRequestFn http_request;
|
||||
LyraSyncGetTextFn get_text;
|
||||
LyraSyncSetTextFn set_text;
|
||||
LyraSyncBuildPayloadFn build_payload;
|
||||
LyraSyncFreePayloadFn free_payload;
|
||||
LyraSyncApplyResponseFn apply_response;
|
||||
LyraSyncVoidFn purge_synced_deleted;
|
||||
LyraSyncLogFn log_http_failure;
|
||||
void *user;
|
||||
} LyraSyncConfig;
|
||||
|
||||
const char *GetLyraSyncResultName(LyraSyncResult result);
|
||||
int IsLyraSyncURLValid(const char *url);
|
||||
int NormalizeLyraSyncURL(const char *input, char *out, size_t out_size);
|
||||
int JoinLyraSyncURL(char *out, size_t out_size,
|
||||
const char *base_url, const char *path);
|
||||
int JoinLyraSyncWebSocketURL(char *out, size_t out_size,
|
||||
const char *base_url, const char *path);
|
||||
int AppendLyraSyncBuffer(LyraSyncBuffer *buffer,
|
||||
const void *data, size_t bytes);
|
||||
int AppendLyraSyncBufferJSONString(LyraSyncBuffer *buffer,
|
||||
const char *text);
|
||||
void FreeLyraSyncBuffer(LyraSyncBuffer *buffer);
|
||||
int FindLyraSyncJSONString(const char *json, const char *key,
|
||||
char *out, size_t out_size);
|
||||
long long FindLyraSyncJSONInt64(const char *json, const char *key,
|
||||
long long fallback);
|
||||
void ClearLyraSyncAuthToken(const LyraSyncConfig *cfg);
|
||||
LyraSyncResult LoginLyraSync(const LyraSyncConfig *cfg);
|
||||
LyraSyncResult RunLyraSync(const LyraSyncConfig *cfg);
|
||||
LyraSyncResult RequestLyraSyncBearer(const LyraSyncConfig *cfg,
|
||||
const char *method,
|
||||
const char *path,
|
||||
const char *body,
|
||||
char *out,
|
||||
size_t out_size);
|
||||
LyraSyncResult DeleteLyraSyncAccount(const LyraSyncConfig *cfg);
|
||||
|
||||
#endif
|
||||
@@ -14,6 +14,12 @@
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#ifndef NOGDI
|
||||
#define NOGDI
|
||||
#endif
|
||||
#ifndef NOUSER
|
||||
#define NOUSER
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#elif defined(PLATFORM_WEB) || defined(__EMSCRIPTEN__)
|
||||
#define KRYON_PLATFORM_NO_THREADS 1
|
||||
|
||||
@@ -131,6 +131,7 @@ typedef struct {
|
||||
UITextInputStyle style;
|
||||
UITextInputFilter filter;
|
||||
void *filter_user_data;
|
||||
int show_line_numbers; /* when nonzero, draw a line-number gutter */
|
||||
} UITextArea;
|
||||
|
||||
typedef struct {
|
||||
|
||||
@@ -12,6 +12,7 @@ int IsUIDesktopMode(void);
|
||||
Camera2D GetUIDefaultCamera(void);
|
||||
void BeginUIFrame(int width, int height, float dpi);
|
||||
void SetUIFrame(Camera2D camera);
|
||||
void SetUIMouseWorldOverride(int enabled, Vector2 position);
|
||||
int SetUIKeyboardInputEnabled(int enabled);
|
||||
int UIKeyboardInputEnabled(void);
|
||||
int UIKeyPressed(int key);
|
||||
|
||||
+30
-30
@@ -44,40 +44,40 @@ typedef struct {
|
||||
} UIProfilePicturePickerResult;
|
||||
|
||||
typedef enum {
|
||||
UI_LYRA_PROFILE_ICON_NONE = 0,
|
||||
UI_LYRA_PROFILE_ICON_BIRD = 1,
|
||||
UI_LYRA_PROFILE_ICON_BOWL = 2,
|
||||
UI_LYRA_PROFILE_ICON_CACTUS = 3,
|
||||
UI_LYRA_PROFILE_ICON_HEART = 4,
|
||||
UI_LYRA_PROFILE_ICON_INCENSE = 5,
|
||||
UI_LYRA_PROFILE_ICON_LOTUS = 6,
|
||||
UI_LYRA_PROFILE_ICON_TREE1 = 7,
|
||||
UI_LYRA_PROFILE_ICON_TREE2 = 8,
|
||||
UI_LYRA_PROFILE_ICON_TREE3 = 9,
|
||||
UI_LYRA_PROFILE_ICON_TREE4 = 10,
|
||||
UI_LYRA_PROFILE_ICON_TREE5 = 11,
|
||||
UI_LYRA_PROFILE_ICON_BAMBUS = 12,
|
||||
UI_LYRA_PROFILE_ICON_BUSH = 13,
|
||||
UI_LYRA_PROFILE_ICON_COFFEE = 14,
|
||||
UI_LYRA_PROFILE_ICON_FLOWER1 = 15,
|
||||
UI_LYRA_PROFILE_ICON_FLOWER2 = 16,
|
||||
UI_LYRA_PROFILE_ICON_MOUNTAIN = 17,
|
||||
UI_LYRA_PROFILE_ICON_MUSHROOM = 18,
|
||||
UI_LYRA_PROFILE_ICON_PERSON1 = 19,
|
||||
UI_LYRA_PROFILE_ICON_RAINBOW = 20,
|
||||
UI_LYRA_PROFILE_ICON_TENT = 21,
|
||||
UI_LYRA_PROFILE_ICON_BUTTERFLY = 22,
|
||||
UI_LYRA_PROFILE_ICON_DRAGONFLY = 23,
|
||||
UI_LYRA_PROFILE_ICON_FIREPLACE = 24,
|
||||
UI_LYRA_PROFILE_ICON_FOX = 25,
|
||||
UI_LYRA_PROFILE_ICON_PALM = 26
|
||||
} UILyraProfileIcon;
|
||||
UI_KSYNC_PROFILE_ICON_NONE = 0,
|
||||
UI_KSYNC_PROFILE_ICON_BIRD = 1,
|
||||
UI_KSYNC_PROFILE_ICON_BOWL = 2,
|
||||
UI_KSYNC_PROFILE_ICON_CACTUS = 3,
|
||||
UI_KSYNC_PROFILE_ICON_HEART = 4,
|
||||
UI_KSYNC_PROFILE_ICON_INCENSE = 5,
|
||||
UI_KSYNC_PROFILE_ICON_LOTUS = 6,
|
||||
UI_KSYNC_PROFILE_ICON_TREE1 = 7,
|
||||
UI_KSYNC_PROFILE_ICON_TREE2 = 8,
|
||||
UI_KSYNC_PROFILE_ICON_TREE3 = 9,
|
||||
UI_KSYNC_PROFILE_ICON_TREE4 = 10,
|
||||
UI_KSYNC_PROFILE_ICON_TREE5 = 11,
|
||||
UI_KSYNC_PROFILE_ICON_BAMBUS = 12,
|
||||
UI_KSYNC_PROFILE_ICON_BUSH = 13,
|
||||
UI_KSYNC_PROFILE_ICON_COFFEE = 14,
|
||||
UI_KSYNC_PROFILE_ICON_FLOWER1 = 15,
|
||||
UI_KSYNC_PROFILE_ICON_FLOWER2 = 16,
|
||||
UI_KSYNC_PROFILE_ICON_MOUNTAIN = 17,
|
||||
UI_KSYNC_PROFILE_ICON_MUSHROOM = 18,
|
||||
UI_KSYNC_PROFILE_ICON_PERSON1 = 19,
|
||||
UI_KSYNC_PROFILE_ICON_RAINBOW = 20,
|
||||
UI_KSYNC_PROFILE_ICON_TENT = 21,
|
||||
UI_KSYNC_PROFILE_ICON_BUTTERFLY = 22,
|
||||
UI_KSYNC_PROFILE_ICON_DRAGONFLY = 23,
|
||||
UI_KSYNC_PROFILE_ICON_FIREPLACE = 24,
|
||||
UI_KSYNC_PROFILE_ICON_FOX = 25,
|
||||
UI_KSYNC_PROFILE_ICON_PALM = 26
|
||||
} UIKsyncProfileIcon;
|
||||
|
||||
int GetUIProfilePictureIconCount(void);
|
||||
UIIconType GetUIProfilePictureIconType(int index);
|
||||
const char *GetUIProfilePictureIconName(int index);
|
||||
UIIconType GetUIProfilePictureIconTypeForLyraID(int lyra_id);
|
||||
int GetUILyraIDForProfilePictureIconType(UIIconType type);
|
||||
UIIconType GetUIProfilePictureIconTypeForKsyncID(int ksync_id);
|
||||
int GetUIKsyncIDForProfilePictureIconType(UIIconType type);
|
||||
UISidebarAccountHeaderResult DrawUISidebarAccountHeader(UISidebarAccountHeader header);
|
||||
UIProfilePicturePickerResult DrawUIProfilePicturePickerModal(UIProfilePicturePickerModal modal);
|
||||
|
||||
|
||||
@@ -15,6 +15,9 @@ int RegisterUISmallFont(const char *name, Font font);
|
||||
int RegisterUIFontSource(const char *name, const char *file_type,
|
||||
const unsigned char *font_data, unsigned int font_size,
|
||||
const int *codepoints, int codepoint_count);
|
||||
int RegisterUIFontFileSource(const char *name, const char *path,
|
||||
const int *codepoints, int codepoint_count,
|
||||
int dynamic_codepoints);
|
||||
int UseUIFont(const char *name);
|
||||
int PushUIFont(const char *name);
|
||||
void PopUIFont(int token);
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
#ifndef UI_TEXT_BACKEND_H
|
||||
#define UI_TEXT_BACKEND_H
|
||||
|
||||
/*
|
||||
* Text-backend seam.
|
||||
*
|
||||
* src/ui/ never reads Font/GlyphInfo struct fields directly. Instead it goes
|
||||
* through these accessors, which the active graphics backend implements. On the
|
||||
* raylib backend (src/backend/raylib_text_backend.c) they forward to raylib's
|
||||
* own glyph accessors; other backends answer them over their own font layout.
|
||||
*
|
||||
* Font stays a real struct (raylib-layout on the raylib backend); only the
|
||||
* atlas internals are hidden behind this seam. Functions take Font by value to
|
||||
* match raylib's own accessor signatures (GetGlyphInfo, GetGlyphAtlasRec).
|
||||
*/
|
||||
#include "kryon.h"
|
||||
|
||||
/* True if `font` is loaded and ready to measure/draw with. */
|
||||
int UIFontReady(Font font);
|
||||
|
||||
/* Base size of the font in pixels (font.baseSize), >= 0. */
|
||||
int UIFontBaseSize(Font font);
|
||||
|
||||
/* Per-glyph padding of the font (font.glyphPadding), >= 0. */
|
||||
int UIFontGlyphPadding(Font font);
|
||||
|
||||
/* Glyph info (offsetX/offsetY/advanceX/value) for a codepoint, falling back to
|
||||
* '?' like raylib's GetGlyphInfo. */
|
||||
GlyphInfo UIFontGlyph(Font font, int codepoint);
|
||||
|
||||
/* Atlas sub-rectangle for a codepoint, falling back to '?' like raylib's
|
||||
* GetGlyphAtlasRec. */
|
||||
Rectangle UIFontAtlasRec(Font font, int codepoint);
|
||||
|
||||
/* The atlas texture holding every glyph image (font.texture). Callers blit a
|
||||
* glyph with DrawTexturePro(atlas, UIFontAtlasRec(font, cp), dst, ...). */
|
||||
Texture2D UIFontAtlasTexture(Font font);
|
||||
|
||||
/* Horizontal pen advance for a codepoint in font units
|
||||
* (glyphs[GetGlyphIndex].advanceX), fallback '?' as raylib. */
|
||||
int UIFontAdvance(Font font, int codepoint);
|
||||
|
||||
/* True if the font provides a glyph for `codepoint` (any glyph slot, not just
|
||||
* the loaded codepoint range). */
|
||||
int UIFontHasGlyphValue(Font font, int codepoint);
|
||||
|
||||
#endif /* UI_TEXT_BACKEND_H */
|
||||
+3
-2
@@ -26,11 +26,12 @@ kryon-raylib-check:
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
$(KRYON_RAYLIB_GENERATED_PUBLIC_HEADER) $(KRYON_RAYLIB_BACKEND_RENAME_HEADER) $(KRYON_RAYLIB_WRAPPERS_C): $(KRYON_DIR)/tools/generate-kryon-compat.sh $(RAYLIB_DIR)/raylib.h
|
||||
$(KRYON_RAYLIB_GENERATED_PUBLIC_HEADER) $(KRYON_RAYLIB_BACKEND_RENAME_HEADER) $(KRYON_RAYLIB_WRAPPERS_C) $(KRYON_NULL_BACKEND_C): $(KRYON_DIR)/tools/generate-kryon-compat.sh $(RAYLIB_DIR)/raylib.h
|
||||
sh $(KRYON_DIR)/tools/generate-kryon-compat.sh $(RAYLIB_DIR)/raylib.h \
|
||||
$(KRYON_RAYLIB_GENERATED_PUBLIC_HEADER) \
|
||||
$(KRYON_RAYLIB_BACKEND_RENAME_HEADER) \
|
||||
$(KRYON_RAYLIB_WRAPPERS_C)
|
||||
$(KRYON_RAYLIB_WRAPPERS_C) \
|
||||
$(KRYON_NULL_BACKEND_C)
|
||||
|
||||
KRYON_RAYLIB_MODULE_AUDIO ?= TRUE
|
||||
KRYON_RAYLIB_MODULE_MODELS ?= TRUE
|
||||
|
||||
@@ -15,6 +15,9 @@ Commands:
|
||||
freebsd, linux, windows, or web package output
|
||||
test run the app test target
|
||||
clean [TARGET] clean all or a target-specific build tree
|
||||
dev-backend run a local Ksync sync server for this project
|
||||
(locates the server at $KSYNC_DIR or ../ksync; prints
|
||||
the sync URL to point your app at)
|
||||
USAGE
|
||||
}
|
||||
|
||||
@@ -115,6 +118,70 @@ package)
|
||||
test)
|
||||
run_make test
|
||||
;;
|
||||
dev-backend)
|
||||
# Run a local Ksync sync server for development. Locates the server source
|
||||
# at $KSYNC_DIR (if set) or as a sibling checkout (../ksync relative to this
|
||||
# script), isolates its data in <project>/.kryon/, and runs it in the
|
||||
# foreground. The server regenerates its token secret each start, so this
|
||||
# is for local development only — do not use it for shared deployments.
|
||||
ksync_dir=${KSYNC_DIR:-}
|
||||
if [ -z "$ksync_dir" ]; then
|
||||
# Try a sibling checkout: walk up from the current directory looking
|
||||
# for a ../ksync that contains the server, then fall back to a sibling
|
||||
# of the script's own location (for the in-tree kryon build).
|
||||
search_dir=$(pwd)
|
||||
while [ "$search_dir" != "/" ]; do
|
||||
candidate=$search_dir/../ksync
|
||||
if [ -f "$candidate/main.go" ] || [ -x "$candidate/ksync" ]; then
|
||||
ksync_dir=$(cd "$candidate" 2>/dev/null && pwd)
|
||||
break
|
||||
fi
|
||||
search_dir=$(dirname "$search_dir")
|
||||
done
|
||||
fi
|
||||
if [ -z "$ksync_dir" ]; then
|
||||
script_dir=$(cd "$(dirname "$0" 2>/dev/null || printf '.')" 2>/dev/null && pwd)
|
||||
candidate=$script_dir/../ksync
|
||||
if [ -f "$candidate/main.go" ] || [ -x "$candidate/ksync" ]; then
|
||||
ksync_dir=$(cd "$candidate" 2>/dev/null && pwd)
|
||||
fi
|
||||
fi
|
||||
if [ -z "$ksync_dir" ] || { [ ! -f "$ksync_dir/main.go" ] && [ ! -x "$ksync_dir/ksync" ]; }; then
|
||||
die "could not find the Ksync server source.
|
||||
Set KSYNC_DIR to its checkout path (e.g. export KSYNC_DIR=/home/wao/src/ksync),
|
||||
or place it as a sibling of a parent directory (../ksync)."
|
||||
fi
|
||||
# Per-project data dir. SQLite needs a native filesystem: shared/virtual
|
||||
# mounts (9p, etc.) fail its WAL/locking with "disk I/O error". Default to
|
||||
# a runtime cache dir on tmpfs, keyed by project so concurrent projects
|
||||
# don't collide; let KSYNC_DB override for users who want it elsewhere.
|
||||
project_tag=$(pwd | cksum | awk '{print $1}')
|
||||
dev_root=${XDG_CACHE_HOME:-${TMPDIR:-/tmp}}/kryon-dev-backend
|
||||
mkdir -p "$dev_root"
|
||||
dev_db=${KSYNC_DB:-$dev_root/ksync-$project_tag.db}
|
||||
dev_addr=${KSYNC_ADDR:-127.0.0.1:8080}
|
||||
printf '== kryon dev-backend ==\n'
|
||||
printf 'server: %s\n' "$ksync_dir"
|
||||
printf 'data: %s\n' "$dev_db"
|
||||
printf 'listen: http://%s\n' "$dev_addr"
|
||||
printf '\nPoint your app at this URL, e.g. by setting the sync base URL\n'
|
||||
printf 'to http://%s before calling RunKsyncSync/RequestKsyncSyncBearer.\n' "$dev_addr"
|
||||
printf '(Tokens are ephemeral; they reset on each restart.)\n\n'
|
||||
export KSYNC_ADDR=$dev_addr
|
||||
export KSYNC_BASE_URL=http://$dev_addr
|
||||
export KSYNC_DB=$dev_db
|
||||
export KSYNC_ALLOW_EPHEMERAL_TOKEN_SECRET=1
|
||||
if [ -x "$ksync_dir/ksync" ]; then
|
||||
exec "$ksync_dir/ksync"
|
||||
fi
|
||||
if ! command -v go >/dev/null 2>&1; then
|
||||
die "found Ksync source at $ksync_dir but 'go' is not on PATH.
|
||||
Install Go, or build the server once with 'make build' in $ksync_dir."
|
||||
fi
|
||||
printf '(building + running via "go run ."; first run compiles liboqs)\n\n'
|
||||
make_cmd=${MAKE:-make}
|
||||
"$make_cmd" -C "$ksync_dir" run
|
||||
;;
|
||||
clean)
|
||||
case "$target" in
|
||||
""|all)
|
||||
|
||||
@@ -3,7 +3,7 @@ set -eu
|
||||
|
||||
usage() {
|
||||
echo "Usage: $0 <module-name> [--apply]"
|
||||
echo "Example: $0 lyra --apply"
|
||||
echo "Example: $0 ksync --apply"
|
||||
exit 1
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ if [ "${2:-}" = "--apply" ]; then APPLY=1; fi
|
||||
SRC_DIR=src
|
||||
TARGET_DIR=$SRC_DIR/$MODULE
|
||||
|
||||
# gather candidate files: src/lyra_*.c and src/lyra_*.h
|
||||
# gather candidate files: src/ksync_*.c and src/ksync_*.h
|
||||
candidates=$(find "$SRC_DIR" -maxdepth 1 -type f \( -name "${MODULE}_*.[ch]" -o -name "${MODULE}*.c" -o -name "${MODULE}*.h" \) | sort)
|
||||
|
||||
if [ -z "$candidates" ]; then
|
||||
|
||||
Executable
+98
@@ -0,0 +1,98 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
usage()
|
||||
{
|
||||
cat >&2 <<EOF
|
||||
usage: subset-fonts.sh OUT_DIR SOURCE_FONT_DIR NAME_PREFIX CORPUS...
|
||||
|
||||
Create app-sized subsets of Kryon's bundled Noto fonts.
|
||||
|
||||
OUT_DIR directory for generated font files
|
||||
SOURCE_FONT_DIR directory containing NotoSans*.ttf/otf sources
|
||||
NAME_PREFIX app/product name inserted into output filenames
|
||||
CORPUS files or directories with text to keep in the subsets
|
||||
EOF
|
||||
exit 2
|
||||
}
|
||||
|
||||
if [ "$#" -lt 4 ]; then
|
||||
usage
|
||||
fi
|
||||
|
||||
out_dir=$1
|
||||
source_dir=$2
|
||||
name_prefix=$3
|
||||
shift 3
|
||||
|
||||
pyftsubset=${PYFTSUBSET:-pyftsubset}
|
||||
command -v "$pyftsubset" >/dev/null 2>&1 || {
|
||||
echo "pyftsubset is required. Install fonttools or set PYFTSUBSET." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
tmp=${TMPDIR:-/tmp}/kryon-font-corpus.$$
|
||||
cleanup()
|
||||
{
|
||||
rm -f "$tmp"
|
||||
}
|
||||
trap cleanup EXIT INT HUP TERM
|
||||
|
||||
mkdir -p "$out_dir"
|
||||
: > "$tmp"
|
||||
|
||||
append_corpus()
|
||||
{
|
||||
path=$1
|
||||
|
||||
if [ -f "$path" ]; then
|
||||
cat "$path" >> "$tmp"
|
||||
printf '\n' >> "$tmp"
|
||||
elif [ -d "$path" ]; then
|
||||
find "$path" -type f | LC_ALL=C sort | while IFS= read -r file; do
|
||||
cat "$file" >> "$tmp"
|
||||
printf '\n' >> "$tmp"
|
||||
done
|
||||
else
|
||||
echo "Missing font corpus input: $path" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
for corpus in "$@"; do
|
||||
append_corpus "$corpus"
|
||||
done
|
||||
|
||||
subset_font()
|
||||
{
|
||||
src=$1
|
||||
out=$2
|
||||
|
||||
if [ ! -f "$src" ]; then
|
||||
echo "Missing source font: $src" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
"$pyftsubset" "$src" \
|
||||
--output-file="$out" \
|
||||
--text-file="$tmp" \
|
||||
--layout-features='*' \
|
||||
--glyph-names \
|
||||
--symbol-cmap \
|
||||
--legacy-cmap \
|
||||
--notdef-glyph \
|
||||
--notdef-outline \
|
||||
--recommended-glyphs \
|
||||
--name-IDs='*' \
|
||||
--name-legacy \
|
||||
--name-languages='*' \
|
||||
--no-hinting
|
||||
}
|
||||
|
||||
subset_font "$source_dir/NotoSans-Regular.ttf" "$out_dir/NotoSans-${name_prefix}-Regular.ttf"
|
||||
subset_font "$source_dir/NotoSansSC-Regular.otf" "$out_dir/NotoSansSC-${name_prefix}-Regular.otf"
|
||||
subset_font "$source_dir/NotoSansJP-Regular.otf" "$out_dir/NotoSansJP-${name_prefix}-Regular.otf"
|
||||
subset_font "$source_dir/NotoSansKR-Regular.otf" "$out_dir/NotoSansKR-${name_prefix}-Regular.otf"
|
||||
subset_font "$source_dir/NotoSansTC-Regular.otf" "$out_dir/NotoSansTC-${name_prefix}-Regular.otf"
|
||||
|
||||
ls -lh "$out_dir"/NotoSans*"${name_prefix}"-Regular.*
|
||||
@@ -1,7 +1,7 @@
|
||||
#include "lyra_account.h"
|
||||
#include "ksync_account.h"
|
||||
|
||||
#if !defined(HAS_LIBOQS)
|
||||
#error "Kryon Lyra accounts require HAS_LIBOQS; build and link liboqs instead of disabling account crypto"
|
||||
#error "Kryon Ksync accounts require HAS_LIBOQS; build and link liboqs instead of disabling account crypto"
|
||||
#endif
|
||||
|
||||
#include <oqs/oqs.h>
|
||||
@@ -11,16 +11,16 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define LYRA_ACCOUNT_KEY_HEADER "lyra-account-key-v1"
|
||||
#define LYRA_LEGACY_UKU_KEY_HEADER "account-key-v1"
|
||||
#define LYRA_LEGACY_INBE_KEY_HEADER "inbe-sync-key-v1"
|
||||
#define KSYNC_ACCOUNT_KEY_HEADER "ksync-account-key-v1"
|
||||
#define KSYNC_LEGACY_UKU_KEY_HEADER "account-key-v1"
|
||||
#define KSYNC_LEGACY_INBE_KEY_HEADER "inbe-sync-key-v1"
|
||||
|
||||
typedef struct LyraSha256Ctx {
|
||||
typedef struct KsyncSha256Ctx {
|
||||
uint32_t state[8];
|
||||
uint64_t bit_len;
|
||||
uint8_t data[64];
|
||||
size_t data_len;
|
||||
} LyraSha256Ctx;
|
||||
} KsyncSha256Ctx;
|
||||
|
||||
static const uint32_t sha256_k[64] = {
|
||||
0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U, 0x3956c25bU, 0x59f111f1U,
|
||||
@@ -43,7 +43,7 @@ rotr32(uint32_t value, uint32_t bits)
|
||||
}
|
||||
|
||||
static void
|
||||
sha256_transform(LyraSha256Ctx *ctx, const uint8_t data[64])
|
||||
sha256_transform(KsyncSha256Ctx *ctx, const uint8_t data[64])
|
||||
{
|
||||
uint32_t m[64];
|
||||
uint32_t a, b, c, d, e, f, g, h;
|
||||
@@ -97,7 +97,7 @@ sha256_transform(LyraSha256Ctx *ctx, const uint8_t data[64])
|
||||
}
|
||||
|
||||
static void
|
||||
sha256_init(LyraSha256Ctx *ctx)
|
||||
sha256_init(KsyncSha256Ctx *ctx)
|
||||
{
|
||||
memset(ctx, 0, sizeof(*ctx));
|
||||
ctx->state[0] = 0x6a09e667U;
|
||||
@@ -111,7 +111,7 @@ sha256_init(LyraSha256Ctx *ctx)
|
||||
}
|
||||
|
||||
static void
|
||||
sha256_update(LyraSha256Ctx *ctx, const uint8_t *data, size_t len)
|
||||
sha256_update(KsyncSha256Ctx *ctx, const uint8_t *data, size_t len)
|
||||
{
|
||||
for(size_t i = 0; i < len; i++) {
|
||||
ctx->data[ctx->data_len++] = data[i];
|
||||
@@ -124,7 +124,7 @@ sha256_update(LyraSha256Ctx *ctx, const uint8_t *data, size_t len)
|
||||
}
|
||||
|
||||
static void
|
||||
sha256_final(LyraSha256Ctx *ctx, uint8_t hash[32])
|
||||
sha256_final(KsyncSha256Ctx *ctx, uint8_t hash[32])
|
||||
{
|
||||
size_t i = ctx->data_len;
|
||||
|
||||
@@ -215,7 +215,7 @@ copy_key_value(char *out, size_t out_size, const char *value, size_t value_len)
|
||||
}
|
||||
|
||||
static void
|
||||
parse_account_line(LyraAccount *account, const char *line, size_t line_len)
|
||||
parse_account_line(KsyncAccount *account, const char *line, size_t line_len)
|
||||
{
|
||||
if(account == NULL || line == NULL)
|
||||
return;
|
||||
@@ -324,10 +324,10 @@ read_file_text(const char *filename)
|
||||
}
|
||||
|
||||
void
|
||||
LyraSha256Hex(const uint8_t *data, size_t len, char out_hex[LYRA_PUBLIC_ID_HEX_SIZE])
|
||||
KsyncSha256Hex(const uint8_t *data, size_t len, char out_hex[KSYNC_PUBLIC_ID_HEX_SIZE])
|
||||
{
|
||||
uint8_t digest[32];
|
||||
LyraSha256Ctx sha;
|
||||
KsyncSha256Ctx sha;
|
||||
|
||||
if(out_hex == NULL)
|
||||
return;
|
||||
@@ -337,27 +337,27 @@ LyraSha256Hex(const uint8_t *data, size_t len, char out_hex[LYRA_PUBLIC_ID_HEX_S
|
||||
sha256_init(&sha);
|
||||
sha256_update(&sha, data, len);
|
||||
sha256_final(&sha, digest);
|
||||
bytes_to_hex(digest, sizeof(digest), out_hex, LYRA_PUBLIC_ID_HEX_SIZE);
|
||||
bytes_to_hex(digest, sizeof(digest), out_hex, KSYNC_PUBLIC_ID_HEX_SIZE);
|
||||
}
|
||||
|
||||
int
|
||||
IsLyraAccountAvailable(void)
|
||||
IsKsyncAccountAvailable(void)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
int
|
||||
HasLyraAccountValues(const LyraAccount *account)
|
||||
HasKsyncAccountValues(const KsyncAccount *account)
|
||||
{
|
||||
return account != NULL && account->public_id[0] != '\0' &&
|
||||
account->public_key_hex[0] != '\0' && account->private_key_hex[0] != '\0';
|
||||
}
|
||||
|
||||
int
|
||||
ValidateLyraAccount(LyraAccount *account)
|
||||
ValidateKsyncAccount(KsyncAccount *account)
|
||||
{
|
||||
uint8_t public_key[1312];
|
||||
char expected_public_id[LYRA_PUBLIC_ID_HEX_SIZE];
|
||||
char expected_public_id[KSYNC_PUBLIC_ID_HEX_SIZE];
|
||||
|
||||
if(account == NULL)
|
||||
return 0;
|
||||
@@ -366,7 +366,7 @@ ValidateLyraAccount(LyraAccount *account)
|
||||
return 0;
|
||||
if(!hex_to_bytes(account->public_key_hex, public_key, sizeof(public_key)))
|
||||
return 0;
|
||||
LyraSha256Hex(public_key, sizeof(public_key), expected_public_id);
|
||||
KsyncSha256Hex(public_key, sizeof(public_key), expected_public_id);
|
||||
if(account->public_id[0] == '\0') {
|
||||
snprintf(account->public_id, sizeof(account->public_id), "%s", expected_public_id);
|
||||
return 1;
|
||||
@@ -377,11 +377,11 @@ ValidateLyraAccount(LyraAccount *account)
|
||||
}
|
||||
|
||||
int
|
||||
ParseLyraAccountText(const char *text, LyraAccount *account)
|
||||
ParseKsyncAccountText(const char *text, KsyncAccount *account)
|
||||
{
|
||||
const char *line;
|
||||
const char *next;
|
||||
char exported_key[LYRA_ACCOUNT_EXPORT_TEXT_SIZE];
|
||||
char exported_key[KSYNC_ACCOUNT_EXPORT_TEXT_SIZE];
|
||||
|
||||
if(text == NULL || account == NULL)
|
||||
return 0;
|
||||
@@ -402,46 +402,46 @@ ParseLyraAccountText(const char *text, LyraAccount *account)
|
||||
parse_account_line(account, line, (size_t)(next - line));
|
||||
line = next + 1;
|
||||
}
|
||||
return ValidateLyraAccount(account);
|
||||
return ValidateKsyncAccount(account);
|
||||
}
|
||||
|
||||
int
|
||||
ExportLyraAccountText(const LyraAccount *account, char *out, size_t out_size)
|
||||
ExportKsyncAccountText(const KsyncAccount *account, char *out, size_t out_size)
|
||||
{
|
||||
int len;
|
||||
|
||||
if(!HasLyraAccountValues(account) || out == NULL || out_size == 0)
|
||||
if(!HasKsyncAccountValues(account) || out == NULL || out_size == 0)
|
||||
return 0;
|
||||
len = snprintf(out, out_size,
|
||||
LYRA_ACCOUNT_KEY_HEADER
|
||||
KSYNC_ACCOUNT_KEY_HEADER
|
||||
"\nalgorithm=ML-DSA-44\npublic_id=%s\npublic_key=%s\nprivate_key=%s\n",
|
||||
account->public_id, account->public_key_hex, account->private_key_hex);
|
||||
return len > 0 && (size_t)len < out_size;
|
||||
}
|
||||
|
||||
int
|
||||
ImportLyraAccountFile(const char *filename, LyraAccount *account)
|
||||
ImportKsyncAccountFile(const char *filename, KsyncAccount *account)
|
||||
{
|
||||
char *body = read_file_text(filename);
|
||||
int ok;
|
||||
|
||||
if(body == NULL)
|
||||
return 0;
|
||||
ok = ParseLyraAccountText(body, account);
|
||||
ok = ParseKsyncAccountText(body, account);
|
||||
free(body);
|
||||
return ok;
|
||||
}
|
||||
|
||||
int
|
||||
ExportLyraAccountFile(const LyraAccount *account, const char *filename)
|
||||
ExportKsyncAccountFile(const KsyncAccount *account, const char *filename)
|
||||
{
|
||||
char body[LYRA_ACCOUNT_EXPORT_TEXT_SIZE];
|
||||
char body[KSYNC_ACCOUNT_EXPORT_TEXT_SIZE];
|
||||
FILE *file;
|
||||
size_t len;
|
||||
int ok;
|
||||
|
||||
if(filename == NULL || filename[0] == '\0' ||
|
||||
!ExportLyraAccountText(account, body, sizeof(body)))
|
||||
!ExportKsyncAccountText(account, body, sizeof(body)))
|
||||
return 0;
|
||||
file = fopen(filename, "wb");
|
||||
if(file == NULL)
|
||||
@@ -454,12 +454,12 @@ ExportLyraAccountFile(const LyraAccount *account, const char *filename)
|
||||
}
|
||||
|
||||
int
|
||||
CreateLyraAccount(LyraAccount *account)
|
||||
CreateKsyncAccount(KsyncAccount *account)
|
||||
{
|
||||
OQS_SIG *sig;
|
||||
uint8_t public_key[1312];
|
||||
uint8_t private_key[2560];
|
||||
LyraAccount generated;
|
||||
KsyncAccount generated;
|
||||
|
||||
if(account == NULL)
|
||||
return 0;
|
||||
@@ -477,7 +477,7 @@ CreateLyraAccount(LyraAccount *account)
|
||||
}
|
||||
OQS_SIG_free(sig);
|
||||
|
||||
LyraSha256Hex(public_key, sizeof(public_key), generated.public_id);
|
||||
KsyncSha256Hex(public_key, sizeof(public_key), generated.public_id);
|
||||
bytes_to_hex(public_key, sizeof(public_key), generated.public_key_hex,
|
||||
sizeof(generated.public_key_hex));
|
||||
bytes_to_hex(private_key, sizeof(private_key), generated.private_key_hex,
|
||||
@@ -487,7 +487,7 @@ CreateLyraAccount(LyraAccount *account)
|
||||
}
|
||||
|
||||
int
|
||||
SignLyraAccountHex(const LyraAccount *account, const uint8_t *message,
|
||||
SignKsyncAccountHex(const KsyncAccount *account, const uint8_t *message,
|
||||
size_t message_len, char *out_signature_hex, size_t out_size)
|
||||
{
|
||||
OQS_SIG *sig;
|
||||
@@ -495,7 +495,7 @@ SignLyraAccountHex(const LyraAccount *account, const uint8_t *message,
|
||||
uint8_t signature[2420];
|
||||
size_t signature_len = 0;
|
||||
|
||||
if(!HasLyraAccountValues(account) || out_signature_hex == NULL ||
|
||||
if(!HasKsyncAccountValues(account) || out_signature_hex == NULL ||
|
||||
out_size < sizeof(signature) * 2 + 1 || (message == NULL && message_len > 0))
|
||||
return 0;
|
||||
out_signature_hex[0] = '\0';
|
||||
@@ -1,39 +1,39 @@
|
||||
#include "lyra_sync.h"
|
||||
#include "ksync_sync.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
#define LYRA_SYNC_PATH "/api/v1/sync"
|
||||
#define LYRA_CHALLENGE_PATH "/api/v1/sync/challenge"
|
||||
#define LYRA_LOGIN_PATH "/api/v1/sync/login"
|
||||
#define LYRA_ACCOUNT_DELETE_WITH_KEY_PATH "/api/v1/account/delete-with-key"
|
||||
#define LYRA_SYNC_AUTH_TOKEN_KEY "sync_auth_token"
|
||||
#define LYRA_SYNC_AUTH_TOKEN_EXPIRES_KEY "sync_auth_token_expires_at"
|
||||
#define LYRA_SYNC_SIGNATURE_CONTEXT "lyra-sync-v1"
|
||||
#define LYRA_SYNC_USER_HEADER "X-Lyra-User"
|
||||
#define LYRA_SYNC_SIGNATURE_HEADER "X-Lyra-Signature"
|
||||
#define KSYNC_SYNC_PATH "/api/v1/sync"
|
||||
#define KSYNC_CHALLENGE_PATH "/api/v1/sync/challenge"
|
||||
#define KSYNC_LOGIN_PATH "/api/v1/sync/login"
|
||||
#define KSYNC_ACCOUNT_DELETE_WITH_KEY_PATH "/api/v1/account/delete-with-key"
|
||||
#define KSYNC_SYNC_AUTH_TOKEN_KEY "sync_auth_token"
|
||||
#define KSYNC_SYNC_AUTH_TOKEN_EXPIRES_KEY "sync_auth_token_expires_at"
|
||||
#define KSYNC_SYNC_SIGNATURE_CONTEXT "ksync-sync-v1"
|
||||
#define KSYNC_SYNC_USER_HEADER "X-Ksync-User"
|
||||
#define KSYNC_SYNC_SIGNATURE_HEADER "X-Ksync-Signature"
|
||||
|
||||
const char *
|
||||
GetLyraSyncResultName(LyraSyncResult result)
|
||||
GetKsyncSyncResultName(KsyncSyncResult result)
|
||||
{
|
||||
switch(result) {
|
||||
case LYRA_SYNC_OK:
|
||||
case KSYNC_SYNC_OK:
|
||||
return "ok";
|
||||
case LYRA_SYNC_INVALID_URL:
|
||||
case KSYNC_SYNC_INVALID_URL:
|
||||
return "invalid_url";
|
||||
case LYRA_SYNC_NO_ACCOUNT:
|
||||
case KSYNC_SYNC_NO_ACCOUNT:
|
||||
return "no_account";
|
||||
case LYRA_SYNC_PAYLOAD_FAILED:
|
||||
case KSYNC_SYNC_PAYLOAD_FAILED:
|
||||
return "payload_failed";
|
||||
case LYRA_SYNC_CHALLENGE_FAILED:
|
||||
case KSYNC_SYNC_CHALLENGE_FAILED:
|
||||
return "challenge_failed";
|
||||
case LYRA_SYNC_SIGN_FAILED:
|
||||
case KSYNC_SYNC_SIGN_FAILED:
|
||||
return "sign_failed";
|
||||
case LYRA_SYNC_REQUEST_FAILED:
|
||||
case KSYNC_SYNC_REQUEST_FAILED:
|
||||
return "request_failed";
|
||||
case LYRA_SYNC_AUTH_FAILED:
|
||||
case KSYNC_SYNC_AUTH_FAILED:
|
||||
return "auth_failed";
|
||||
default:
|
||||
return "unknown";
|
||||
@@ -70,7 +70,7 @@ sync_loopback_authority_valid(const char *authority)
|
||||
}
|
||||
|
||||
int
|
||||
IsLyraSyncURLValid(const char *url)
|
||||
IsKsyncSyncURLValid(const char *url)
|
||||
{
|
||||
if(url == NULL || url[0] == '\0')
|
||||
return 0;
|
||||
@@ -82,14 +82,14 @@ IsLyraSyncURLValid(const char *url)
|
||||
}
|
||||
|
||||
int
|
||||
NormalizeLyraSyncURL(const char *input, char *out, size_t out_size)
|
||||
NormalizeKsyncSyncURL(const char *input, char *out, size_t out_size)
|
||||
{
|
||||
int len;
|
||||
|
||||
if(out == NULL || out_size == 0)
|
||||
return 0;
|
||||
out[0] = '\0';
|
||||
if(!IsLyraSyncURLValid(input))
|
||||
if(!IsKsyncSyncURLValid(input))
|
||||
return 0;
|
||||
if(sync_has_prefix(input, "https://") || sync_has_prefix(input, "http://"))
|
||||
len = snprintf(out, out_size, "%s", input);
|
||||
@@ -99,7 +99,7 @@ NormalizeLyraSyncURL(const char *input, char *out, size_t out_size)
|
||||
}
|
||||
|
||||
int
|
||||
JoinLyraSyncURL(char *out, size_t out_size, const char *base_url, const char *path)
|
||||
JoinKsyncSyncURL(char *out, size_t out_size, const char *base_url, const char *path)
|
||||
{
|
||||
size_t len;
|
||||
int written;
|
||||
@@ -117,7 +117,7 @@ JoinLyraSyncURL(char *out, size_t out_size, const char *base_url, const char *pa
|
||||
}
|
||||
|
||||
int
|
||||
JoinLyraSyncWebSocketURL(char *out, size_t out_size, const char *base_url, const char *path)
|
||||
JoinKsyncSyncWebSocketURL(char *out, size_t out_size, const char *base_url, const char *path)
|
||||
{
|
||||
char http_url[768];
|
||||
const char *body;
|
||||
@@ -127,7 +127,7 @@ JoinLyraSyncWebSocketURL(char *out, size_t out_size, const char *base_url, const
|
||||
if(out == NULL || out_size == 0)
|
||||
return 0;
|
||||
out[0] = '\0';
|
||||
if(!JoinLyraSyncURL(http_url, sizeof(http_url), base_url, path))
|
||||
if(!JoinKsyncSyncURL(http_url, sizeof(http_url), base_url, path))
|
||||
return 0;
|
||||
if(sync_has_prefix(http_url, "https://")) {
|
||||
scheme = "wss://";
|
||||
@@ -143,7 +143,7 @@ JoinLyraSyncWebSocketURL(char *out, size_t out_size, const char *base_url, const
|
||||
}
|
||||
|
||||
int
|
||||
AppendLyraSyncBuffer(LyraSyncBuffer *buffer, const void *data, size_t bytes)
|
||||
AppendKsyncSyncBuffer(KsyncSyncBuffer *buffer, const void *data, size_t bytes)
|
||||
{
|
||||
char *next;
|
||||
size_t next_cap;
|
||||
@@ -167,11 +167,11 @@ AppendLyraSyncBuffer(LyraSyncBuffer *buffer, const void *data, size_t bytes)
|
||||
}
|
||||
|
||||
int
|
||||
AppendLyraSyncBufferJSONString(LyraSyncBuffer *buffer, const char *text)
|
||||
AppendKsyncSyncBufferJSONString(KsyncSyncBuffer *buffer, const char *text)
|
||||
{
|
||||
const char *p;
|
||||
|
||||
if(!AppendLyraSyncBuffer(buffer, "\"", 1))
|
||||
if(!AppendKsyncSyncBuffer(buffer, "\"", 1))
|
||||
return 0;
|
||||
if(text == NULL)
|
||||
text = "";
|
||||
@@ -179,38 +179,38 @@ AppendLyraSyncBufferJSONString(LyraSyncBuffer *buffer, const char *text)
|
||||
char escaped[2];
|
||||
switch(*p) {
|
||||
case '\\':
|
||||
if(!AppendLyraSyncBuffer(buffer, "\\\\", 2))
|
||||
if(!AppendKsyncSyncBuffer(buffer, "\\\\", 2))
|
||||
return 0;
|
||||
break;
|
||||
case '"':
|
||||
if(!AppendLyraSyncBuffer(buffer, "\\\"", 2))
|
||||
if(!AppendKsyncSyncBuffer(buffer, "\\\"", 2))
|
||||
return 0;
|
||||
break;
|
||||
case '\n':
|
||||
if(!AppendLyraSyncBuffer(buffer, "\\n", 2))
|
||||
if(!AppendKsyncSyncBuffer(buffer, "\\n", 2))
|
||||
return 0;
|
||||
break;
|
||||
case '\r':
|
||||
if(!AppendLyraSyncBuffer(buffer, "\\r", 2))
|
||||
if(!AppendKsyncSyncBuffer(buffer, "\\r", 2))
|
||||
return 0;
|
||||
break;
|
||||
case '\t':
|
||||
if(!AppendLyraSyncBuffer(buffer, "\\t", 2))
|
||||
if(!AppendKsyncSyncBuffer(buffer, "\\t", 2))
|
||||
return 0;
|
||||
break;
|
||||
default:
|
||||
escaped[0] = *p;
|
||||
escaped[1] = '\0';
|
||||
if(!AppendLyraSyncBuffer(buffer, escaped, 1))
|
||||
if(!AppendKsyncSyncBuffer(buffer, escaped, 1))
|
||||
return 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return AppendLyraSyncBuffer(buffer, "\"", 1);
|
||||
return AppendKsyncSyncBuffer(buffer, "\"", 1);
|
||||
}
|
||||
|
||||
void
|
||||
FreeLyraSyncBuffer(LyraSyncBuffer *buffer)
|
||||
FreeKsyncSyncBuffer(KsyncSyncBuffer *buffer)
|
||||
{
|
||||
if(buffer == NULL)
|
||||
return;
|
||||
@@ -219,7 +219,7 @@ FreeLyraSyncBuffer(LyraSyncBuffer *buffer)
|
||||
}
|
||||
|
||||
int
|
||||
FindLyraSyncJSONString(const char *json, const char *key, char *out, size_t out_size)
|
||||
FindKsyncSyncJSONString(const char *json, const char *key, char *out, size_t out_size)
|
||||
{
|
||||
char pattern[64];
|
||||
const char *p;
|
||||
@@ -255,7 +255,7 @@ FindLyraSyncJSONString(const char *json, const char *key, char *out, size_t out_
|
||||
}
|
||||
|
||||
long long
|
||||
FindLyraSyncJSONInt64(const char *json, const char *key, long long fallback)
|
||||
FindKsyncSyncJSONInt64(const char *json, const char *key, long long fallback)
|
||||
{
|
||||
const char *p;
|
||||
char pattern[64];
|
||||
@@ -276,7 +276,7 @@ FindLyraSyncJSONInt64(const char *json, const char *key, long long fallback)
|
||||
}
|
||||
|
||||
static int
|
||||
sync_config_valid(const LyraSyncConfig *cfg)
|
||||
sync_config_valid(const KsyncSyncConfig *cfg)
|
||||
{
|
||||
return cfg != NULL && cfg->base_url != NULL && cfg->account != NULL &&
|
||||
cfg->client_id != NULL && cfg->http_request != NULL &&
|
||||
@@ -284,7 +284,7 @@ sync_config_valid(const LyraSyncConfig *cfg)
|
||||
}
|
||||
|
||||
static void
|
||||
sync_log_http_failure(const LyraSyncConfig *cfg, const char *step,
|
||||
sync_log_http_failure(const KsyncSyncConfig *cfg, const char *step,
|
||||
long status, const char *response)
|
||||
{
|
||||
if(cfg != NULL && cfg->log_http_failure != NULL)
|
||||
@@ -292,7 +292,7 @@ sync_log_http_failure(const LyraSyncConfig *cfg, const char *step,
|
||||
}
|
||||
|
||||
static int
|
||||
sync_build_message(const LyraSyncConfig *cfg, const char *method, const char *path,
|
||||
sync_build_message(const KsyncSyncConfig *cfg, const char *method, const char *path,
|
||||
const char *nonce_hex, const char *body, char *out,
|
||||
size_t out_size)
|
||||
{
|
||||
@@ -303,37 +303,37 @@ sync_build_message(const LyraSyncConfig *cfg, const char *method, const char *pa
|
||||
if(cfg == NULL || method == NULL || path == NULL || nonce_hex == NULL ||
|
||||
body == NULL || out == NULL || out_size == 0)
|
||||
return 0;
|
||||
LyraSha256Hex((const uint8_t *)body, strlen(body), body_hash);
|
||||
KsyncSha256Hex((const uint8_t *)body, strlen(body), body_hash);
|
||||
if(body_hash[0] == '\0')
|
||||
return 0;
|
||||
context = cfg->signature_context != NULL && cfg->signature_context[0] != '\0'
|
||||
? cfg->signature_context
|
||||
: LYRA_SYNC_SIGNATURE_CONTEXT;
|
||||
: KSYNC_SYNC_SIGNATURE_CONTEXT;
|
||||
len = snprintf(out, out_size, "%s\n%s\n%s\n%s\n%s\n", context, method,
|
||||
path, body_hash, nonce_hex);
|
||||
return len > 0 && (size_t)len < out_size;
|
||||
}
|
||||
|
||||
static const char *
|
||||
sync_user_header_name(const LyraSyncConfig *cfg)
|
||||
sync_user_header_name(const KsyncSyncConfig *cfg)
|
||||
{
|
||||
return cfg != NULL && cfg->user_header_name != NULL &&
|
||||
cfg->user_header_name[0] != '\0'
|
||||
? cfg->user_header_name
|
||||
: LYRA_SYNC_USER_HEADER;
|
||||
: KSYNC_SYNC_USER_HEADER;
|
||||
}
|
||||
|
||||
static const char *
|
||||
sync_signature_header_name(const LyraSyncConfig *cfg)
|
||||
sync_signature_header_name(const KsyncSyncConfig *cfg)
|
||||
{
|
||||
return cfg != NULL && cfg->signature_header_name != NULL &&
|
||||
cfg->signature_header_name[0] != '\0'
|
||||
? cfg->signature_header_name
|
||||
: LYRA_SYNC_SIGNATURE_HEADER;
|
||||
: KSYNC_SYNC_SIGNATURE_HEADER;
|
||||
}
|
||||
|
||||
static int
|
||||
sync_load_valid_auth_token(const LyraSyncConfig *cfg, char *out, size_t out_size)
|
||||
sync_load_valid_auth_token(const KsyncSyncConfig *cfg, char *out, size_t out_size)
|
||||
{
|
||||
const char *token;
|
||||
const char *expires_text;
|
||||
@@ -343,9 +343,9 @@ sync_load_valid_auth_token(const LyraSyncConfig *cfg, char *out, size_t out_size
|
||||
if(!sync_config_valid(cfg) || out == NULL || out_size == 0)
|
||||
return 0;
|
||||
out[0] = '\0';
|
||||
token = cfg->get_text(LYRA_SYNC_AUTH_TOKEN_KEY, cfg->user);
|
||||
token = cfg->get_text(KSYNC_SYNC_AUTH_TOKEN_KEY, cfg->user);
|
||||
snprintf(token_copy, sizeof(token_copy), "%s", token != NULL ? token : "");
|
||||
expires_text = cfg->get_text(LYRA_SYNC_AUTH_TOKEN_EXPIRES_KEY, cfg->user);
|
||||
expires_text = cfg->get_text(KSYNC_SYNC_AUTH_TOKEN_EXPIRES_KEY, cfg->user);
|
||||
expires_at = expires_text != NULL ? atoll(expires_text) : 0;
|
||||
if(token_copy[0] == '\0' || expires_at <= (long long)time(NULL))
|
||||
return 0;
|
||||
@@ -354,91 +354,91 @@ sync_load_valid_auth_token(const LyraSyncConfig *cfg, char *out, size_t out_size
|
||||
}
|
||||
|
||||
void
|
||||
ClearLyraSyncAuthToken(const LyraSyncConfig *cfg)
|
||||
ClearKsyncSyncAuthToken(const KsyncSyncConfig *cfg)
|
||||
{
|
||||
if(!sync_config_valid(cfg))
|
||||
return;
|
||||
cfg->set_text(LYRA_SYNC_AUTH_TOKEN_KEY, "", cfg->user);
|
||||
cfg->set_text(LYRA_SYNC_AUTH_TOKEN_EXPIRES_KEY, "", cfg->user);
|
||||
cfg->set_text(KSYNC_SYNC_AUTH_TOKEN_KEY, "", cfg->user);
|
||||
cfg->set_text(KSYNC_SYNC_AUTH_TOKEN_EXPIRES_KEY, "", cfg->user);
|
||||
}
|
||||
|
||||
static LyraSyncResult
|
||||
sync_fetch_challenge(const LyraSyncConfig *cfg, const char *user_id,
|
||||
static KsyncSyncResult
|
||||
sync_fetch_challenge(const KsyncSyncConfig *cfg, const char *user_id,
|
||||
char nonce_hex[65])
|
||||
{
|
||||
char url[768];
|
||||
LyraSyncBuffer response = {0};
|
||||
KsyncSyncBuffer response = {0};
|
||||
long status = 0;
|
||||
int ok;
|
||||
|
||||
nonce_hex[0] = '\0';
|
||||
if(!JoinLyraSyncURL(url, sizeof(url), cfg->base_url,
|
||||
LYRA_CHALLENGE_PATH))
|
||||
return LYRA_SYNC_INVALID_URL;
|
||||
if(!JoinKsyncSyncURL(url, sizeof(url), cfg->base_url,
|
||||
KSYNC_CHALLENGE_PATH))
|
||||
return KSYNC_SYNC_INVALID_URL;
|
||||
if(strlen(url) + strlen(user_id) + 10 >= sizeof(url))
|
||||
return LYRA_SYNC_INVALID_URL;
|
||||
return KSYNC_SYNC_INVALID_URL;
|
||||
strncat(url, "?user_id=", sizeof(url) - strlen(url) - 1);
|
||||
strncat(url, user_id, sizeof(url) - strlen(url) - 1);
|
||||
ok = cfg->http_request("GET", url, NULL, NULL, 0, &response, &status, cfg->user);
|
||||
if(!ok || status != 200 ||
|
||||
!FindLyraSyncJSONString(response.data, "nonce", nonce_hex, 65) ||
|
||||
!FindKsyncSyncJSONString(response.data, "nonce", nonce_hex, 65) ||
|
||||
strlen(nonce_hex) != 64) {
|
||||
sync_log_http_failure(cfg, "challenge", status, response.data);
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return status == 401 ? LYRA_SYNC_AUTH_FAILED : LYRA_SYNC_CHALLENGE_FAILED;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return status == 401 ? KSYNC_SYNC_AUTH_FAILED : KSYNC_SYNC_CHALLENGE_FAILED;
|
||||
}
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_OK;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_OK;
|
||||
}
|
||||
|
||||
LyraSyncResult
|
||||
LoginLyraSync(const LyraSyncConfig *cfg)
|
||||
KsyncSyncResult
|
||||
LoginKsyncSync(const KsyncSyncConfig *cfg)
|
||||
{
|
||||
char nonce_hex[65];
|
||||
char message[256];
|
||||
char signature_hex[LYRA_SIGNATURE_HEX_SIZE];
|
||||
char signature_hex[KSYNC_SIGNATURE_HEX_SIZE];
|
||||
char url[768];
|
||||
char user_header[96];
|
||||
char signature_header[LYRA_SIGNATURE_HEX_SIZE + 32];
|
||||
char signature_header[KSYNC_SIGNATURE_HEX_SIZE + 32];
|
||||
const char *headers[3];
|
||||
LyraSyncBuffer body = {0};
|
||||
LyraSyncBuffer response = {0};
|
||||
KsyncSyncBuffer body = {0};
|
||||
KsyncSyncBuffer response = {0};
|
||||
long status = 0;
|
||||
LyraSyncResult challenge_result;
|
||||
KsyncSyncResult challenge_result;
|
||||
int ok;
|
||||
char token[4096];
|
||||
long long expires_in;
|
||||
long long expires_at;
|
||||
|
||||
if(!sync_config_valid(cfg) || !HasLyraAccountValues(cfg->account))
|
||||
return LYRA_SYNC_NO_ACCOUNT;
|
||||
if(!AppendLyraSyncBuffer(&body, "{\"user_id_hash\":", strlen("{\"user_id_hash\":")) ||
|
||||
!AppendLyraSyncBufferJSONString(&body, cfg->account->public_id) ||
|
||||
!AppendLyraSyncBuffer(&body, ",\"client_id\":", strlen(",\"client_id\":")) ||
|
||||
!AppendLyraSyncBufferJSONString(&body, cfg->client_id) ||
|
||||
!AppendLyraSyncBuffer(&body, ",\"public_key\":", strlen(",\"public_key\":")) ||
|
||||
!AppendLyraSyncBufferJSONString(&body, cfg->account->public_key_hex) ||
|
||||
!AppendLyraSyncBuffer(&body, "}", 1)) {
|
||||
FreeLyraSyncBuffer(&body);
|
||||
return LYRA_SYNC_PAYLOAD_FAILED;
|
||||
if(!sync_config_valid(cfg) || !HasKsyncAccountValues(cfg->account))
|
||||
return KSYNC_SYNC_NO_ACCOUNT;
|
||||
if(!AppendKsyncSyncBuffer(&body, "{\"user_id_hash\":", strlen("{\"user_id_hash\":")) ||
|
||||
!AppendKsyncSyncBufferJSONString(&body, cfg->account->public_id) ||
|
||||
!AppendKsyncSyncBuffer(&body, ",\"client_id\":", strlen(",\"client_id\":")) ||
|
||||
!AppendKsyncSyncBufferJSONString(&body, cfg->client_id) ||
|
||||
!AppendKsyncSyncBuffer(&body, ",\"public_key\":", strlen(",\"public_key\":")) ||
|
||||
!AppendKsyncSyncBufferJSONString(&body, cfg->account->public_key_hex) ||
|
||||
!AppendKsyncSyncBuffer(&body, "}", 1)) {
|
||||
FreeKsyncSyncBuffer(&body);
|
||||
return KSYNC_SYNC_PAYLOAD_FAILED;
|
||||
}
|
||||
|
||||
challenge_result = sync_fetch_challenge(cfg, cfg->account->public_id, nonce_hex);
|
||||
if(challenge_result != LYRA_SYNC_OK) {
|
||||
FreeLyraSyncBuffer(&body);
|
||||
if(challenge_result != KSYNC_SYNC_OK) {
|
||||
FreeKsyncSyncBuffer(&body);
|
||||
return challenge_result;
|
||||
}
|
||||
if(!sync_build_message(cfg, "POST", LYRA_LOGIN_PATH, nonce_hex,
|
||||
if(!sync_build_message(cfg, "POST", KSYNC_LOGIN_PATH, nonce_hex,
|
||||
body.data, message, sizeof(message))) {
|
||||
FreeLyraSyncBuffer(&body);
|
||||
return LYRA_SYNC_SIGN_FAILED;
|
||||
FreeKsyncSyncBuffer(&body);
|
||||
return KSYNC_SYNC_SIGN_FAILED;
|
||||
}
|
||||
if(!SignLyraAccountHex(cfg->account, (const uint8_t *)message, strlen(message),
|
||||
if(!SignKsyncAccountHex(cfg->account, (const uint8_t *)message, strlen(message),
|
||||
signature_hex, sizeof(signature_hex))) {
|
||||
FreeLyraSyncBuffer(&body);
|
||||
return LYRA_SYNC_SIGN_FAILED;
|
||||
FreeKsyncSyncBuffer(&body);
|
||||
return KSYNC_SYNC_SIGN_FAILED;
|
||||
}
|
||||
JoinLyraSyncURL(url, sizeof(url), cfg->base_url, LYRA_LOGIN_PATH);
|
||||
JoinKsyncSyncURL(url, sizeof(url), cfg->base_url, KSYNC_LOGIN_PATH);
|
||||
snprintf(user_header, sizeof(user_header), "%s: %s", sync_user_header_name(cfg),
|
||||
cfg->account->public_id);
|
||||
snprintf(signature_header, sizeof(signature_header), "%s: %s",
|
||||
@@ -447,27 +447,27 @@ LoginLyraSync(const LyraSyncConfig *cfg)
|
||||
headers[1] = user_header;
|
||||
headers[2] = signature_header;
|
||||
ok = cfg->http_request("POST", url, body.data, headers, 3, &response, &status, cfg->user);
|
||||
FreeLyraSyncBuffer(&body);
|
||||
FreeKsyncSyncBuffer(&body);
|
||||
if(!ok) {
|
||||
sync_log_http_failure(cfg, "login request", status, response.data);
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_REQUEST_FAILED;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_REQUEST_FAILED;
|
||||
}
|
||||
if(status == 401) {
|
||||
sync_log_http_failure(cfg, "login auth", status, response.data);
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_AUTH_FAILED;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_AUTH_FAILED;
|
||||
}
|
||||
if(status < 200 || status >= 300) {
|
||||
sync_log_http_failure(cfg, "login", status, response.data);
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_REQUEST_FAILED;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_REQUEST_FAILED;
|
||||
}
|
||||
expires_in = FindLyraSyncJSONInt64(response.data, "expires_in_seconds", 3600);
|
||||
if(!FindLyraSyncJSONString(response.data, "auth_token", token, sizeof(token))) {
|
||||
expires_in = FindKsyncSyncJSONInt64(response.data, "expires_in_seconds", 3600);
|
||||
if(!FindKsyncSyncJSONString(response.data, "auth_token", token, sizeof(token))) {
|
||||
sync_log_http_failure(cfg, "login payload", status, response.data);
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_PAYLOAD_FAILED;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_PAYLOAD_FAILED;
|
||||
}
|
||||
expires_at = (long long)time(NULL) + expires_in - 30;
|
||||
if(expires_at < (long long)time(NULL))
|
||||
@@ -475,25 +475,25 @@ LoginLyraSync(const LyraSyncConfig *cfg)
|
||||
{
|
||||
char text[32];
|
||||
snprintf(text, sizeof(text), "%lld", expires_at);
|
||||
cfg->set_text(LYRA_SYNC_AUTH_TOKEN_KEY, token, cfg->user);
|
||||
cfg->set_text(LYRA_SYNC_AUTH_TOKEN_EXPIRES_KEY, text, cfg->user);
|
||||
cfg->set_text(KSYNC_SYNC_AUTH_TOKEN_KEY, token, cfg->user);
|
||||
cfg->set_text(KSYNC_SYNC_AUTH_TOKEN_EXPIRES_KEY, text, cfg->user);
|
||||
}
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_OK;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_OK;
|
||||
}
|
||||
|
||||
static LyraSyncResult
|
||||
sync_send_bearer(const LyraSyncConfig *cfg, const char *body, const char *token)
|
||||
static KsyncSyncResult
|
||||
sync_send_bearer(const KsyncSyncConfig *cfg, const char *body, const char *token)
|
||||
{
|
||||
char url[768];
|
||||
char user_header[96];
|
||||
char auth_header[4200];
|
||||
const char *headers[3];
|
||||
LyraSyncBuffer response = {0};
|
||||
KsyncSyncBuffer response = {0};
|
||||
long status = 0;
|
||||
int ok;
|
||||
|
||||
JoinLyraSyncURL(url, sizeof(url), cfg->base_url, LYRA_SYNC_PATH);
|
||||
JoinKsyncSyncURL(url, sizeof(url), cfg->base_url, KSYNC_SYNC_PATH);
|
||||
snprintf(user_header, sizeof(user_header), "%s: %s", sync_user_header_name(cfg),
|
||||
cfg->account->public_id);
|
||||
snprintf(auth_header, sizeof(auth_header), "Authorization: Bearer %s",
|
||||
@@ -504,68 +504,68 @@ sync_send_bearer(const LyraSyncConfig *cfg, const char *body, const char *token)
|
||||
ok = cfg->http_request("POST", url, body, headers, 3, &response, &status, cfg->user);
|
||||
if(!ok) {
|
||||
sync_log_http_failure(cfg, "sync request", status, response.data);
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_REQUEST_FAILED;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_REQUEST_FAILED;
|
||||
}
|
||||
if(status == 401) {
|
||||
sync_log_http_failure(cfg, "sync auth", status, response.data);
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_AUTH_FAILED;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_AUTH_FAILED;
|
||||
}
|
||||
if(status < 200 || status >= 300) {
|
||||
sync_log_http_failure(cfg, "sync", status, response.data);
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_REQUEST_FAILED;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_REQUEST_FAILED;
|
||||
}
|
||||
if(cfg->apply_response == NULL || !cfg->apply_response(response.data, cfg->user)) {
|
||||
sync_log_http_failure(cfg, "sync payload", status, response.data);
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_PAYLOAD_FAILED;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_PAYLOAD_FAILED;
|
||||
}
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_OK;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_OK;
|
||||
}
|
||||
|
||||
LyraSyncResult
|
||||
RunLyraSync(const LyraSyncConfig *cfg)
|
||||
KsyncSyncResult
|
||||
RunKsyncSync(const KsyncSyncConfig *cfg)
|
||||
{
|
||||
char *payload;
|
||||
LyraSyncResult result;
|
||||
KsyncSyncResult result;
|
||||
char token[4096];
|
||||
|
||||
if(!sync_config_valid(cfg) || cfg->build_payload == NULL || cfg->free_payload == NULL)
|
||||
return LYRA_SYNC_PAYLOAD_FAILED;
|
||||
if(!IsLyraSyncURLValid(cfg->base_url))
|
||||
return LYRA_SYNC_INVALID_URL;
|
||||
if(!HasLyraAccountValues(cfg->account))
|
||||
return LYRA_SYNC_NO_ACCOUNT;
|
||||
return KSYNC_SYNC_PAYLOAD_FAILED;
|
||||
if(!IsKsyncSyncURLValid(cfg->base_url))
|
||||
return KSYNC_SYNC_INVALID_URL;
|
||||
if(!HasKsyncAccountValues(cfg->account))
|
||||
return KSYNC_SYNC_NO_ACCOUNT;
|
||||
if(!sync_load_valid_auth_token(cfg, token, sizeof(token))) {
|
||||
result = LoginLyraSync(cfg);
|
||||
if(result != LYRA_SYNC_OK)
|
||||
result = LoginKsyncSync(cfg);
|
||||
if(result != KSYNC_SYNC_OK)
|
||||
return result;
|
||||
if(!sync_load_valid_auth_token(cfg, token, sizeof(token)))
|
||||
return LYRA_SYNC_AUTH_FAILED;
|
||||
return KSYNC_SYNC_AUTH_FAILED;
|
||||
}
|
||||
payload = cfg->build_payload(cfg->account->public_id, cfg->account->public_key_hex, cfg->user);
|
||||
if(payload == NULL)
|
||||
return LYRA_SYNC_PAYLOAD_FAILED;
|
||||
return KSYNC_SYNC_PAYLOAD_FAILED;
|
||||
result = sync_send_bearer(cfg, payload, token);
|
||||
if(result == LYRA_SYNC_AUTH_FAILED) {
|
||||
ClearLyraSyncAuthToken(cfg);
|
||||
result = LoginLyraSync(cfg);
|
||||
if(result == LYRA_SYNC_OK && sync_load_valid_auth_token(cfg, token, sizeof(token)))
|
||||
if(result == KSYNC_SYNC_AUTH_FAILED) {
|
||||
ClearKsyncSyncAuthToken(cfg);
|
||||
result = LoginKsyncSync(cfg);
|
||||
if(result == KSYNC_SYNC_OK && sync_load_valid_auth_token(cfg, token, sizeof(token)))
|
||||
result = sync_send_bearer(cfg, payload, token);
|
||||
else if(result == LYRA_SYNC_OK)
|
||||
result = LYRA_SYNC_AUTH_FAILED;
|
||||
else if(result == KSYNC_SYNC_OK)
|
||||
result = KSYNC_SYNC_AUTH_FAILED;
|
||||
}
|
||||
cfg->free_payload(payload, cfg->user);
|
||||
if(result == LYRA_SYNC_OK && cfg->purge_synced_deleted != NULL)
|
||||
if(result == KSYNC_SYNC_OK && cfg->purge_synced_deleted != NULL)
|
||||
cfg->purge_synced_deleted(cfg->user);
|
||||
return result;
|
||||
}
|
||||
|
||||
static int
|
||||
sync_copy_response_text(const LyraSyncBuffer *response, char *out, size_t out_size)
|
||||
sync_copy_response_text(const KsyncSyncBuffer *response, char *out, size_t out_size)
|
||||
{
|
||||
if(out == NULL || out_size == 0)
|
||||
return 1;
|
||||
@@ -578,8 +578,8 @@ sync_copy_response_text(const LyraSyncBuffer *response, char *out, size_t out_si
|
||||
return 1;
|
||||
}
|
||||
|
||||
LyraSyncResult
|
||||
RequestLyraSyncBearer(const LyraSyncConfig *cfg, const char *method,
|
||||
KsyncSyncResult
|
||||
RequestKsyncSyncBearer(const KsyncSyncConfig *cfg, const char *method,
|
||||
const char *path, const char *body,
|
||||
char *out, size_t out_size)
|
||||
{
|
||||
@@ -589,33 +589,33 @@ RequestLyraSyncBearer(const LyraSyncConfig *cfg, const char *method,
|
||||
char auth_header[4200];
|
||||
const char *headers[3];
|
||||
int header_count = 0;
|
||||
LyraSyncBuffer response = {0};
|
||||
KsyncSyncBuffer response = {0};
|
||||
long status = 0;
|
||||
LyraSyncResult result;
|
||||
KsyncSyncResult result;
|
||||
int ok;
|
||||
int retried_auth = 0;
|
||||
|
||||
if(out != NULL && out_size > 0)
|
||||
out[0] = '\0';
|
||||
if(!sync_config_valid(cfg))
|
||||
return LYRA_SYNC_PAYLOAD_FAILED;
|
||||
if(!IsLyraSyncURLValid(cfg->base_url))
|
||||
return LYRA_SYNC_INVALID_URL;
|
||||
return KSYNC_SYNC_PAYLOAD_FAILED;
|
||||
if(!IsKsyncSyncURLValid(cfg->base_url))
|
||||
return KSYNC_SYNC_INVALID_URL;
|
||||
if(method == NULL || path == NULL)
|
||||
return LYRA_SYNC_PAYLOAD_FAILED;
|
||||
if(!HasLyraAccountValues(cfg->account))
|
||||
return LYRA_SYNC_NO_ACCOUNT;
|
||||
return KSYNC_SYNC_PAYLOAD_FAILED;
|
||||
if(!HasKsyncAccountValues(cfg->account))
|
||||
return KSYNC_SYNC_NO_ACCOUNT;
|
||||
if(!sync_load_valid_auth_token(cfg, token, sizeof(token))) {
|
||||
result = LoginLyraSync(cfg);
|
||||
if(result != LYRA_SYNC_OK)
|
||||
result = LoginKsyncSync(cfg);
|
||||
if(result != KSYNC_SYNC_OK)
|
||||
return result;
|
||||
if(!sync_load_valid_auth_token(cfg, token, sizeof(token)))
|
||||
return LYRA_SYNC_AUTH_FAILED;
|
||||
return KSYNC_SYNC_AUTH_FAILED;
|
||||
}
|
||||
|
||||
retry:
|
||||
if(!JoinLyraSyncURL(url, sizeof(url), cfg->base_url, path))
|
||||
return LYRA_SYNC_INVALID_URL;
|
||||
if(!JoinKsyncSyncURL(url, sizeof(url), cfg->base_url, path))
|
||||
return KSYNC_SYNC_INVALID_URL;
|
||||
snprintf(user_header, sizeof(user_header), "%s: %s", sync_user_header_name(cfg),
|
||||
cfg->account->public_id);
|
||||
snprintf(auth_header, sizeof(auth_header), "Authorization: Bearer %s", token);
|
||||
@@ -627,73 +627,73 @@ retry:
|
||||
&response, &status, cfg->user);
|
||||
if(!ok) {
|
||||
sync_log_http_failure(cfg, path, status, response.data);
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_REQUEST_FAILED;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_REQUEST_FAILED;
|
||||
}
|
||||
if(status == 401) {
|
||||
FreeLyraSyncBuffer(&response);
|
||||
ClearLyraSyncAuthToken(cfg);
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
ClearKsyncSyncAuthToken(cfg);
|
||||
if(retried_auth)
|
||||
return LYRA_SYNC_AUTH_FAILED;
|
||||
return KSYNC_SYNC_AUTH_FAILED;
|
||||
retried_auth = 1;
|
||||
result = LoginLyraSync(cfg);
|
||||
if(result != LYRA_SYNC_OK)
|
||||
result = LoginKsyncSync(cfg);
|
||||
if(result != KSYNC_SYNC_OK)
|
||||
return result;
|
||||
if(!sync_load_valid_auth_token(cfg, token, sizeof(token)))
|
||||
return LYRA_SYNC_AUTH_FAILED;
|
||||
return KSYNC_SYNC_AUTH_FAILED;
|
||||
status = 0;
|
||||
header_count = 0;
|
||||
goto retry;
|
||||
}
|
||||
if(status < 200 || status >= 300) {
|
||||
sync_log_http_failure(cfg, path, status, response.data);
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_REQUEST_FAILED;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_REQUEST_FAILED;
|
||||
}
|
||||
if(!sync_copy_response_text(&response, out, out_size)) {
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_PAYLOAD_FAILED;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_PAYLOAD_FAILED;
|
||||
}
|
||||
FreeLyraSyncBuffer(&response);
|
||||
return LYRA_SYNC_OK;
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
return KSYNC_SYNC_OK;
|
||||
}
|
||||
|
||||
LyraSyncResult
|
||||
DeleteLyraSyncAccount(const LyraSyncConfig *cfg)
|
||||
KsyncSyncResult
|
||||
DeleteKsyncSyncAccount(const KsyncSyncConfig *cfg)
|
||||
{
|
||||
char url[768];
|
||||
char exported_key[LYRA_ACCOUNT_EXPORT_TEXT_SIZE];
|
||||
LyraSyncBuffer body = {0};
|
||||
LyraSyncBuffer response = {0};
|
||||
char exported_key[KSYNC_ACCOUNT_EXPORT_TEXT_SIZE];
|
||||
KsyncSyncBuffer body = {0};
|
||||
KsyncSyncBuffer response = {0};
|
||||
const char *headers[1] = {"Content-Type: application/json"};
|
||||
long status = 0;
|
||||
int ok;
|
||||
|
||||
if(!sync_config_valid(cfg))
|
||||
return LYRA_SYNC_PAYLOAD_FAILED;
|
||||
if(!IsLyraSyncURLValid(cfg->base_url))
|
||||
return LYRA_SYNC_INVALID_URL;
|
||||
if(!HasLyraAccountValues(cfg->account))
|
||||
return LYRA_SYNC_NO_ACCOUNT;
|
||||
if(!ExportLyraAccountText(cfg->account, exported_key, sizeof(exported_key)))
|
||||
return LYRA_SYNC_PAYLOAD_FAILED;
|
||||
if(!AppendLyraSyncBuffer(&body, "{\"user_id_hash\":", strlen("{\"user_id_hash\":")) ||
|
||||
!AppendLyraSyncBufferJSONString(&body, cfg->account->public_id) ||
|
||||
!AppendLyraSyncBuffer(&body, ",\"exported_key\":", strlen(",\"exported_key\":")) ||
|
||||
!AppendLyraSyncBufferJSONString(&body, exported_key) ||
|
||||
!AppendLyraSyncBuffer(&body, "}", 1)) {
|
||||
FreeLyraSyncBuffer(&body);
|
||||
return LYRA_SYNC_PAYLOAD_FAILED;
|
||||
return KSYNC_SYNC_PAYLOAD_FAILED;
|
||||
if(!IsKsyncSyncURLValid(cfg->base_url))
|
||||
return KSYNC_SYNC_INVALID_URL;
|
||||
if(!HasKsyncAccountValues(cfg->account))
|
||||
return KSYNC_SYNC_NO_ACCOUNT;
|
||||
if(!ExportKsyncAccountText(cfg->account, exported_key, sizeof(exported_key)))
|
||||
return KSYNC_SYNC_PAYLOAD_FAILED;
|
||||
if(!AppendKsyncSyncBuffer(&body, "{\"user_id_hash\":", strlen("{\"user_id_hash\":")) ||
|
||||
!AppendKsyncSyncBufferJSONString(&body, cfg->account->public_id) ||
|
||||
!AppendKsyncSyncBuffer(&body, ",\"exported_key\":", strlen(",\"exported_key\":")) ||
|
||||
!AppendKsyncSyncBufferJSONString(&body, exported_key) ||
|
||||
!AppendKsyncSyncBuffer(&body, "}", 1)) {
|
||||
FreeKsyncSyncBuffer(&body);
|
||||
return KSYNC_SYNC_PAYLOAD_FAILED;
|
||||
}
|
||||
|
||||
JoinLyraSyncURL(url, sizeof(url), cfg->base_url,
|
||||
LYRA_ACCOUNT_DELETE_WITH_KEY_PATH);
|
||||
JoinKsyncSyncURL(url, sizeof(url), cfg->base_url,
|
||||
KSYNC_ACCOUNT_DELETE_WITH_KEY_PATH);
|
||||
ok = cfg->http_request("POST", url, body.data, headers, 1, &response, &status, cfg->user);
|
||||
FreeLyraSyncBuffer(&body);
|
||||
FreeLyraSyncBuffer(&response);
|
||||
FreeKsyncSyncBuffer(&body);
|
||||
FreeKsyncSyncBuffer(&response);
|
||||
if(!ok)
|
||||
return LYRA_SYNC_REQUEST_FAILED;
|
||||
return KSYNC_SYNC_REQUEST_FAILED;
|
||||
if(status == 401 || status == 403)
|
||||
return LYRA_SYNC_AUTH_FAILED;
|
||||
return status >= 200 && status < 300 ? LYRA_SYNC_OK : LYRA_SYNC_REQUEST_FAILED;
|
||||
return KSYNC_SYNC_AUTH_FAILED;
|
||||
return status >= 200 && status < 300 ? KSYNC_SYNC_OK : KSYNC_SYNC_REQUEST_FAILED;
|
||||
}
|
||||
+33
-33
@@ -28,32 +28,32 @@ static const UIIconType ui_profile_picture_icons[] = {
|
||||
UI_ICON_TYPE_PFP_TREE4
|
||||
};
|
||||
|
||||
static const int ui_profile_picture_lyra_ids[] = {
|
||||
UI_LYRA_PROFILE_ICON_BAMBUS,
|
||||
UI_LYRA_PROFILE_ICON_BIRD,
|
||||
UI_LYRA_PROFILE_ICON_BOWL,
|
||||
UI_LYRA_PROFILE_ICON_BUSH,
|
||||
UI_LYRA_PROFILE_ICON_BUTTERFLY,
|
||||
UI_LYRA_PROFILE_ICON_CACTUS,
|
||||
UI_LYRA_PROFILE_ICON_COFFEE,
|
||||
UI_LYRA_PROFILE_ICON_DRAGONFLY,
|
||||
UI_LYRA_PROFILE_ICON_FIREPLACE,
|
||||
UI_LYRA_PROFILE_ICON_FLOWER1,
|
||||
UI_LYRA_PROFILE_ICON_FLOWER2,
|
||||
UI_LYRA_PROFILE_ICON_FOX,
|
||||
UI_LYRA_PROFILE_ICON_HEART,
|
||||
UI_LYRA_PROFILE_ICON_INCENSE,
|
||||
UI_LYRA_PROFILE_ICON_LOTUS,
|
||||
UI_LYRA_PROFILE_ICON_MOUNTAIN,
|
||||
UI_LYRA_PROFILE_ICON_MUSHROOM,
|
||||
UI_LYRA_PROFILE_ICON_PALM,
|
||||
UI_LYRA_PROFILE_ICON_PERSON1,
|
||||
UI_LYRA_PROFILE_ICON_RAINBOW,
|
||||
UI_LYRA_PROFILE_ICON_TENT,
|
||||
UI_LYRA_PROFILE_ICON_TREE1,
|
||||
UI_LYRA_PROFILE_ICON_TREE2,
|
||||
UI_LYRA_PROFILE_ICON_TREE3,
|
||||
UI_LYRA_PROFILE_ICON_TREE4
|
||||
static const int ui_profile_picture_ksync_ids[] = {
|
||||
UI_KSYNC_PROFILE_ICON_BAMBUS,
|
||||
UI_KSYNC_PROFILE_ICON_BIRD,
|
||||
UI_KSYNC_PROFILE_ICON_BOWL,
|
||||
UI_KSYNC_PROFILE_ICON_BUSH,
|
||||
UI_KSYNC_PROFILE_ICON_BUTTERFLY,
|
||||
UI_KSYNC_PROFILE_ICON_CACTUS,
|
||||
UI_KSYNC_PROFILE_ICON_COFFEE,
|
||||
UI_KSYNC_PROFILE_ICON_DRAGONFLY,
|
||||
UI_KSYNC_PROFILE_ICON_FIREPLACE,
|
||||
UI_KSYNC_PROFILE_ICON_FLOWER1,
|
||||
UI_KSYNC_PROFILE_ICON_FLOWER2,
|
||||
UI_KSYNC_PROFILE_ICON_FOX,
|
||||
UI_KSYNC_PROFILE_ICON_HEART,
|
||||
UI_KSYNC_PROFILE_ICON_INCENSE,
|
||||
UI_KSYNC_PROFILE_ICON_LOTUS,
|
||||
UI_KSYNC_PROFILE_ICON_MOUNTAIN,
|
||||
UI_KSYNC_PROFILE_ICON_MUSHROOM,
|
||||
UI_KSYNC_PROFILE_ICON_PALM,
|
||||
UI_KSYNC_PROFILE_ICON_PERSON1,
|
||||
UI_KSYNC_PROFILE_ICON_RAINBOW,
|
||||
UI_KSYNC_PROFILE_ICON_TENT,
|
||||
UI_KSYNC_PROFILE_ICON_TREE1,
|
||||
UI_KSYNC_PROFILE_ICON_TREE2,
|
||||
UI_KSYNC_PROFILE_ICON_TREE3,
|
||||
UI_KSYNC_PROFILE_ICON_TREE4
|
||||
};
|
||||
|
||||
static const char *ui_profile_picture_names[] = {
|
||||
@@ -108,27 +108,27 @@ GetUIProfilePictureIconName(int index)
|
||||
}
|
||||
|
||||
UIIconType
|
||||
GetUIProfilePictureIconTypeForLyraID(int lyra_id)
|
||||
GetUIProfilePictureIconTypeForKsyncID(int ksync_id)
|
||||
{
|
||||
if(lyra_id == UI_LYRA_PROFILE_ICON_NONE)
|
||||
if(ksync_id == UI_KSYNC_PROFILE_ICON_NONE)
|
||||
return UI_ICON_TYPE_NONE;
|
||||
for(int i = 0; i < GetUIProfilePictureIconCount(); i++) {
|
||||
if(ui_profile_picture_lyra_ids[i] == lyra_id)
|
||||
if(ui_profile_picture_ksync_ids[i] == ksync_id)
|
||||
return ui_profile_picture_icons[i];
|
||||
}
|
||||
return UI_ICON_TYPE_NONE;
|
||||
}
|
||||
|
||||
int
|
||||
GetUILyraIDForProfilePictureIconType(UIIconType type)
|
||||
GetUIKsyncIDForProfilePictureIconType(UIIconType type)
|
||||
{
|
||||
if(type == UI_ICON_TYPE_NONE)
|
||||
return UI_LYRA_PROFILE_ICON_NONE;
|
||||
return UI_KSYNC_PROFILE_ICON_NONE;
|
||||
for(int i = 0; i < GetUIProfilePictureIconCount(); i++) {
|
||||
if(ui_profile_picture_icons[i] == type)
|
||||
return ui_profile_picture_lyra_ids[i];
|
||||
return ui_profile_picture_ksync_ids[i];
|
||||
}
|
||||
return UI_LYRA_PROFILE_ICON_NONE;
|
||||
return UI_KSYNC_PROFILE_ICON_NONE;
|
||||
}
|
||||
|
||||
static void
|
||||
|
||||
+270
-86
@@ -29,6 +29,8 @@ static int g_ui_pointer_start_y = 0;
|
||||
static int g_ui_transition_cues_enabled = 0;
|
||||
static int g_ui_release_consumed = 0;
|
||||
static int g_ui_keyboard_input_enabled = 1;
|
||||
static int g_ui_mouse_world_override_enabled = 0;
|
||||
static Vector2 g_ui_mouse_world_override = {0};
|
||||
|
||||
int g_ui_pointer_owner = UI_POINTER_OWNER_NONE;
|
||||
|
||||
@@ -43,7 +45,9 @@ static int g_ui_platform_text_input_active = 0;
|
||||
static int g_ui_text_input_requested = 0;
|
||||
static UITextInputPlatformCallback g_ui_text_input_platform_callback = NULL;
|
||||
static int g_ui_text_area_drag_id = 0;
|
||||
static int *g_ui_text_area_drag_owner = NULL;
|
||||
static int g_ui_text_area_last_click_id = 0;
|
||||
static int *g_ui_text_area_last_click_owner = NULL;
|
||||
static int g_ui_text_area_last_click_cursor = -1;
|
||||
static int g_ui_text_area_last_click_x = 0;
|
||||
static int g_ui_text_area_last_click_y = 0;
|
||||
@@ -51,6 +55,7 @@ static double g_ui_text_area_last_click_time = 0.0;
|
||||
|
||||
typedef struct UITextSelection {
|
||||
int id;
|
||||
int *owner;
|
||||
int anchor;
|
||||
int cursor;
|
||||
int dragging;
|
||||
@@ -59,6 +64,7 @@ typedef struct UITextSelection {
|
||||
static UITextSelection g_ui_text_area_selection = {0};
|
||||
static UITextSelection g_ui_text_field_selection = {0};
|
||||
static int g_ui_text_field_drag_id = 0;
|
||||
static int *g_ui_text_field_drag_owner = NULL;
|
||||
/* Identity of the widget that currently owns text input focus, recorded as the
|
||||
* address of its `focused` flag. Ownership is PERSISTENT across frames: it does
|
||||
* not reset at frame start, it only changes when a text input is clicked (or
|
||||
@@ -103,12 +109,70 @@ typedef struct UIInputCapture {
|
||||
static UIInputCapture g_ui_input_capture_stack[UI_INPUT_CAPTURE_STACK_MAX];
|
||||
static int g_ui_input_capture_stack_count = 0;
|
||||
|
||||
static void
|
||||
ui_text_selection_clear(UITextSelection *selection)
|
||||
{
|
||||
if(selection == NULL)
|
||||
return;
|
||||
selection->id = 0;
|
||||
selection->owner = NULL;
|
||||
selection->anchor = 0;
|
||||
selection->cursor = 0;
|
||||
selection->dragging = 0;
|
||||
}
|
||||
|
||||
static void
|
||||
ui_clear_text_field_selection(void)
|
||||
{
|
||||
ui_text_selection_clear(&g_ui_text_field_selection);
|
||||
g_ui_text_field_drag_id = 0;
|
||||
g_ui_text_field_drag_owner = NULL;
|
||||
}
|
||||
|
||||
static void
|
||||
ui_clear_text_area_selection(void)
|
||||
{
|
||||
ui_text_selection_clear(&g_ui_text_area_selection);
|
||||
g_ui_text_area_drag_id = 0;
|
||||
g_ui_text_area_drag_owner = NULL;
|
||||
}
|
||||
|
||||
static int
|
||||
ui_text_selection_matches(UITextSelection selection, int id, int *owner)
|
||||
{
|
||||
if(owner != NULL && selection.owner == owner)
|
||||
return 1;
|
||||
return id > 0 && selection.id == id;
|
||||
}
|
||||
|
||||
static void
|
||||
ui_text_selection_set(UITextSelection *selection, int id, int *owner,
|
||||
int anchor, int cursor, int dragging)
|
||||
{
|
||||
if(selection == NULL)
|
||||
return;
|
||||
selection->id = id;
|
||||
selection->owner = owner;
|
||||
selection->anchor = anchor;
|
||||
selection->cursor = cursor;
|
||||
selection->dragging = dragging;
|
||||
}
|
||||
|
||||
Vector2
|
||||
ui_mouse_world(void)
|
||||
{
|
||||
if(g_ui_mouse_world_override_enabled)
|
||||
return g_ui_mouse_world_override;
|
||||
return GetScreenToWorld2D(GetMousePosition(), g_ui_camera);
|
||||
}
|
||||
|
||||
void
|
||||
SetUIMouseWorldOverride(int enabled, Vector2 position)
|
||||
{
|
||||
g_ui_mouse_world_override_enabled = enabled ? 1 : 0;
|
||||
g_ui_mouse_world_override = position;
|
||||
}
|
||||
|
||||
static void
|
||||
ui_set_cursor_intent(int cursor, int priority)
|
||||
{
|
||||
@@ -908,6 +972,26 @@ ClaimUITextFocus(int *focused)
|
||||
*focused = 1;
|
||||
}
|
||||
|
||||
static void
|
||||
ClaimUITextFieldFocus(int *focused)
|
||||
{
|
||||
int *previous = g_ui_text_focus_owner;
|
||||
|
||||
ClaimUITextFocus(focused);
|
||||
if(g_ui_text_focus_owner == focused && previous != focused)
|
||||
ui_clear_text_area_selection();
|
||||
}
|
||||
|
||||
static void
|
||||
ClaimUITextAreaFocus(int *focused)
|
||||
{
|
||||
int *previous = g_ui_text_focus_owner;
|
||||
|
||||
ClaimUITextFocus(focused);
|
||||
if(g_ui_text_focus_owner == focused && previous != focused)
|
||||
ui_clear_text_field_selection();
|
||||
}
|
||||
|
||||
static int
|
||||
IsUITextFocusOwner(int *focused)
|
||||
{
|
||||
@@ -1306,8 +1390,10 @@ DrawUIButton(UIButton button)
|
||||
DrawUIFocus(button.bounds);
|
||||
}
|
||||
|
||||
DrawFittedUITextInRect(button.label ? button.label : "", button.bounds,
|
||||
font, UI_TEXT_8, text);
|
||||
DrawCenteredUIControlText(button.label ? button.label : "",
|
||||
(int)(button.bounds.x + button.bounds.width * 0.5f),
|
||||
(int)(button.bounds.y + button.bounds.height * 0.5f),
|
||||
font, text);
|
||||
if(clicked)
|
||||
UIConsumeRelease();
|
||||
EndUIWidget(&widget);
|
||||
@@ -1768,10 +1854,15 @@ static int
|
||||
ui_syntax_c_keyword(const char *text, int len)
|
||||
{
|
||||
static const char *keywords[] = {
|
||||
"break", "case", "char", "const", "continue", "default", "do",
|
||||
"double", "else", "enum", "float", "for", "goto", "if", "int", "long",
|
||||
"return", "short", "sizeof", "static", "struct", "switch",
|
||||
"typedef", "void", "while"
|
||||
"auto", "break", "case", "char", "const", "continue", "default",
|
||||
"do", "double", "else", "enum", "extern", "float", "for", "goto",
|
||||
"if", "inline", "int", "long", "register", "restrict", "return",
|
||||
"short", "signed", "sizeof", "static", "struct", "switch", "typedef",
|
||||
"union", "unsigned", "void", "volatile", "while",
|
||||
/* Common C99/C11 standard-library types highlighted as keywords. */
|
||||
"bool", "true", "false", "size_t", "ssize_t", "ptrdiff_t",
|
||||
"int8_t", "int16_t", "int32_t", "int64_t",
|
||||
"uint8_t", "uint16_t", "uint32_t", "uint64_t", "NULL"
|
||||
};
|
||||
|
||||
for(size_t i = 0; i < sizeof(keywords) / sizeof(keywords[0]); i++) {
|
||||
@@ -1812,11 +1903,17 @@ ui_syntax_token_color(UISyntaxMode syntax, const char *text, int len,
|
||||
if((syntax == UI_SYNTAX_KRY || syntax == UI_SYNTAX_MAKE) &&
|
||||
first_token && text[0] == '#')
|
||||
return comment;
|
||||
if(syntax == UI_SYNTAX_C && first_token && text[0] == '#')
|
||||
return path;
|
||||
if(text[0] == '"')
|
||||
return string;
|
||||
if(syntax == UI_SYNTAX_C && text[0] == '\'')
|
||||
return string;
|
||||
if((text[0] >= '0' && text[0] <= '9') ||
|
||||
(text[0] == '-' && len > 1 && text[1] >= '0' && text[1] <= '9'))
|
||||
return number;
|
||||
if(syntax == UI_SYNTAX_C && len >= 2 && text[0] == '/' && text[1] == '*')
|
||||
return comment;
|
||||
if(syntax == UI_SYNTAX_KRY &&
|
||||
(text[0] == '/' ||
|
||||
(text[0] == '.' && len > 1 && (text[1] == '/' || text[1] == '.')) ||
|
||||
@@ -1835,12 +1932,26 @@ ui_syntax_token_color(UISyntaxMode syntax, const char *text, int len,
|
||||
|
||||
static int
|
||||
ui_syntax_token_len(const char *line, int len, int index, UISyntaxMode syntax,
|
||||
int first_token)
|
||||
int first_token, int *in_block_comment)
|
||||
{
|
||||
int i = index;
|
||||
|
||||
if(i >= len)
|
||||
return 0;
|
||||
/* Continuing a C block comment from a previous line: consume to the
|
||||
closing star-slash (or to end of line, leaving the flag set). */
|
||||
if(in_block_comment != NULL && *in_block_comment) {
|
||||
while(i < len) {
|
||||
if(line[i] == '*' && i + 1 < len && line[i + 1] == '/') {
|
||||
i += 2;
|
||||
*in_block_comment = 0;
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
if(i > index)
|
||||
return i - index;
|
||||
}
|
||||
if(line[i] == ' ' || line[i] == '\t') {
|
||||
while(i < len && (line[i] == ' ' || line[i] == '\t'))
|
||||
i++;
|
||||
@@ -1849,6 +1960,8 @@ ui_syntax_token_len(const char *line, int len, int index, UISyntaxMode syntax,
|
||||
if((syntax == UI_SYNTAX_KRY || syntax == UI_SYNTAX_MAKE) &&
|
||||
first_token && line[i] == '#')
|
||||
return len - index;
|
||||
if(syntax == UI_SYNTAX_C && first_token && line[i] == '#')
|
||||
return len - index;
|
||||
if(syntax == UI_SYNTAX_C && line[i] == '/' && i + 1 < len &&
|
||||
line[i + 1] == '/')
|
||||
return len - index;
|
||||
@@ -1864,6 +1977,36 @@ ui_syntax_token_len(const char *line, int len, int index, UISyntaxMode syntax,
|
||||
}
|
||||
return i - index;
|
||||
}
|
||||
if(syntax == UI_SYNTAX_C && line[i] == '\'') {
|
||||
i++;
|
||||
while(i < len) {
|
||||
if(line[i] == '\\' && i + 1 < len) {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if(line[i++] == '\'')
|
||||
break;
|
||||
}
|
||||
return i - index;
|
||||
}
|
||||
if(syntax == UI_SYNTAX_C && line[i] == '/' && i + 1 < len &&
|
||||
line[i + 1] == '*') {
|
||||
/* C block comment open-slash-star: closes on this line, or runs to
|
||||
EOL and leaves in_block_comment set for the following lines. */
|
||||
i += 2;
|
||||
while(i < len) {
|
||||
if(line[i] == '*' && i + 1 < len && line[i + 1] == '/') {
|
||||
i += 2;
|
||||
if(in_block_comment != NULL)
|
||||
*in_block_comment = 0;
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
if(i >= len && in_block_comment != NULL)
|
||||
*in_block_comment = 1;
|
||||
return i - index;
|
||||
}
|
||||
if(line[i] == '/' || line[i] == '%' ||
|
||||
(syntax == UI_SYNTAX_MAKE && line[i] == '$') ||
|
||||
(line[i] == '.' && i + 1 < len && (line[i + 1] == '/' || line[i + 1] == '.'))) {
|
||||
@@ -1926,15 +2069,18 @@ ui_draw_text_area_selection(const char *text, int line_start, int line_end,
|
||||
|
||||
static void
|
||||
ui_draw_syntax_line(const char *line, int len, int x, int y, int font,
|
||||
UISyntaxMode syntax, UITextInputStyle style)
|
||||
UISyntaxMode syntax, UITextInputStyle style,
|
||||
int *in_block_comment)
|
||||
{
|
||||
char token[1024];
|
||||
int offset = 0;
|
||||
int first_token = 1;
|
||||
|
||||
while(offset < len) {
|
||||
int was_in_block_comment = in_block_comment != NULL &&
|
||||
*in_block_comment;
|
||||
int token_len = ui_syntax_token_len(line, len, offset, syntax,
|
||||
first_token);
|
||||
first_token, in_block_comment);
|
||||
Color color;
|
||||
int token_is_first;
|
||||
|
||||
@@ -1945,8 +2091,11 @@ ui_draw_syntax_line(const char *line, int len, int x, int y, int font,
|
||||
memcpy(token, line + offset, (size_t)token_len);
|
||||
token[token_len] = '\0';
|
||||
token_is_first = first_token;
|
||||
color = ui_syntax_token_color(syntax, token, token_len, token_is_first,
|
||||
style);
|
||||
if(was_in_block_comment)
|
||||
color = (Color){88, 88, 88, 255};
|
||||
else
|
||||
color = ui_syntax_token_color(syntax, token, token_len,
|
||||
token_is_first, style);
|
||||
if(token[0] != ' ' && token[0] != '\t')
|
||||
first_token = 0;
|
||||
DrawUIText(token, x, y, font, color);
|
||||
@@ -1960,16 +2109,20 @@ ui_draw_text_area_text(const char *text, int cursor, int focused,
|
||||
Rectangle bounds, int font, int line_gap,
|
||||
int scroll_y, UISyntaxMode syntax,
|
||||
UITextInputStyle style, int selection_start,
|
||||
int selection_end)
|
||||
int selection_end, int text_x_offset)
|
||||
{
|
||||
char line[1024];
|
||||
char num[16];
|
||||
int len;
|
||||
int line_start = 0;
|
||||
int line_no = 1;
|
||||
int in_block_comment = 0;
|
||||
int padding_x = style.padding_x > 0 ? style.padding_x : ScaleUIPx(10);
|
||||
int padding_y = style.padding_y > 0 ? style.padding_y : ScaleUIPx(8);
|
||||
int text_x = (int)bounds.x + padding_x;
|
||||
int text_x = (int)bounds.x + padding_x + text_x_offset;
|
||||
int text_y = (int)bounds.y + padding_y - scroll_y;
|
||||
int draw_y = text_y;
|
||||
Color gutter_color = (Color){88, 88, 88, 255};
|
||||
|
||||
if(text == NULL)
|
||||
text = "";
|
||||
@@ -1991,13 +2144,22 @@ ui_draw_text_area_text(const char *text, int cursor, int focused,
|
||||
DrawUIText(line, text_x, draw_y, line_font, style.text);
|
||||
else
|
||||
ui_draw_syntax_line(line, line_len, text_x, draw_y,
|
||||
line_font, syntax, style);
|
||||
line_font, syntax, style,
|
||||
&in_block_comment);
|
||||
if(focused && cursor >= line_start && cursor <= i && (((int)(GetTime() * 2.0)) % 2 == 0)) {
|
||||
int cursor_x = text_x + ui_text_column_x(text, line_start, cursor, line_font);
|
||||
DrawRectangle(cursor_x, draw_y, ScaleUIPx(2), GetUITextLineHeight(line_font), style.cursor);
|
||||
}
|
||||
if(text_x_offset > 0) {
|
||||
snprintf(num, sizeof(num), "%d", line_no);
|
||||
DrawUIText(num,
|
||||
(int)bounds.x + padding_x + text_x_offset -
|
||||
MeasureUIText(num, line_font) - ScaleUIPx(6),
|
||||
draw_y, line_font, gutter_color);
|
||||
}
|
||||
draw_y += line_h;
|
||||
line_start = i + 1;
|
||||
line_no++;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2047,6 +2209,18 @@ DrawUITextArea(UITextArea area)
|
||||
line_h = GetUITextLineHeight(font) + line_gap;
|
||||
padding_x = area.style.padding_x > 0 ? area.style.padding_x : ScaleUIPx(10);
|
||||
padding_y = area.style.padding_y > 0 ? area.style.padding_y : ScaleUIPx(8);
|
||||
int gutter_w = 0;
|
||||
if(area.show_line_numbers) {
|
||||
int total_lines = 1;
|
||||
const char *p;
|
||||
for(p = area.text; *p; p++)
|
||||
if(*p == '\n')
|
||||
total_lines++;
|
||||
char digit_str[16];
|
||||
snprintf(digit_str, sizeof(digit_str), "%d", total_lines);
|
||||
/* Room for the widest line number plus a right gap. */
|
||||
gutter_w = MeasureUIText(digit_str, font) + ScaleUIPx(12);
|
||||
}
|
||||
first_line_y = GetUIControlTextY("Hg", (int)area.bounds.y + padding_y,
|
||||
line_h, font);
|
||||
focused = *area.focused != 0;
|
||||
@@ -2055,6 +2229,7 @@ DrawUITextArea(UITextArea area)
|
||||
|
||||
if(area.focus_id > 0 && RegisterUIFocus(area.focus_id, area.bounds)) {
|
||||
focused = 1;
|
||||
ClaimUITextAreaFocus(area.focused);
|
||||
DrawUIFocus(area.bounds);
|
||||
}
|
||||
|
||||
@@ -2074,12 +2249,13 @@ DrawUITextArea(UITextArea area)
|
||||
int double_click_slop = ScaleUIPx(6);
|
||||
|
||||
focused = 1;
|
||||
ClaimUITextFocus(area.focused);
|
||||
ClaimUITextAreaFocus(area.focused);
|
||||
clicked_cursor = ui_text_area_cursor_from_point(area.text, font, line_gap,
|
||||
(int)area.bounds.x + padding_x, (int)area.bounds.y + padding_y,
|
||||
(int)area.bounds.x + padding_x + gutter_w, (int)area.bounds.y + padding_y,
|
||||
(int)mouse_world.x, (int)mouse_world.y, scroll_y);
|
||||
*area.cursor_position = clicked_cursor;
|
||||
if(g_ui_text_area_last_click_id == drag_id &&
|
||||
if(g_ui_text_area_last_click_owner == area.focused &&
|
||||
(drag_id <= 0 || g_ui_text_area_last_click_id == drag_id) &&
|
||||
now - g_ui_text_area_last_click_time <= 0.45 &&
|
||||
click_dx >= -double_click_slop &&
|
||||
click_dx <= double_click_slop &&
|
||||
@@ -2090,23 +2266,24 @@ DrawUITextArea(UITextArea area)
|
||||
|
||||
if(ui_text_area_select_word(area.text, clicked_cursor,
|
||||
&word_start, &word_end)) {
|
||||
g_ui_text_area_selection.id = drag_id;
|
||||
g_ui_text_area_selection.anchor = word_start;
|
||||
g_ui_text_area_selection.cursor = word_end;
|
||||
g_ui_text_area_selection.dragging = 0;
|
||||
ui_text_selection_set(&g_ui_text_area_selection, drag_id,
|
||||
area.focused, word_start, word_end,
|
||||
0);
|
||||
*area.cursor_position = word_end;
|
||||
double_clicked = 1;
|
||||
g_ui_text_area_drag_id = 0;
|
||||
g_ui_text_area_drag_owner = NULL;
|
||||
}
|
||||
}
|
||||
if(!double_clicked) {
|
||||
g_ui_text_area_drag_id = drag_id;
|
||||
g_ui_text_area_selection.id = drag_id;
|
||||
g_ui_text_area_selection.anchor = *area.cursor_position;
|
||||
g_ui_text_area_selection.cursor = *area.cursor_position;
|
||||
g_ui_text_area_selection.dragging = 1;
|
||||
g_ui_text_area_drag_owner = area.focused;
|
||||
ui_text_selection_set(&g_ui_text_area_selection, drag_id,
|
||||
area.focused, *area.cursor_position,
|
||||
*area.cursor_position, 1);
|
||||
}
|
||||
g_ui_text_area_last_click_id = drag_id;
|
||||
g_ui_text_area_last_click_owner = area.focused;
|
||||
g_ui_text_area_last_click_cursor = clicked_cursor;
|
||||
g_ui_text_area_last_click_x = (int)mouse_world.x;
|
||||
g_ui_text_area_last_click_y = (int)mouse_world.y;
|
||||
@@ -2115,7 +2292,8 @@ DrawUITextArea(UITextArea area)
|
||||
focused = 0;
|
||||
}
|
||||
}
|
||||
if(g_ui_text_area_drag_id == drag_id && IsMouseButtonDown(MOUSE_BUTTON_LEFT)) {
|
||||
if(g_ui_text_area_drag_owner == area.focused &&
|
||||
IsMouseButtonDown(MOUSE_BUTTON_LEFT)) {
|
||||
if((int)mouse_world.y < (int)area.bounds.y + padding_y)
|
||||
scroll_y -= line_h;
|
||||
if((int)mouse_world.y > (int)(area.bounds.y + area.bounds.height) - padding_y)
|
||||
@@ -2123,18 +2301,22 @@ DrawUITextArea(UITextArea area)
|
||||
if(scroll_y < 0)
|
||||
scroll_y = 0;
|
||||
focused = 1;
|
||||
ClaimUITextFocus(area.focused);
|
||||
ClaimUITextAreaFocus(area.focused);
|
||||
*area.cursor_position = ui_text_area_cursor_from_point(area.text, font, line_gap,
|
||||
(int)area.bounds.x + padding_x, (int)area.bounds.y + padding_y,
|
||||
(int)area.bounds.x + padding_x + gutter_w, (int)area.bounds.y + padding_y,
|
||||
(int)mouse_world.x, (int)mouse_world.y, scroll_y);
|
||||
if(g_ui_text_area_selection.id == drag_id) {
|
||||
if(ui_text_selection_matches(g_ui_text_area_selection, drag_id,
|
||||
area.focused)) {
|
||||
g_ui_text_area_selection.cursor = *area.cursor_position;
|
||||
g_ui_text_area_selection.dragging = 1;
|
||||
}
|
||||
}
|
||||
if(g_ui_text_area_drag_id == drag_id && IsMouseButtonReleased(MOUSE_BUTTON_LEFT)) {
|
||||
if(g_ui_text_area_drag_owner == area.focused &&
|
||||
IsMouseButtonReleased(MOUSE_BUTTON_LEFT)) {
|
||||
g_ui_text_area_drag_id = 0;
|
||||
if(g_ui_text_area_selection.id == drag_id)
|
||||
g_ui_text_area_drag_owner = NULL;
|
||||
if(ui_text_selection_matches(g_ui_text_area_selection, drag_id,
|
||||
area.focused))
|
||||
g_ui_text_area_selection.dragging = 0;
|
||||
}
|
||||
|
||||
@@ -2144,7 +2326,8 @@ DrawUITextArea(UITextArea area)
|
||||
(UIKeyPressed(KEY_ENTER) ||
|
||||
UIKeyPressed(KEY_KP_ENTER) ||
|
||||
g_ui_text_input_enter_count > 0);
|
||||
if(g_ui_text_area_selection.id == drag_id) {
|
||||
if(focused && ui_text_selection_matches(g_ui_text_area_selection, drag_id,
|
||||
area.focused)) {
|
||||
selection_start = g_ui_text_area_selection.anchor;
|
||||
selection_end = g_ui_text_area_selection.cursor;
|
||||
if(selection_start > selection_end) {
|
||||
@@ -2159,10 +2342,8 @@ DrawUITextArea(UITextArea area)
|
||||
if(ui_mod_key_down() && UIKeyPressed(KEY_A)) {
|
||||
int len = (int)strlen(area.text);
|
||||
|
||||
g_ui_text_area_selection.id = drag_id;
|
||||
g_ui_text_area_selection.anchor = 0;
|
||||
g_ui_text_area_selection.cursor = len;
|
||||
g_ui_text_area_selection.dragging = 0;
|
||||
ui_text_selection_set(&g_ui_text_area_selection, drag_id,
|
||||
area.focused, 0, len, 0);
|
||||
*area.cursor_position = len;
|
||||
selection_start = 0;
|
||||
selection_end = len;
|
||||
@@ -2179,8 +2360,9 @@ DrawUITextArea(UITextArea area)
|
||||
ui_text_delete_range(area.text, area.text_size,
|
||||
area.cursor_position, selection_start,
|
||||
selection_end)) {
|
||||
g_ui_text_area_selection.anchor = *area.cursor_position;
|
||||
g_ui_text_area_selection.cursor = *area.cursor_position;
|
||||
ui_text_selection_set(&g_ui_text_area_selection, drag_id,
|
||||
area.focused, *area.cursor_position,
|
||||
*area.cursor_position, 0);
|
||||
changed = 1;
|
||||
}
|
||||
selection_key_handled = 1;
|
||||
@@ -2200,8 +2382,9 @@ DrawUITextArea(UITextArea area)
|
||||
}, 1)) {
|
||||
changed = 1;
|
||||
}
|
||||
g_ui_text_area_selection.anchor = *area.cursor_position;
|
||||
g_ui_text_area_selection.cursor = *area.cursor_position;
|
||||
ui_text_selection_set(&g_ui_text_area_selection, drag_id,
|
||||
area.focused, *area.cursor_position,
|
||||
*area.cursor_position, 0);
|
||||
selection_key_handled = 1;
|
||||
} else if(ui_mod_key_down() && UIKeyPressed(KEY_V)) {
|
||||
if(ui_text_paste_clipboard((UITextEdit){
|
||||
@@ -2212,8 +2395,9 @@ DrawUITextArea(UITextArea area)
|
||||
.filter = area.filter,
|
||||
.filter_user_data = area.filter_user_data
|
||||
}, 1)) {
|
||||
g_ui_text_area_selection.anchor = *area.cursor_position;
|
||||
g_ui_text_area_selection.cursor = *area.cursor_position;
|
||||
ui_text_selection_set(&g_ui_text_area_selection, drag_id,
|
||||
area.focused, *area.cursor_position,
|
||||
*area.cursor_position, 0);
|
||||
changed = 1;
|
||||
}
|
||||
selection_key_handled = 1;
|
||||
@@ -2223,8 +2407,9 @@ DrawUITextArea(UITextArea area)
|
||||
if(ui_text_delete_range(area.text, area.text_size,
|
||||
area.cursor_position, selection_start,
|
||||
selection_end)) {
|
||||
g_ui_text_area_selection.anchor = *area.cursor_position;
|
||||
g_ui_text_area_selection.cursor = *area.cursor_position;
|
||||
ui_text_selection_set(&g_ui_text_area_selection, drag_id,
|
||||
area.focused, *area.cursor_position,
|
||||
*area.cursor_position, 0);
|
||||
changed = 1;
|
||||
}
|
||||
g_ui_text_input_backspace_count = 0;
|
||||
@@ -2298,10 +2483,9 @@ DrawUITextArea(UITextArea area)
|
||||
inserted = 1;
|
||||
}
|
||||
if(inserted) {
|
||||
g_ui_text_area_selection.id = drag_id;
|
||||
g_ui_text_area_selection.anchor = *area.cursor_position;
|
||||
g_ui_text_area_selection.cursor = *area.cursor_position;
|
||||
g_ui_text_area_selection.dragging = 0;
|
||||
ui_text_selection_set(&g_ui_text_area_selection, drag_id,
|
||||
area.focused, *area.cursor_position,
|
||||
*area.cursor_position, 0);
|
||||
selection_key_handled = 1;
|
||||
}
|
||||
}
|
||||
@@ -2336,9 +2520,9 @@ DrawUITextArea(UITextArea area)
|
||||
UIKeyPressed(KEY_HOME) || UIKeyPressed(KEY_END) ||
|
||||
UIKeyPressed(KEY_UP) || UIKeyPressed(KEY_DOWN)) {
|
||||
if(!g_ui_text_area_selection.dragging) {
|
||||
g_ui_text_area_selection.id = drag_id;
|
||||
g_ui_text_area_selection.anchor = *area.cursor_position;
|
||||
g_ui_text_area_selection.cursor = *area.cursor_position;
|
||||
ui_text_selection_set(&g_ui_text_area_selection, drag_id,
|
||||
area.focused, *area.cursor_position,
|
||||
*area.cursor_position, 0);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -2369,13 +2553,13 @@ DrawUITextArea(UITextArea area)
|
||||
ui_begin_world_clip((Rectangle){area.bounds.x + padding_x, area.bounds.y + padding_y,
|
||||
area.bounds.width - padding_x * 2, area.bounds.height - padding_y * 2});
|
||||
if(area.text[0] == '\0' && !focused && area.placeholder != NULL)
|
||||
DrawUIText(area.placeholder, (int)area.bounds.x + padding_x,
|
||||
DrawUIText(area.placeholder, (int)area.bounds.x + padding_x + gutter_w,
|
||||
first_line_y, font, area.style.border);
|
||||
else
|
||||
ui_draw_text_area_text(area.text, *area.cursor_position, focused,
|
||||
area.bounds, font, line_gap, scroll_y,
|
||||
area.syntax, area.style, selection_start,
|
||||
selection_end);
|
||||
selection_end, gutter_w);
|
||||
EndUIClip();
|
||||
EndUIWidget(&widget);
|
||||
return changed;
|
||||
@@ -2415,10 +2599,8 @@ SetUITextAreaSelection(int focus_id, int anchor, int cursor)
|
||||
{
|
||||
if(focus_id <= 0)
|
||||
return;
|
||||
g_ui_text_area_selection.id = focus_id;
|
||||
g_ui_text_area_selection.anchor = anchor;
|
||||
g_ui_text_area_selection.cursor = cursor;
|
||||
g_ui_text_area_selection.dragging = 0;
|
||||
ui_text_selection_set(&g_ui_text_area_selection, focus_id, NULL,
|
||||
anchor, cursor, 0);
|
||||
}
|
||||
|
||||
int
|
||||
@@ -2460,6 +2642,7 @@ DrawUITextField(UITextField field)
|
||||
|
||||
if(field.focus_id > 0 && RegisterUIFocus(field.focus_id, field.bounds)) {
|
||||
focused = 1;
|
||||
ClaimUITextFieldFocus(field.focused);
|
||||
DrawUIFocus(field.bounds);
|
||||
}
|
||||
|
||||
@@ -2472,38 +2655,40 @@ DrawUITextField(UITextField field)
|
||||
if(IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
|
||||
if(mouse_inside && !captured) {
|
||||
focused = 1;
|
||||
ClaimUITextFocus(field.focused);
|
||||
ClaimUITextFieldFocus(field.focused);
|
||||
*field.cursor_position = ui_text_cursor_from_x(
|
||||
field.text, font, (int)field.bounds.x + padding_x,
|
||||
(int)mouse_world.x);
|
||||
g_ui_text_field_selection.id = field.focus_id;
|
||||
g_ui_text_field_selection.anchor = *field.cursor_position;
|
||||
g_ui_text_field_selection.cursor = *field.cursor_position;
|
||||
g_ui_text_field_selection.dragging = 1;
|
||||
g_ui_text_field_drag_id = field.focus_id;
|
||||
g_ui_text_field_drag_owner = field.focused;
|
||||
ui_text_selection_set(&g_ui_text_field_selection, field.focus_id,
|
||||
field.focused, *field.cursor_position,
|
||||
*field.cursor_position, 1);
|
||||
} else if(focused) {
|
||||
focused = 0;
|
||||
}
|
||||
}
|
||||
if(g_ui_text_field_drag_id == field.focus_id &&
|
||||
if(g_ui_text_field_drag_owner == field.focused &&
|
||||
IsMouseButtonDown(MOUSE_BUTTON_LEFT)) {
|
||||
focused = 1;
|
||||
ClaimUITextFocus(field.focused);
|
||||
ClaimUITextFieldFocus(field.focused);
|
||||
*field.cursor_position = ui_text_cursor_from_x(
|
||||
field.text, font, (int)field.bounds.x + padding_x,
|
||||
(int)mouse_world.x);
|
||||
g_ui_text_field_selection.cursor = *field.cursor_position;
|
||||
g_ui_text_field_selection.dragging = 1;
|
||||
}
|
||||
if(g_ui_text_field_drag_id == field.focus_id &&
|
||||
if(g_ui_text_field_drag_owner == field.focused &&
|
||||
IsMouseButtonReleased(MOUSE_BUTTON_LEFT)) {
|
||||
g_ui_text_field_drag_id = 0;
|
||||
g_ui_text_field_drag_owner = NULL;
|
||||
g_ui_text_field_selection.dragging = 0;
|
||||
}
|
||||
|
||||
*field.focused = focused;
|
||||
SetUIFocusTextInputActive(focused);
|
||||
if(g_ui_text_field_selection.id == field.focus_id)
|
||||
if(focused && ui_text_selection_matches(g_ui_text_field_selection,
|
||||
field.focus_id, field.focused))
|
||||
ui_selection_range(g_ui_text_field_selection, field.text,
|
||||
&selection_start, &selection_end);
|
||||
|
||||
@@ -2511,10 +2696,8 @@ DrawUITextField(UITextField field)
|
||||
if(ui_mod_key_down() && UIKeyPressed(KEY_A)) {
|
||||
int len = (int)strlen(field.text);
|
||||
|
||||
g_ui_text_field_selection.id = field.focus_id;
|
||||
g_ui_text_field_selection.anchor = 0;
|
||||
g_ui_text_field_selection.cursor = len;
|
||||
g_ui_text_field_selection.dragging = 0;
|
||||
ui_text_selection_set(&g_ui_text_field_selection, field.focus_id,
|
||||
field.focused, 0, len, 0);
|
||||
*field.cursor_position = len;
|
||||
selection_start = 0;
|
||||
selection_end = len;
|
||||
@@ -2541,8 +2724,9 @@ DrawUITextField(UITextField field)
|
||||
*field.cursor_position = 0;
|
||||
changed = 1;
|
||||
}
|
||||
g_ui_text_field_selection.anchor = *field.cursor_position;
|
||||
g_ui_text_field_selection.cursor = *field.cursor_position;
|
||||
ui_text_selection_set(&g_ui_text_field_selection, field.focus_id,
|
||||
field.focused, *field.cursor_position,
|
||||
*field.cursor_position, 0);
|
||||
selection_start = selection_end = *field.cursor_position;
|
||||
selection_handled = 1;
|
||||
}
|
||||
@@ -2560,8 +2744,9 @@ DrawUITextField(UITextField field)
|
||||
.filter_user_data = field.filter_user_data
|
||||
}, 0))
|
||||
changed = 1;
|
||||
g_ui_text_field_selection.anchor = *field.cursor_position;
|
||||
g_ui_text_field_selection.cursor = *field.cursor_position;
|
||||
ui_text_selection_set(&g_ui_text_field_selection, field.focus_id,
|
||||
field.focused, *field.cursor_position,
|
||||
*field.cursor_position, 0);
|
||||
selection_start = selection_end = *field.cursor_position;
|
||||
selection_handled = 1;
|
||||
}
|
||||
@@ -2572,8 +2757,9 @@ DrawUITextField(UITextField field)
|
||||
selection_end))
|
||||
changed = 1;
|
||||
g_ui_text_input_backspace_count = 0;
|
||||
g_ui_text_field_selection.anchor = *field.cursor_position;
|
||||
g_ui_text_field_selection.cursor = *field.cursor_position;
|
||||
ui_text_selection_set(&g_ui_text_field_selection, field.focus_id,
|
||||
field.focused, *field.cursor_position,
|
||||
*field.cursor_position, 0);
|
||||
selection_start = selection_end = *field.cursor_position;
|
||||
selection_handled = 1;
|
||||
}
|
||||
@@ -2618,8 +2804,10 @@ DrawUITextField(UITextField field)
|
||||
if(g_ui_text_input_codepoint_count > 0)
|
||||
g_ui_text_input_codepoint_count = 0;
|
||||
if(inserted) {
|
||||
g_ui_text_field_selection.anchor = *field.cursor_position;
|
||||
g_ui_text_field_selection.cursor = *field.cursor_position;
|
||||
ui_text_selection_set(&g_ui_text_field_selection,
|
||||
field.focus_id, field.focused,
|
||||
*field.cursor_position,
|
||||
*field.cursor_position, 0);
|
||||
selection_start = selection_end = *field.cursor_position;
|
||||
selection_handled = 1;
|
||||
}
|
||||
@@ -2640,20 +2828,16 @@ DrawUITextField(UITextField field)
|
||||
if(changed || UIKeyPressed(KEY_LEFT) || UIKeyPressed(KEY_RIGHT) ||
|
||||
UIKeyPressed(KEY_HOME) || UIKeyPressed(KEY_END)) {
|
||||
if(!g_ui_text_field_selection.dragging) {
|
||||
g_ui_text_field_selection.id = field.focus_id;
|
||||
g_ui_text_field_selection.anchor = *field.cursor_position;
|
||||
g_ui_text_field_selection.cursor = *field.cursor_position;
|
||||
ui_text_selection_set(&g_ui_text_field_selection,
|
||||
field.focus_id, field.focused,
|
||||
*field.cursor_position,
|
||||
*field.cursor_position, 0);
|
||||
selection_start = selection_end = *field.cursor_position;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
int len = (int)strlen(field.text);
|
||||
*field.cursor_position = ui_clampi(*field.cursor_position, 0, len);
|
||||
if(g_ui_text_field_selection.id == field.focus_id) {
|
||||
g_ui_text_field_selection.anchor = *field.cursor_position;
|
||||
g_ui_text_field_selection.cursor = *field.cursor_position;
|
||||
selection_start = selection_end = *field.cursor_position;
|
||||
}
|
||||
}
|
||||
|
||||
DrawUITextInputEx(field.bounds, field.text, *field.cursor_position,
|
||||
|
||||
+212
-78
@@ -1,4 +1,5 @@
|
||||
#include "ui_text.h"
|
||||
#include "ui_text_backend.h"
|
||||
#include "ui_clip.h"
|
||||
#include "ui_internal.h"
|
||||
#include "ui_widget.h"
|
||||
@@ -17,13 +18,17 @@
|
||||
|
||||
typedef struct UIFontEntry {
|
||||
char name[32];
|
||||
char file_type_buf[8];
|
||||
Font font;
|
||||
Font small_font;
|
||||
const char *file_type;
|
||||
const unsigned char *font_data;
|
||||
unsigned int font_data_size;
|
||||
int owns_font_data;
|
||||
int dynamic_codepoints;
|
||||
int *codepoints;
|
||||
int codepoint_count;
|
||||
int codepoint_cap;
|
||||
Font cache[UI_FONT_CACHE_COUNT];
|
||||
int cache_size[UI_FONT_CACHE_COUNT];
|
||||
} UIFontEntry;
|
||||
@@ -58,22 +63,13 @@ text_world_rect_to_screen(Rectangle rect)
|
||||
static int
|
||||
font_valid(Font font)
|
||||
{
|
||||
return font.texture.id != 0 && font.glyphs != NULL && font.recs != NULL &&
|
||||
font.glyphCount > 0 && font.baseSize > 0;
|
||||
return UIFontReady(font);
|
||||
}
|
||||
|
||||
int
|
||||
UIFontHasGlyph(Font font, int codepoint)
|
||||
{
|
||||
if(!font_valid(font))
|
||||
return 0;
|
||||
|
||||
for(int i = 0; i < font.glyphCount; i++) {
|
||||
if(font.glyphs[i].value == codepoint)
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
return UIFontHasGlyphValue(font, codepoint);
|
||||
}
|
||||
|
||||
static int
|
||||
@@ -133,6 +129,66 @@ clear_font_cache(UIFontEntry *entry)
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
clear_font_entry(UIFontEntry *entry)
|
||||
{
|
||||
if(entry == NULL)
|
||||
return;
|
||||
clear_font_cache(entry);
|
||||
if(entry->owns_font_data)
|
||||
UnloadFileData((unsigned char *)entry->font_data);
|
||||
free(entry->codepoints);
|
||||
entry->font = (Font){0};
|
||||
entry->small_font = (Font){0};
|
||||
entry->file_type = NULL;
|
||||
entry->file_type_buf[0] = '\0';
|
||||
entry->font_data = NULL;
|
||||
entry->font_data_size = 0;
|
||||
entry->owns_font_data = 0;
|
||||
entry->dynamic_codepoints = 0;
|
||||
entry->codepoints = NULL;
|
||||
entry->codepoint_count = 0;
|
||||
entry->codepoint_cap = 0;
|
||||
}
|
||||
|
||||
static int
|
||||
font_entry_has_codepoint(UIFontEntry *entry, int codepoint)
|
||||
{
|
||||
if(entry == NULL || codepoint <= 0)
|
||||
return 0;
|
||||
for(int i = 0; i < entry->codepoint_count; i++) {
|
||||
if(entry->codepoints[i] == codepoint)
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
font_entry_add_codepoint(UIFontEntry *entry, int codepoint)
|
||||
{
|
||||
int *next;
|
||||
int next_cap;
|
||||
|
||||
if(entry == NULL || codepoint <= 0 || codepoint >= 0x110000)
|
||||
return 0;
|
||||
if(codepoint >= 0xD800 && codepoint <= 0xDFFF)
|
||||
return 0;
|
||||
if(font_entry_has_codepoint(entry, codepoint))
|
||||
return 1;
|
||||
|
||||
if(entry->codepoint_count >= entry->codepoint_cap) {
|
||||
next_cap = entry->codepoint_cap == 0 ? 128 : entry->codepoint_cap * 2;
|
||||
next = realloc(entry->codepoints, (size_t)next_cap * sizeof(*next));
|
||||
if(next == NULL)
|
||||
return 0;
|
||||
entry->codepoints = next;
|
||||
entry->codepoint_cap = next_cap;
|
||||
}
|
||||
|
||||
entry->codepoints[entry->codepoint_count++] = codepoint;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static Font
|
||||
load_font_source_size(UIFontEntry *entry, int physical_size)
|
||||
{
|
||||
@@ -146,7 +202,7 @@ load_font_source_size(UIFontEntry *entry, int physical_size)
|
||||
entry->font_data, (int)entry->font_data_size, physical_size,
|
||||
entry->codepoints, entry->codepoint_count);
|
||||
if(font_valid(font))
|
||||
SetTextureFilter(font.texture, TEXTURE_FILTER_BILINEAR);
|
||||
SetTextureFilter(UIFontAtlasTexture(font), TEXTURE_FILTER_BILINEAR);
|
||||
return font;
|
||||
}
|
||||
|
||||
@@ -177,17 +233,55 @@ entry_source_font_for_size(UIFontEntry *entry, int font_size)
|
||||
return entry->cache[empty];
|
||||
}
|
||||
|
||||
static Font
|
||||
entry_font_for_size(UIFontEntry *entry, int font_size)
|
||||
{
|
||||
Font font;
|
||||
|
||||
if(entry == NULL)
|
||||
return (Font){0};
|
||||
|
||||
font = entry_source_font_for_size(entry, font_size);
|
||||
if(font_valid(font))
|
||||
return font;
|
||||
if(font_size == UI_TEXT_8 && font_valid(entry->small_font))
|
||||
return entry->small_font;
|
||||
if(font_valid(entry->font))
|
||||
return entry->font;
|
||||
return (Font){0};
|
||||
}
|
||||
|
||||
static Font
|
||||
entry_font_for_codepoint(UIFontEntry *entry, int codepoint, int font_size)
|
||||
{
|
||||
Font font;
|
||||
|
||||
if(entry == NULL)
|
||||
return (Font){0};
|
||||
if(entry->dynamic_codepoints && codepoint > 0 &&
|
||||
!font_entry_has_codepoint(entry, codepoint)) {
|
||||
if(font_entry_add_codepoint(entry, codepoint))
|
||||
clear_font_cache(entry);
|
||||
}
|
||||
|
||||
font = entry_font_for_size(entry, font_size);
|
||||
if(!font_valid(font))
|
||||
return (Font){0};
|
||||
if(codepoint <= 0 || codepoint == ' ' || codepoint == '\t' ||
|
||||
UIFontHasGlyphValue(font, codepoint))
|
||||
return font;
|
||||
return (Font){0};
|
||||
}
|
||||
|
||||
static Font
|
||||
active_font(void)
|
||||
{
|
||||
if(g_ui_active_font >= 0 && g_ui_active_font < g_ui_font_count) {
|
||||
Font font;
|
||||
Font font = entry_font_for_size(&g_ui_fonts[g_ui_active_font],
|
||||
UI_TEXT_BASE_SIZE);
|
||||
|
||||
font = entry_source_font_for_size(&g_ui_fonts[g_ui_active_font], UI_TEXT_BASE_SIZE);
|
||||
if(font_valid(font))
|
||||
return font;
|
||||
if(font_valid(g_ui_fonts[g_ui_active_font].font))
|
||||
return g_ui_fonts[g_ui_active_font].font;
|
||||
}
|
||||
|
||||
return GetFontDefault();
|
||||
@@ -197,13 +291,10 @@ static Font
|
||||
active_font_for_size(int font_size)
|
||||
{
|
||||
if(g_ui_active_font >= 0 && g_ui_active_font < g_ui_font_count) {
|
||||
Font font;
|
||||
Font font = entry_font_for_size(&g_ui_fonts[g_ui_active_font], font_size);
|
||||
|
||||
font = entry_source_font_for_size(&g_ui_fonts[g_ui_active_font], font_size);
|
||||
if(font_valid(font))
|
||||
return font;
|
||||
if(font_size == UI_TEXT_8 && font_valid(g_ui_fonts[g_ui_active_font].small_font))
|
||||
return g_ui_fonts[g_ui_active_font].small_font;
|
||||
}
|
||||
|
||||
return active_font();
|
||||
@@ -212,26 +303,39 @@ active_font_for_size(int font_size)
|
||||
static Font
|
||||
font_for_codepoint(int codepoint, int font_size)
|
||||
{
|
||||
Font font = active_font_for_size(font_size);
|
||||
if(g_ui_active_font >= 0 && g_ui_active_font < g_ui_font_count) {
|
||||
Font font = entry_font_for_codepoint(&g_ui_fonts[g_ui_active_font],
|
||||
codepoint, font_size);
|
||||
|
||||
(void)codepoint;
|
||||
return font;
|
||||
if(font_valid(font))
|
||||
return font;
|
||||
}
|
||||
|
||||
for(int i = 0; i < g_ui_font_count; i++) {
|
||||
Font font;
|
||||
|
||||
if(i == g_ui_active_font)
|
||||
continue;
|
||||
font = entry_font_for_codepoint(&g_ui_fonts[i], codepoint, font_size);
|
||||
if(font_valid(font))
|
||||
return font;
|
||||
}
|
||||
|
||||
return active_font_for_size(font_size);
|
||||
}
|
||||
|
||||
static Font
|
||||
font_for_scaled_codepoint(int codepoint)
|
||||
{
|
||||
Font font = active_font();
|
||||
|
||||
(void)codepoint;
|
||||
return font;
|
||||
return font_for_codepoint(codepoint, UI_TEXT_BASE_SIZE);
|
||||
}
|
||||
|
||||
static float
|
||||
font_size_scale(Font font, int font_size)
|
||||
{
|
||||
int target_size = font_physical_size(font_size);
|
||||
int base_size = font.baseSize > 0 ? font.baseSize : UI_TEXT_BASE_SIZE;
|
||||
int base = UIFontBaseSize(font);
|
||||
int base_size = base > 0 ? base : UI_TEXT_BASE_SIZE;
|
||||
|
||||
return (float)target_size / (float)base_size;
|
||||
}
|
||||
@@ -254,7 +358,7 @@ RegisterUIFont(const char *name, Font font)
|
||||
if(index < 0)
|
||||
return 0;
|
||||
|
||||
clear_font_cache(&g_ui_fonts[index]);
|
||||
clear_font_entry(&g_ui_fonts[index]);
|
||||
g_ui_fonts[index].font = font;
|
||||
return 1;
|
||||
}
|
||||
@@ -271,7 +375,7 @@ RegisterUISmallFont(const char *name, Font font)
|
||||
if(index < 0)
|
||||
return 0;
|
||||
|
||||
clear_font_cache(&g_ui_fonts[index]);
|
||||
clear_font_entry(&g_ui_fonts[index]);
|
||||
g_ui_fonts[index].small_font = font;
|
||||
return 1;
|
||||
}
|
||||
@@ -290,10 +394,7 @@ RegisterUIFontSource(const char *name, const char *file_type,
|
||||
if(index < 0)
|
||||
return 0;
|
||||
|
||||
clear_font_cache(&g_ui_fonts[index]);
|
||||
free(g_ui_fonts[index].codepoints);
|
||||
g_ui_fonts[index].codepoints = NULL;
|
||||
g_ui_fonts[index].codepoint_count = 0;
|
||||
clear_font_entry(&g_ui_fonts[index]);
|
||||
|
||||
if(codepoints != NULL && codepoint_count > 0) {
|
||||
g_ui_fonts[index].codepoints = calloc((size_t)codepoint_count, sizeof(*codepoints));
|
||||
@@ -302,6 +403,7 @@ RegisterUIFontSource(const char *name, const char *file_type,
|
||||
memcpy(g_ui_fonts[index].codepoints, codepoints,
|
||||
(size_t)codepoint_count * sizeof(*codepoints));
|
||||
g_ui_fonts[index].codepoint_count = codepoint_count;
|
||||
g_ui_fonts[index].codepoint_cap = codepoint_count;
|
||||
}
|
||||
|
||||
g_ui_fonts[index].file_type = file_type;
|
||||
@@ -312,6 +414,47 @@ RegisterUIFontSource(const char *name, const char *file_type,
|
||||
return font_valid(entry_source_font_for_size(&g_ui_fonts[index], UI_TEXT_BASE_SIZE));
|
||||
}
|
||||
|
||||
int
|
||||
RegisterUIFontFileSource(const char *name, const char *path,
|
||||
const int *codepoints, int codepoint_count,
|
||||
int dynamic_codepoints)
|
||||
{
|
||||
const char *dot;
|
||||
unsigned char *data;
|
||||
int data_size = 0;
|
||||
int ok;
|
||||
|
||||
if(path == NULL || path[0] == '\0')
|
||||
return 0;
|
||||
|
||||
data = LoadFileData(path, &data_size);
|
||||
if(data == NULL || data_size <= 0)
|
||||
return 0;
|
||||
|
||||
dot = strrchr(path, '.');
|
||||
if(dot == NULL || dot[0] == '\0')
|
||||
dot = ".ttf";
|
||||
|
||||
ok = RegisterUIFontSource(name, dot, data, (unsigned int)data_size,
|
||||
codepoints, codepoint_count);
|
||||
if(!ok) {
|
||||
UnloadFileData(data);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int index = font_entry_index(name);
|
||||
if(index < 0) {
|
||||
UnloadFileData(data);
|
||||
return 0;
|
||||
}
|
||||
snprintf(g_ui_fonts[index].file_type_buf, sizeof(g_ui_fonts[index].file_type_buf),
|
||||
"%s", dot);
|
||||
g_ui_fonts[index].file_type = g_ui_fonts[index].file_type_buf;
|
||||
g_ui_fonts[index].owns_font_data = 1;
|
||||
g_ui_fonts[index].dynamic_codepoints = dynamic_codepoints != 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int
|
||||
UseUIFont(const char *name)
|
||||
{
|
||||
@@ -405,7 +548,7 @@ LoadUIFontFromMemory(const char *file_type, const unsigned char *font_data,
|
||||
free(codepoints);
|
||||
|
||||
if(font_valid(font))
|
||||
SetTextureFilter(font.texture, TEXTURE_FILTER_BILINEAR);
|
||||
SetTextureFilter(UIFontAtlasTexture(font), TEXTURE_FILTER_BILINEAR);
|
||||
return font;
|
||||
}
|
||||
|
||||
@@ -449,8 +592,7 @@ void
|
||||
ClearUIFonts(void)
|
||||
{
|
||||
for(int i = 0; i < g_ui_font_count; i++) {
|
||||
clear_font_cache(&g_ui_fonts[i]);
|
||||
free(g_ui_fonts[i].codepoints);
|
||||
clear_font_entry(&g_ui_fonts[i]);
|
||||
}
|
||||
memset(g_ui_fonts, 0, sizeof(g_ui_fonts));
|
||||
g_ui_font_count = 0;
|
||||
@@ -463,20 +605,18 @@ MeasureUIText(const char *text, int font_size)
|
||||
Font font = active_font_for_size(font_size);
|
||||
int width = 0;
|
||||
|
||||
if(text == NULL || font.texture.id == 0 || font.glyphs == NULL || font.baseSize <= 0)
|
||||
if(text == NULL || !UIFontReady(font))
|
||||
return 0;
|
||||
|
||||
for(int i = 0; text[i] != '\0';) {
|
||||
int codepoint_byte_count = 0;
|
||||
int codepoint = GetCodepointNext(&text[i], &codepoint_byte_count);
|
||||
Font glyph_font;
|
||||
int index;
|
||||
|
||||
if(codepoint == '\n')
|
||||
break;
|
||||
glyph_font = font_for_codepoint(codepoint, font_size);
|
||||
index = GetGlyphIndex(glyph_font, codepoint);
|
||||
width += (int)((float)glyph_font.glyphs[index].advanceX *
|
||||
width += (int)((float)UIFontAdvance(glyph_font, codepoint) *
|
||||
font_size_scale(glyph_font, font_size) + 0.5f);
|
||||
i += codepoint_byte_count;
|
||||
}
|
||||
@@ -528,15 +668,13 @@ ui_text_width_bytes(const char *text, int byte_len, int font_size)
|
||||
Font font = active_font_for_size(font_size);
|
||||
int width = 0;
|
||||
|
||||
if(text == NULL || byte_len <= 0 || font.texture.id == 0 ||
|
||||
font.glyphs == NULL || font.baseSize <= 0)
|
||||
if(text == NULL || byte_len <= 0 || !UIFontReady(font))
|
||||
return 0;
|
||||
|
||||
for(int i = 0; i < byte_len && text[i] != '\0';) {
|
||||
int codepoint_byte_count = 0;
|
||||
int codepoint = GetCodepointNext(&text[i], &codepoint_byte_count);
|
||||
Font glyph_font;
|
||||
int index;
|
||||
|
||||
if(codepoint == '\n')
|
||||
break;
|
||||
@@ -545,8 +683,7 @@ ui_text_width_bytes(const char *text, int byte_len, int font_size)
|
||||
if(i + codepoint_byte_count > byte_len)
|
||||
break;
|
||||
glyph_font = font_for_codepoint(codepoint, font_size);
|
||||
index = GetGlyphIndex(glyph_font, codepoint);
|
||||
width += (int)((float)glyph_font.glyphs[index].advanceX *
|
||||
width += (int)((float)UIFontAdvance(glyph_font, codepoint) *
|
||||
font_size_scale(glyph_font, font_size) + 0.5f);
|
||||
i += codepoint_byte_count;
|
||||
}
|
||||
@@ -567,7 +704,6 @@ ui_text_byte_offset_at_x(const char *text, int font_size, int target_x)
|
||||
int codepoint_byte_count = 0;
|
||||
int codepoint = GetCodepointNext(&text[i], &codepoint_byte_count);
|
||||
Font glyph_font;
|
||||
int index;
|
||||
int advance;
|
||||
|
||||
if(codepoint_byte_count <= 0)
|
||||
@@ -575,8 +711,7 @@ ui_text_byte_offset_at_x(const char *text, int font_size, int target_x)
|
||||
if(i + codepoint_byte_count > byte_len)
|
||||
return i;
|
||||
glyph_font = font_for_codepoint(codepoint, font_size);
|
||||
index = GetGlyphIndex(glyph_font, codepoint);
|
||||
advance = (int)((float)glyph_font.glyphs[index].advanceX *
|
||||
advance = (int)((float)UIFontAdvance(glyph_font, codepoint) *
|
||||
font_size_scale(glyph_font, font_size) + 0.5f);
|
||||
if(target_x < cursor_x + advance / 2)
|
||||
return i;
|
||||
@@ -651,7 +786,7 @@ GetUITextHeight(const char *text, int font_size)
|
||||
float max_bottom = 0.0f;
|
||||
int seen_glyph = 0;
|
||||
|
||||
if(text == NULL || text[0] == '\0' || font.texture.id == 0 || font.baseSize <= 0)
|
||||
if(text == NULL || text[0] == '\0' || !UIFontReady(font))
|
||||
return font_size;
|
||||
|
||||
scale = font_size_scale(font, font_size);
|
||||
@@ -663,12 +798,12 @@ GetUITextHeight(const char *text, int font_size)
|
||||
break;
|
||||
if(codepoint != ' ' && codepoint != '\t') {
|
||||
Font glyph_font = font_for_codepoint(codepoint, font_size);
|
||||
int index = GetGlyphIndex(glyph_font, codepoint);
|
||||
GlyphInfo glyph = glyph_font.glyphs[index];
|
||||
Rectangle rec = glyph_font.recs[index];
|
||||
GlyphInfo glyph = UIFontGlyph(glyph_font, codepoint);
|
||||
Rectangle rec = UIFontAtlasRec(glyph_font, codepoint);
|
||||
float glyph_scale = font_size_scale(glyph_font, font_size);
|
||||
float glyph_top = (float)glyph.offsetY * glyph_scale - (float)glyph_font.glyphPadding * glyph_scale;
|
||||
float glyph_bottom = glyph_top + ((float)rec.height + 2.0f * (float)glyph_font.glyphPadding) * glyph_scale;
|
||||
int padding = UIFontGlyphPadding(glyph_font);
|
||||
float glyph_top = (float)glyph.offsetY * glyph_scale - (float)padding * glyph_scale;
|
||||
float glyph_bottom = glyph_top + ((float)rec.height + 2.0f * (float)padding) * glyph_scale;
|
||||
|
||||
if(!seen_glyph) {
|
||||
min_top = glyph_top;
|
||||
@@ -685,7 +820,7 @@ GetUITextHeight(const char *text, int font_size)
|
||||
}
|
||||
|
||||
if(!seen_glyph)
|
||||
return (int)((float)font.baseSize * scale + 0.5f);
|
||||
return (int)((float)UIFontBaseSize(font) * scale + 0.5f);
|
||||
return (int)(max_bottom - min_top + 0.5f);
|
||||
}
|
||||
|
||||
@@ -694,8 +829,9 @@ GetUITextLineHeight(int font_size)
|
||||
{
|
||||
Font font = active_font_for_size(font_size);
|
||||
float scale = font_size_scale(font, font_size);
|
||||
int base = UIFontBaseSize(font);
|
||||
|
||||
return font.baseSize > 0 ? (int)((float)font.baseSize * scale + 0.5f) :
|
||||
return base > 0 ? (int)((float)base * scale + 0.5f) :
|
||||
(int)((float)UI_TEXT_BASE_SIZE * scale + 0.5f);
|
||||
}
|
||||
|
||||
@@ -705,7 +841,7 @@ MeasureScaledUIText(const char *text, int scale)
|
||||
Font font = active_font();
|
||||
int width = 0;
|
||||
|
||||
if(text == NULL || font.texture.id == 0 || font.glyphs == NULL || font.baseSize <= 0)
|
||||
if(text == NULL || !UIFontReady(font))
|
||||
return 0;
|
||||
if(scale < 1)
|
||||
scale = 1;
|
||||
@@ -718,8 +854,7 @@ MeasureScaledUIText(const char *text, int scale)
|
||||
break;
|
||||
|
||||
Font glyph_font = font_for_scaled_codepoint(codepoint);
|
||||
int index = GetGlyphIndex(glyph_font, codepoint);
|
||||
width += glyph_font.glyphs[index].advanceX * scale;
|
||||
width += UIFontAdvance(glyph_font, codepoint) * scale;
|
||||
i += codepoint_byte_count;
|
||||
}
|
||||
|
||||
@@ -740,7 +875,7 @@ DrawUITextEx(const char *text, int x, int y, int font_size, Color color,
|
||||
int selected_start = 0;
|
||||
int selected_end = 0;
|
||||
|
||||
if(text == NULL || font.texture.id == 0 || font.glyphs == NULL || font.recs == NULL)
|
||||
if(text == NULL || !UIFontReady(font))
|
||||
return;
|
||||
|
||||
selectable = selectable_arg && g_ui_text_selectable && text[0] != '\0';
|
||||
@@ -820,7 +955,6 @@ DrawUITextEx(const char *text, int x, int y, int font_size, Color color,
|
||||
int codepoint_byte_count = 0;
|
||||
int codepoint = GetCodepointNext(&text[i], &codepoint_byte_count);
|
||||
Font glyph_font;
|
||||
int index;
|
||||
float scale;
|
||||
GlyphInfo glyph;
|
||||
Rectangle src;
|
||||
@@ -829,10 +963,9 @@ DrawUITextEx(const char *text, int x, int y, int font_size, Color color,
|
||||
break;
|
||||
|
||||
glyph_font = font_for_codepoint(codepoint, font_size);
|
||||
index = GetGlyphIndex(glyph_font, codepoint);
|
||||
scale = font_size_scale(glyph_font, font_size);
|
||||
glyph = glyph_font.glyphs[index];
|
||||
src = glyph_font.recs[index];
|
||||
glyph = UIFontGlyph(glyph_font, codepoint);
|
||||
src = UIFontAtlasRec(glyph_font, codepoint);
|
||||
|
||||
if(src.width > 0.0f && src.height > 0.0f) {
|
||||
Rectangle dst = {
|
||||
@@ -841,7 +974,7 @@ DrawUITextEx(const char *text, int x, int y, int font_size, Color color,
|
||||
.width = src.width * scale,
|
||||
.height = src.height * scale
|
||||
};
|
||||
DrawTexturePro(glyph_font.texture, src, dst, (Vector2){0.0f, 0.0f}, 0.0f, color);
|
||||
DrawTexturePro(UIFontAtlasTexture(glyph_font), src, dst, (Vector2){0.0f, 0.0f}, 0.0f, color);
|
||||
}
|
||||
|
||||
cursor_x += (int)((float)glyph.advanceX * scale + 0.5f);
|
||||
@@ -888,7 +1021,7 @@ DrawScaledUIText(const char *text, int x, int y, int scale, Color color)
|
||||
Font font = active_font();
|
||||
int cursor_x = x;
|
||||
|
||||
if(text == NULL || font.texture.id == 0 || font.glyphs == NULL || font.recs == NULL)
|
||||
if(text == NULL || !UIFontReady(font))
|
||||
return;
|
||||
if(scale < 1)
|
||||
scale = 1;
|
||||
@@ -901,9 +1034,8 @@ DrawScaledUIText(const char *text, int x, int y, int scale, Color color)
|
||||
break;
|
||||
|
||||
Font glyph_font = font_for_scaled_codepoint(codepoint);
|
||||
int index = GetGlyphIndex(glyph_font, codepoint);
|
||||
GlyphInfo glyph = glyph_font.glyphs[index];
|
||||
Rectangle src = glyph_font.recs[index];
|
||||
GlyphInfo glyph = UIFontGlyph(glyph_font, codepoint);
|
||||
Rectangle src = UIFontAtlasRec(glyph_font, codepoint);
|
||||
|
||||
if(src.width > 0.0f && src.height > 0.0f) {
|
||||
Rectangle dst = {
|
||||
@@ -912,7 +1044,7 @@ DrawScaledUIText(const char *text, int x, int y, int scale, Color color)
|
||||
.width = src.width * (float)scale,
|
||||
.height = src.height * (float)scale
|
||||
};
|
||||
DrawTexturePro(glyph_font.texture, src, dst, (Vector2){0.0f, 0.0f}, 0.0f, color);
|
||||
DrawTexturePro(UIFontAtlasTexture(glyph_font), src, dst, (Vector2){0.0f, 0.0f}, 0.0f, color);
|
||||
}
|
||||
|
||||
cursor_x += glyph.advanceX * scale;
|
||||
@@ -952,10 +1084,12 @@ GetScaledUITextY(const char *text, int box_y, int box_h, int scale)
|
||||
{
|
||||
Font font = active_font();
|
||||
int font_size;
|
||||
int base;
|
||||
|
||||
if(scale < 1)
|
||||
scale = 1;
|
||||
font_size = font.baseSize > 0 ? font.baseSize * scale : 16 * scale;
|
||||
base = UIFontBaseSize(font);
|
||||
font_size = base > 0 ? base * scale : 16 * scale;
|
||||
return GetUITextY(text, box_y, box_h, font_size);
|
||||
}
|
||||
|
||||
@@ -967,7 +1101,7 @@ GetUITextY(const char *text, int box_y, int box_h, int font_size)
|
||||
float max_bottom = 0.0f;
|
||||
int seen_glyph = 0;
|
||||
|
||||
if(text == NULL || text[0] == '\0' || font.texture.id == 0 || font.baseSize <= 0)
|
||||
if(text == NULL || text[0] == '\0' || !UIFontReady(font))
|
||||
return box_y + (int)(((float)box_h - (float)font_size) * 0.5f + 0.5f);
|
||||
|
||||
for(int i = 0; text[i] != '\0';) {
|
||||
@@ -979,12 +1113,12 @@ GetUITextY(const char *text, int box_y, int box_h, int font_size)
|
||||
|
||||
if(codepoint != ' ' && codepoint != '\t') {
|
||||
Font glyph_font = font_for_codepoint(codepoint, font_size);
|
||||
int index = GetGlyphIndex(glyph_font, codepoint);
|
||||
GlyphInfo glyph = glyph_font.glyphs[index];
|
||||
Rectangle rec = glyph_font.recs[index];
|
||||
GlyphInfo glyph = UIFontGlyph(glyph_font, codepoint);
|
||||
Rectangle rec = UIFontAtlasRec(glyph_font, codepoint);
|
||||
float glyph_scale = font_size_scale(glyph_font, font_size);
|
||||
float glyph_top = (float)glyph.offsetY * glyph_scale - (float)glyph_font.glyphPadding * glyph_scale;
|
||||
float glyph_bottom = glyph_top + ((float)rec.height + 2.0f * (float)glyph_font.glyphPadding) * glyph_scale;
|
||||
int padding = UIFontGlyphPadding(glyph_font);
|
||||
float glyph_top = (float)glyph.offsetY * glyph_scale - (float)padding * glyph_scale;
|
||||
float glyph_bottom = glyph_top + ((float)rec.height + 2.0f * (float)padding) * glyph_scale;
|
||||
|
||||
if(!seen_glyph) {
|
||||
min_top = glyph_top;
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
#include "ui_text_backend.h"
|
||||
|
||||
/*
|
||||
* Backend-neutral implementation of the text-backend seam (declared in
|
||||
* ui_text_backend.h). Every function forwards to a public-surface accessor
|
||||
* (GetGlyphInfo, GetGlyphAtlasRec, GetGlyphIndex) that the active graphics
|
||||
* backend provides, so this single source file works for all backends.
|
||||
*
|
||||
* The two validity/base-size helpers read Font struct fields because raylib
|
||||
* exposes no accessor for them; that is the one struct coupling that remains,
|
||||
* confined to these helpers rather than scattered through ui_text.c.
|
||||
*/
|
||||
|
||||
int
|
||||
UIFontReady(Font font)
|
||||
{
|
||||
return font.texture.id != 0 && font.glyphs != NULL && font.recs != NULL &&
|
||||
font.glyphCount > 0 && font.baseSize > 0;
|
||||
}
|
||||
|
||||
int
|
||||
UIFontBaseSize(Font font)
|
||||
{
|
||||
return font.baseSize;
|
||||
}
|
||||
|
||||
int
|
||||
UIFontGlyphPadding(Font font)
|
||||
{
|
||||
return font.glyphPadding;
|
||||
}
|
||||
|
||||
GlyphInfo
|
||||
UIFontGlyph(Font font, int codepoint)
|
||||
{
|
||||
return GetGlyphInfo(font, codepoint);
|
||||
}
|
||||
|
||||
Rectangle
|
||||
UIFontAtlasRec(Font font, int codepoint)
|
||||
{
|
||||
return GetGlyphAtlasRec(font, codepoint);
|
||||
}
|
||||
|
||||
Texture2D
|
||||
UIFontAtlasTexture(Font font)
|
||||
{
|
||||
return font.texture;
|
||||
}
|
||||
|
||||
int
|
||||
UIFontAdvance(Font font, int codepoint)
|
||||
{
|
||||
return GetGlyphInfo(font, codepoint).advanceX;
|
||||
}
|
||||
|
||||
int
|
||||
UIFontHasGlyphValue(Font font, int codepoint)
|
||||
{
|
||||
GlyphInfo glyph;
|
||||
|
||||
if(!UIFontReady(font))
|
||||
return 0;
|
||||
|
||||
glyph = GetGlyphInfo(font, codepoint);
|
||||
return glyph.value == codepoint;
|
||||
}
|
||||
+44
-1
@@ -656,6 +656,44 @@ ui_tree_toggle_expanded(UICascadingTreeExpansion *expansion, int id)
|
||||
*expansion->count = count;
|
||||
}
|
||||
|
||||
static void
|
||||
ui_tree_remove_expanded(UICascadingTreeExpansion *expansion, int id)
|
||||
{
|
||||
int index;
|
||||
int count;
|
||||
|
||||
if(expansion == NULL || expansion->ids == NULL || expansion->count == NULL)
|
||||
return;
|
||||
count = *expansion->count;
|
||||
index = ui_tree_expanded_index(*expansion, id);
|
||||
if(index < 0)
|
||||
return;
|
||||
for(int i = index; i + 1 < count; i++)
|
||||
expansion->ids[i] = expansion->ids[i + 1];
|
||||
if(count > 0)
|
||||
expansion->ids[count - 1] = 0;
|
||||
*expansion->count = count - 1;
|
||||
}
|
||||
|
||||
static void
|
||||
ui_tree_collapse_item_and_children(const UICascadingTreeItem *items,
|
||||
int item_count, int index,
|
||||
UICascadingTreeExpansion *expansion)
|
||||
{
|
||||
int depth;
|
||||
|
||||
if(items == NULL || index < 0 || index >= item_count || expansion == NULL)
|
||||
return;
|
||||
depth = items[index].depth;
|
||||
ui_tree_remove_expanded(expansion, items[index].id);
|
||||
for(int i = index + 1; i < item_count; i++) {
|
||||
if(items[i].depth <= depth)
|
||||
break;
|
||||
if(items[i].is_dir)
|
||||
ui_tree_remove_expanded(expansion, items[i].id);
|
||||
}
|
||||
}
|
||||
|
||||
static int
|
||||
ui_tree_item_visible(const UICascadingTreeItem *items, int index,
|
||||
UICascadingTreeExpansion expansion)
|
||||
@@ -810,7 +848,12 @@ DrawUICascadingTreeView(UICascadingTreeView tree)
|
||||
|
||||
if(hot && IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
|
||||
if(item->is_dir) {
|
||||
ui_tree_toggle_expanded(&tree.expanded, item->id);
|
||||
if(expanded)
|
||||
ui_tree_collapse_item_and_children(tree.items,
|
||||
tree.item_count, i,
|
||||
&tree.expanded);
|
||||
else
|
||||
ui_tree_toggle_expanded(&tree.expanded, item->id);
|
||||
changed = 1;
|
||||
} else if(item->selectable && tree.selected_id != NULL) {
|
||||
*tree.selected_id = item->id;
|
||||
|
||||
+320
-1
@@ -151,7 +151,11 @@ grep -Fq 'value >>= 1;' "$out/src/valid.c"
|
||||
grep -q 'while(value < 3)' "$out/src/valid.c"
|
||||
grep -q 'DrawThing( value, (ThingSpec){ .value = value, .label = "hello" } );' "$out/src/valid.c"
|
||||
grep -q 'value = value + 1;' "$out/src/valid.c"
|
||||
grep -q 'if(CheckThing( value, 1)) {' "$out/src/valid.c"
|
||||
# A call used as an if condition is wrapped so it registers a source location
|
||||
# for click-to-source: Push, evaluate into a temp, Pop, then test the temp.
|
||||
grep -Eq '__auto_type __kryon_cond_[0-9]+ = CheckThing\( value, 1\);' "$out/src/valid.c"
|
||||
grep -Eq 'if\(__kryon_cond_[0-9]+\) \{' "$out/src/valid.c"
|
||||
# A non-call condition is emitted unchanged.
|
||||
grep -Fq 'if(value > 0 && first >= 0) {' "$out/src/valid.c"
|
||||
grep -Fq 'for(int j = 0; j < 2; j++) {' "$out/src/valid.c"
|
||||
grep -q 'value = value > 0 ? value : 1;' "$out/src/valid.c"
|
||||
@@ -948,3 +952,318 @@ if "$kc" --no-main --root "$work" -o "$out" "$work/src/unbalanced.kry" >"$err" 2
|
||||
fi
|
||||
grep -q 'unbalanced braces' "$err"
|
||||
grep -Eq 'unbalanced\.kry:[0-9]+:1: error:' "$err"
|
||||
|
||||
# --- defer: deferred statements run at scope exit, before return/break/continue
|
||||
cat > "$work/src/defer.kry" <<'EOF'
|
||||
#import "thing.h"
|
||||
|
||||
work :: (x: int) -> int {
|
||||
f := x
|
||||
defer Release(f)
|
||||
if x < 0 {
|
||||
return 0
|
||||
}
|
||||
if x > 10 {
|
||||
return x
|
||||
}
|
||||
for int i = 0; i < 3; i++ {
|
||||
defer Log(i)
|
||||
if i == 1 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return x + f
|
||||
}
|
||||
EOF
|
||||
|
||||
"$kc" --no-main --root "$work" -o "$out" "$work/src/defer.kry" >"$err" 2>&1
|
||||
# Function-body defer fires before each return and before the final return.
|
||||
# The defer and return land on consecutive lines; use grep -A1 (no -q, since
|
||||
# -q suppresses the context lines the second grep needs to see).
|
||||
grep -Fq 'Release(f);' "$out/src/defer.c"
|
||||
grep -E -A1 'Release\(f\);$' "$out/src/defer.c" | grep -Eq 'return 0;'
|
||||
grep -Fq 'return x;' "$out/src/defer.c"
|
||||
grep -Fq 'return x + f;' "$out/src/defer.c"
|
||||
# Loop-body defer fires before break (registered before the break in source).
|
||||
grep -E -A1 'Log\(i\);$' "$out/src/defer.c" | grep -Eq 'break;'
|
||||
# Loop-body defer also fires at the end of each non-break iteration.
|
||||
grep -E -B1 'Log\(i\);$' "$out/src/defer.c" | grep -Eq '\}'
|
||||
# The original `defer` declaration must not survive into the output.
|
||||
if grep -q 'defer ' "$out/src/defer.c"; then
|
||||
echo "defer declaration leaked into generated C" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- defer: multiple defers in one scope run in reverse (LIFO) order
|
||||
cat > "$work/src/defer_order.kry" <<'EOF'
|
||||
#import "thing.h"
|
||||
|
||||
multi :: () -> int {
|
||||
defer First()
|
||||
defer Second()
|
||||
defer Third()
|
||||
return 0
|
||||
}
|
||||
EOF
|
||||
|
||||
"$kc" --no-main --root "$work" -o "$out" "$work/src/defer_order.kry" >"$err" 2>&1
|
||||
# Defers run in reverse (LIFO) order: Third (registered last) runs first,
|
||||
# First (registered first) runs last. Compare line numbers in the output.
|
||||
l_third=$(grep -n 'Third();' "$out/src/defer_order.c" | cut -d: -f1)
|
||||
l_second=$(grep -n 'Second();' "$out/src/defer_order.c" | cut -d: -f1)
|
||||
l_first=$(grep -n 'First();' "$out/src/defer_order.c" | cut -d: -f1)
|
||||
[ -n "$l_third" ] && [ -n "$l_second" ] && [ -n "$l_first" ] || {
|
||||
echo "defer order: missing one of Third/Second/First" >&2; exit 1; }
|
||||
[ "$l_third" -lt "$l_second" ] && [ "$l_second" -lt "$l_first" ] || {
|
||||
echo "defer order: expected Third < Second < First by line" >&2; exit 1; }
|
||||
|
||||
# --- defer: break/continue unwind only the enclosing loop body
|
||||
cat > "$work/src/defer_break.kry" <<'EOF'
|
||||
#import "thing.h"
|
||||
|
||||
loop_fn :: (n: int) -> int {
|
||||
for int i = 0; i < n; i++ {
|
||||
defer Cleanup(i)
|
||||
if i == 2 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
EOF
|
||||
|
||||
"$kc" --no-main --root "$work" -o "$out" "$work/src/defer_break.kry" >"$err" 2>&1
|
||||
# Cleanup fires before the break (defer declared before the break in source).
|
||||
grep -E -A1 'Cleanup\(i\);$' "$out/src/defer_break.c" | grep -Eq 'break;'
|
||||
# Cleanup also fires at the end of each iteration that reaches the loop close.
|
||||
grep -E -B1 'Cleanup\(i\);$' "$out/src/defer_break.c" | grep -Eq '\}'
|
||||
|
||||
# --- defer: malformed (missing statement) is a clean error
|
||||
cat > "$work/src/bad_defer.kry" <<'EOF'
|
||||
screen bad {
|
||||
defer
|
||||
}
|
||||
EOF
|
||||
|
||||
if "$kc" --no-main --root "$work" -o "$out" "$work/src/bad_defer.kry" >"$err" 2>&1; then
|
||||
echo "empty defer was accepted" >&2
|
||||
exit 1
|
||||
fi
|
||||
grep -q 'expected defer statement' "$err"
|
||||
grep -Eq 'bad_defer\.kry:2:1: error:' "$err"
|
||||
|
||||
# --- defer inside switch cases: each case's defers fire on its own path only
|
||||
# (regression: apply_defers previously treated the switch as one scope, leaking
|
||||
# case defers across cases — a defer in case 1 ran in default too)
|
||||
cat > "$work/src/defer_switch.kry" <<'EOF'
|
||||
#import "thing.h"
|
||||
sw :: (s: int) -> int {
|
||||
switch s {
|
||||
case 1:
|
||||
defer Cleanup(s)
|
||||
break
|
||||
case 2:
|
||||
defer Other(s)
|
||||
return s
|
||||
default:
|
||||
defer Default(s)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
EOF
|
||||
|
||||
"$kc" --no-main --root "$work" -o "$out" "$work/src/defer_switch.kry" >"$err" 2>&1
|
||||
# Cleanup fires before break (case 1 path).
|
||||
grep -E -A1 'Cleanup\(s\);$' "$out/src/defer_switch.c" | grep -Eq 'break;'
|
||||
# Other fires before return (case 2 path).
|
||||
grep -E -A1 'Other\(s\);$' "$out/src/defer_switch.c" | grep -Eq 'return s;'
|
||||
# Default fires at the switch close (default fall-through path).
|
||||
grep -E -B1 'Default\(s\);$' "$out/src/defer_switch.c" | grep -Eq 'default:'
|
||||
# No defer leaks across cases: Cleanup must NOT appear after case 2 or default,
|
||||
# Other must NOT appear after default. Count occurrences — each should fire
|
||||
# exactly once.
|
||||
[ "$(grep -c 'Cleanup(s);' "$out/src/defer_switch.c")" = 1 ] || {
|
||||
echo "defer_switch: Cleanup leaked across cases" >&2; exit 1; }
|
||||
[ "$(grep -c 'Other(s);' "$out/src/defer_switch.c")" = 1 ] || {
|
||||
echo "defer_switch: Other leaked across cases" >&2; exit 1; }
|
||||
[ "$(grep -c 'Default(s);' "$out/src/defer_switch.c")" = 1 ] || {
|
||||
echo "defer_switch: Default fired more than once" >&2; exit 1; }
|
||||
|
||||
# --- a call used as an if condition registers its source line for inspection
|
||||
# (regression: WidgetButton-in-if previously had no source, so click-to-source
|
||||
# on buttons did nothing)
|
||||
cat > "$work/src/if_call.kry" <<'EOF'
|
||||
#import "thing.h"
|
||||
|
||||
screen IfCall {
|
||||
if WidgetButton(0, 0, 100, 40, "Click", UI_BUTTON_STYLE_PRIMARY) {
|
||||
DoThing()
|
||||
}
|
||||
if value > 0 {
|
||||
DoThing()
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
"$kc" --no-main --root "$work" -o "$out" "$work/src/if_call.kry" >"$err" 2>&1
|
||||
# The call condition is wrapped: Push, temp assign, Pop, then test the temp.
|
||||
grep -Eq 'PushUIInspectSource\([^)]*if_call\.kry", 4\);' "$out/src/if_call.c"
|
||||
grep -Eq '__auto_type __kryon_cond_4 = WidgetButton\(' "$out/src/if_call.c"
|
||||
grep -Eq 'PopUIInspectSource\(\);' "$out/src/if_call.c"
|
||||
grep -Eq 'if\(__kryon_cond_4\) \{' "$out/src/if_call.c"
|
||||
# A non-call condition is emitted unchanged (no temp, no wrapping).
|
||||
grep -Fq 'if(value > 0) {' "$out/src/if_call.c"
|
||||
|
||||
# --- compound assignment operators not previously covered (-=, *=, /=, --)
|
||||
cat > "$work/src/compound.kry" <<'EOF'
|
||||
#import "thing.h"
|
||||
screen Compound {
|
||||
v := 10
|
||||
v -= 2
|
||||
v *= 3
|
||||
v /= 4
|
||||
v--
|
||||
}
|
||||
EOF
|
||||
|
||||
"$kc" --no-main --root "$work" -o "$out" "$work/src/compound.kry" >"$err" 2>&1
|
||||
grep -Fq 'v -= 2;' "$out/src/compound.c"
|
||||
grep -Fq 'v *= 3;' "$out/src/compound.c"
|
||||
grep -Fq 'v /= 4;' "$out/src/compound.c"
|
||||
grep -Fq 'v--;' "$out/src/compound.c"
|
||||
|
||||
# --- defer inside a while loop and before continue (loop-body defer)
|
||||
cat > "$work/src/defer_while.kry" <<'EOF'
|
||||
#import "thing.h"
|
||||
loop :: (n: int) -> int {
|
||||
i := 0
|
||||
while i < n {
|
||||
defer Tick(i)
|
||||
i++
|
||||
if i == 2 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
return i
|
||||
}
|
||||
EOF
|
||||
|
||||
"$kc" --no-main --root "$work" -o "$out" "$work/src/defer_while.kry" >"$err" 2>&1
|
||||
# defer declared before the continue fires before the continue.
|
||||
grep -E -A1 'Tick\(i\);$' "$out/src/defer_while.c" | grep -Eq 'continue;'
|
||||
# defer also fires at the end of each iteration that reaches the loop close.
|
||||
grep -E -B1 'Tick\(i\);$' "$out/src/defer_while.c" | grep -Eq '\}'
|
||||
|
||||
# --- defer inside an anonymous block scope (block-close defer)
|
||||
cat > "$work/src/defer_block.kry" <<'EOF'
|
||||
#import "thing.h"
|
||||
block_fn :: () -> int {
|
||||
s := 1
|
||||
{
|
||||
defer Scoped()
|
||||
s = 2
|
||||
}
|
||||
return s
|
||||
}
|
||||
EOF
|
||||
|
||||
"$kc" --no-main --root "$work" -o "$out" "$work/src/defer_block.kry" >"$err" 2>&1
|
||||
# Scoped fires at the anonymous block's closing brace (after s = 2).
|
||||
grep -E -B1 'Scoped\(\);$' "$out/src/defer_block.c" | grep -Eq 's = 2;'
|
||||
|
||||
# --- main generation: omitting --no-main emits an int main entry point
|
||||
cat > "$work/src/withmain.kry" <<'EOF'
|
||||
#import "thing.h"
|
||||
app "Test App" {
|
||||
size 800 600
|
||||
fps 60
|
||||
}
|
||||
screen Main {
|
||||
WidgetText("hi", 0, 0, 16, GetThemeText())
|
||||
}
|
||||
EOF
|
||||
|
||||
"$kc" --root "$work" -o "$out" "$work/src/withmain.kry" >"$err" 2>&1
|
||||
grep -Eq '^int$' "$out/src/withmain.c"
|
||||
grep -Eq '^main\(void\)$' "$out/src/withmain.c"
|
||||
grep -q 'InitWindow(800, 600, "Test App");' "$out/src/withmain.c"
|
||||
grep -q 'SetTargetFPS(60);' "$out/src/withmain.c"
|
||||
grep -q 'while(!WindowShouldClose())' "$out/src/withmain.c"
|
||||
grep -q 'Main_kry_draw();' "$out/src/withmain.c"
|
||||
# --no-main must NOT emit main.
|
||||
"$kc" --no-main --root "$work" -o "$out" "$work/src/withmain.kry" >"$err" 2>&1
|
||||
if grep -q 'int main' "$out/src/withmain.c"; then
|
||||
echo "--no-main still emitted main" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- removed keyword: 'let' produces a removal error
|
||||
cat > "$work/src/bad_let.kry" <<'EOF'
|
||||
screen bad {
|
||||
let x = 1
|
||||
}
|
||||
EOF
|
||||
|
||||
if "$kc" --no-main --root "$work" -o "$out" "$work/src/bad_let.kry" >"$err" 2>&1; then
|
||||
echo "let was accepted" >&2
|
||||
exit 1
|
||||
fi
|
||||
grep -q "'let' syntax was removed" "$err"
|
||||
grep -Eq 'bad_let\.kry:2:1: error:' "$err"
|
||||
|
||||
# --- --dump-ast reconstructs an AST with no unclassified (UNKNOWN) nodes
|
||||
cat > "$work/src/ast.kry" <<'EOF'
|
||||
#import "thing.h"
|
||||
ast_fn :: (n: int) -> int {
|
||||
v := 0
|
||||
count: int = 5
|
||||
name: const char* = "hi"
|
||||
defer Cleanup(v)
|
||||
if n > 0 {
|
||||
return n
|
||||
}
|
||||
for int i = 0; i < n; i++ {
|
||||
v += i
|
||||
if i == 2 {
|
||||
break
|
||||
}
|
||||
}
|
||||
while v < 3 {
|
||||
v++
|
||||
}
|
||||
switch v {
|
||||
case 1:
|
||||
v = 2
|
||||
default:
|
||||
v = 3
|
||||
}
|
||||
unused v
|
||||
return v
|
||||
}
|
||||
EOF
|
||||
|
||||
"$kc" --dump-ast --no-main --root "$work" -o "$out" "$work/src/ast.kry" >"$err" 2>&1
|
||||
# The dump header names the function.
|
||||
grep -q 'function ast_fn' "$err"
|
||||
# Every statement kind is classified — no UNKNOWN nodes (full capture).
|
||||
if grep -q ' UNKNOWN ' "$err"; then
|
||||
echo "dump-ast produced unclassified nodes" >&2
|
||||
exit 1
|
||||
fi
|
||||
# The expected control-flow kinds are present.
|
||||
grep -Eq '^IF ' "$err"
|
||||
grep -Eq '^FOR ' "$err"
|
||||
grep -Eq '^WHILE ' "$err"
|
||||
grep -Eq '^SWITCH ' "$err"
|
||||
grep -Eq '^DEFER ' "$err"
|
||||
grep -Eq '^RETURN ' "$err"
|
||||
# Typed declarations classify as DECL (not ASSIGN): "int count = 5;" and
|
||||
# "const char* name = "hi";" are declarations, while "v += i" is an assignment.
|
||||
grep -Eq '^DECL .*int count = 5;' "$err"
|
||||
grep -Eq '^DECL .*const char\* name =' "$err"
|
||||
grep -Eq '^ ASSIGN .*v \+= i;' "$err"
|
||||
# --dump-ast must NOT write the generated .c/.h (it parses but skips emit).
|
||||
if [ -f "$out/src/ast.c" ]; then
|
||||
echo "dump-ast wrote generated files" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "lyra_account.h"
|
||||
#include "ksync_account.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -30,7 +30,7 @@ bytes_to_hex_local(const unsigned char *bytes, size_t len, char *out, size_t out
|
||||
}
|
||||
|
||||
static void
|
||||
make_account(LyraAccount *account)
|
||||
make_account(KsyncAccount *account)
|
||||
{
|
||||
unsigned char public_key[1312];
|
||||
unsigned char private_key[2560];
|
||||
@@ -40,7 +40,7 @@ make_account(LyraAccount *account)
|
||||
public_key[i] = (unsigned char)(i * 7U + 11U);
|
||||
for(size_t i = 0; i < sizeof(private_key); i++)
|
||||
private_key[i] = (unsigned char)(i * 17U + 3U);
|
||||
LyraSha256Hex(public_key, sizeof(public_key), account->public_id);
|
||||
KsyncSha256Hex(public_key, sizeof(public_key), account->public_id);
|
||||
bytes_to_hex_local(public_key, sizeof(public_key), account->public_key_hex,
|
||||
sizeof(account->public_key_hex));
|
||||
bytes_to_hex_local(private_key, sizeof(private_key), account->private_key_hex,
|
||||
@@ -50,14 +50,14 @@ make_account(LyraAccount *account)
|
||||
static void
|
||||
test_export_parse_roundtrip(void)
|
||||
{
|
||||
LyraAccount account;
|
||||
LyraAccount parsed;
|
||||
char text[LYRA_ACCOUNT_EXPORT_TEXT_SIZE];
|
||||
KsyncAccount account;
|
||||
KsyncAccount parsed;
|
||||
char text[KSYNC_ACCOUNT_EXPORT_TEXT_SIZE];
|
||||
|
||||
make_account(&account);
|
||||
check_true("export text", ExportLyraAccountText(&account, text, sizeof(text)));
|
||||
check_true("generic header", strstr(text, "lyra-account-key-v1\n") == text);
|
||||
check_true("parse exported text", ParseLyraAccountText(text, &parsed));
|
||||
check_true("export text", ExportKsyncAccountText(&account, text, sizeof(text)));
|
||||
check_true("generic header", strstr(text, "ksync-account-key-v1\n") == text);
|
||||
check_true("parse exported text", ParseKsyncAccountText(text, &parsed));
|
||||
check_true("roundtrip public id", strcmp(parsed.public_id, account.public_id) == 0);
|
||||
check_true("roundtrip public key", strcmp(parsed.public_key_hex, account.public_key_hex) == 0);
|
||||
check_true("roundtrip private key",
|
||||
@@ -67,41 +67,46 @@ test_export_parse_roundtrip(void)
|
||||
static void
|
||||
test_old_imports(void)
|
||||
{
|
||||
LyraAccount account;
|
||||
LyraAccount parsed;
|
||||
char text[LYRA_ACCOUNT_EXPORT_TEXT_SIZE];
|
||||
char json[LYRA_ACCOUNT_EXPORT_TEXT_SIZE + 128];
|
||||
KsyncAccount account;
|
||||
KsyncAccount parsed;
|
||||
char text[KSYNC_ACCOUNT_EXPORT_TEXT_SIZE];
|
||||
char json[KSYNC_ACCOUNT_EXPORT_TEXT_SIZE + 128];
|
||||
|
||||
make_account(&account);
|
||||
snprintf(text, sizeof(text),
|
||||
"inbe-sync-key-v1\nalgorithm=ML-DSA-44\npublic_key=%s\nsecret_key=%s\n",
|
||||
account.public_key_hex, account.private_key_hex);
|
||||
check_true("old secret_key import", ParseLyraAccountText(text, &parsed));
|
||||
check_true("old secret_key import", ParseKsyncAccountText(text, &parsed));
|
||||
check_true("old derived public id", strcmp(parsed.public_id, account.public_id) == 0);
|
||||
|
||||
snprintf(text, sizeof(text),
|
||||
"account-key-v1\nalgorithm=ML-DSA-44\npublic_id=%s\npublic_key=%s\nprivate_key=%s\n",
|
||||
account.public_id, account.public_key_hex, account.private_key_hex);
|
||||
check_true("old account-key import", ParseLyraAccountText(text, &parsed));
|
||||
check_true("old account-key import", ParseKsyncAccountText(text, &parsed));
|
||||
|
||||
snprintf(text, sizeof(text),
|
||||
"lyra-account-key-v1\nalgorithm=ML-DSA-44\npublic_id=%s\npublic_key=%s\nprivate_key=%s\n",
|
||||
account.public_id, account.public_key_hex, account.private_key_hex);
|
||||
check_true("old lyra account-key import", ParseKsyncAccountText(text, &parsed));
|
||||
|
||||
snprintf(json, sizeof(json),
|
||||
"{\"exported_key\":\"lyra-account-key-v1\\nalgorithm=ML-DSA-44\\npublic_id=%s\\npublic_key=%s\\nprivate_key=%s\\n\"}",
|
||||
"{\"exported_key\":\"ksync-account-key-v1\\nalgorithm=ML-DSA-44\\npublic_id=%s\\npublic_key=%s\\nprivate_key=%s\\n\"}",
|
||||
account.public_id, account.public_key_hex, account.private_key_hex);
|
||||
check_true("json exported_key import", ParseLyraAccountText(json, &parsed));
|
||||
check_true("json exported_key import", ParseKsyncAccountText(json, &parsed));
|
||||
}
|
||||
|
||||
static void
|
||||
test_reject_mismatch(void)
|
||||
{
|
||||
LyraAccount account;
|
||||
char text[LYRA_ACCOUNT_EXPORT_TEXT_SIZE];
|
||||
KsyncAccount account;
|
||||
char text[KSYNC_ACCOUNT_EXPORT_TEXT_SIZE];
|
||||
|
||||
make_account(&account);
|
||||
account.public_id[0] = account.public_id[0] == '0' ? '1' : '0';
|
||||
snprintf(text, sizeof(text),
|
||||
"lyra-account-key-v1\nalgorithm=ML-DSA-44\npublic_id=%s\npublic_key=%s\nprivate_key=%s\n",
|
||||
"ksync-account-key-v1\nalgorithm=ML-DSA-44\npublic_id=%s\npublic_key=%s\nprivate_key=%s\n",
|
||||
account.public_id, account.public_key_hex, account.private_key_hex);
|
||||
check_true("reject mismatched public id", !ParseLyraAccountText(text, &account));
|
||||
check_true("reject mismatched public id", !ParseKsyncAccountText(text, &account));
|
||||
}
|
||||
|
||||
int
|
||||
@@ -112,6 +117,6 @@ main(void)
|
||||
test_reject_mismatch();
|
||||
if(failures != 0)
|
||||
return 1;
|
||||
printf("lyra account tests passed\n");
|
||||
printf("ksync account tests passed\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "lyra_sync.h"
|
||||
#include "ksync_sync.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -53,7 +53,7 @@ test_set_text(const char *key, const char *value, void *user)
|
||||
static int
|
||||
test_http(const char *method, const char *url, const char *body,
|
||||
const char *const *headers, int header_count,
|
||||
LyraSyncBuffer *response, long *status, void *user)
|
||||
KsyncSyncBuffer *response, long *status, void *user)
|
||||
{
|
||||
TestCtx *ctx = user;
|
||||
snprintf(ctx->last_method, sizeof(ctx->last_method), "%s", method != NULL ? method : "");
|
||||
@@ -66,17 +66,15 @@ test_http(const char *method, const char *url, const char *body,
|
||||
if(headers[i] != NULL && strncmp(headers[i], "Authorization:", 14) == 0)
|
||||
snprintf(ctx->last_auth, sizeof(ctx->last_auth), "%s", headers[i]);
|
||||
if(headers[i] != NULL &&
|
||||
(strncmp(headers[i], "X-Lyra-User:", 12) == 0 ||
|
||||
strncmp(headers[i], "X-Inbe-User:", 12) == 0))
|
||||
strncmp(headers[i], "X-Ksync-User:", strlen("X-Ksync-User:")) == 0)
|
||||
snprintf(ctx->last_user, sizeof(ctx->last_user), "%s", headers[i]);
|
||||
if(headers[i] != NULL &&
|
||||
(strncmp(headers[i], "X-Lyra-Signature:", 17) == 0 ||
|
||||
strncmp(headers[i], "X-Inbe-Signature:", 17) == 0))
|
||||
strncmp(headers[i], "X-Ksync-Signature:", strlen("X-Ksync-Signature:")) == 0)
|
||||
snprintf(ctx->last_signature, sizeof(ctx->last_signature), "%s", headers[i]);
|
||||
}
|
||||
if(status != NULL)
|
||||
*status = 200;
|
||||
return AppendLyraSyncBuffer(response, "{\"status\":\"ok\",\"changes\":{}}",
|
||||
return AppendKsyncSyncBuffer(response, "{\"status\":\"ok\",\"changes\":{}}",
|
||||
strlen("{\"status\":\"ok\",\"changes\":{}}"));
|
||||
}
|
||||
|
||||
@@ -115,7 +113,7 @@ test_purge(void *user)
|
||||
}
|
||||
|
||||
static void
|
||||
fill_account(LyraAccount *account)
|
||||
fill_account(KsyncAccount *account)
|
||||
{
|
||||
memset(account, 0, sizeof(*account));
|
||||
memset(account->public_id, 'a', 64);
|
||||
@@ -129,17 +127,17 @@ test_url_helpers(void)
|
||||
{
|
||||
char out[128];
|
||||
|
||||
check(IsLyraSyncURLValid("https://api.example.test"), "https url valid");
|
||||
check(IsLyraSyncURLValid("localhost:8080"), "localhost shorthand valid");
|
||||
check(!IsLyraSyncURLValid("http://example.test"), "plain remote http rejected");
|
||||
check(NormalizeLyraSyncURL("localhost:8080", out, sizeof(out)) &&
|
||||
check(IsKsyncSyncURLValid("https://api.example.test"), "https url valid");
|
||||
check(IsKsyncSyncURLValid("localhost:8080"), "localhost shorthand valid");
|
||||
check(!IsKsyncSyncURLValid("http://example.test"), "plain remote http rejected");
|
||||
check(NormalizeKsyncSyncURL("localhost:8080", out, sizeof(out)) &&
|
||||
strcmp(out, "http://localhost:8080") == 0,
|
||||
"normalize localhost");
|
||||
check(JoinLyraSyncURL(out, sizeof(out), "https://api.example.test/",
|
||||
check(JoinKsyncSyncURL(out, sizeof(out), "https://api.example.test/",
|
||||
"/api/v1/sync") &&
|
||||
strcmp(out, "https://api.example.test/api/v1/sync") == 0,
|
||||
"join trims trailing slash");
|
||||
check(JoinLyraSyncWebSocketURL(out, sizeof(out), "https://api.example.test",
|
||||
check(JoinKsyncSyncWebSocketURL(out, sizeof(out), "https://api.example.test",
|
||||
"/api/v1/sync/ws") &&
|
||||
strcmp(out, "wss://api.example.test/api/v1/sync/ws") == 0,
|
||||
"join websocket https");
|
||||
@@ -148,18 +146,18 @@ test_url_helpers(void)
|
||||
static void
|
||||
test_json_helpers(void)
|
||||
{
|
||||
LyraSyncBuffer buffer = {0};
|
||||
KsyncSyncBuffer buffer = {0};
|
||||
char value[32];
|
||||
|
||||
check(AppendLyraSyncBufferJSONString(&buffer, "a\"b\n") &&
|
||||
check(AppendKsyncSyncBufferJSONString(&buffer, "a\"b\n") &&
|
||||
strcmp(buffer.data, "\"a\\\"b\\n\"") == 0,
|
||||
"json string escaping");
|
||||
FreeLyraSyncBuffer(&buffer);
|
||||
check(FindLyraSyncJSONString("{\"auth_token\":\"tok\"}", "auth_token",
|
||||
FreeKsyncSyncBuffer(&buffer);
|
||||
check(FindKsyncSyncJSONString("{\"auth_token\":\"tok\"}", "auth_token",
|
||||
value, sizeof(value)) &&
|
||||
strcmp(value, "tok") == 0,
|
||||
"json string find");
|
||||
check(FindLyraSyncJSONInt64("{\"expires_in_seconds\":42}",
|
||||
check(FindKsyncSyncJSONInt64("{\"expires_in_seconds\":42}",
|
||||
"expires_in_seconds", 0) == 42,
|
||||
"json int find");
|
||||
}
|
||||
@@ -168,9 +166,9 @@ static void
|
||||
test_sync_run_with_valid_token(void)
|
||||
{
|
||||
TestCtx ctx = {0};
|
||||
LyraAccount account;
|
||||
LyraSyncConfig cfg;
|
||||
LyraSyncResult result;
|
||||
KsyncAccount account;
|
||||
KsyncSyncConfig cfg;
|
||||
KsyncSyncResult result;
|
||||
|
||||
fill_account(&account);
|
||||
snprintf(ctx.token, sizeof(ctx.token), "saved-token");
|
||||
@@ -188,14 +186,14 @@ test_sync_run_with_valid_token(void)
|
||||
cfg.purge_synced_deleted = test_purge;
|
||||
cfg.user = &ctx;
|
||||
|
||||
result = RunLyraSync(&cfg);
|
||||
check(result == LYRA_SYNC_OK, "sync run returns ok");
|
||||
result = RunKsyncSync(&cfg);
|
||||
check(result == KSYNC_SYNC_OK, "sync run returns ok");
|
||||
check(strcmp(ctx.last_method, "POST") == 0, "sync uses post");
|
||||
check(strcmp(ctx.last_url, "https://api.example.test/api/v1/sync") == 0,
|
||||
"sync posts to sync path");
|
||||
check(strcmp(ctx.last_auth, "Authorization: Bearer saved-token") == 0,
|
||||
"sync sends bearer token");
|
||||
check(strncmp(ctx.last_user, "X-Lyra-User:", 12) == 0,
|
||||
check(strncmp(ctx.last_user, "X-Ksync-User:", strlen("X-Ksync-User:")) == 0,
|
||||
"sync uses generic user header by default");
|
||||
check(ctx.apply_called == 1, "sync applies response");
|
||||
check(ctx.purge_called == 1, "sync purges after success");
|
||||
@@ -204,21 +202,21 @@ test_sync_run_with_valid_token(void)
|
||||
static int
|
||||
test_login_http(const char *method, const char *url, const char *body,
|
||||
const char *const *headers, int header_count,
|
||||
LyraSyncBuffer *response, long *status, void *user)
|
||||
KsyncSyncBuffer *response, long *status, void *user)
|
||||
{
|
||||
TestCtx *ctx = user;
|
||||
|
||||
test_http(method, url, body, headers, header_count, response, status, user);
|
||||
if(strstr(url, "/challenge") != NULL) {
|
||||
FreeLyraSyncBuffer(response);
|
||||
return AppendLyraSyncBuffer(response,
|
||||
FreeKsyncSyncBuffer(response);
|
||||
return AppendKsyncSyncBuffer(response,
|
||||
"{\"nonce\":\"0000000000000000000000000000000000000000000000000000000000000000\"}",
|
||||
strlen("{\"nonce\":\"0000000000000000000000000000000000000000000000000000000000000000\"}"));
|
||||
}
|
||||
if(strstr(url, "/login") != NULL) {
|
||||
(void)ctx;
|
||||
FreeLyraSyncBuffer(response);
|
||||
return AppendLyraSyncBuffer(response,
|
||||
FreeKsyncSyncBuffer(response);
|
||||
return AppendKsyncSyncBuffer(response,
|
||||
"{\"auth_token\":\"new-token\",\"expires_in_seconds\":3600}",
|
||||
strlen("{\"auth_token\":\"new-token\",\"expires_in_seconds\":3600}"));
|
||||
}
|
||||
@@ -229,11 +227,11 @@ static void
|
||||
test_login_uses_configured_wire_names(void)
|
||||
{
|
||||
TestCtx ctx = {0};
|
||||
LyraAccount account;
|
||||
LyraSyncConfig cfg;
|
||||
LyraSyncResult result;
|
||||
KsyncAccount account;
|
||||
KsyncSyncConfig cfg;
|
||||
KsyncSyncResult result;
|
||||
|
||||
if(!CreateLyraAccount(&account)) {
|
||||
if(!CreateKsyncAccount(&account)) {
|
||||
check(0, "create account for login override test");
|
||||
return;
|
||||
}
|
||||
@@ -241,19 +239,20 @@ test_login_uses_configured_wire_names(void)
|
||||
cfg.base_url = "https://api.example.test";
|
||||
cfg.account = &account;
|
||||
cfg.client_id = "client-123";
|
||||
cfg.signature_context = "inbe-sync-v1";
|
||||
cfg.user_header_name = "X-Inbe-User";
|
||||
cfg.signature_header_name = "X-Inbe-Signature";
|
||||
cfg.signature_context = "ksync-sync-v1";
|
||||
cfg.user_header_name = "X-Ksync-User";
|
||||
cfg.signature_header_name = "X-Ksync-Signature";
|
||||
cfg.http_request = test_login_http;
|
||||
cfg.get_text = test_get_text;
|
||||
cfg.set_text = test_set_text;
|
||||
cfg.user = &ctx;
|
||||
|
||||
result = LoginLyraSync(&cfg);
|
||||
check(result == LYRA_SYNC_OK, "login with configured wire names returns ok");
|
||||
check(strncmp(ctx.last_user, "X-Inbe-User:", 12) == 0,
|
||||
result = LoginKsyncSync(&cfg);
|
||||
check(result == KSYNC_SYNC_OK, "login with configured wire names returns ok");
|
||||
check(strncmp(ctx.last_user, "X-Ksync-User:", strlen("X-Ksync-User:")) == 0,
|
||||
"login uses configured user header");
|
||||
check(strncmp(ctx.last_signature, "X-Inbe-Signature:", 17) == 0,
|
||||
check(strncmp(ctx.last_signature, "X-Ksync-Signature:",
|
||||
strlen("X-Ksync-Signature:")) == 0,
|
||||
"login uses configured signature header");
|
||||
check(strcmp(ctx.token, "new-token") == 0, "login saves auth token");
|
||||
}
|
||||
@@ -5,6 +5,7 @@ raylib_header=${1:-vendor/raylib/src/raylib.h}
|
||||
public_header=${2:-include/kryon_compat.generated.h}
|
||||
rename_header=${3:-build/generated/raylib_backend_rename.h}
|
||||
wrapper_source=${4:-build/generated/kryon_raylib_wrappers.c}
|
||||
null_backend_source=${5:-build/generated/kryon_null_backend.c}
|
||||
backend_prefix=${KRYON_RAYLIB_BACKEND_PREFIX:-KryonRaylibBackend_}
|
||||
|
||||
if [ ! -f "$raylib_header" ]; then
|
||||
@@ -12,11 +13,27 @@ if [ ! -f "$raylib_header" ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$(dirname "$public_header")" "$(dirname "$rename_header")" "$(dirname "$wrapper_source")"
|
||||
mkdir -p "$(dirname "$public_header")" "$(dirname "$rename_header")" "$(dirname "$wrapper_source")" "$(dirname "$null_backend_source")"
|
||||
|
||||
{
|
||||
echo "/* Generated by tools/generate-kryon-compat.sh; do not edit. */"
|
||||
echo "/* Kryon exposes this Raylib-compatible surface through kryon.h. */"
|
||||
cat <<'EOF'
|
||||
/*
|
||||
* Kryon graphics/input API surface.
|
||||
*
|
||||
* This header defines kryon's public graphics, input, and asset API. It
|
||||
* currently tracks raylib's surface verbatim so that existing raylib-style
|
||||
* code (DrawRectangle, Font, BeginDrawing, ...) compiles unchanged, and so
|
||||
* the raylib backend (build/generated/kryon_raylib_wrappers.c) can implement
|
||||
* every symbol by forwarding to raylib.
|
||||
*
|
||||
* Kryon owns this surface. It is not "raylib that kryon happens to use":
|
||||
* other backends implement these same function and type names without raylib
|
||||
* (for example an HTML5 canvas backend). Selection is link-time, via the
|
||||
* KRYON_BACKEND make variable. The raylib version tracked below is the
|
||||
* baseline; kryon may evolve this surface independently over time.
|
||||
*/
|
||||
EOF
|
||||
cat "$raylib_header"
|
||||
} > "$public_header"
|
||||
|
||||
@@ -90,6 +107,39 @@ function emit_regular_wrapper(return_type, name, args, backend_args, returns_voi
|
||||
print "extern " return_type " " prefix name "(" args ");"
|
||||
print return_type " " name "(" args ")"
|
||||
print "{"
|
||||
if(name == "IsMouseButtonPressed" || name == "IsMouseButtonDown" || name == "IsMouseButtonReleased") {
|
||||
print " if(g_kryon_input_override.enabled &&"
|
||||
print " (!g_kryon_input_override.mouse_inside ||"
|
||||
print " !g_kryon_input_override.pass_buttons))"
|
||||
print " return false;"
|
||||
} else if(name == "IsMouseButtonUp") {
|
||||
print " if(g_kryon_input_override.enabled &&"
|
||||
print " (!g_kryon_input_override.mouse_inside ||"
|
||||
print " !g_kryon_input_override.pass_buttons))"
|
||||
print " return true;"
|
||||
} else if(name == "GetMouseX") {
|
||||
print " if(g_kryon_input_override.enabled)"
|
||||
print " return (int)g_kryon_input_override.mouse_position.x;"
|
||||
} else if(name == "GetMouseY") {
|
||||
print " if(g_kryon_input_override.enabled)"
|
||||
print " return (int)g_kryon_input_override.mouse_position.y;"
|
||||
} else if(name == "GetMousePosition") {
|
||||
print " if(g_kryon_input_override.enabled)"
|
||||
print " return g_kryon_input_override.mouse_position;"
|
||||
} else if(name == "GetMouseDelta") {
|
||||
print " if(g_kryon_input_override.enabled)"
|
||||
print " return g_kryon_input_override.mouse_delta;"
|
||||
} else if(name == "GetMouseWheelMove") {
|
||||
print " if(g_kryon_input_override.enabled &&"
|
||||
print " (!g_kryon_input_override.mouse_inside ||"
|
||||
print " !g_kryon_input_override.pass_buttons))"
|
||||
print " return 0.0f;"
|
||||
} else if(name == "GetMouseWheelMoveV") {
|
||||
print " if(g_kryon_input_override.enabled &&"
|
||||
print " (!g_kryon_input_override.mouse_inside ||"
|
||||
print " !g_kryon_input_override.pass_buttons))"
|
||||
print " return (Vector2){0.0f, 0.0f};"
|
||||
}
|
||||
if(returns_void) {
|
||||
print " " prefix name "(" backend_args ");"
|
||||
} else {
|
||||
@@ -127,6 +177,30 @@ BEGIN {
|
||||
print "#include <stdarg.h>"
|
||||
print "#include <stdio.h>"
|
||||
print ""
|
||||
print "#define KRYON_INPUT_OVERRIDE_STACK_CAP 8"
|
||||
print "static KryonInputOverride g_kryon_input_override = {0};"
|
||||
print "static KryonInputOverride g_kryon_input_override_stack[KRYON_INPUT_OVERRIDE_STACK_CAP];"
|
||||
print "static int g_kryon_input_override_depth = 0;"
|
||||
print ""
|
||||
print "void BeginKryonInputOverride(KryonInputOverride input)"
|
||||
print "{"
|
||||
print " if(g_kryon_input_override_depth < KRYON_INPUT_OVERRIDE_STACK_CAP)"
|
||||
print " g_kryon_input_override_stack[g_kryon_input_override_depth++] ="
|
||||
print " g_kryon_input_override;"
|
||||
print " input.enabled = 1;"
|
||||
print " g_kryon_input_override = input;"
|
||||
print "}"
|
||||
print ""
|
||||
print "void EndKryonInputOverride(void)"
|
||||
print "{"
|
||||
print " if(g_kryon_input_override_depth > 0) {"
|
||||
print " g_kryon_input_override ="
|
||||
print " g_kryon_input_override_stack[--g_kryon_input_override_depth];"
|
||||
print " return;"
|
||||
print " }"
|
||||
print " g_kryon_input_override = (KryonInputOverride){0};"
|
||||
print "}"
|
||||
print ""
|
||||
}
|
||||
|
||||
/^[[:space:]]*(RLAPI|RMAPI)[[:space:]]/ {
|
||||
@@ -148,3 +222,100 @@ BEGIN {
|
||||
}
|
||||
}
|
||||
' "$raylib_header" > "$wrapper_source"
|
||||
|
||||
# Null backend: a link-time backend (KRYON_BACKEND=null) that provides a
|
||||
# zero-return no-op stub for every public-surface symbol so libkryon.a links
|
||||
# and runs headless with no GPU/window. Generated from the same raylib.h so it
|
||||
# stays in sync with the surface automatically. Used for widget unit tests.
|
||||
awk -v prefix="$backend_prefix" '
|
||||
function trim(s) {
|
||||
sub(/^[[:space:]]+/, "", s)
|
||||
sub(/[[:space:]]+$/, "", s)
|
||||
return s
|
||||
}
|
||||
|
||||
function function_name_from_prefix(prefix_text, parts, n) {
|
||||
n = split(prefix_text, parts, /[[:space:]\*]+/)
|
||||
return parts[n]
|
||||
}
|
||||
|
||||
function return_type_from_prefix(prefix_text, name) {
|
||||
sub(/^[[:space:]]*(RLAPI|RMAPI)[[:space:]]+/, "", prefix_text)
|
||||
sub("[[:space:]]*" name "$", "", prefix_text)
|
||||
return trim(prefix_text)
|
||||
}
|
||||
|
||||
function is_pointer_return(return_type) {
|
||||
return return_type ~ /\*$/
|
||||
}
|
||||
|
||||
function arg_name(arg, parts, n, name) {
|
||||
arg = trim(arg)
|
||||
sub(/=.*/, "", arg)
|
||||
gsub(/\[[^]]*\]/, "", arg)
|
||||
n = split(arg, parts, /[[:space:]\*]+/)
|
||||
name = parts[n]
|
||||
gsub(/[^A-Za-z0-9_]/, "", name)
|
||||
return name
|
||||
}
|
||||
|
||||
BEGIN {
|
||||
print "/* Generated by tools/generate-kryon-compat.sh; do not edit. */"
|
||||
print "/* Null backend: zero-return no-op stubs for the kryon surface."
|
||||
print " * Selected via KRYON_BACKEND=null for headless links (tests). */"
|
||||
print "#include \"kryon.h\""
|
||||
print "#include <stdarg.h>"
|
||||
print "#include <stdio.h>"
|
||||
print ""
|
||||
}
|
||||
|
||||
/^[[:space:]]*(RLAPI|RMAPI)[[:space:]]/ {
|
||||
line = $0
|
||||
sub(/\/\/.*$/, "", line)
|
||||
line = trim(line)
|
||||
sub(/;$/, "", line)
|
||||
prefix_text = line
|
||||
sub(/\(.*/, "", prefix_text)
|
||||
name = function_name_from_prefix(prefix_text)
|
||||
return_type = return_type_from_prefix(prefix_text, name)
|
||||
args = line
|
||||
sub(/^[^(]*\(/, "", args)
|
||||
sub(/\)$/, "", args)
|
||||
|
||||
# Variadic stubs: TextFormat returns "", TraceLog is a no-op.
|
||||
if(name == "TextFormat") {
|
||||
print "const char *TextFormat(const char *text, ...) { (void)text; return \"\"; }"
|
||||
print ""
|
||||
next
|
||||
}
|
||||
if(name == "TraceLog") {
|
||||
print "void TraceLog(int logLevel, const char *text, ...) { (void)logLevel; (void)text; }"
|
||||
print ""
|
||||
next
|
||||
}
|
||||
|
||||
print return_type " " name "(" args ")"
|
||||
print "{"
|
||||
# Cast every named parameter to void to suppress -Wunused-parameter.
|
||||
n_args = split(args, arg_parts, /,[[:space:]]*/)
|
||||
for(ai = 1; ai <= n_args; ai++) {
|
||||
an = arg_name(arg_parts[ai])
|
||||
if(an != "" && an != "void")
|
||||
print " (void)" an ";"
|
||||
}
|
||||
if(return_type == "void") {
|
||||
# nothing
|
||||
} else if(is_pointer_return(return_type)) {
|
||||
print " return 0;"
|
||||
} else if(return_type ~ /^(int|long|short|char|bool|unsigned|float|double|size_t|[us]int8_t|[us]int16_t|[us]int32_t|[us]int64_t|GLenum|GLuint|GLint|GLfloat)/ ||
|
||||
return_type ~ /(_t|Flags|Key|MouseButton|Cursor|Gesture|BlendMode|TextureFilter|CubemapLayout|ShaderLocationIndex|ShaderUniformDataType|ShaderAttributeDataType|PixelFormat|BlendMode|Tex2D|MaterialMapIndex|NPatchLayout|KeyboardKey|GamepadButton|GamepadAxis)$/ ) {
|
||||
print " return 0;"
|
||||
} else {
|
||||
# struct return (Color, Rectangle, Vector2, Image, Texture2D, Font, ...) -> zero-init
|
||||
print " " return_type " r = {0};"
|
||||
print " return r;"
|
||||
}
|
||||
print "}"
|
||||
print ""
|
||||
}
|
||||
' "$raylib_header" > "$null_backend_source"
|
||||
Reference in new issue
Block a user