Expand description
§Oxide SDK
Guest-side SDK for building WebAssembly applications that run inside the
Oxide browser. This crate provides
safe Rust wrappers around the raw host-imported functions exposed by the
"oxide" wasm import module.
The desktop shell uses GPUI (Zed’s GPU-accelerated UI framework) to render guest draw commands. The SDK exposes a drawing API that maps directly onto GPUI primitives — filled quads, GPU-shaped text, vector paths, and image textures — so your canvas output gets full GPU acceleration without you having to link GPUI itself.
§Quick Start
[lib]
crate-type = ["cdylib"]
[dependencies]
oxide-sdk = "0.4"§Static app (one-shot render)
use oxide_sdk::*;
#[no_mangle]
pub extern "C" fn start_app() {
log("Hello from Oxide!");
canvas_clear(30, 30, 46, 255);
canvas_text(20.0, 40.0, 28.0, 255, 255, 255, 255, "Welcome to Oxide");
}§Interactive app (frame loop)
use oxide_sdk::*;
#[no_mangle]
pub extern "C" fn start_app() {
log("Interactive app started");
}
#[no_mangle]
pub extern "C" fn on_frame(_dt_ms: u32) {
canvas_clear(30, 30, 46, 255);
let (mx, my) = mouse_position();
canvas_circle(mx, my, 20.0, 255, 100, 100, 255);
if ui_button(1, 20.0, 20.0, 100.0, 30.0, "Click me!") {
log("Button was clicked!");
}
}§High-level drawing API
The draw module provides GPUI-inspired ergonomic types for less
boilerplate:
use oxide_sdk::draw::*;
#[no_mangle]
pub extern "C" fn start_app() {
let c = Canvas::new();
c.clear(Color::hex(0x1e1e2e));
c.fill_rect(Rect::new(10.0, 10.0, 200.0, 100.0), Color::rgb(80, 120, 200));
c.fill_circle(Point2D::new(300.0, 200.0), 50.0, Color::RED);
c.text("Hello!", Point2D::new(20.0, 30.0), 24.0, Color::WHITE);
}Build with cargo build --target wasm32-unknown-unknown --release.
§API Categories
§Guest Module Contract
Every .wasm module loaded by Oxide must:
- Export
start_app—extern "C" fn()entry point, called once on load. - Optionally export
on_frame—extern "C" fn(dt_ms: u32)for interactive apps with a render loop (called every frame, fuel replenished). - Optionally export
on_timer—extern "C" fn(callback_id: u32)to receive callbacks fromset_timeout,set_interval, andrequest_animation_frame. - Compile as
cdylib—crate-type = ["cdylib"]inCargo.toml. - Target
wasm32-unknown-unknown— no WASI, pure capability-based I/O.
§Full API Documentation
See https://docs.oxide.foundation/oxide_sdk/ for the complete API reference, or browse the individual function documentation below.
Modules§
- draw
- Higher-level drawing API inspired by GPUI’s rendering model.
- gpu_
usage - GPU buffer usage flags (matches WebGPU
GPUBufferUsage). - proto
- Lightweight protobuf wire-format encoder/decoder.
Structs§
- Fetch
Response - Response from an HTTP fetch call.
- RtcData
Channel Info - Information about a newly opened remote data channel.
- RtcMessage
- Received data channel message.
- RtcTrack
Info - Information about a remote media track received from a peer.
- Uploaded
File - File returned from the native file picker.
- WsMessage
- A received WebSocket message.
Enums§
- Audio
Format - Detected or hinted audio container (host codes: 0 unknown, 1 WAV, 2 MP3, 3 Ogg, 4 FLAC).
- Fetch
Chunk - Result of a non-blocking
fetch_recvpoll. - Video
Format - Container or hint for
video_load_with_format(host codes: 0 unknown, 1 MP4, 2 WebM, 3 AV1).
Constants§
- FETCH_
ABORTED - Request was aborted by the guest.
- FETCH_
DONE - Body fully delivered (the queue may still have trailing chunks to drain).
- FETCH_
ERROR - Request failed. Call
fetch_errorfor the message. - FETCH_
PENDING - Request dispatched; waiting for response headers.
- FETCH_
STREAMING - Headers received; body chunks may still be arriving.
- GRADIENT_
LINEAR - Gradient type constants.
- GRADIENT_
RADIAL - KEY_0
- KEY_1
- KEY_2
- KEY_3
- KEY_4
- KEY_5
- KEY_6
- KEY_7
- KEY_8
- KEY_9
- KEY_A
- KEY_B
- KEY_
BACKSPACE - KEY_C
- KEY_D
- KEY_
DELETE - KEY_
DOWN - KEY_E
- KEY_END
- KEY_
ENTER - KEY_
ESCAPE - KEY_F
- KEY_G
- KEY_H
- KEY_
HOME - KEY_I
- KEY_J
- KEY_K
- KEY_L
- KEY_
LEFT - KEY_M
- KEY_N
- KEY_O
- KEY_P
- KEY_
PAGE_ DOWN - KEY_
PAGE_ UP - KEY_Q
- KEY_R
- KEY_
RIGHT - KEY_S
- KEY_
SPACE - KEY_T
- KEY_TAB
- KEY_U
- KEY_UP
- KEY_V
- KEY_W
- KEY_X
- KEY_Y
- KEY_Z
- RTC_
STATE_ CLOSED - Peer connection has been closed.
- RTC_
STATE_ CONNECTED - Peer connection is established.
- RTC_
STATE_ CONNECTING - Peer is attempting to connect.
- RTC_
STATE_ DISCONNECTED - Transport was temporarily interrupted.
- RTC_
STATE_ FAILED - Connection attempt failed.
- RTC_
STATE_ NEW - Connection state returned by
rtc_connection_state. - RTC_
TRACK_ AUDIO - Track kind: audio.
- RTC_
TRACK_ VIDEO - Track kind: video.
- WS_
CLOSED - WebSocket ready-state: connection is closed.
- WS_
CLOSING - WebSocket ready-state: close handshake in progress.
- WS_
CONNECTING - WebSocket ready-state: connection is being established.
- WS_OPEN
- WebSocket ready-state: connection is open and ready.
Functions§
- alt_
held - Returns
trueif Alt is held. - audio_
channel_ play - Play audio on a specific channel. Multiple channels play simultaneously.
Channel 0 is the default used by
audio_play. Use channels 1+ for layered sound effects, background music, etc. - audio_
channel_ play_ with_ format - Like
audio_channel_playwith an optionalAudioFormathint. - audio_
channel_ set_ volume - Set volume for a specific channel (0.0 silent, 1.0 normal, up to 2.0 boost).
- audio_
channel_ stop - Stop playback on a specific channel.
- audio_
detect_ format - Sniff the container/codec from raw bytes (magic bytes / MP3 sync). Does not decode audio.
- audio_
duration - Get the total duration of the currently loaded track in milliseconds. Returns 0 if unknown or nothing is loaded.
- audio_
get_ volume - Get the current audio volume.
- audio_
is_ playing - Returns
trueif audio is currently playing (not paused and not empty). - audio_
last_ url_ content_ type Content-Typeheader from the last successfulaudio_play_urlresponse (may be empty).- audio_
pause - Pause audio playback.
- audio_
play - Play audio from encoded bytes (WAV, MP3, OGG, FLAC). The host decodes and plays the audio. Returns 0 on success, negative on error.
- audio_
play_ url - Fetch audio from a URL and play it.
The host sends an
Acceptheader listing supported codecs, records the responseContent-Type, and rejects obvious HTML/JSON error bodies when no audio signature is found (-4). Returns 0 on success, negative on error. - audio_
play_ with_ format - Play with an optional format hint (
AudioFormat::Unknown= same asaudio_play). If the hint disagrees with what the host sniffs from the bytes, the host logs a warning but still decodes. - audio_
position - Get the current playback position in milliseconds.
- audio_
resume - Resume paused audio playback.
- audio_
seek - Seek to a position in milliseconds. Returns 0 on success, negative on error.
- audio_
set_ loop - Enable or disable looping on the default channel.
When enabled, subsequent
audio_playcalls will loop indefinitely. - audio_
set_ volume - Set audio volume. 1.0 is normal, 0.0 is silent, up to 2.0 for boost.
- audio_
stop - Stop audio playback and clear the queue.
- base64_
decode - Decode a base64-encoded string back to bytes.
- base64_
encode - Base64-encode arbitrary bytes.
- camera_
capture_ frame - Captures one RGBA8 frame into
out. Returns the number of bytes written (0if the camera is not open or capture failed). Querycamera_frame_dimensionsafter a successful write. - camera_
close - Stops the camera stream opened by
camera_open. - camera_
frame_ dimensions - Width and height in pixels of the last
camera_capture_framebuffer. - camera_
open - Opens the default camera after a host permission dialog.
- cancel_
animation_ frame - Cancel a pending animation frame request.
- canvas_
arc - Draw a circular arc stroke from
start_angletoend_angle(in radians, clockwise from +X). - canvas_
bezier - Draw a cubic Bézier curve stroke from
(x1,y1)to(x2,y2)with two control points. - canvas_
circle - Draw a filled circle.
- canvas_
clear - Clear the canvas with a solid RGBA color.
- canvas_
clip - Intersect the current clipping region with an axis-aligned rectangle. Coordinates are in the current (possibly transformed) canvas space.
- canvas_
dimensions - Returns
(width, height)of the canvas in pixels. - canvas_
gradient - Draw a gradient-filled rectangle.
- canvas_
image - Draw an image on the canvas from encoded image bytes (PNG, JPEG, GIF, WebP). The browser decodes the image and renders it at the given rectangle.
- canvas_
line - Draw a line between two points with RGBA color.
- canvas_
opacity - Set the layer opacity for subsequent draw commands (0.0 = transparent, 1.0 = opaque).
Multiplied with any parent opacity set via nested
canvas_save/canvas_opacity. - canvas_
rect - Draw a filled rectangle.
- canvas_
restore - Pop and restore the most recently saved canvas state.
- canvas_
rounded_ rect - Draw a filled rounded rectangle with uniform corner radius.
- canvas_
save - Push the current canvas state (transform, clip, opacity) onto an internal stack.
Use with
canvas_restoreto scope transformations and effects. - canvas_
text - Draw text on the canvas with RGBA color.
- canvas_
transform - Apply a 2D affine transformation to subsequent draw commands.
- clear_
hyperlinks - Remove all previously registered hyperlinks.
- clear_
timer - Cancel a timer previously created with
set_timeoutorset_interval. - clipboard_
read - Read text from the system clipboard.
- clipboard_
write - Copy text to the system clipboard.
- ctrl_
held - Returns
trueif Ctrl (or Cmd on macOS) is held. - error
- Print an error to the browser console.
- fetch
- Perform an HTTP request. Returns the status code and response body.
- fetch_
abort - Abort an in-flight request. Returns
trueif the handle was known. - fetch_
begin - Dispatch an HTTP request that streams its response back to the guest.
- fetch_
begin_ get - Convenience wrapper for GET.
- fetch_
delete - HTTP DELETE.
- fetch_
error - Retrieve the error message for a failed request, if any.
- fetch_
get - HTTP GET request.
- fetch_
post - HTTP POST with raw bytes.
- fetch_
post_ proto - HTTP POST with protobuf body (sets
Content-Type: application/protobuf). - fetch_
put - HTTP PUT with raw bytes.
- fetch_
recv - Poll the next body chunk as an owned
Vec<u8>. - fetch_
recv_ into - Poll the next body chunk into a caller-provided scratch buffer.
- fetch_
remove - Free host-side resources for a completed or aborted request.
- fetch_
state - Current lifecycle state of a streaming request. See the
FETCH_*constants. - fetch_
status - HTTP status code for
handle, or0until the response headers arrive. - get_
location - Get the device’s mock geolocation as a
"lat,lon"string. - get_
state - Retrieve the opaque state bytes attached to the current history entry.
Returns
Noneif no state has been set. - get_url
- Get the URL of the currently loaded page.
- gpu_
create_ buffer - Create a GPU buffer of
sizebytes. Returns a handle (0 = failure). - gpu_
create_ compute_ pipeline - Create a compute pipeline from a shader. Returns a handle (0 = failure).
- gpu_
create_ pipeline - Create a render pipeline from a shader. Returns a handle (0 = failure).
- gpu_
create_ shader - Compile a WGSL shader module. Returns a handle (0 = failure).
- gpu_
create_ texture - Create a 2D RGBA8 texture. Returns a handle (0 = failure).
- gpu_
destroy_ buffer - Destroy a GPU buffer.
- gpu_
destroy_ texture - Destroy a GPU texture.
- gpu_
dispatch_ compute - Submit a compute dispatch with the given workgroup counts.
- gpu_
draw - Submit a render pass: draw
vertex_countvertices withinstance_countinstances. - gpu_
write_ buffer - Write data to a GPU buffer at the given byte offset.
- hash_
sha256 - Compute the SHA-256 hash of the given data. Returns 32 bytes.
- hash_
sha256_ hex - Return SHA-256 hash as a lowercase hex string.
- history_
back - Navigate backward in history. Returns
trueif a navigation was queued. - history_
forward - Navigate forward in history. Returns
trueif a navigation was queued. - history_
length - Return the total number of entries in the history stack.
- key_
down - Returns
trueif the given key is currently held down. SeeKEY_*constants for key codes. - key_
pressed - Returns
trueif the given key was pressed this frame. - kv_
store_ delete - Delete a key from the persistent KV store. Returns
trueon success. - kv_
store_ get - Retrieve a value from the persistent KV store.
Returns
Noneif the key does not exist. - kv_
store_ get_ str - Convenience wrapper: retrieve a UTF-8 string value.
- kv_
store_ set - Store a key-value pair in the persistent on-disk KV store.
Returns
trueon success. - kv_
store_ set_ str - Convenience wrapper: store a UTF-8 string value.
- load_
module - Fetch and execute another
.wasmmodule from a URL. The loaded module shares the same canvas, console, and storage context. Returns 0 on success, negative error code on failure. - log
- Print a message to the browser console (log level).
- media_
pipeline_ stats - Host-side pipeline counters: total camera frames captured (high 32 bits) and current microphone ring depth in samples (low 32 bits).
- microphone_
close - microphone_
open - Starts microphone capture (mono
f32ring buffer) after a host permission dialog. - microphone_
read_ samples - Dequeues up to
out.len()monof32samples from the microphone ring buffer. Returns how many samples were written. - microphone_
sample_ rate - Sample rate of the opened input stream in Hz (
0if the microphone is not open). - midi_
close - Close a MIDI input or output handle and free host-side resources.
- midi_
input_ count - Number of available MIDI input ports (physical and virtual).
- midi_
input_ name - Name of the MIDI input port at
index. - midi_
open_ input - Open a MIDI input port by index and start receiving messages.
- midi_
open_ output - Open a MIDI output port by index for sending messages.
- midi_
output_ count - Number of available MIDI output ports.
- midi_
output_ name - Name of the MIDI output port at
index. - midi_
recv - Poll for the next queued MIDI message on an input
handle. - midi_
send - Send raw MIDI bytes on an output
handle. - modifiers
- Returns modifier key state as a bitmask: bit 0 = Shift, bit 1 = Ctrl, bit 2 = Alt.
- mouse_
button_ clicked - Returns
trueif the given mouse button was clicked this frame. - mouse_
button_ down - Returns
trueif the given mouse button is currently held down. Button 0 = primary (left), 1 = secondary (right), 2 = middle. - mouse_
position - Get the mouse position in canvas-local coordinates.
- navigate
- Navigate to a new URL. The URL can be absolute or relative to the current
page. Navigation happens asynchronously after the current
start_appreturns. Returns 0 on success, negative on invalid URL. - notify
- Send a notification to the user (rendered in the browser console).
- push_
state - Push a new entry onto the browser’s history stack without triggering a
module reload. This is analogous to
history.pushState()in web browsers. - random_
f64 - Get a random f64 in [0, 1).
- random_
u64 - Get a random u64 from the host.
- register_
hyperlink - Register a rectangular region on the canvas as a clickable hyperlink.
- replace_
state - Replace the current history entry (no new entry is pushed).
Analogous to
history.replaceState(). - request_
animation_ frame - Schedule a callback for the next animation frame (vsync-aligned repaint).
- rtc_
add_ ice_ candidate - Add a trickled ICE candidate (JSON string from the remote peer).
- rtc_
add_ track - Attach a media track (audio or video) to a peer connection.
- rtc_
close_ peer - Close and release a peer connection.
- rtc_
connection_ state - Poll the current connection state of a peer.
- rtc_
create_ answer - Generate an SDP answer (after setting the remote offer) and set it as the local description.
- rtc_
create_ data_ channel - Create a data channel on a peer connection.
- rtc_
create_ offer - Generate an SDP offer for the peer and set it as the local description.
- rtc_
create_ peer - Create a new WebRTC peer connection.
- rtc_
poll_ data_ channel - Poll for a remotely-created data channel that the peer opened.
- rtc_
poll_ ice_ candidate - Poll for a locally gathered ICE candidate (JSON). Returns
Nonewhen the queue is empty. - rtc_
poll_ track - Poll for a remote media track added by the peer.
- rtc_
recv - Poll for an incoming message on any channel of the peer (pass
channel_id = 0) or on a specific channel. - rtc_
send - Send data on a channel, choosing text or binary mode.
- rtc_
send_ binary - Send binary data on a data channel.
- rtc_
send_ text - Send a UTF-8 text message on a data channel.
- rtc_
set_ local_ description - Set the local SDP description explicitly.
- rtc_
set_ remote_ description - Set the remote SDP description received from the other peer.
- rtc_
signal_ connect - Connect to a signaling server at
urlfor bootstrapping peer connections. - rtc_
signal_ join_ room - Join (or create) a signaling room for peer discovery.
- rtc_
signal_ recv - Poll for an incoming signaling message.
- rtc_
signal_ send - Send a signaling message (JSON bytes) to the connected signaling server.
- screen_
capture - Captures the primary display as RGBA8 after permission dialogs (OS may prompt separately).
- screen_
capture_ dimensions - Width and height of the last
screen_captureimage. - scroll_
delta - Get the scroll wheel delta for this frame.
- set_
interval - Schedule a repeating timer that fires every
interval_msmilliseconds. When it fires the host calls your exportedon_timer(callback_id). Returns a timer ID that can be passed toclear_timer. - set_
timeout - Schedule a one-shot timer that fires after
delay_msmilliseconds. When it fires the host calls your exportedon_timer(callback_id). Returns a timer ID that can be passed toclear_timer. - shift_
held - Returns
trueif Shift is held. - storage_
get - Retrieve a value from local storage. Returns empty string if not found.
- storage_
remove - Remove a key from local storage.
- storage_
set - Store a key-value pair in sandboxed local storage.
- subtitle_
clear - subtitle_
load_ srt - Load SubRip subtitles (cues rendered on
video_render). - subtitle_
load_ vtt - Load WebVTT subtitles.
- time_
now_ ms - Get the current time in milliseconds since the UNIX epoch.
- ui_
button - Render a button at the given position. Returns
trueif it was clicked on the previous frame. - ui_
checkbox - Render a checkbox. Returns the current checked state.
- ui_
slider - Render a slider. Returns the current value.
- ui_
text_ input - Render a single-line text input. Returns the current text content.
- upload_
file - Opens the native OS file picker and returns the selected file.
Returns
Noneif the user cancels. - url_
decode - Decode a percent-encoded string.
- url_
encode - Percent-encode a string for safe inclusion in URL components.
- url_
resolve - Resolve a relative URL against a base URL (WHATWG algorithm).
Returns
Noneif either URL is invalid. - video_
detect_ format - Sniff container from leading bytes (magic only; does not decode).
- video_
duration - video_
get_ volume - video_
hls_ open_ variant - Open a variant playlist by index (after loading a master with
video_load_url). - video_
hls_ variant_ count - Number of variant stream URIs parsed from the last HLS master playlist (0 if not a master).
- video_
hls_ variant_ url - Resolved variant URL for
index, written intobuf-style API (use fixed buffer). - video_
last_ url_ content_ type Content-Typefrom the last successfulvideo_load_url(may be empty).- video_
load - Load video from encoded bytes (MP4, WebM, etc.). Requires FFmpeg on the host. Returns 0 on success, negative on error.
- video_
load_ url - Open a progressive or adaptive (HLS) URL. The host uses FFmpeg; master playlists may list variants.
- video_
load_ with_ format - Load with a
VideoFormathint (unknown = same asvideo_load). - video_
pause - video_
play - video_
position - video_
render - Draw the current video frame into the given rectangle (same coordinate space as canvas).
- video_
seek - video_
set_ loop - video_
set_ pip - Floating picture-in-picture preview (host mirrors the last rendered frame).
- video_
set_ volume - Volume multiplier for the video track (0.0–2.0; embedded audio mixing may follow in future hosts).
- video_
stop - warn
- Print a warning to the browser console.
- ws_
close - Initiate a graceful close handshake on
id. - ws_
connect - Open a WebSocket connection to
url(e.g."ws://example.com/chat"). - ws_
ready_ state - Query the current ready-state of a connection.
- ws_recv
- Poll for the next queued incoming frame on
id. - ws_
remove - Release host-side resources for a closed connection.
- ws_
send_ binary - Send a binary frame on the given connection.
- ws_
send_ text - Send a UTF-8 text frame on the given connection.