Desktop plugins
On the desktop a plugin is a shared library — a .dll or .so — that the host loads when it
starts. There is nothing to generate and the host is not rebuilt: you build the library with any
compiler and drop the file into a folder. It is also the fastest way to try a native capability.
The app's side is the same as for any plugin: a Service,
checked with Service.supported(name).
A desktop plugin provides services and synchronous methods. It does not draw: a native view on the desktop needs a host built with it.
The app's side
const supported = Service.supported('acme.dial')
const label = UIText(supported ? 'Dial: —' : 'Dial not available on this device')
UIScreen(label).style({ p: 16, pt: 'safe-top' }).open()
if (supported) {
const dial = Service('acme.dial', { rate: 60 })
dial.on('reading', r => { label.text = `Dial: ${r.angle.toFixed(0)}°` })
dial.call('start').catch(e => { label.text = `Dial failed: ${e.message}` })
}Service(…) never throws: the session opens on the first call(), and that is what rejects on a
host without the service. Register listeners before the call that starts the events.
The plugin, in C
One header, lecodes_plugin.h, and one exported function. The plugin never links against the host:
only strings and function pointers cross the boundary.
#include <stdlib.h>
#include <string.h>
#include "lecodes_plugin.h"
static const LecodesHostApi* host;
typedef struct { int32_t id; /* your state, threads, handles */ } Session;
static void* dial_open(void* ctx, int32_t session_id, const char* params_json) {
Session* s = calloc(1, sizeof(Session));
s->id = session_id;
return s; /* NULL refuses the session */
}
static void dial_call(void* ctx, void* session, int32_t session_id, uint64_t call_id,
const char* method, const char* args_json) {
if (strcmp(method, "read") == 0) {
host->service_resolve(session_id, call_id, "{\"angle\":12.5,\"button\":false}");
} else if (strcmp(method, "start") == 0) {
/* start a worker thread; it emits from there */
host->service_resolve(session_id, call_id, NULL); /* NULL = undefined */
} else {
host->service_reject(session_id, call_id, "unknown method");
}
}
static void dial_close(void* ctx, void* session, int32_t session_id) {
/* stop AND JOIN every thread this session started, then free */
free(session);
}
static const LecodesServiceVTable VT = { dial_open, dial_call, dial_close };
LECODES_PLUGIN_EXPORT int32_t lecodes_plugin_register(const LecodesHostApi* api) {
if (api->abi_version != LECODES_PLUGIN_ABI_VERSION) return 1; /* refuse an unknown host */
host = api;
return host->register_service("acme.dial", &VT, NULL);
}An event is sent with the session's id, from any thread:
host->service_emit(s->id, "reading", "{\"angle\":31.0,\"button\":true}");Build it as any shared library, for example cl /LD acme_dial.c /I <folder of the header> from a
Visual Studio prompt.
The rules that keep it safe
- Settle every call exactly once, with
service_resolve(a JSON value, orNULLforundefined) orservice_reject(a message, which the app'sErrorcarries). A call that is never settled leaves the app's promise waiting. service_resolve,service_rejectandservice_emitmay be called from any thread. Everything else —open,call,close, the registration — runs on the app's thread.openis cheap. No I/O, no port, no dialog: that belongs to the first call that needs it. The app opens and closes sessions freely, and a reload duringlecodes devdoes too.closestops and joins. After it returns, the memory a late event would touch is gone.- A string the host passes is valid during the call only: copy what you keep.
args_jsonis a JSON array of the call's arguments. JSON has no bytes: aUint8Arrayarrives as an array of numbers.
The same plugin in Rust
The interface is plain C, so a cdylib crate works as it is. Two rules on top of the ones above:
- Never let a panic cross the boundary. Wrap the body of every
extern "C"function incatch_unwindand reject the call instead. - Keep a
CStringalive until the host's function returns.CString::new(x).unwrap().as_ptr()as a temporary is a dangling pointer.
// Cargo.toml: [lib] crate-type = ["cdylib"]
unsafe extern "C" fn call(_ctx: *mut c_void, session: *mut c_void, id: i32, call_id: u64,
method: *const c_char, _args: *const c_char) {
let _ = catch_unwind(|| {
let _s = &mut *(session as *mut Session);
match CStr::from_ptr(method).to_string_lossy().as_ref() {
"read" => resolve(id, call_id, &serde_json::json!({ "angle": 12.5, "button": false })),
_ => reject(id, call_id, "unknown method"),
}
}).map_err(|_| reject(id, call_id, "plugin panicked"));
}
fn resolve(id: i32, call_id: u64, v: &serde_json::Value) {
let json = CString::new(v.to_string()).unwrap(); // alive until the call returns
unsafe { ((*HOST).service_resolve)(id, call_id, json.as_ptr()) }
}One value every frame: a synchronous method
When the app needs a number every frame and a promise is too much, register a method at a dotted path of your own. It runs on the app's thread, at once:
static void dial_angle(void* ctx, LecodesMethodCall* call, const char* args_json) {
host->method_return(call, "12.5");
}
host->register_method("acme.dialAngle", dial_angle, NULL); /* inside lecodes_plugin_register */declare const acme: { dialAngle(): string } // the global the host installed
const angle = JSON.parse(acme.dialAngle()) // the result arrives as a stringThis is an escape hatch. The result is a string the app parses, the arguments are scalars only, and a slow method holds the frame. Anything with state, events or I/O belongs in a service.
Where the host looks for plugins
my-app/
app.json
plugins/acme_dial.dll # or .so
main.tslecodes desktop run, lecodes render --desktop and lecodes test --desktop (and their --sim
forms) hand the project's plugins/ folder to the host. The host also looks in plugins/ next to
the bundle and next to its own executable. CREATOR_PLUGIN_DIRS, a list of folders in the form of
PATH, adds more.
Ship it with the app
lecodes app build desktop copies every library of plugins/ into the built folder, so the app
carries its plugins.
A plugin kept in a repository of its own is named in app.json — the key is its manifest's id —
and its manifest points at the built library for each machine:
{ "plugins": { "acme-dial": "github:acme/lecodes-dial@v1.2.0" } }{
"id": "acme-dial",
"version": "1.2.0",
"desktop": { "library": { "win32-x64": "dist/acme_dial.dll", "linux-x64": "dist/libacme_dial.so" } },
"ios": null,
"android": null
}A machine that has no entry skips the plugin. A file that is named and missing fails the build; a run warns and goes on without it.
This desktop manifest is its own kind: the manifest of a plugin for iOS, Android and the web has
no desktop branch, and lecodes plugin gen refuses one.
Check that it works
Run the app with its logs and read the loader's lines:
lecodes render --sim --script tests/dial.flow.json --logs[svc] service registered: "acme.dial"
[plugin:acme_dial.dll] loaded (C:\…\my-app\plugins\acme_dial.dll)In this order:
Service.supported('acme.dial')is true. If not, the library did not register: look for a[plugin:…] skippedline (it failed to load, usually a missing dependency) ornot a lecodes plugin(the exported function is missing or misspelt).- A call goes there and back; a rejection arrives as a rejected promise; an unknown method rejects.
- Events reach the app from the plugin's own thread.
- Close and reopen the session: the next call must open a fresh one.
- The app still runs with the folder empty — that is what the web and a headless render see.
Keep it as a flow test: log a line per step in the app and expect it with expect.log
(Render and test).
Traps
- An old host has no loader and ignores
plugins/without a word.lecodes desktopprints the host in use;lecodes desktop updatemoves it forward. - Names collide once. The first registration of a name wins and the second is refused with a log line. Prefix with your vendor.
- A version mismatch skips the plugin, it does not crash: read the log before you doubt your code.
- The host without a window runs frames as fast as it can, so a worker that paces itself by the clock may send nothing before a short
--simrun ends. Give the flow enough frames, or check timing with--desktop. - A desktop-only plugin in
app.jsonstopslecodes app syncfor iOS and Android: its manifest says"ios": null, which the shell's sync refuses. - macOS loads
.dylibplugins from the same folders, butlecodes app build desktopthere puts none into the.app.
Next
- Service — the app-side API in full
- Write a native plugin — the same capability on iOS, Android and the web