feat(runtime): Java platform bridge and platform detection tooling

ElBridge.java: Android Java companion to el_android.c — all public methods are
static, dispatches View mutations to the UI thread via runOnUiThread/CountDownLatch,
and exposes native callbacks (nativeOnClick, nativeOnChange, nativeOnSubmit).

PLATFORM_BRIDGE_SPEC.md: authoritative spec for implementing new platform bridges
(slot table contract, required __* functions, callback dispatch pattern).

detect-platforms: shell script that probes for available bridge toolchains and
prints what can be built on the current machine.

new-platform: scaffold generator that creates a new el_<name>.c with all 33
required stubs wired up.
This commit is contained in:
2026-06-29 12:40:26 -05:00
parent 6271cb42b2
commit edff25180e
4 changed files with 2184 additions and 0 deletions
+711
View File
@@ -0,0 +1,711 @@
/*
* ElBridge.java — Android Java companion to el_android.c.
*
* All public methods are static. The C JNI layer calls these to create views,
* set properties, and manage the widget tree. Views are identified by integer
* slot indices matching the C-side handle values.
*
* Threading: every method that touches a View dispatches to the UI thread
* using Activity.runOnUiThread(Runnable) and blocks with a CountDownLatch
* until the UI thread completes the operation. This mirrors the AppKit
* dispatch_sync(main_queue, ^{}) pattern in el_appkit.m.
*
* Callbacks: Java sets listeners on views that call back into C via:
* nativeOnClick(int slot)
* nativeOnChange(int slot, String text)
* nativeOnSubmit(int slot, String text)
* These are declared native and implemented in el_android.c.
*
* Usage (in your Activity.onCreate):
* System.loadLibrary("elruntime");
* ElBridge.init(this);
*
* The native library calls __native_init() which calls nativeRegisterActivity
* via the C side; alternatively call ElBridge.init(this) directly from Java.
*
* Compile requirements:
* Android minSdkVersion 21 (Lollipop) or higher.
* No third-party dependencies — uses only android.* framework classes.
* For image loading from arbitrary file paths, BitmapFactory is used.
* To replace with Glide/Picasso, edit createImageView only.
*/
package com.neuron.el;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import java.util.concurrent.CountDownLatch;
public class ElBridge {
/* ── Native callbacks (implemented in el_android.c) ─────────────────── */
public static native void nativeOnClick(int slot);
public static native void nativeOnChange(int slot, String text);
public static native void nativeOnSubmit(int slot, String text);
public static native void nativeRegisterActivity(Activity activity);
/* ── State ───────────────────────────────────────────────────────────── */
private static final int MAX_SLOTS = 4096;
private static Activity sActivity;
private static Handler sUiHandler;
private static View[] sViews = new View[MAX_SLOTS];
private static int sNextSlot = 1; /* slot 0 reserved / null */
/* ── Init ────────────────────────────────────────────────────────────── */
/**
* Must be called from the Activity before any widget operations.
* Typically called from Activity.onCreate after System.loadLibrary.
*/
public static void init(Activity activity) {
sActivity = activity;
sUiHandler = new Handler(Looper.getMainLooper());
nativeRegisterActivity(activity);
}
/* ── Slot management ─────────────────────────────────────────────────── */
private static int allocSlot(View v) {
/* Find a free slot starting from sNextSlot, wrap around. */
for (int i = 0; i < MAX_SLOTS - 1; i++) {
int idx = ((sNextSlot - 1 + i) % (MAX_SLOTS - 1)) + 1;
if (sViews[idx] == null) {
sViews[idx] = v;
sNextSlot = (idx % (MAX_SLOTS - 1)) + 1;
return idx;
}
}
android.util.Log.e("ElBridge", "allocSlot: slot table full");
return -1;
}
private static View getView(int slot) {
if (slot <= 0 || slot >= MAX_SLOTS) return null;
return sViews[slot];
}
/* ── UI-thread dispatch helper ───────────────────────────────────────── */
/*
* Dispatch r on the UI thread and block until it completes.
* Safe to call from the UI thread itself (runs inline without posting).
*/
private static void runSync(final Runnable r) {
if (Looper.myLooper() == Looper.getMainLooper()) {
r.run();
} else {
final CountDownLatch latch = new CountDownLatch(1);
sUiHandler.post(new Runnable() {
@Override public void run() {
try { r.run(); } finally { latch.countDown(); }
}
});
try { latch.await(); } catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
/* ── Integer slot returning runSync helper ───────────────────────────── */
private interface IntSupplier { int get(); }
private static int runSyncInt(final IntSupplier s) {
final int[] result = { -1 };
runSync(new Runnable() {
@Override public void run() { result[0] = s.get(); }
});
return result[0];
}
/* ── Context accessor ────────────────────────────────────────────────── */
private static Context ctx() { return sActivity; }
/* ── View creation ───────────────────────────────────────────────────── */
/**
* Create a LinearLayout.
* @param orientation 1=VERTICAL, 0=HORIZONTAL
* @param spacing gap between children in dp; applied as bottom/right margin
*/
public static int createLinearLayout(final int orientation, final int spacing) {
return runSyncInt(new IntSupplier() {
@Override public int get() {
LinearLayout ll = new LinearLayout(ctx());
ll.setOrientation(orientation == 1
? LinearLayout.VERTICAL
: LinearLayout.HORIZONTAL);
ll.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
/* Spacing is stored so addChild can apply margins. */
ll.setTag(R_TAG_SPACING, spacing);
return allocSlot(ll);
}
});
}
/** Create a FrameLayout (ZStack equivalent). */
public static int createFrameLayout() {
return runSyncInt(new IntSupplier() {
@Override public int get() {
FrameLayout fl = new FrameLayout(ctx());
fl.setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return allocSlot(fl);
}
});
}
/** Create a ScrollView. */
public static int createScrollView() {
return runSyncInt(new IntSupplier() {
@Override public int get() {
ScrollView sv = new ScrollView(ctx());
sv.setLayoutParams(new ScrollView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
sv.setFillViewport(true);
return allocSlot(sv);
}
});
}
/** Create a TextView with initial text. */
public static int createTextView(final String text) {
return runSyncInt(new IntSupplier() {
@Override public int get() {
TextView tv = new TextView(ctx());
tv.setText(text != null ? text : "");
tv.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return allocSlot(tv);
}
});
}
/** Create a Button with a label. */
public static int createButton(final String label) {
return runSyncInt(new IntSupplier() {
@Override public int get() {
Button btn = new Button(ctx());
btn.setText(label != null ? label : "");
btn.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return allocSlot(btn);
}
});
}
/**
* Create an EditText.
* @param placeholder hint text
* @param singleLine true = single-line text field; false = multi-line text area
*/
public static int createEditText(final String placeholder, final boolean singleLine) {
return runSyncInt(new IntSupplier() {
@Override public int get() {
EditText et = new EditText(ctx());
et.setHint(placeholder != null ? placeholder : "");
if (singleLine) {
et.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
et.setMaxLines(1);
et.setSingleLine(true);
} else {
et.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_FLAG_MULTI_LINE);
et.setMinLines(3);
et.setSingleLine(false);
et.setGravity(Gravity.TOP | Gravity.START);
}
et.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return allocSlot(et);
}
});
}
/**
* Create an ImageView, loading from a file path via BitmapFactory.
* If path is null/empty the ImageView is created with no image.
*/
public static int createImageView(final String path) {
return runSyncInt(new IntSupplier() {
@Override public int get() {
ImageView iv = new ImageView(ctx());
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
iv.setAdjustViewBounds(true);
if (path != null && !path.isEmpty()) {
Bitmap bmp = BitmapFactory.decodeFile(path);
if (bmp != null) {
iv.setImageBitmap(bmp);
} else {
android.util.Log.w("ElBridge",
"createImageView: failed to decode " + path);
}
}
iv.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return allocSlot(iv);
}
});
}
/* ── Window operations ───────────────────────────────────────────────── */
/** Set the Activity's content view to the view at slot. */
public static void setContentView(final int slot) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (v != null && sActivity != null) {
sActivity.setContentView(v);
}
}
});
}
/** Set the Activity title. */
public static void setTitle(final String title) {
runSync(new Runnable() {
@Override public void run() {
if (sActivity != null) {
sActivity.setTitle(title != null ? title : "");
}
}
});
}
/* ── Tree operations ─────────────────────────────────────────────────── */
/**
* Add child view to parent view.
* LinearLayout: child added as arranged child with spacing margin.
* ScrollView: child replaces current document view.
* FrameLayout / other ViewGroup: plain addView.
*/
public static void addChild(final int parentSlot, final int childSlot) {
runSync(new Runnable() {
@Override public void run() {
View parent = getView(parentSlot);
View child = getView(childSlot);
if (parent == null || child == null) return;
/* Remove child from existing parent first. */
if (child.getParent() instanceof ViewGroup) {
((ViewGroup) child.getParent()).removeView(child);
}
if (parent instanceof LinearLayout) {
LinearLayout ll = (LinearLayout) parent;
Object tag = ll.getTag(R_TAG_SPACING);
int spacing = (tag instanceof Integer) ? (Integer) tag : 0;
LinearLayout.LayoutParams lp;
Object existingLp = child.getLayoutParams();
if (existingLp instanceof LinearLayout.LayoutParams) {
lp = (LinearLayout.LayoutParams) existingLp;
} else {
lp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
/* Apply spacing as margin on the leading/top edge (after first child). */
if (ll.getChildCount() > 0 && spacing > 0) {
int px = dpToPx(spacing);
if (ll.getOrientation() == LinearLayout.VERTICAL) {
lp.topMargin = px;
} else {
lp.leftMargin = px;
}
}
child.setLayoutParams(lp);
ll.addView(child);
} else if (parent instanceof ScrollView) {
ScrollView sv = (ScrollView) parent;
sv.removeAllViews();
sv.addView(child);
} else if (parent instanceof ViewGroup) {
((ViewGroup) parent).addView(child);
}
}
});
}
/** Remove child from its parent. */
public static void removeChild(final int parentSlot, final int childSlot) {
runSync(new Runnable() {
@Override public void run() {
View parent = getView(parentSlot);
View child = getView(childSlot);
if (parent instanceof ViewGroup && child != null) {
((ViewGroup) parent).removeView(child);
}
}
});
}
/** Remove the view from its parent and release the slot. */
public static void destroyView(final int slot) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (v == null) return;
if (v.getParent() instanceof ViewGroup) {
((ViewGroup) v.getParent()).removeView(v);
}
sViews[slot] = null;
}
});
}
/* ── Property setters ────────────────────────────────────────────────── */
public static void setText(final int slot, final String text) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
String s = text != null ? text : "";
if (v instanceof EditText) {
((EditText) v).setText(s);
} else if (v instanceof Button) {
((Button) v).setText(s);
} else if (v instanceof TextView) {
((TextView) v).setText(s);
}
}
});
}
public static String getText(final int slot) {
final String[] result = { "" };
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (v instanceof TextView) {
CharSequence cs = ((TextView) v).getText();
result[0] = cs != null ? cs.toString() : "";
}
}
});
return result[0];
}
/** Set foreground text color. Components in [0,1]. */
public static void setTextColor(final int slot, final float r, final float g,
final float b, final float a) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (v instanceof TextView) {
((TextView) v).setTextColor(floatToArgb(r, g, b, a));
}
}
});
}
/** Set background color using a GradientDrawable so corner radius is preserved. */
public static void setBackgroundColor(final int slot, final float r, final float g,
final float b, final float a) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (v == null) return;
ensureGradientBackground(v);
GradientDrawable gd = (GradientDrawable) v.getBackground();
gd.setColor(floatToArgb(r, g, b, a));
}
});
}
/**
* Set font family and size.
* family: "system" or null → system default; otherwise tries to load by name.
* bold: if true uses Typeface.BOLD.
*/
public static void setFont(final int slot, final String family,
final int sizeSp, final boolean bold) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (!(v instanceof TextView)) return;
TextView tv = (TextView) v;
Typeface tf;
if (family != null && !family.isEmpty()
&& !family.equals("system")) {
Typeface base = Typeface.create(family,
bold ? Typeface.BOLD : Typeface.NORMAL);
tf = (base != null) ? base
: Typeface.defaultFromStyle(bold ? Typeface.BOLD : Typeface.NORMAL);
} else {
tf = Typeface.defaultFromStyle(bold ? Typeface.BOLD : Typeface.NORMAL);
}
tv.setTypeface(tf);
tv.setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, sizeSp);
}
});
}
/** Set padding in dp. */
public static void setPadding(final int slot, final int top, final int right,
final int bottom, final int left) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (v != null) {
v.setPadding(dpToPx(left), dpToPx(top), dpToPx(right), dpToPx(bottom));
}
}
});
}
/** Set explicit width in dp. Passes MATCH_PARENT for negative values. */
public static void setWidth(final int slot, final int widthDp) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (v == null) return;
ViewGroup.LayoutParams lp = v.getLayoutParams();
if (lp == null) lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lp.width = widthDp < 0
? ViewGroup.LayoutParams.MATCH_PARENT
: dpToPx(widthDp);
v.setLayoutParams(lp);
}
});
}
/** Set explicit height in dp. */
public static void setHeight(final int slot, final int heightDp) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (v == null) return;
ViewGroup.LayoutParams lp = v.getLayoutParams();
if (lp == null) lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lp.height = heightDp < 0
? ViewGroup.LayoutParams.MATCH_PARENT
: dpToPx(heightDp);
v.setLayoutParams(lp);
}
});
}
/**
* Set flex weight on a child of a LinearLayout.
* flex > 0 → weight = flex, width/height = 0dp (expand).
* flex == 0 → weight = 0, wrap_content (shrink to content).
*/
public static void setFlex(final int slot, final int flex) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (v == null) return;
ViewGroup.LayoutParams lp = v.getLayoutParams();
if (lp instanceof LinearLayout.LayoutParams) {
LinearLayout.LayoutParams llp = (LinearLayout.LayoutParams) lp;
if (flex > 0) {
llp.weight = (float) flex;
/* Determine orientation from parent to set 0dp on the right axis. */
if (v.getParent() instanceof LinearLayout) {
LinearLayout parent = (LinearLayout) v.getParent();
if (parent.getOrientation() == LinearLayout.VERTICAL) {
llp.height = 0;
} else {
llp.width = 0;
}
}
} else {
llp.weight = 0f;
}
v.setLayoutParams(llp);
}
}
});
}
/** Set corner radius in dp using a GradientDrawable background. */
public static void setCornerRadius(final int slot, final float radiusDp) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (v == null) return;
ensureGradientBackground(v);
GradientDrawable gd = (GradientDrawable) v.getBackground();
gd.setCornerRadius(dpToPxF(radiusDp));
}
});
}
public static void setEnabled(final int slot, final boolean enabled) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (v != null) v.setEnabled(enabled);
}
});
}
/**
* Show or hide a view.
* @param visible true = VISIBLE, false = GONE (matches AppKit setHidden semantics)
*/
public static void setVisibility(final int slot, final boolean visible) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (v != null) v.setVisibility(visible ? View.VISIBLE : View.GONE);
}
});
}
/* ── Event listener registration ─────────────────────────────────────── */
/** Register an OnClickListener that calls back into C nativeOnClick. */
public static void setOnClickListener(final int slot) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (v == null) return;
final int capturedSlot = slot;
v.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
nativeOnClick(capturedSlot);
}
});
}
});
}
/**
* Register a TextWatcher on an EditText that calls back nativeOnChange
* for every text change.
*/
public static void setOnChangeListener(final int slot) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (!(v instanceof EditText)) return;
final int capturedSlot = slot;
((EditText) v).addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence s, int start,
int count, int after) {}
@Override public void onTextChanged(CharSequence s, int start,
int before, int count) {}
@Override public void afterTextChanged(Editable s) {
nativeOnChange(capturedSlot, s != null ? s.toString() : "");
}
});
}
});
}
/**
* Register an OnEditorActionListener on a single-line EditText that calls
* nativeOnSubmit when the user presses the action/enter key.
*/
public static void setOnSubmitListener(final int slot) {
runSync(new Runnable() {
@Override public void run() {
View v = getView(slot);
if (!(v instanceof EditText)) return;
final int capturedSlot = slot;
((EditText) v).setOnEditorActionListener(
new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView tv, int actionId,
android.view.KeyEvent event) {
nativeOnSubmit(capturedSlot,
tv.getText() != null ? tv.getText().toString() : "");
return true;
}
});
}
});
}
/* ── Internal helpers ─────────────────────────────────────────────────── */
/*
* Tag key used to stash the spacing value on LinearLayouts so addChild
* can apply the correct margin between children.
* We use a stable integer resource-id-like value; because we do not have
* a resources file here we use View.generateViewId() lazily.
*/
private static int sSpacingTagKey = 0;
private static int R_TAG_SPACING;
static {
R_TAG_SPACING = View.generateViewId();
}
/** Convert dp to pixels using the Activity's display metrics. */
private static int dpToPx(float dp) {
if (sActivity == null) return (int) dp;
float density = sActivity.getResources().getDisplayMetrics().density;
return Math.round(dp * density);
}
private static float dpToPxF(float dp) {
if (sActivity == null) return dp;
float density = sActivity.getResources().getDisplayMetrics().density;
return dp * density;
}
/** Convert RGBA float components (01) to an Android ARGB int. */
private static int floatToArgb(float r, float g, float b, float a) {
int ai = Math.round(a * 255f);
int ri = Math.round(r * 255f);
int gi = Math.round(g * 255f);
int bi = Math.round(b * 255f);
return Color.argb(ai, ri, gi, bi);
}
/**
* Ensure the view has a GradientDrawable background so that both color
* and corner radius can be set independently. If the current background
* is already a GradientDrawable it is reused; otherwise a new transparent
* one is installed.
*/
private static void ensureGradientBackground(View v) {
if (!(v.getBackground() instanceof GradientDrawable)) {
GradientDrawable gd = new GradientDrawable();
gd.setColor(Color.TRANSPARENT);
v.setBackground(gd);
}
}
}
@@ -0,0 +1,554 @@
# Platform Bridge Specification — el-native
This document is the authoritative reference for anyone implementing a new platform bridge for the el-native widget system. Read it top to bottom before writing a single line of code.
---
## What a Platform Bridge Is
The el compiler (`elc`) emits C code. That C code calls `__`-prefixed functions for everything OS-related: printing, file I/O, threading, and — when building a native UI app — widget creation and event handling. These `__` functions are the *OS boundary*.
For native UI, the bridge is the translation layer between that fixed C API and whatever platform toolkit you are targeting. The bridge owns:
1. A **slot table** of up to 4096 widget objects, indexed by `int64_t` handle.
2. Implementations of all 33 `__*` widget functions declared in `el_native_target.h`.
3. Callback dispatch from platform events back into El function symbols resolved via `dlsym` (or a platform equivalent).
The thin wrappers in `el_seed.c` (`#ifdef EL_TARGET_*` blocks) marshal between `el_val_t` and native C types, then call through to the bridge. The bridge itself never touches `el_val_t` — it works only with plain C types (`int64_t`, `const char*`, `int`, `float`).
**Existing bridges:**
| File | Platform | Toolkit | Language |
|------|----------|---------|----------|
| `el_appkit.m` | macOS | AppKit | ObjC (MRC) |
| `el_gtk4.c` | Linux | GTK4 | C |
| `el_win32.c` | Windows | Win32/ComCtl | C |
| `el_uikit.m` | iOS | UIKit | ObjC (MRC) |
| `el_android.c` + `ElBridge.java` | Android | View/JNI | C + Java |
| `el_sdl2.c` | Embedded Linux / Pi | SDL2 | C |
| `el_lvgl.c` | Microcontrollers | LVGL | C |
---
## The Slot System
Every widget — window, button, label, container, image — is stored in a static array:
```c
#define EL_<PLATFORM>_MAX_WIDGETS 4096
typedef struct {
ElWidgetKind kind;
/* platform-specific object reference (pointer, handle, ID...) */
/* callback names */
char* cb_click;
char* cb_change;
} ElWidget;
static ElWidget _el_widgets[EL_<PLATFORM>_MAX_WIDGETS];
```
Rules:
- **Slot 0 is never valid.** Scan starts at index 1. This ensures 0 is never a valid handle.
- **Handle = slot index.** An `int64_t` value returned to El code is a direct index into `_el_widgets[]`.
- **-1 = invalid.** All create functions return -1 on failure (table full, platform API error).
- **Slot is FREE until allocated, FREE again after destroy.** Use an `ElWidgetKind` enum where `0 = EL_WIDGET_FREE` to track liveness.
- **4096 slots is the system-wide maximum.** This is intentional and sufficient for any realistic UI. Do not increase it without a compelling reason.
### Slot allocation and release pattern
```c
static int64_t el_widget_alloc(ElWidgetKind kind, /* platform object ref */) {
for (int i = 1; i < EL_<PLATFORM>_MAX_WIDGETS; i++) {
if (_el_widgets[i].kind == EL_WIDGET_FREE) {
_el_widgets[i].kind = kind;
/* store platform object ref — retain/addref if needed */
_el_widgets[i].cb_click = NULL;
_el_widgets[i].cb_change = NULL;
return (int64_t)i;
}
}
return -1; /* table full */
}
static ElWidget* el_widget_get(int64_t handle) {
if (handle <= 0 || handle >= EL_<PLATFORM>_MAX_WIDGETS) return NULL;
if (_el_widgets[handle].kind == EL_WIDGET_FREE) return NULL;
return &_el_widgets[handle];
}
static void el_widget_free(int64_t handle) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
/* release platform object ref */
w->kind = EL_WIDGET_FREE;
free(w->cb_click); w->cb_click = NULL;
free(w->cb_change); w->cb_change = NULL;
}
```
**NULL handle guard:** `el_widget_get` must return `NULL` for any handle that is 0, negative, out of range, or points to a `FREE` slot. Every `__` function that takes a handle must null-check the result of `el_widget_get` before doing anything. Failing to do so causes crashes or corruption when El code passes an uninitialized handle.
---
## The 33 Required Functions
Every bridge must implement all 33 functions listed below. They are grouped by category. The signatures shown are from `el_native_target.h` and from `el_seed.c`'s wrapper layer; the bridge itself uses plain C types (the wrappers do the `el_val_t` ↔ C-type conversion).
### Internal C signatures (what the bridge implements)
These are what your `.c` / `.m` file defines. The `el_seed.c` wrappers call these.
#### Lifecycle (2 functions)
```c
void el_<platform>_init(void);
```
**Purpose:** Initialize the platform UI toolkit. Must be idempotent (safe to call more than once). Called once from `__native_init` before any widget creation.
**Edge cases:** On platforms where the toolkit must be initialized before a display connection is established (X11, Wayland), this is where that happens. On Android, this is a no-op because ElBridge.java calls init from Java.
```c
void el_<platform>_run_loop(void);
```
**Purpose:** Start the platform event loop. On most platforms this **never returns**. Exceptions: Android (the loop is Java-managed — this must be a no-op) and headless test builds.
**Edge cases:** Must be called from the main thread. On iOS/UIKit, calls `UIApplicationMain` which never returns; El code must set `el_main_entry_fn` before calling this.
#### Window (3 functions)
```c
int64_t el_<platform>_window_create(const char* title, int w, int h, int mw, int mh);
```
**Purpose:** Create a top-level window. `w`/`h` = initial size in logical pixels. `mw`/`mh` = minimum size (0 = no minimum).
**Returns:** Slot handle, or -1 on failure.
**Edge cases:** NULL or empty `title` must be handled gracefully (use `""`). On mobile (iOS, Android), the concept of a "window" maps to the root view controller / activity root view — create that here.
```c
void el_<platform>_window_show(int64_t handle);
```
**Purpose:** Make the window visible. On some platforms windows are hidden at creation; this makes them appear.
**Edge cases:** NULL handle → return silently. Calling on an already-visible window is a no-op.
```c
void el_<platform>_window_set_title(int64_t handle, const char* title);
```
**Purpose:** Update the window's title bar text at runtime.
**Edge cases:** NULL handle or NULL title → no-op.
#### Layout containers (4 functions)
```c
int64_t el_<platform>_vstack_create(int spacing);
int64_t el_<platform>_hstack_create(int spacing);
```
**Purpose:** Create a vertical/horizontal linear container. `spacing` = gap between children in logical pixels.
**Returns:** Slot handle, or -1.
**Edge cases:** spacing = 0 is valid and common.
```c
int64_t el_<platform>_zstack_create(void);
```
**Purpose:** Create a z-axis layered container (children overlap, no stacking direction). Used for overlays.
**Returns:** Slot handle, or -1.
```c
int64_t el_<platform>_scroll_create(void);
```
**Purpose:** Create a scrollable container. Scrolls vertically by default. Only the first child added is the scrollable content.
**Returns:** Slot handle, or -1.
#### Leaf widgets (5 functions)
```c
int64_t el_<platform>_label_create(const char* text);
```
**Purpose:** Create a non-editable text label.
**Edge cases:** NULL/empty text → label with empty string, not a crash.
```c
int64_t el_<platform>_button_create(const char* label);
```
**Purpose:** Create a clickable button. The `label` is the button's visible text.
**Edge cases:** The button must wire up an action target at creation time so that click callbacks registered later via `el_<platform>_widget_on_click` will fire. On platforms with target-action (AppKit, UIKit), allocate the delegate object here.
```c
int64_t el_<platform>_text_field_create(const char* placeholder);
```
**Purpose:** Create a single-line text input. `placeholder` is the hint text shown when empty.
**Edge cases:** NULL placeholder → no hint text displayed.
```c
int64_t el_<platform>_text_area_create(const char* placeholder);
```
**Purpose:** Create a multi-line text input (scrollable).
**Edge cases:** Same as text_field_create. On AppKit, this wraps NSTextView inside NSScrollView — the slot's `obj` points to the scroll view, not the text view.
```c
int64_t el_<platform>_image_create(const char* path_or_name);
```
**Purpose:** Create an image widget. `path_or_name` can be a filesystem path or a platform resource name. Try path first, fall back to named resource.
**Edge cases:** Non-existent path → create an empty image widget (do not crash). NULL → same.
#### Widget properties (12 functions)
```c
void el_<platform>_widget_set_text(int64_t handle, const char* text);
```
**Purpose:** Update the text content of a label, button, text field, text area, or window title. Must dispatch on `kind` to use the correct API.
**Edge cases:** NULL handle → no-op. NULL text → treat as `""`.
```c
const char* el_<platform>_widget_get_text(int64_t handle);
```
**Purpose:** Return the current text of a widget. Returns a `const char*` that the `el_seed.c` wrapper wraps into an `el_val_t` string.
**Edge cases:** NULL handle → return `""` (never NULL). The caller in `el_seed.c` handles the `strdup` lifetime issue — see the AppKit reference implementation notes.
```c
void el_<platform>_widget_set_color(int64_t h, float r, float g, float b, float a);
void el_<platform>_widget_set_bg_color(int64_t h, float r, float g, float b, float a);
```
**Purpose:** Set foreground (text) color and background color respectively. All channels are normalized floats [0.0, 1.0].
**Edge cases:** For containers, `set_color` may be a no-op (no text); `set_bg_color` should set the layer/surface background. On platforms without alpha compositing, clamp alpha to 0 or 1.
```c
void el_<platform>_widget_set_font(int64_t h, const char* family, int size, int bold);
```
**Purpose:** Set the font on a text-bearing widget. `family` = font family name or `"system"` for the platform default. `size` = point size. `bold` = 0 or 1.
**Edge cases:** If `family` is not found, fall back to the system font. Non-text widgets (containers, images) → no-op.
```c
void el_<platform>_widget_set_padding(int64_t h, int top, int right, int bottom, int left);
```
**Purpose:** Set internal padding/insets for a container or text area.
**Edge cases:** On platforms where padding is per-view (not per-container), map to the nearest equivalent (margin, insets, text container inset). For leaf widgets other than text areas, this may be a partial no-op.
```c
void el_<platform>_widget_set_width(int64_t h, int width);
void el_<platform>_widget_set_height(int64_t h, int height);
```
**Purpose:** Apply a fixed-size constraint. `width`/`height` in logical pixels.
**Edge cases:** On platforms with Auto Layout or constraint systems, add a fixed-size constraint. Do not apply to windows (size is set at creation). Calling multiple times should override the previous constraint, not add another.
```c
void el_<platform>_widget_set_flex(int64_t h, int flex);
```
**Purpose:** Set the flex/expansion factor. `flex > 0` → the widget expands to fill available space. `flex == 0` → hugs content size.
**Edge cases:** Maps to content-hugging priority (AppKit), `GtkWidget::hexpand`/`vexpand` (GTK4), or layout weight (Android). For windows → no-op.
```c
void el_<platform>_widget_set_corner_radius(int64_t h, int radius);
```
**Purpose:** Apply rounded corners to the widget's visual layer.
**Edge cases:** Requires backing layer / GPU surface. On platforms without layer compositing (Win32 without DX), this may be a no-op or require manual painting. Radius in logical pixels.
```c
void el_<platform>_widget_set_disabled(int64_t h, int disabled);
```
**Purpose:** Enable or disable user interaction. `disabled = 1` → greyed out, non-interactive.
**Edge cases:** Only meaningful for interactive widgets (button, text field). For containers/labels → no-op.
```c
void el_<platform>_widget_set_hidden(int64_t h, int hidden);
```
**Purpose:** Show or hide the widget. `hidden = 1` → invisible but still in layout.
**Edge cases:** For windows, map to `orderOut`/`hide` or equivalent. For views, use `setHidden`/`gtk_widget_set_visible` or equivalent.
#### Tree management (3 functions)
```c
void el_<platform>_widget_add_child(int64_t parent, int64_t child);
```
**Purpose:** Attach a child widget to a parent container. Dispatch on parent kind:
- Window → add to root content view/container
- VStack/HStack → add as arranged/linear child
- ZStack → add as overlapping subview
- Scroll → set as document/content view (first child only)
- Other → add as plain subview
**Edge cases:** NULL parent or child handle → no-op. Attempting to add a window as a child → no-op. Adding the same child twice is platform-defined behavior (tolerate it).
```c
void el_<platform>_widget_remove_child(int64_t parent, int64_t child);
```
**Purpose:** Detach child from its parent. The child slot remains allocated; the widget is not destroyed.
**Edge cases:** NULL handles → no-op. Child not currently attached → no-op.
```c
void el_<platform>_widget_destroy(int64_t handle);
```
**Purpose:** Destroy a widget: remove from superview/parent, release the platform object, release callback strings, mark slot as FREE.
**Edge cases:** For windows, close the window. Free any delegate/target objects stored in side tables. After destroy, the handle is invalid — El code must not use it again (this is the caller's responsibility, not enforced here).
#### Event registration (3 functions)
```c
void el_<platform>_widget_on_click(int64_t h, const char* fn_name);
void el_<platform>_widget_on_change(int64_t h, const char* fn_name);
void el_<platform>_widget_on_submit(int64_t h, const char* fn_name);
```
**Purpose:** Register an El callback function by symbol name.
- `on_click` → button press
- `on_change` → text field value change (keystroke-level)
- `on_submit` → text field Enter key (text field only; stored in `cb_click` slot in AppKit)
The implementation stores `strdup(fn_name)` in the widget's `cb_click` or `cb_change` field. The platform event handler calls `el_<platform>_invoke_cb` (see callback ABI section).
**Edge cases:** NULL or empty `fn_name` → clear the callback (`free` + set NULL). Calling on a non-interactive widget (label, image) → no-op or store silently (harmless).
#### Manifest reader (1 function)
```c
/* Note: __manifest_read is implemented in el_seed.c, not in the bridge. */
/* Bridges do NOT need to implement this. */
```
`__manifest_read` is handled entirely in the platform-independent section of `el_seed.c`. It reads a JSON/EL manifest file from the path in the `EL_MANIFEST` environment variable. Bridge authors do not need to implement this.
---
## The Callback ABI
When a platform event fires (button clicked, text changed), the bridge must call back into the El runtime. The mechanism:
```c
typedef void (*ElCb2)(int64_t handle, int64_t data);
static void el_<platform>_invoke_cb(const char* fn_name, int64_t handle, const char* data) {
if (!fn_name || !*fn_name) return;
void* sym = dlsym(RTLD_DEFAULT, fn_name);
if (!sym) return;
ElCb2 fn = (ElCb2)sym;
fn(handle, (int64_t)(uintptr_t)(data ? data : ""));
}
```
The El callback signature (in El source):
```
fn handler(handle: Int, data: String) -> Void
```
Which compiles to:
```c
void handler(int64_t handle, int64_t data)
```
Where `data` is a `const char*` cast to `int64_t` (the el `String` representation). For click events, `data` is `""`. For change/submit events, `data` is the current widget text.
**On platforms without `dlsym`** (Windows, some embedded systems): use `GetProcAddress(GetModuleHandle(NULL), fn_name)` on Windows, or maintain a manual symbol registration table for embedded targets where dynamic linking is unavailable.
**Thread safety for callbacks:** Callbacks fired from a background thread must be marshalled to the UI thread before calling into El code. El code may call `__widget_set_text` or other UI functions synchronously from within the callback — those must run on the UI thread.
---
## Thread Safety Contract
**All platform UI operations must execute on the main/UI thread.** This is a hard requirement on every platform (AppKit, UIKit, GTK4, Win32, Android View, SDL2 main thread rule).
The reference pattern (AppKit):
```c
static void el_appkit_sync_main(void (^block)(void)) {
if ([NSThread isMainThread]) {
block();
} else {
dispatch_sync(dispatch_get_main_queue(), block);
}
}
```
For other platforms:
- **GTK4:** `g_main_context_invoke` or `g_idle_add` + semaphore for synchronous dispatch
- **Win32:** `SendMessage(hwnd, WM_APP, ...)` or `PostMessage` + wait
- **Android:** `Activity.runOnUiThread`
- **SDL2:** All ops must be called from the thread that initialized SDL (the main thread)
- **LVGL:** `lv_lock()` / `lv_unlock()` for thread-safe access
El program flow is: `main()` → build UI (on main thread) → `__native_run_loop()`. Because UI is built before the run loop starts, most widget creation calls are already on the main thread. The sync dispatch wrapper exists to handle callbacks that arrive on worker threads (e.g., network callbacks that update UI).
---
## Integration Pattern
### In `el_native_target.h`
Add an `#ifdef EL_TARGET_<PLATFORM>` block declaring all 33 `__*` functions with their `el_val_t` signatures (identical to the existing blocks for MACOS, LINUX, etc.):
```c
#ifdef EL_TARGET_<PLATFORM>
void __native_init(void);
void __native_run_loop(void);
el_val_t __window_create(el_val_t title, el_val_t width, el_val_t height,
el_val_t min_width, el_val_t min_height);
void __window_show(el_val_t handle);
void __window_set_title(el_val_t handle, el_val_t title);
el_val_t __vstack_create(el_val_t spacing);
el_val_t __hstack_create(el_val_t spacing);
el_val_t __zstack_create(void);
el_val_t __scroll_create(void);
el_val_t __label_create(el_val_t text);
el_val_t __button_create(el_val_t label);
el_val_t __text_field_create(el_val_t placeholder);
el_val_t __text_area_create(el_val_t placeholder);
el_val_t __image_create(el_val_t path_or_name);
void __widget_set_text(el_val_t handle, el_val_t text);
el_val_t __widget_get_text(el_val_t handle);
void __widget_set_color(el_val_t handle, el_val_t r, el_val_t g,
el_val_t b, el_val_t a);
void __widget_set_bg_color(el_val_t handle, el_val_t r, el_val_t g,
el_val_t b, el_val_t a);
void __widget_set_font(el_val_t handle, el_val_t family,
el_val_t size, el_val_t bold);
void __widget_set_padding(el_val_t handle, el_val_t top, el_val_t right,
el_val_t bottom, el_val_t left);
void __widget_set_width(el_val_t handle, el_val_t width);
void __widget_set_height(el_val_t handle, el_val_t height);
void __widget_set_flex(el_val_t handle, el_val_t flex);
void __widget_set_corner_radius(el_val_t handle, el_val_t radius);
void __widget_set_disabled(el_val_t handle, el_val_t disabled);
void __widget_set_hidden(el_val_t handle, el_val_t hidden);
void __widget_add_child(el_val_t parent, el_val_t child);
void __widget_remove_child(el_val_t parent, el_val_t child);
void __widget_destroy(el_val_t handle);
void __widget_on_click(el_val_t handle, el_val_t fn_name);
void __widget_on_change(el_val_t handle, el_val_t fn_name);
void __widget_on_submit(el_val_t handle, el_val_t fn_name);
el_val_t __manifest_read(el_val_t path);
#endif /* EL_TARGET_<PLATFORM> */
```
### In `el_seed.c`
Add an `#ifdef EL_TARGET_<PLATFORM>` block containing:
1. `extern` declarations of all `el_<platform>_*` functions (your bridge's C API)
2. Thin wrapper functions that marshal `el_val_t` ↔ C types and call through
The wrapper pattern (copy from the `EL_TARGET_MACOS` block and substitute the platform name):
```c
#ifdef EL_TARGET_<PLATFORM>
/* Forward declarations — implemented in el_<platform>.c */
extern void el_<platform>_init(void);
extern void el_<platform>_run_loop(void);
extern int64_t el_<platform>_window_create(const char* title, int w, int h, int mw, int mh);
/* ... all others ... */
/* Wrappers */
void __native_init(void) { el_<platform>_init(); }
void __native_run_loop(void) { el_<platform>_run_loop(); }
el_val_t __window_create(el_val_t title, el_val_t width, el_val_t height,
el_val_t min_width, el_val_t min_height) {
return (el_val_t)el_<platform>_window_create(
EL_CSTR(title),
(int)(int64_t)width, (int)(int64_t)height,
(int)(int64_t)min_width, (int)(int64_t)min_height);
}
void __window_show(el_val_t h) { el_<platform>_window_show((int64_t)h); }
void __window_set_title(el_val_t h, el_val_t t) { el_<platform>_window_set_title((int64_t)h, EL_CSTR(t)); }
/* ... continue for all 33 functions ... */
#endif /* EL_TARGET_<PLATFORM> */
```
Key marshalling rules:
- `el_val_t``int64_t` handle: `(int64_t)h`
- `el_val_t``int`: `(int)(int64_t)value`
- `el_val_t``const char*`: `EL_CSTR(value)`
- `el_val_t``float`: `(float)el_to_float(value)` (for color channels)
- `int64_t` handle → `el_val_t`: `(el_val_t)handle`
- `const char*``el_val_t`: `EL_STR(str)` — but read the get_text note below
**`__widget_get_text` note:** The bridge returns `const char*`. The `el_seed.c` wrapper wraps it with `EL_STR(s)`. The returned pointer must remain valid until the El program is done with it. The AppKit implementation returns a `strdup`'d string — the caller (seed wrapper) stores it without tracking it in the arena. This is a known lifetime edge; be consistent with the platform's existing pattern.
---
## How el Strings Work
Inside El compiled C code, strings are `el_val_t` values where the value is the `uintptr_t` cast of a `const char*`:
```c
#define EL_STR(s) ((el_val_t)(uintptr_t)(s))
#define EL_CSTR(v) ((const char*)(uintptr_t)(v))
```
To construct a string result in `el_seed.c`:
```c
static char* s = strdup("hello");
return EL_STR(s);
```
To read a string argument passed from El:
```c
const char* text = EL_CSTR(some_el_val_t_argument);
```
The `EL_STR` / `EL_CSTR` macros are defined in `el_seed.h` and are available in `el_seed.c`. Bridge files (`el_<platform>.c`) do not use these macros — they only deal in `const char*` at their API boundary.
---
## Known Gotchas
### Duplicate symbols with `el_runtime.c`
`el_runtime.c` defines many of the same `__`-prefixed symbols as `el_seed.c`. When linking both (required for the native-hello example), the linker will reject duplicate definitions. The build system uses `nmedit` (macOS) to hide the `el_runtime.c` copies of symbols that `el_seed.c` already defines, keeping `el_seed.c` canonical.
If you are writing a build script for a new platform and see duplicate symbol link errors involving `__println`, `__print`, `__str_len`, etc., apply the same nmedit / `objcopy --weaken-symbol` / `strip --strip-symbol` trick from the macOS build to your platform's object file handling.
### The `nmedit` trick on macOS
```bash
# Build a keep-list: symbols defined in el_seed.o but also in el_runtime.o
nm el_seed.o | awk '/^[0-9a-f]+ T _/{print $3}' | sort > .seed_T.txt
nm el_runtime.o | awk '/^[0-9a-f]+ T _/{print $3}' | sort > .rt_T.txt
# Keep only symbols unique to el_runtime.o
comm -23 .rt_T.txt .seed_T.txt > .rt_keep.txt
nmedit -s .rt_keep.txt el_runtime.o
```
On Linux, use `objcopy` with `--weaken-symbol` for each duplicate, or link `el_seed.o` before `el_runtime.o` and use `--allow-multiple-definition` if your use case permits it.
### ObjC bridges must use MRC, not ARC
Bridges that use Objective-C (AppKit, UIKit) **must** compile without ARC (`-fno-objc-arc`). The reason: the widget table stores `id` values in a plain C struct. ARC cannot insert retain/release through C struct boundaries, and will reject explicit `[obj retain]` / `[obj release]` calls in ARC mode. Use:
```bash
clang -ObjC -fno-objc-arc -framework Cocoa -c el_appkit.m
```
### Widget table struct — don't put `id` fields in C structs under ARC
If you ever add ARC-managed object fields to the `ElWidget` struct, you will get a compile error. Keep the struct C-only (pointers as `void*` if you must, cast when using) or compile as MRC.
### The `el_seed.c` `__manifest_read` is platform-independent
`__manifest_read` is already implemented in `el_seed.c` (in the section compiled unconditionally). You do not implement it in your bridge. You do need to declare it in the `el_native_target.h` block for your platform (matching the other platforms), but `el_seed.c` already has the implementation.
---
## Completion Checklist
Before declaring your bridge ready for integration:
- [ ] All 33 `__*` functions implemented (including `__manifest_read` declaration, implementation is in seed)
- [ ] Slot table with 4096 entries, scan starting at index 1
- [ ] `el_widget_get` returns NULL for handle 0, negative, out-of-range, and FREE slots
- [ ] All functions null-check `el_widget_get` result before use
- [ ] `el_<platform>_init` is idempotent
- [ ] `el_<platform>_run_loop` either never returns or is documented as a no-op (Android)
- [ ] Callback dispatch via `dlsym` (or platform equivalent) implemented
- [ ] All UI operations dispatched to the main/UI thread
- [ ] `el_native_target.h` updated with `#ifdef EL_TARGET_<PLATFORM>` block
- [ ] `el_seed.c` updated with `#ifdef EL_TARGET_<PLATFORM>` extern + wrapper block
- [ ] Bridge compiles cleanly with no warnings: `cc -DEL_TARGET_<PLATFORM> -Wall -Wextra -c el_<platform>.c`
- [ ] Bridge links cleanly with `el_seed.o` and `el_runtime.o` (duplicate symbol check)
- [ ] `detect-platforms` script updated with detection logic for the new platform
- [ ] Basic smoke test: create window → add label → show window → run loop
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env bash
# detect-platforms — probe available platform bridge dependencies
#
# Reports which el-native platform bridges can be built on this machine,
# with install instructions for anything that is missing.
#
# Usage: ./detect-platforms
# ./build.sh platforms (from native-hello)
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# ── Helpers ───────────────────────────────────────────────────────────────────
PASS="[+]"
FAIL="[ ]"
_ok() { printf " ${PASS} %-22s %s\n" "$1" "$2"; }
_miss() { printf " ${FAIL} %-22s %s\n" "$1" "$2"; }
# ── Header ────────────────────────────────────────────────────────────────────
echo ""
echo "==> el-native platform detection"
echo ""
echo " Checking build dependencies for each platform bridge..."
echo ""
AVAILABLE=0
MISSING=0
# ── macOS / AppKit ────────────────────────────────────────────────────────────
if [[ "$(uname)" == "Darwin" ]]; then
if xcrun --find clang &>/dev/null && xcrun --find xcodebuild &>/dev/null 2>/dev/null || \
xcrun --find cc &>/dev/null; then
CLT_INFO="Xcode CLT $(xcode-select -p 2>/dev/null | sed 's|/Developer||' || echo '')"
_ok "macOS/AppKit" "-DEL_TARGET_MACOS ${CLT_INFO}"
AVAILABLE=$((AVAILABLE + 1))
else
_miss "macOS/AppKit" "-DEL_TARGET_MACOS (Xcode CLT missing — xcode-select --install)"
MISSING=$((MISSING + 1))
fi
else
_miss "macOS/AppKit" "-DEL_TARGET_MACOS (not on macOS)"
fi
# ── iOS / UIKit ───────────────────────────────────────────────────────────────
if [[ "$(uname)" == "Darwin" ]]; then
if xcrun --sdk iphoneos --show-sdk-path &>/dev/null 2>&1; then
SDK_VER=$(xcrun --sdk iphoneos --show-sdk-version 2>/dev/null || echo "")
_ok "iOS/UIKit" "-DEL_TARGET_IOS SDK ${SDK_VER} (requires Xcode.app)"
AVAILABLE=$((AVAILABLE + 1))
else
_miss "iOS/UIKit" "-DEL_TARGET_IOS (iOS SDK not found — install Xcode.app)"
MISSING=$((MISSING + 1))
fi
else
_miss "iOS/UIKit" "-DEL_TARGET_IOS (not on macOS — requires Xcode)"
fi
# ── Linux / GTK4 ──────────────────────────────────────────────────────────────
if pkg-config --exists gtk4 2>/dev/null; then
GTK_VER=$(pkg-config --modversion gtk4 2>/dev/null)
_ok "Linux/GTK4" "-DEL_TARGET_LINUX gtk4 ${GTK_VER}"
AVAILABLE=$((AVAILABLE + 1))
else
_miss "Linux/GTK4" "-DEL_TARGET_LINUX (gtk4 not found)"
echo " Install: apt install libgtk-4-dev"
echo " or: dnf install gtk4-devel"
echo " or: brew install gtk4"
MISSING=$((MISSING + 1))
fi
# ── SDL2 / Embedded Linux / Pi ────────────────────────────────────────────────
SDL2_OK=0
if pkg-config --exists sdl2 2>/dev/null; then
SDL2_VER=$(pkg-config --modversion sdl2 2>/dev/null)
# Also check for SDL2_ttf (needed for text rendering)
if pkg-config --exists SDL2_ttf 2>/dev/null; then
TTF_VER=$(pkg-config --modversion SDL2_ttf 2>/dev/null)
_ok "SDL2/Embedded" "-DEL_TARGET_SDL2 sdl2 ${SDL2_VER}, SDL2_ttf ${TTF_VER}"
else
_ok "SDL2/Embedded" "-DEL_TARGET_SDL2 sdl2 ${SDL2_VER} (SDL2_ttf missing — needed for text)"
echo " Install: apt install libsdl2-ttf-dev"
fi
SDL2_OK=1
AVAILABLE=$((AVAILABLE + 1))
elif command -v sdl2-config &>/dev/null; then
SDL2_VER=$(sdl2-config --version 2>/dev/null || echo "")
_ok "SDL2/Embedded" "-DEL_TARGET_SDL2 sdl2 ${SDL2_VER} (via sdl2-config)"
SDL2_OK=1
AVAILABLE=$((AVAILABLE + 1))
fi
if [[ $SDL2_OK -eq 0 ]]; then
_miss "SDL2/Embedded" "-DEL_TARGET_SDL2 (sdl2 not found)"
echo " Install: apt install libsdl2-dev libsdl2-ttf-dev libsdl2-image-dev"
echo " or: brew install sdl2 sdl2_ttf sdl2_image"
MISSING=$((MISSING + 1))
fi
# ── LVGL / Microcontrollers ───────────────────────────────────────────────────
LVGL_OK=0
LVGL_WHERE=""
if [ -f "${SCRIPT_DIR}/lvgl/lvgl.h" ]; then
LVGL_WHERE="./lvgl/lvgl.h"
LVGL_OK=1
elif [ -f "${SCRIPT_DIR}/../lvgl/lvgl.h" ]; then
LVGL_WHERE="adjacent lvgl/"
LVGL_OK=1
elif [ -f "/usr/include/lvgl/lvgl.h" ]; then
LVGL_WHERE="/usr/include/lvgl"
LVGL_OK=1
elif [ -f "/usr/local/include/lvgl/lvgl.h" ]; then
LVGL_WHERE="/usr/local/include/lvgl"
LVGL_OK=1
elif pkg-config --exists lvgl 2>/dev/null; then
LVGL_WHERE="pkg-config ($(pkg-config --modversion lvgl 2>/dev/null))"
LVGL_OK=1
fi
if [[ $LVGL_OK -eq 1 ]]; then
_ok "LVGL/MCU" "-DEL_TARGET_LVGL ${LVGL_WHERE}"
AVAILABLE=$((AVAILABLE + 1))
else
_miss "LVGL/MCU" "-DEL_TARGET_LVGL (lvgl.h not found)"
echo " Install: git clone https://github.com/lvgl/lvgl"
echo " (place lvgl/ next to el-compiler/runtime/)"
MISSING=$((MISSING + 1))
fi
# ── Android / JNI ─────────────────────────────────────────────────────────────
ANDROID_OK=0
ANDROID_WHERE=""
if [ -n "${ANDROID_NDK_HOME:-}" ] && [ -d "${ANDROID_NDK_HOME}" ]; then
NDK_VER=""
if [ -f "${ANDROID_NDK_HOME}/source.properties" ]; then
NDK_VER=$(grep "Pkg.Revision" "${ANDROID_NDK_HOME}/source.properties" \
2>/dev/null | cut -d= -f2 | tr -d ' ' || echo "")
fi
ANDROID_WHERE="NDK ${NDK_VER:-(version unknown)} at \$ANDROID_NDK_HOME"
ANDROID_OK=1
elif command -v ndk-build &>/dev/null; then
ANDROID_WHERE="ndk-build in PATH"
ANDROID_OK=1
elif [ -n "${ANDROID_HOME:-}" ] && [ -d "${ANDROID_HOME}/ndk" ]; then
ANDROID_WHERE="NDK via \$ANDROID_HOME/ndk"
ANDROID_OK=1
fi
if [[ $ANDROID_OK -eq 1 ]]; then
_ok "Android/JNI" "-DEL_TARGET_ANDROID ${ANDROID_WHERE}"
AVAILABLE=$((AVAILABLE + 1))
else
_miss "Android/JNI" "-DEL_TARGET_ANDROID (ANDROID_NDK_HOME not set)"
echo " Install: https://developer.android.com/studio/releases/ndk"
echo " Then: export ANDROID_NDK_HOME=/path/to/ndk"
MISSING=$((MISSING + 1))
fi
# ── Windows / Win32 (cross or native) ─────────────────────────────────────────
WIN32_OK=0
WIN32_WHERE=""
if [[ "$(uname)" == MINGW* ]] || [[ "$(uname)" == CYGWIN* ]] || \
[[ "$(uname)" == MSYS* ]]; then
WIN32_WHERE="native Windows ($(uname))"
WIN32_OK=1
elif command -v x86_64-w64-mingw32-gcc &>/dev/null; then
MINGW_VER=$(x86_64-w64-mingw32-gcc --version 2>/dev/null | head -1 || echo "")
WIN32_WHERE="mingw cross-compiler — ${MINGW_VER}"
WIN32_OK=1
elif command -v i686-w64-mingw32-gcc &>/dev/null; then
WIN32_WHERE="mingw 32-bit cross-compiler"
WIN32_OK=1
fi
if [[ $WIN32_OK -eq 1 ]]; then
_ok "Windows/Win32" "-DEL_TARGET_WIN32 ${WIN32_WHERE}"
AVAILABLE=$((AVAILABLE + 1))
else
_miss "Windows/Win32" "-DEL_TARGET_WIN32 (mingw cross-compiler not found)"
echo " Install: brew install mingw-w64"
echo " or: apt install gcc-mingw-w64"
MISSING=$((MISSING + 1))
fi
# ── Summary ───────────────────────────────────────────────────────────────────
echo ""
echo " ${AVAILABLE} platform(s) available, ${MISSING} unavailable on this machine."
echo ""
if [[ -x "${SCRIPT_DIR}/new-platform" ]]; then
echo " Scaffold a new bridge: ${SCRIPT_DIR}/new-platform <name>"
fi
echo " Bridge contract: ${SCRIPT_DIR}/PLATFORM_BRIDGE_SPEC.md"
echo ""
+711
View File
@@ -0,0 +1,711 @@
#!/usr/bin/env bash
# new-platform — scaffold a new el-native platform bridge
#
# Usage: ./new-platform <platform-name>
#
# Example:
# ./new-platform myplatform
#
# Creates el_myplatform.c with all 33 required __* functions stubbed out,
# the ElWidget slot table, and the dlsym callback dispatcher.
#
# After running, follow the printed instructions to wire the bridge into
# el_native_target.h and el_seed.c.
#
# See PLATFORM_BRIDGE_SPEC.md for the full bridge contract.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# ── Argument validation ───────────────────────────────────────────────────────
if [[ $# -lt 1 ]]; then
echo "Usage: $0 <platform-name>" >&2
echo "" >&2
echo " <platform-name> lowercase identifier, e.g. myrtos, wayland, qt6" >&2
echo "" >&2
echo "This creates el_<platform-name>.c in the current directory." >&2
exit 1
fi
PLATFORM_LOWER="${1,,}" # force lowercase
PLATFORM_UPPER="${PLATFORM_LOWER^^}" # force uppercase
# Validate: letters, digits, underscores only
if [[ ! "${PLATFORM_LOWER}" =~ ^[a-z][a-z0-9_]*$ ]]; then
echo "Error: platform name must start with a letter and contain only a-z, 0-9, _" >&2
exit 1
fi
OUTPUT_FILE="${SCRIPT_DIR}/el_${PLATFORM_LOWER}.c"
if [[ -f "${OUTPUT_FILE}" ]]; then
echo "Error: ${OUTPUT_FILE} already exists." >&2
echo " Remove it first if you want to regenerate it." >&2
exit 1
fi
# ── Generate the bridge file ──────────────────────────────────────────────────
cat > "${OUTPUT_FILE}" << BRIDGE_FILE
/*
* el_${PLATFORM_LOWER}.c — el-native platform bridge for ${PLATFORM_UPPER}.
*
* Generated by new-platform. Replace the TODO stubs with real implementations.
* See PLATFORM_BRIDGE_SPEC.md for the full contract.
*
* ── Slot system ──────────────────────────────────────────────────────────────
* Every widget (window, button, label, container, image) is stored in a static
* array of ElWidget structs. The el program holds an int64_t "handle" which is
* a direct index into that array. Rules:
* - Slot 0 is NEVER valid. Scans start at index 1.
* - Handle -1 means "invalid" / "create failed".
* - Maximum 4096 concurrent widgets.
* - el_widget_get() returns NULL for 0, negative, out-of-range, or FREE slots.
*
* ── Callback ABI ─────────────────────────────────────────────────────────────
* When a platform event fires (click, text change), call el_${PLATFORM_LOWER}_invoke_cb:
*
* el_${PLATFORM_LOWER}_invoke_cb(w->cb_click, slot_index, "");
*
* The El callback signature:
* fn handler(handle: Int, data: String) -> Void
* compiles to:
* void handler(int64_t handle, int64_t data)
* where data is a const char* cast to int64_t (el String representation).
*
* ── Thread safety ────────────────────────────────────────────────────────────
* ALL platform UI calls must run on the main/UI thread. If your platform
* delivers events on background threads (e.g., from a network callback that
* updates a label), marshal to the main thread before calling any widget op.
*
* ── Compile ──────────────────────────────────────────────────────────────────
* cc -DEL_TARGET_${PLATFORM_UPPER} \\
* \$(pkg-config --cflags <your-toolkit>) \\
* -c el_${PLATFORM_LOWER}.c -o el_${PLATFORM_LOWER}.o
*
* ── Link ─────────────────────────────────────────────────────────────────────
* cc el_${PLATFORM_LOWER}.o el_seed.o el_runtime.o -o myapp \\
* \$(pkg-config --libs <your-toolkit>) -ldl -lpthread
*/
#ifdef EL_TARGET_${PLATFORM_UPPER}
/* ── TODO: add platform-specific includes here ──────────────────────────────
* Examples:
* #include <gtk/gtk.h> // GTK4
* #include <SDL2/SDL.h> // SDL2
* #include "lvgl/lvgl.h" // LVGL
* #include <windows.h> // Win32
*/
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <dlfcn.h> /* dlsym — replace with GetProcAddress on Windows */
/* ── Widget table ─────────────────────────────────────────────────────────── */
#define EL_${PLATFORM_UPPER}_MAX_WIDGETS 4096
typedef enum {
EL_WIDGET_FREE = 0,
EL_WIDGET_WINDOW = 1,
EL_WIDGET_VSTACK = 2,
EL_WIDGET_HSTACK = 3,
EL_WIDGET_ZSTACK = 4,
EL_WIDGET_SCROLL = 5,
EL_WIDGET_LABEL = 6,
EL_WIDGET_BUTTON = 7,
EL_WIDGET_TEXTFIELD = 8,
EL_WIDGET_TEXTAREA = 9,
EL_WIDGET_IMAGE = 10,
} ElWidgetKind;
typedef struct {
ElWidgetKind kind;
/* TODO: add your platform's native widget reference here.
* Examples:
* GtkWidget* widget; // GTK4
* SDL_Rect rect; // SDL2 (no object, just geometry)
* lv_obj_t* obj; // LVGL
* HWND hwnd; // Win32
* void* native; // generic pointer
*/
void* native; /* platform widget reference — replace as needed */
/* Text content (cached for platforms that don't provide a get-text API) */
char* text;
/* Foreground / background color (RGBA, 0.0-1.0) */
float fg_r, fg_g, fg_b, fg_a;
float bg_r, bg_g, bg_b, bg_a;
/* Geometry */
int width; /* 0 = not set */
int height; /* 0 = not set */
int flex; /* 0 = hug content, >0 = expand */
/* Padding (top, right, bottom, left) */
int pad_top, pad_right, pad_bottom, pad_left;
/* Corner radius */
int corner_radius;
/* State */
int disabled; /* 0 = enabled, 1 = disabled */
int hidden; /* 0 = visible, 1 = hidden */
/* Event callbacks — El function name resolved at event time via dlsym */
char* cb_click; /* on_click / on_submit */
char* cb_change; /* on_change */
} ElWidget;
static ElWidget _el_widgets[EL_${PLATFORM_UPPER}_MAX_WIDGETS];
/* ── Slot management ──────────────────────────────────────────────────────── */
static int64_t el_widget_alloc(ElWidgetKind kind, void* native) {
for (int i = 1; i < EL_${PLATFORM_UPPER}_MAX_WIDGETS; i++) {
if (_el_widgets[i].kind == EL_WIDGET_FREE) {
memset(&_el_widgets[i], 0, sizeof(ElWidget));
_el_widgets[i].kind = kind;
_el_widgets[i].native = native;
return (int64_t)i;
}
}
fprintf(stderr, "el_${PLATFORM_LOWER}: widget table full (max %d)\n",
EL_${PLATFORM_UPPER}_MAX_WIDGETS);
return -1;
}
static ElWidget* el_widget_get(int64_t handle) {
if (handle <= 0 || handle >= EL_${PLATFORM_UPPER}_MAX_WIDGETS) return NULL;
if (_el_widgets[handle].kind == EL_WIDGET_FREE) return NULL;
return &_el_widgets[handle];
}
static void el_widget_free(int64_t handle) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
/* TODO: release w->native (toolkit-specific) */
free(w->text);
free(w->cb_click);
free(w->cb_change);
memset(w, 0, sizeof(ElWidget)); /* sets kind = EL_WIDGET_FREE (0) */
}
/* ── Callback dispatcher ─────────────────────────────────────────────────── */
/*
* Invoke an El function by symbol name. The El function must have the
* compiled signature: void fn(int64_t handle, int64_t data)
* where data is a const char* cast to int64_t (el String representation).
*
* On platforms without dlsym (e.g., Windows), replace with:
* GetProcAddress(GetModuleHandle(NULL), fn_name)
* On embedded targets without dynamic linking, maintain a manual symbol table.
*/
typedef void (*ElCb2)(int64_t handle, int64_t data);
static void el_${PLATFORM_LOWER}_invoke_cb(const char* fn_name,
int64_t handle,
const char* data) {
if (!fn_name || !*fn_name) return;
void* sym = dlsym(RTLD_DEFAULT, fn_name);
if (!sym) {
fprintf(stderr, "el_${PLATFORM_LOWER}: callback symbol not found: %s\n", fn_name);
return;
}
ElCb2 fn = (ElCb2)sym;
fn(handle, (int64_t)(uintptr_t)(data ? data : ""));
}
/* ── Lifecycle ────────────────────────────────────────────────────────────── */
/*
* el_${PLATFORM_LOWER}_init — initialize the platform toolkit.
* Must be idempotent (safe to call more than once).
* Called once from __native_init before any widget creation.
*/
void el_${PLATFORM_LOWER}_init(void) {
static int done = 0;
if (done) return;
done = 1;
/* TODO: initialize your platform toolkit here.
* Examples:
* gtk_init(NULL, NULL); // GTK4
* SDL_Init(SDL_INIT_VIDEO); // SDL2
* lv_init(); // LVGL
*/
}
/*
* el_${PLATFORM_LOWER}_run_loop — start the platform event loop.
* On most platforms this NEVER returns. Exceptions: Android (no-op).
* Must be called from the main thread.
*/
void el_${PLATFORM_LOWER}_run_loop(void) {
/* TODO: start the platform event/render loop.
* Examples:
* gtk_main(); // GTK4
* while (1) { SDL_PollEvent(...); render(); SDL_Delay(16); } // SDL2
* while (1) { lv_task_handler(); usleep(5000); } // LVGL
*/
}
/* ── Window ───────────────────────────────────────────────────────────────── */
int64_t el_${PLATFORM_LOWER}_window_create(const char* title, int w, int h,
int mw, int mh) {
/* TODO: create a top-level window.
* title may be NULL — treat as "".
* mw/mh are minimum dimensions (0 = no minimum).
* Return slot handle on success, -1 on failure.
*/
(void)title; (void)w; (void)h; (void)mw; (void)mh;
return -1; /* TODO: implement */
}
void el_${PLATFORM_LOWER}_window_show(int64_t handle) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
/* TODO: make the window visible. */
}
void el_${PLATFORM_LOWER}_window_set_title(int64_t handle, const char* title) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
/* TODO: update the window title. title may be NULL — treat as "". */
(void)title;
}
/* ── Layout containers ────────────────────────────────────────────────────── */
int64_t el_${PLATFORM_LOWER}_vstack_create(int spacing) {
/* TODO: create a vertical linear container with the given spacing (px). */
(void)spacing;
return -1; /* TODO: implement */
}
int64_t el_${PLATFORM_LOWER}_hstack_create(int spacing) {
/* TODO: create a horizontal linear container with the given spacing (px). */
(void)spacing;
return -1; /* TODO: implement */
}
int64_t el_${PLATFORM_LOWER}_zstack_create(void) {
/* TODO: create a z-axis overlay container (children overlap). */
return -1; /* TODO: implement */
}
int64_t el_${PLATFORM_LOWER}_scroll_create(void) {
/* TODO: create a scrollable container (vertical scroll, first child = content). */
return -1; /* TODO: implement */
}
/* ── Leaf widgets ─────────────────────────────────────────────────────────── */
int64_t el_${PLATFORM_LOWER}_label_create(const char* text) {
/* TODO: create a non-editable text label. text may be NULL — treat as "". */
(void)text;
return -1; /* TODO: implement */
}
int64_t el_${PLATFORM_LOWER}_button_create(const char* label) {
/* TODO: create a clickable button with the given label text.
* Wire up the platform event handler so on_click callbacks fire later. */
(void)label;
return -1; /* TODO: implement */
}
int64_t el_${PLATFORM_LOWER}_text_field_create(const char* placeholder) {
/* TODO: create a single-line text input. placeholder may be NULL. */
(void)placeholder;
return -1; /* TODO: implement */
}
int64_t el_${PLATFORM_LOWER}_text_area_create(const char* placeholder) {
/* TODO: create a multi-line text input (scrollable). placeholder may be NULL. */
(void)placeholder;
return -1; /* TODO: implement */
}
int64_t el_${PLATFORM_LOWER}_image_create(const char* path_or_name) {
/* TODO: create an image widget.
* Try path_or_name as a filesystem path first, then as a named resource.
* If neither resolves, create an empty image widget (do not crash). */
(void)path_or_name;
return -1; /* TODO: implement */
}
/* ── Widget property setters ─────────────────────────────────────────────── */
void el_${PLATFORM_LOWER}_widget_set_text(int64_t handle, const char* text) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
/* TODO: update text on label, button, text field, text area, or window title.
* Dispatch on w->kind. text may be NULL — treat as "".
* Cache in w->text if the platform has no get-text API. */
free(w->text);
w->text = strdup(text ? text : "");
}
const char* el_${PLATFORM_LOWER}_widget_get_text(int64_t handle) {
ElWidget* w = el_widget_get(handle);
if (!w) return "";
/* TODO: return the current text of the widget.
* If the platform provides a get-text API, use it.
* Otherwise return w->text (populated by set_text).
* NEVER return NULL — return "" on failure. */
return w->text ? w->text : "";
}
void el_${PLATFORM_LOWER}_widget_set_color(int64_t handle,
float r, float g, float b, float a) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
w->fg_r = r; w->fg_g = g; w->fg_b = b; w->fg_a = a;
/* TODO: apply foreground (text) color to the platform widget. */
}
void el_${PLATFORM_LOWER}_widget_set_bg_color(int64_t handle,
float r, float g, float b, float a) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
w->bg_r = r; w->bg_g = g; w->bg_b = b; w->bg_a = a;
/* TODO: apply background color to the platform widget. */
}
void el_${PLATFORM_LOWER}_widget_set_font(int64_t handle,
const char* family, int size, int bold) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
/* TODO: set font on text-bearing widgets (label, button, text field, text area).
* family may be "system" — use the platform default font in that case.
* Fall back to system font if family is not found. */
(void)family; (void)size; (void)bold;
}
void el_${PLATFORM_LOWER}_widget_set_padding(int64_t handle,
int top, int right,
int bottom, int left) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
w->pad_top = top; w->pad_right = right;
w->pad_bottom = bottom; w->pad_left = left;
/* TODO: apply padding/insets to the platform container or text widget. */
}
void el_${PLATFORM_LOWER}_widget_set_width(int64_t handle, int width) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
w->width = width;
/* TODO: apply a fixed-width constraint to the platform widget. */
}
void el_${PLATFORM_LOWER}_widget_set_height(int64_t handle, int height) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
w->height = height;
/* TODO: apply a fixed-height constraint to the platform widget. */
}
void el_${PLATFORM_LOWER}_widget_set_flex(int64_t handle, int flex) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
w->flex = flex;
/* TODO: set the flex/expand factor.
* flex > 0 → widget expands to fill available space.
* flex == 0 → widget hugs content size.
* Maps to: content hugging priority (AppKit), hexpand/vexpand (GTK4),
* layout_weight (Android), stretch factor (SDL2 manual layout). */
}
void el_${PLATFORM_LOWER}_widget_set_corner_radius(int64_t handle, int radius) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
w->corner_radius = radius;
/* TODO: apply rounded corners (requires GPU layer / backing surface on most platforms). */
}
void el_${PLATFORM_LOWER}_widget_set_disabled(int64_t handle, int disabled) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
w->disabled = disabled;
/* TODO: enable or disable the widget (buttons, text fields). No-op for containers/labels. */
}
void el_${PLATFORM_LOWER}_widget_set_hidden(int64_t handle, int hidden) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
w->hidden = hidden;
/* TODO: show or hide the widget.
* hidden=1 → invisible but still occupies layout space (visibility:hidden semantics).
* For windows: minimize or hide. */
}
/* ── Tree management ─────────────────────────────────────────────────────── */
void el_${PLATFORM_LOWER}_widget_add_child(int64_t parent, int64_t child) {
ElWidget* pw = el_widget_get(parent);
ElWidget* cw = el_widget_get(child);
if (!pw || !cw) return;
/* TODO: attach child to parent. Dispatch on pw->kind:
* EL_WIDGET_WINDOW → add to root content view/container
* EL_WIDGET_VSTACK → add as vertical child
* EL_WIDGET_HSTACK → add as horizontal child
* EL_WIDGET_ZSTACK → add as overlapping subview
* EL_WIDGET_SCROLL → set as the scrollable content view (first child only)
* default → add as plain subview
* Do NOT add a window widget as a child. */
(void)pw; (void)cw;
}
void el_${PLATFORM_LOWER}_widget_remove_child(int64_t parent, int64_t child) {
ElWidget* pw = el_widget_get(parent);
ElWidget* cw = el_widget_get(child);
if (!pw || !cw) return;
/* TODO: detach child from parent. The child slot remains allocated (not destroyed). */
(void)pw; (void)cw;
}
void el_${PLATFORM_LOWER}_widget_destroy(int64_t handle) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
/* TODO: remove the widget from its parent/superview.
* For windows: close the window.
* Free any platform delegate/target objects stored in side tables.
* Then free the slot: */
el_widget_free(handle);
}
/* ── Event registration ───────────────────────────────────────────────────── */
void el_${PLATFORM_LOWER}_widget_on_click(int64_t handle, const char* fn_name) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
free(w->cb_click);
w->cb_click = (fn_name && *fn_name) ? strdup(fn_name) : NULL;
}
void el_${PLATFORM_LOWER}_widget_on_change(int64_t handle, const char* fn_name) {
ElWidget* w = el_widget_get(handle);
if (!w) return;
free(w->cb_change);
w->cb_change = (fn_name && *fn_name) ? strdup(fn_name) : NULL;
}
void el_${PLATFORM_LOWER}_widget_on_submit(int64_t handle, const char* fn_name) {
/* Submit (Enter key in text field) reuses the cb_click slot, matching AppKit convention. */
el_${PLATFORM_LOWER}_widget_on_click(handle, fn_name);
}
/* ── Example event handler (adapt to your platform's callback mechanism) ─── */
/*
* When a button is clicked in your platform event loop, call:
*
* ElWidget* w = el_widget_get(slot_index);
* if (w && w->cb_click) {
* el_${PLATFORM_LOWER}_invoke_cb(w->cb_click, slot_index, "");
* }
*
* When a text field changes:
*
* ElWidget* w = el_widget_get(slot_index);
* if (w && w->cb_change) {
* el_${PLATFORM_LOWER}_invoke_cb(w->cb_change, slot_index, current_text);
* }
*/
#endif /* EL_TARGET_${PLATFORM_UPPER} */
BRIDGE_FILE
chmod 644 "${OUTPUT_FILE}"
# ── Print next-steps instructions ────────────────────────────────────────────
UPPER="${PLATFORM_UPPER}"
LOWER="${PLATFORM_LOWER}"
cat << INSTRUCTIONS
Created: el_${LOWER}.c
Next steps:
────────────────────────────────────────────────────────────────────────────
1. Add to el_native_target.h (inside a new #ifdef EL_TARGET_${UPPER} block):
#ifdef EL_TARGET_${UPPER}
void __native_init(void);
void __native_run_loop(void);
el_val_t __window_create(el_val_t title, el_val_t width, el_val_t height,
el_val_t min_width, el_val_t min_height);
void __window_show(el_val_t handle);
void __window_set_title(el_val_t handle, el_val_t title);
el_val_t __vstack_create(el_val_t spacing);
el_val_t __hstack_create(el_val_t spacing);
el_val_t __zstack_create(void);
el_val_t __scroll_create(void);
el_val_t __label_create(el_val_t text);
el_val_t __button_create(el_val_t label);
el_val_t __text_field_create(el_val_t placeholder);
el_val_t __text_area_create(el_val_t placeholder);
el_val_t __image_create(el_val_t path_or_name);
void __widget_set_text(el_val_t handle, el_val_t text);
el_val_t __widget_get_text(el_val_t handle);
void __widget_set_color(el_val_t handle, el_val_t r, el_val_t g,
el_val_t b, el_val_t a);
void __widget_set_bg_color(el_val_t handle, el_val_t r, el_val_t g,
el_val_t b, el_val_t a);
void __widget_set_font(el_val_t handle, el_val_t family,
el_val_t size, el_val_t bold);
void __widget_set_padding(el_val_t handle, el_val_t top, el_val_t right,
el_val_t bottom, el_val_t left);
void __widget_set_width(el_val_t handle, el_val_t width);
void __widget_set_height(el_val_t handle, el_val_t height);
void __widget_set_flex(el_val_t handle, el_val_t flex);
void __widget_set_corner_radius(el_val_t handle, el_val_t radius);
void __widget_set_disabled(el_val_t handle, el_val_t disabled);
void __widget_set_hidden(el_val_t handle, el_val_t hidden);
void __widget_add_child(el_val_t parent, el_val_t child);
void __widget_remove_child(el_val_t parent, el_val_t child);
void __widget_destroy(el_val_t handle);
void __widget_on_click(el_val_t handle, el_val_t fn_name);
void __widget_on_change(el_val_t handle, el_val_t fn_name);
void __widget_on_submit(el_val_t handle, el_val_t fn_name);
el_val_t __manifest_read(el_val_t path);
#endif /* EL_TARGET_${UPPER} */
────────────────────────────────────────────────────────────────────────────
2. Add to el_seed.c (copy the EL_TARGET_MACOS block as a template and
substitute el_appkit_ → el_${LOWER}_):
#ifdef EL_TARGET_${UPPER}
/* Forward declarations — implemented in el_${LOWER}.c */
extern void el_${LOWER}_init(void);
extern void el_${LOWER}_run_loop(void);
extern int64_t el_${LOWER}_window_create(const char* title, int w, int h, int mw, int mh);
extern void el_${LOWER}_window_show(int64_t handle);
extern void el_${LOWER}_window_set_title(int64_t handle, const char* title);
extern int64_t el_${LOWER}_vstack_create(int spacing);
extern int64_t el_${LOWER}_hstack_create(int spacing);
extern int64_t el_${LOWER}_zstack_create(void);
extern int64_t el_${LOWER}_scroll_create(void);
extern int64_t el_${LOWER}_label_create(const char* text);
extern int64_t el_${LOWER}_button_create(const char* label);
extern int64_t el_${LOWER}_text_field_create(const char* placeholder);
extern int64_t el_${LOWER}_text_area_create(const char* placeholder);
extern int64_t el_${LOWER}_image_create(const char* path_or_name);
extern void el_${LOWER}_widget_set_text(int64_t handle, const char* text);
extern const char* el_${LOWER}_widget_get_text(int64_t handle);
extern void el_${LOWER}_widget_set_color(int64_t h, float r, float g, float b, float a);
extern void el_${LOWER}_widget_set_bg_color(int64_t h, float r, float g, float b, float a);
extern void el_${LOWER}_widget_set_font(int64_t h, const char* family, int size, int bold);
extern void el_${LOWER}_widget_set_padding(int64_t h, int top, int right, int bottom, int left);
extern void el_${LOWER}_widget_set_width(int64_t h, int width);
extern void el_${LOWER}_widget_set_height(int64_t h, int height);
extern void el_${LOWER}_widget_set_flex(int64_t h, int flex);
extern void el_${LOWER}_widget_set_corner_radius(int64_t h, int radius);
extern void el_${LOWER}_widget_set_disabled(int64_t h, int disabled);
extern void el_${LOWER}_widget_set_hidden(int64_t h, int hidden);
extern void el_${LOWER}_widget_add_child(int64_t parent, int64_t child);
extern void el_${LOWER}_widget_remove_child(int64_t parent, int64_t child);
extern void el_${LOWER}_widget_destroy(int64_t handle);
extern void el_${LOWER}_widget_on_click(int64_t h, const char* fn_name);
extern void el_${LOWER}_widget_on_change(int64_t h, const char* fn_name);
extern void el_${LOWER}_widget_on_submit(int64_t h, const char* fn_name);
void __native_init(void) { el_${LOWER}_init(); }
void __native_run_loop(void) { el_${LOWER}_run_loop(); }
el_val_t __window_create(el_val_t title, el_val_t width, el_val_t height,
el_val_t min_width, el_val_t min_height) {
return (el_val_t)el_${LOWER}_window_create(
EL_CSTR(title),
(int)(int64_t)width, (int)(int64_t)height,
(int)(int64_t)min_width, (int)(int64_t)min_height);
}
void __window_show(el_val_t h) { el_${LOWER}_window_show((int64_t)h); }
void __window_set_title(el_val_t h, el_val_t t) { el_${LOWER}_window_set_title((int64_t)h, EL_CSTR(t)); }
el_val_t __vstack_create(el_val_t s) { return (el_val_t)el_${LOWER}_vstack_create((int)(int64_t)s); }
el_val_t __hstack_create(el_val_t s) { return (el_val_t)el_${LOWER}_hstack_create((int)(int64_t)s); }
el_val_t __zstack_create(void) { return (el_val_t)el_${LOWER}_zstack_create(); }
el_val_t __scroll_create(void) { return (el_val_t)el_${LOWER}_scroll_create(); }
el_val_t __label_create(el_val_t t) { return (el_val_t)el_${LOWER}_label_create(EL_CSTR(t)); }
el_val_t __button_create(el_val_t l) { return (el_val_t)el_${LOWER}_button_create(EL_CSTR(l)); }
el_val_t __text_field_create(el_val_t p) { return (el_val_t)el_${LOWER}_text_field_create(EL_CSTR(p)); }
el_val_t __text_area_create(el_val_t p) { return (el_val_t)el_${LOWER}_text_area_create(EL_CSTR(p)); }
el_val_t __image_create(el_val_t p) { return (el_val_t)el_${LOWER}_image_create(EL_CSTR(p)); }
void __widget_set_text(el_val_t h, el_val_t t) { el_${LOWER}_widget_set_text((int64_t)h, EL_CSTR(t)); }
el_val_t __widget_get_text(el_val_t h) {
const char* s = el_${LOWER}_widget_get_text((int64_t)h);
return EL_STR(s ? s : "");
}
void __widget_set_color(el_val_t h, el_val_t r, el_val_t g, el_val_t b, el_val_t a) {
el_${LOWER}_widget_set_color((int64_t)h,
(float)el_to_float(r), (float)el_to_float(g),
(float)el_to_float(b), (float)el_to_float(a));
}
void __widget_set_bg_color(el_val_t h, el_val_t r, el_val_t g, el_val_t b, el_val_t a) {
el_${LOWER}_widget_set_bg_color((int64_t)h,
(float)el_to_float(r), (float)el_to_float(g),
(float)el_to_float(b), (float)el_to_float(a));
}
void __widget_set_font(el_val_t h, el_val_t family, el_val_t size, el_val_t bold) {
el_${LOWER}_widget_set_font((int64_t)h, EL_CSTR(family),
(int)(int64_t)size, (int)(int64_t)bold);
}
void __widget_set_padding(el_val_t h, el_val_t top, el_val_t right,
el_val_t bottom, el_val_t left) {
el_${LOWER}_widget_set_padding((int64_t)h,
(int)(int64_t)top, (int)(int64_t)right,
(int)(int64_t)bottom, (int)(int64_t)left);
}
void __widget_set_width(el_val_t h, el_val_t w) { el_${LOWER}_widget_set_width((int64_t)h, (int)(int64_t)w); }
void __widget_set_height(el_val_t h, el_val_t ht) { el_${LOWER}_widget_set_height((int64_t)h, (int)(int64_t)ht); }
void __widget_set_flex(el_val_t h, el_val_t f) { el_${LOWER}_widget_set_flex((int64_t)h, (int)(int64_t)f); }
void __widget_set_corner_radius(el_val_t h, el_val_t r) { el_${LOWER}_widget_set_corner_radius((int64_t)h, (int)(int64_t)r); }
void __widget_set_disabled(el_val_t h, el_val_t d) { el_${LOWER}_widget_set_disabled((int64_t)h, (int)(int64_t)d); }
void __widget_set_hidden(el_val_t h, el_val_t hid) { el_${LOWER}_widget_set_hidden((int64_t)h, (int)(int64_t)hid); }
void __widget_add_child(el_val_t p, el_val_t c) { el_${LOWER}_widget_add_child((int64_t)p, (int64_t)c); }
void __widget_remove_child(el_val_t p, el_val_t c) { el_${LOWER}_widget_remove_child((int64_t)p, (int64_t)c); }
void __widget_destroy(el_val_t h) { el_${LOWER}_widget_destroy((int64_t)h); }
void __widget_on_click(el_val_t h, el_val_t fn) { el_${LOWER}_widget_on_click((int64_t)h, EL_CSTR(fn)); }
void __widget_on_change(el_val_t h, el_val_t fn) { el_${LOWER}_widget_on_change((int64_t)h, EL_CSTR(fn)); }
void __widget_on_submit(el_val_t h, el_val_t fn) { el_${LOWER}_widget_on_submit((int64_t)h, EL_CSTR(fn)); }
#endif /* EL_TARGET_${UPPER} */
────────────────────────────────────────────────────────────────────────────
3. Implement each TODO in el_${LOWER}.c.
4. Compile:
cc -DEL_TARGET_${UPPER} -Wall \\
\$(pkg-config --cflags <your-toolkit> 2>/dev/null) \\
-c el_${LOWER}.c -o el_${LOWER}.o
5. Link:
cc el_${LOWER}.o el_seed.o el_runtime.o -o myapp \\
\$(pkg-config --libs <your-toolkit> 2>/dev/null) \\
-ldl -lpthread
See PLATFORM_BRIDGE_SPEC.md for the full bridge contract and gotchas.
INSTRUCTIONS