Skip to main content

Crate oxide_sdk

Crate oxide_sdk 

Source
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

CategoryKey types / functions
Drawing (high-level)draw::Canvas, draw::Color, draw::Rect, draw::Point2D, draw::GradientStop
Canvas (low-level)canvas_clear, canvas_rect, canvas_circle, canvas_text, canvas_line, canvas_image, canvas_dimensions
Extended shapescanvas_rounded_rect, canvas_arc, canvas_bezier, canvas_gradient
Canvas statecanvas_save, canvas_restore, canvas_transform, canvas_clip, canvas_opacity
GPUgpu_create_buffer, gpu_create_texture, gpu_create_shader, gpu_create_pipeline, gpu_draw, gpu_dispatch_compute
Consolelog, warn, error
HTTPfetch, fetch_get, fetch_post, fetch_post_proto, fetch_put, fetch_delete
HTTP (streaming)fetch_begin, fetch_begin_get, fetch_state, fetch_status, fetch_recv, fetch_error, fetch_abort, fetch_remove
Protobufproto::ProtoEncoder, proto::ProtoDecoder
Storagestorage_set, storage_get, storage_remove, kv_store_set, kv_store_get, kv_store_delete
Audioaudio_play, audio_play_url, audio_detect_format, audio_play_with_format, audio_pause, audio_channel_play
Videovideo_load, video_load_url, video_render, video_play, video_hls_open_variant, subtitle_load_srt
Media capturecamera_open, camera_capture_frame, microphone_open, microphone_read_samples, screen_capture
WebRTCrtc_create_peer, rtc_create_offer, rtc_create_answer, rtc_create_data_channel, rtc_send, rtc_recv, rtc_signal_connect
WebSocketws_connect, ws_send_text, ws_send_binary, ws_recv, ws_ready_state, ws_close, ws_remove
MIDImidi_input_count, midi_output_count, midi_input_name, midi_output_name, midi_open_input, midi_open_output, midi_send, midi_recv, midi_close
Timersset_timeout, set_interval, clear_timer, request_animation_frame, cancel_animation_frame, time_now_ms
Eventson_event, off_event, emit_event, event_type, event_data, event_data_into
Navigationnavigate, push_state, replace_state, get_url, history_back, history_forward
Inputmouse_position, mouse_button_down, mouse_button_clicked, key_down, key_pressed, scroll_delta, modifiers
Widgetsui_button, ui_checkbox, ui_slider, ui_text_input, ui_text_area
Cryptohash_sha256, hash_sha256_hex, base64_encode, base64_decode
Otherclipboard_write, clipboard_read, random_u64, random_f64, notify, upload_file, load_module

§Guest Module Contract

Every .wasm module loaded by Oxide must:

  1. Export start_appextern "C" fn() entry point, called once on load.
  2. Optionally export on_frameextern "C" fn(dt_ms: u32) for interactive apps with a render loop (called every frame, fuel replenished).
  3. Optionally export on_timerextern "C" fn(callback_id: u32) to receive callbacks from set_timeout, set_interval, and request_animation_frame.
  4. Optionally export on_eventextern "C" fn(callback_id: u32) to receive built-in (resize, focus, touch_*, gamepad_*, drop_files, …) and custom events registered via on_event / emit_event.
  5. Compile as cdylibcrate-type = ["cdylib"] in Cargo.toml.
  6. 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§

FetchResponse
Response from an HTTP fetch call.
FileMetadata
Metadata returned by file_metadata, parsed from the host’s JSON reply.
FolderEntry
One child returned by folder_entries.
RtcDataChannelInfo
Information about a newly opened remote data channel.
RtcMessage
Received data channel message.
RtcTrackInfo
Information about a remote media track received from a peer.
TextMetrics
Shaped-line metrics returned by canvas_measure_text. All values are in pixels.
UploadedFile
File returned from the native file picker.
WsMessage
A received WebSocket message.

Enums§

AudioFormat
Detected or hinted audio container (host codes: 0 unknown, 1 WAV, 2 MP3, 3 Ogg, 4 FLAC).
FetchChunk
Result of a non-blocking fetch_recv poll.
VideoFormat
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_error for the message.
FETCH_PENDING
Request dispatched; waiting for response headers.
FETCH_STREAMING
Headers received; body chunks may still be arriving.
FONT_STYLE_ITALIC
Italic font style.
FONT_STYLE_NORMAL
Normal (upright) font style. Pass to canvas_text_ex / canvas_measure_text.
FONT_STYLE_OBLIQUE
Oblique font style (slanted upright; falls back to italic where oblique isn’t available).
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.
TEXT_ALIGN_CENTER
Text is horizontally centred around x.
TEXT_ALIGN_LEFT
Text is anchored at its left edge (baseline (x, y)).
TEXT_ALIGN_RIGHT
Text is anchored at its right edge (x is the right edge).
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 true if 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_play with an optional AudioFormat hint.
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 true if audio is currently playing (not paused and not empty).
audio_last_url_content_type
Content-Type header from the last successful audio_play_url response (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 Accept header listing supported codecs, records the response Content-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 as audio_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_play calls 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 (0 if the camera is not open or capture failed). Query camera_frame_dimensions after 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_frame buffer.
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_angle to end_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_measure_text
Measure a line of text shaped with the given font parameters. Returns the shaped advance width plus ascent/descent in pixels. Pass an empty family to use the system UI font; pass 0 for weight to use the default (400).
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_restore to scope transformations and effects.
canvas_text
Draw text on the canvas with RGBA color.
canvas_text_ex
Draw text with explicit family, weight (CSS 100..=900; 0 = default 400), style (FONT_STYLE_NORMAL / FONT_STYLE_ITALIC / FONT_STYLE_OBLIQUE), and horizontal alignment (TEXT_ALIGN_LEFT / TEXT_ALIGN_CENTER / TEXT_ALIGN_RIGHT).
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_timeout or set_interval.
clipboard_read
Read text from the system clipboard.
clipboard_write
Copy text to the system clipboard.
ctrl_held
Returns true if Ctrl (or Cmd on macOS) is held.
emit_event
Emit a custom event with an arbitrary payload. Listeners registered for this event type via on_event will be invoked on the next frame (before timers and on_frame).
error
Print an error to the browser console.
event_data
Copy the current event’s payload bytes into out and return the number of bytes written. Truncates if out is smaller than the payload.
event_data_into
Allocate a fresh Vec<u8> containing the current event’s payload.
event_type
The type name of the event currently being delivered. Only meaningful inside an on_event callback; returns an empty string otherwise.
fetch
Perform an HTTP request. Returns the status code and response body.
fetch_abort
Abort an in-flight request. Returns true if 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, or 0 until the response headers arrive.
file_metadata
Inspect a picked file or folder: name, size, MIME type, last-modified.
file_pick
Open the native file picker and return the selected file handles.
file_read
Read the full contents of a picked file.
file_read_range
Read len bytes from offset of a picked file.
folder_entries
List the children of a picked folder handle.
folder_pick
Open the native folder picker and return a directory handle.
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 None if no state has been set.
get_url
Get the URL of the currently loaded page.
gpu_create_buffer
Create a GPU buffer of size bytes. 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_count vertices with instance_count instances.
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 true if a navigation was queued.
history_forward
Navigate forward in history. Returns true if a navigation was queued.
history_length
Return the total number of entries in the history stack.
key_down
Returns true if the given key is currently held down. See KEY_* constants for key codes.
key_pressed
Returns true if the given key was pressed this frame.
kv_store_delete
Delete a key from the persistent KV store. Returns true on success.
kv_store_get
Retrieve a value from the persistent KV store. Returns None if 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 true on success.
kv_store_set_str
Convenience wrapper: store a UTF-8 string value.
load_module
Fetch and execute another .wasm module 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 f32 ring buffer) after a host permission dialog.
microphone_read_samples
Dequeues up to out.len() mono f32 samples from the microphone ring buffer. Returns how many samples were written.
microphone_sample_rate
Sample rate of the opened input stream in Hz (0 if 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 true if the given mouse button was clicked this frame.
mouse_button_down
Returns true if 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_app returns. Returns 0 on success, negative on invalid URL.
notify
Send a notification to the user (rendered in the browser console).
off_event
Cancel a previously-registered listener. Returns true if a listener with that ID existed and was removed.
on_event
Register a listener for events of event_type. When an event fires, the host invokes the guest-exported on_event(callback_id) and exposes the event payload via event_type / event_data.
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 None when 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 url for 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_capture image.
scroll_delta
Get the scroll wheel delta for this frame.
set_interval
Schedule a repeating timer that fires every interval_ms milliseconds. When it fires the host calls your exported on_timer(callback_id). Returns a timer ID that can be passed to clear_timer.
set_timeout
Schedule a one-shot timer that fires after delay_ms milliseconds. When it fires the host calls your exported on_timer(callback_id). Returns a timer ID that can be passed to clear_timer.
shift_held
Returns true if 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 true if 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_area
Render a multi-line text area of height h (pixels). Returns the current UTF-8 text.
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 None if 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 None if 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 into buf-style API (use fixed buffer).
video_last_url_content_type
Content-Type from the last successful video_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 VideoFormat hint (unknown = same as video_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.