This commit is contained in:
1 parent
ccb809bdc3
commit
7caadb3f7f
59 files changed
+7495
-16
No files matched your search
@@ -0,0 +1,274 @@
|
||||
// #region subtask
|
||||
|
||||
///|
|
||||
priv struct SubTask {
|
||||
handle : Int
|
||||
state : SubTaskState
|
||||
}
|
||||
|
||||
///|
|
||||
priv enum SubTaskState {
|
||||
Starting = 0
|
||||
Started = 1
|
||||
Returned = 2
|
||||
Cancelled_before_started = 3
|
||||
Cancelled_before_returned = 4
|
||||
}
|
||||
|
||||
///|
|
||||
fn SubTaskState::from(int : Int) -> SubTaskState {
|
||||
match int {
|
||||
0 => Starting
|
||||
1 => Started
|
||||
2 => Returned
|
||||
3 => Cancelled_before_started
|
||||
4 => Cancelled_before_returned
|
||||
_ => panic()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn SubTask::from(code : Int) -> SubTask {
|
||||
{ handle: code >> 4, state: SubTaskState::from(code & 0xf) }
|
||||
}
|
||||
|
||||
///|
|
||||
/// The baseline intrinsic cooperatively waits in the component model and
|
||||
/// returns only after the subtask reaches a terminal state.
|
||||
fn SubTask::cancel(self : SubTask) -> SubTaskState {
|
||||
SubTaskState::from(subtask_cancel(self.handle))
|
||||
}
|
||||
|
||||
// #endregion
|
||||
|
||||
// #region events
|
||||
|
||||
///|
|
||||
priv enum EventCode {
|
||||
None = 0
|
||||
SubTask = 1
|
||||
StreamRead = 2
|
||||
StreamWrite = 3
|
||||
FutureRead = 4
|
||||
FutureWrite = 5
|
||||
TaskCancelled = 6
|
||||
}
|
||||
|
||||
///|
|
||||
fn EventCode::from(int : Int) -> EventCode {
|
||||
match int {
|
||||
0 => None
|
||||
1 => SubTask
|
||||
2 => StreamRead
|
||||
3 => StreamWrite
|
||||
4 => FutureRead
|
||||
5 => FutureWrite
|
||||
6 => TaskCancelled
|
||||
_ => panic()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
priv enum Events {
|
||||
None
|
||||
Subtask(Int, SubTaskState)
|
||||
StreamRead(Int, StreamResult)
|
||||
StreamWrite(Int, StreamResult)
|
||||
FutureRead(Int, FutureReadResult)
|
||||
FutureWrite(Int, FutureWriteResult)
|
||||
TaskCancelled
|
||||
}
|
||||
|
||||
///|
|
||||
fn Events::new(code : EventCode, i : Int, j : Int) -> Events {
|
||||
match code {
|
||||
None => None
|
||||
SubTask => Subtask(i, SubTaskState::from(j))
|
||||
StreamRead => StreamRead(i, StreamResult::from(j))
|
||||
StreamWrite => StreamWrite(i, StreamResult::from(j))
|
||||
FutureRead => FutureRead(i, FutureReadResult::from(j))
|
||||
FutureWrite => FutureWrite(i, FutureWriteResult::from(j))
|
||||
TaskCancelled => TaskCancelled
|
||||
}
|
||||
}
|
||||
|
||||
// #endregion
|
||||
|
||||
// #region waitable set
|
||||
|
||||
///|
|
||||
#borrow(array)
|
||||
extern "wasm" fn int_array2ptr(array : FixedArray[Int]) -> Int =
|
||||
#|(func (param i32) (result i32) local.get 0)
|
||||
|
||||
///|
|
||||
struct WaitableSet(Int) derive(Eq, Hash)
|
||||
|
||||
///|
|
||||
#deprecated
|
||||
pub extend WaitableSet with Eq::{not_equal, equal}
|
||||
|
||||
///|
|
||||
#deprecated
|
||||
pub extend WaitableSet with Hash::{hash, hash_combine}
|
||||
|
||||
///|
|
||||
fn WaitableSet::new() -> WaitableSet {
|
||||
WaitableSet(waitable_set_new())
|
||||
}
|
||||
|
||||
///|
|
||||
fn WaitableSet::drop(self : Self) -> Unit {
|
||||
waitable_set_drop(self.0)
|
||||
}
|
||||
|
||||
///|
|
||||
fn WaitableSet::poll(self : Self) -> (Events, Int) {
|
||||
let payload : FixedArray[Int] = FixedArray::make(2, 0)
|
||||
let event = waitable_set_poll(self.0, int_array2ptr(payload))
|
||||
(Events::new(EventCode::from(event), payload[0], payload[1]), payload[0])
|
||||
}
|
||||
|
||||
// #endregion
|
||||
|
||||
// #region Future
|
||||
|
||||
///|
|
||||
priv enum FutureReadResult {
|
||||
Completed = 0
|
||||
Cancelled = 2
|
||||
}
|
||||
|
||||
///|
|
||||
fn FutureReadResult::from(int : Int) -> FutureReadResult {
|
||||
match int {
|
||||
0 => Completed
|
||||
2 => Cancelled
|
||||
_ => panic()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
priv enum FutureWriteResult {
|
||||
Completed = 0
|
||||
Dropped = 1
|
||||
Cancelled = 2
|
||||
}
|
||||
|
||||
///|
|
||||
fn FutureWriteResult::from(int : Int) -> FutureWriteResult {
|
||||
match int {
|
||||
0 => Completed
|
||||
1 => Dropped
|
||||
2 => Cancelled
|
||||
_ => panic()
|
||||
}
|
||||
}
|
||||
|
||||
// #endregion
|
||||
|
||||
// #region Stream
|
||||
|
||||
///|
|
||||
priv struct StreamResult {
|
||||
progress : Int
|
||||
copy_result : CopyResult
|
||||
}
|
||||
|
||||
///|
|
||||
fn StreamResult::from(int : Int) -> StreamResult {
|
||||
let progress = int >> 4
|
||||
let copy_result = CopyResult::from(int & 0xf)
|
||||
{ progress, copy_result }
|
||||
}
|
||||
|
||||
///|
|
||||
priv enum CopyResult {
|
||||
Completed = 0
|
||||
Dropped = 1
|
||||
Cancelled = 2
|
||||
}
|
||||
|
||||
///|
|
||||
fn CopyResult::from(int : Int) -> CopyResult {
|
||||
match int {
|
||||
0 => Completed
|
||||
1 => Dropped
|
||||
2 => Cancelled
|
||||
_ => panic()
|
||||
}
|
||||
}
|
||||
|
||||
// #endregion
|
||||
|
||||
// #region callback code
|
||||
|
||||
///|
|
||||
/// Code to let the runtime know what to do in the callback
|
||||
priv enum CallbackCode {
|
||||
Completed
|
||||
Yield
|
||||
Wait(WaitableSet)
|
||||
}
|
||||
|
||||
///|
|
||||
fn CallbackCode::encode(self : Self) -> Int {
|
||||
match self {
|
||||
Completed => 0
|
||||
Yield => 1
|
||||
Wait(id) => 2 | (id.0 << 4)
|
||||
}
|
||||
}
|
||||
|
||||
// #endregion
|
||||
|
||||
// #region Component async primitives
|
||||
|
||||
///|
|
||||
fn subtask_cancel(id : Int) -> Int = "$root" "[subtask-cancel]"
|
||||
|
||||
///|
|
||||
fn subtask_drop(id : Int) = "$root" "[subtask-drop]"
|
||||
|
||||
///|
|
||||
fn tls_set(tls : Int) = "$root" "[context-set-0]"
|
||||
|
||||
///|
|
||||
fn tls_get() -> Int = "$root" "[context-get-0]"
|
||||
|
||||
///|
|
||||
fn task_cancel() = "[export]$root" "[task-cancel]"
|
||||
|
||||
///|
|
||||
fn waitable_set_new() -> Int = "$root" "[waitable-set-new]"
|
||||
|
||||
///|
|
||||
fn waitable_set_drop(set : Int) = "$root" "[waitable-set-drop]"
|
||||
|
||||
///|
|
||||
/// This poll is deliberately non-cancellable. Component-task cancellation is
|
||||
/// delivered by the stackless callback instead of being consumed here.
|
||||
fn waitable_set_poll(set : Int, payload : Int) -> Int = "$root" "[waitable-set-poll]"
|
||||
|
||||
///|
|
||||
fn task_wakeup_stream_new() -> Int64 = "$root" "[stream-new-unit]"
|
||||
|
||||
///|
|
||||
fn task_wakeup_stream_read(handle : Int, ptr : Int, len : Int) -> Int = "$root" "[async-lower][stream-read-unit]"
|
||||
|
||||
///|
|
||||
fn task_wakeup_stream_write(handle : Int, ptr : Int, len : Int) -> Int = "$root" "[async-lower][stream-write-unit]"
|
||||
|
||||
///|
|
||||
fn task_wakeup_stream_cancel_read(handle : Int) -> Int = "$root" "[stream-cancel-read-unit]"
|
||||
|
||||
///|
|
||||
fn task_wakeup_stream_drop_readable(handle : Int) = "$root" "[stream-drop-readable-unit]"
|
||||
|
||||
///|
|
||||
fn task_wakeup_stream_drop_writable(handle : Int) = "$root" "[stream-drop-writable-unit]"
|
||||
|
||||
///|
|
||||
fn waitable_join(waitable : Int, set : Int) = "$root" "[waitable-join]"
|
||||
|
||||
// #endregion
|
||||
@@ -0,0 +1,73 @@
|
||||
// Copyright 2025 International Digital Economy Academy
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
///|
|
||||
priv struct CondVarWaiter {
|
||||
// Once a signal is assigned, cancellation must not lose it before the
|
||||
// waiter resumes. This matches moonbitlang/async's condition variable.
|
||||
mut woken : Bool
|
||||
mut coro : Coroutine?
|
||||
}
|
||||
|
||||
///|
|
||||
/// A condition variable for synchronization between tasks.
|
||||
pub struct CondVar {
|
||||
priv waiters : @deque.Deque[CondVarWaiter]
|
||||
}
|
||||
|
||||
///|
|
||||
/// Create a new condition variable.
|
||||
#alias(new, deprecated)
|
||||
pub fn CondVar::CondVar() -> CondVar {
|
||||
{ waiters: Deque([]) }
|
||||
}
|
||||
|
||||
///|
|
||||
/// Wait until the condition variable is signaled.
|
||||
pub async fn CondVar::wait(self : CondVar) -> Unit noraise {
|
||||
let waiter = { woken: false, coro: Some(current_coroutine()) }
|
||||
self.waiters.push_back(waiter)
|
||||
match suspend_check_cancel() {
|
||||
Continue => ()
|
||||
Cancelled if waiter.woken => ()
|
||||
Cancelled => {
|
||||
waiter.coro = None
|
||||
raise_cancellation_signal()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Wake the first waiting task. Does nothing when no task is waiting.
|
||||
pub fn CondVar::signal(self : CondVar) -> Unit {
|
||||
while self.waiters.pop_front() is Some(waiter) {
|
||||
if waiter.coro is Some(coro) {
|
||||
waiter.woken = true
|
||||
coro.wake()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Wake all waiting tasks. Does nothing when no task is waiting.
|
||||
pub fn CondVar::broadcast(self : CondVar) -> Unit {
|
||||
for waiter in self.waiters {
|
||||
if waiter.coro is Some(coro) {
|
||||
waiter.woken = true
|
||||
coro.wake()
|
||||
}
|
||||
}
|
||||
self.waiters.clear()
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
// Copyright 2025 International Digital Economy Academy
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
///|
|
||||
priv enum SuspendResult {
|
||||
Continue
|
||||
Cancelled
|
||||
}
|
||||
|
||||
///|
|
||||
priv enum State {
|
||||
Done
|
||||
Fail(Error)
|
||||
Cancelled
|
||||
Running
|
||||
Suspend((SuspendResult) -> Unit)
|
||||
}
|
||||
|
||||
///|
|
||||
struct Coroutine {
|
||||
coro_id : Int
|
||||
lane : TaskLane
|
||||
mut state : State
|
||||
mut shielded : Bool
|
||||
mut cancelled : Bool
|
||||
mut ready : Bool
|
||||
mut spawner : ((async () -> Unit) -> Unit)?
|
||||
downstream : Set[Coroutine]
|
||||
}
|
||||
|
||||
///|
|
||||
impl Eq for Coroutine with fn equal(c1, c2) {
|
||||
c1.coro_id == c2.coro_id
|
||||
}
|
||||
|
||||
///|
|
||||
impl Hash for Coroutine with fn hash_combine(self, hasher) {
|
||||
Hash::hash_combine(self.coro_id, hasher)
|
||||
}
|
||||
|
||||
///|
|
||||
fn Coroutine::wake(self : Coroutine) -> Unit {
|
||||
if !self.ready {
|
||||
self.ready = true
|
||||
enqueue(self)
|
||||
signal_component_task(self.lane)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn is_being_cancelled() -> Bool {
|
||||
let coro = current_coroutine()
|
||||
coro.cancelled && !coro.shielded
|
||||
}
|
||||
|
||||
///|
|
||||
pub async fn check_cancellation() -> Unit noraise {
|
||||
if is_being_cancelled() {
|
||||
raise_cancellation_signal()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Coroutine::cancel(self : Coroutine) -> Unit {
|
||||
match self.state {
|
||||
Done | Fail(_) | Cancelled => return
|
||||
Running | Suspend(_) => ()
|
||||
}
|
||||
self.cancelled = true
|
||||
if !self.shielded {
|
||||
self.wake()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
async fn suspend_check_cancel() -> SuspendResult noraise {
|
||||
guard! scheduler.curr_coro is Some(coro)
|
||||
if coro.cancelled && !coro.shielded {
|
||||
return Cancelled
|
||||
}
|
||||
coro.lane.blocking += 1
|
||||
defer {
|
||||
coro.lane.blocking -= 1
|
||||
}
|
||||
async_suspend(fn(cont) {
|
||||
guard! coro.state is Running
|
||||
coro.state = Suspend(cont)
|
||||
})
|
||||
}
|
||||
|
||||
///|
|
||||
async fn suspend() -> Unit noraise {
|
||||
match suspend_check_cancel() {
|
||||
Continue => ()
|
||||
Cancelled => raise_cancellation_signal()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn spawn_owned(
|
||||
f : async () -> Unit,
|
||||
lane : TaskLane,
|
||||
inherited_spawner : ((async () -> Unit) -> Unit)?,
|
||||
) -> Coroutine {
|
||||
scheduler.coro_id += 1
|
||||
let coro = {
|
||||
state: Running,
|
||||
ready: true,
|
||||
shielded: false,
|
||||
downstream: Set([]),
|
||||
coro_id: scheduler.coro_id,
|
||||
lane,
|
||||
cancelled: false,
|
||||
spawner: inherited_spawner,
|
||||
}
|
||||
fn run(_) {
|
||||
run_async(() => {
|
||||
// Even a task cancelled before its first turn enters its body, so entry
|
||||
// defers run. Cancellation is delivered at its first suspension/check.
|
||||
try capture_cancellation(f, handler=() => coro.state = Cancelled) catch {
|
||||
err => coro.state = Fail(err)
|
||||
} noraise {
|
||||
_ if coro.state is Running => coro.state = Done
|
||||
_ => ()
|
||||
}
|
||||
for coro in coro.downstream {
|
||||
coro.wake()
|
||||
}
|
||||
coro.downstream.clear()
|
||||
})
|
||||
}
|
||||
|
||||
coro.state = Suspend(run)
|
||||
enqueue(coro)
|
||||
coro
|
||||
}
|
||||
|
||||
///|
|
||||
fn spawn(f : async () -> Unit) -> Coroutine {
|
||||
match scheduler.curr_coro {
|
||||
Some(parent) => spawn_owned(f, parent.lane, parent.spawner)
|
||||
None => {
|
||||
let waitable_set = current_waitableset()
|
||||
let task_state = component_task_state(waitable_set).unwrap()
|
||||
spawn_owned(f, task_state.lane, None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Coroutine::unwrap(self : Coroutine) -> SuspendResult raise {
|
||||
match self.state {
|
||||
Done => Continue
|
||||
Cancelled => Cancelled
|
||||
Fail(err) => raise err
|
||||
Running | Suspend(_) => panic()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
async fn Coroutine::wait(target : Coroutine) -> SuspendResult {
|
||||
guard! scheduler.curr_coro is Some(coro)
|
||||
guard! !physical_equal(coro, target)
|
||||
match target.state {
|
||||
Done => return Continue
|
||||
Cancelled => return Cancelled
|
||||
Fail(err) => raise err
|
||||
Running | Suspend(_) => ()
|
||||
}
|
||||
target.downstream.add(coro)
|
||||
defer target.downstream.remove(coro)
|
||||
suspend()
|
||||
target.unwrap()
|
||||
}
|
||||
|
||||
///|
|
||||
fn Coroutine::check_error(coro : Coroutine) -> Unit raise {
|
||||
match coro.state {
|
||||
Fail(err) => raise err
|
||||
Done | Cancelled | Running | Suspend(_) => ()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub async fn[X] protect_from_cancel(f : async () -> X) -> X nocancel {
|
||||
guard! scheduler.curr_coro is Some(coro)
|
||||
// The shield prevents delivery; capture_cancellation expresses that invariant
|
||||
// in the effect type without changing normal error propagation.
|
||||
capture_cancellation(handler=() => panic(), () => {
|
||||
if coro.shielded {
|
||||
f()
|
||||
} else {
|
||||
coro.shielded = true
|
||||
defer {
|
||||
coro.shielded = false
|
||||
}
|
||||
f()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
///|
|
||||
/// Observe cancellation without clearing the task's sticky cancelled state.
|
||||
/// Returns None on cancellation, Some on success, and propagates normal errors.
|
||||
pub async fn[X] handle_cancellation(f : async () -> X) -> X? {
|
||||
capture_cancellation(handler=() => None, () => Some(f()))
|
||||
}
|
||||
@@ -0,0 +1,658 @@
|
||||
// Copyright 2025 International Digital Economy Academy
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
///|
|
||||
/// State owned by one P3 component task. `task.state` is the sole completion
|
||||
/// source; `owned_coroutines` contains only runtime bridge coroutines.
|
||||
priv struct ComponentTaskState {
|
||||
lane : TaskLane
|
||||
subscribers : Map[Int, Subscriber]
|
||||
task : Coroutine
|
||||
owned_coroutines : @set.Set[Coroutine]
|
||||
mut resolution : TaskResolution
|
||||
mut cancellation_pending : Bool
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct TaskWakeup {
|
||||
reader : Int
|
||||
writer : Int
|
||||
mut reading : Bool
|
||||
mut signaled : Bool
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct Subscriber {
|
||||
mut event : Events?
|
||||
coro : @set.Set[Coroutine]
|
||||
}
|
||||
|
||||
///|
|
||||
priv enum TaskResolution {
|
||||
Pending
|
||||
FlushPending
|
||||
Resolved
|
||||
}
|
||||
|
||||
///|
|
||||
fn current_waitableset() -> WaitableSet {
|
||||
WaitableSet(tls_get())
|
||||
}
|
||||
|
||||
///|
|
||||
fn component_task_state(waitable_set : WaitableSet) -> ComponentTaskState? {
|
||||
component_tasks.get(waitable_set)
|
||||
}
|
||||
|
||||
///|
|
||||
fn finish_waitableset(
|
||||
waitable_set : WaitableSet,
|
||||
task_state : ComponentTaskState,
|
||||
) -> Unit {
|
||||
guard task_state.owned_coroutines.is_empty() else { panic() }
|
||||
guard task_state.lane.blocking == 0 && task_state.lane.run_later.is_empty() else {
|
||||
panic()
|
||||
}
|
||||
drop_task_wakeup(task_state)
|
||||
guard task_state.subscribers.is_empty() else { panic() }
|
||||
component_tasks.remove(waitable_set)
|
||||
waitable_set.drop()
|
||||
tls_set(0)
|
||||
}
|
||||
|
||||
///|
|
||||
fn acknowledge_cancellation(task_state : ComponentTaskState) -> Unit {
|
||||
guard task_state.cancellation_pending else { return }
|
||||
match task_state.task.state {
|
||||
Done => () // The generated wrapper already called task.return.
|
||||
Fail(_) | Cancelled =>
|
||||
if task_state.resolution is Pending {
|
||||
task_cancel()
|
||||
task_state.resolution = Resolved
|
||||
}
|
||||
Running | Suspend(_) => return
|
||||
}
|
||||
task_state.cancellation_pending = false
|
||||
}
|
||||
|
||||
///|
|
||||
fn notify_subscriber(
|
||||
task_state : ComponentTaskState,
|
||||
waitable_id : Int,
|
||||
event : Events,
|
||||
) -> Unit {
|
||||
if task_state.lane.wakeup is Some(wakeup) && wakeup.reader == waitable_id {
|
||||
guard! event is StreamRead(i, { progress: 1, copy_result: Completed }) &&
|
||||
i == waitable_id
|
||||
wakeup.reading = false
|
||||
wakeup.signaled = false
|
||||
task_state.subscribers.remove(waitable_id)
|
||||
waitable_join(waitable_id, 0)
|
||||
return
|
||||
}
|
||||
guard! task_state.subscribers.get(waitable_id) is Some(subscriber)
|
||||
subscriber.event = Some(event)
|
||||
subscriber.coro.each(Coroutine::wake)
|
||||
// Keep the delivered event discoverable until its waiter consumes it. A
|
||||
// local cancellation can race with the wakeup, and cancelling an already
|
||||
// terminal canonical operation would trap.
|
||||
waitable_join(waitable_id, 0)
|
||||
}
|
||||
|
||||
///|
|
||||
fn next_callback(
|
||||
waitable_set : WaitableSet,
|
||||
task_state : ComponentTaskState,
|
||||
) -> Int {
|
||||
if task_state.resolution is FlushPending {
|
||||
task_state.resolution = Resolved
|
||||
reschedule(task_state.lane)
|
||||
}
|
||||
acknowledge_cancellation(task_state)
|
||||
if task_state.task.state is (Done | Fail(_) | Cancelled) &&
|
||||
no_more_work(task_state.lane) {
|
||||
let resolution = task_state.resolution
|
||||
finish_waitableset(waitable_set, task_state)
|
||||
guard! resolution is Resolved
|
||||
return CallbackCode::Completed.encode()
|
||||
}
|
||||
if has_immediately_ready_task(task_state.lane) {
|
||||
if !task_state.subscribers.is_empty() {
|
||||
let (event, waitable_id) = waitable_set.poll()
|
||||
match event {
|
||||
None => ()
|
||||
TaskCancelled => panic()
|
||||
_ => notify_subscriber(task_state, waitable_id, event)
|
||||
}
|
||||
}
|
||||
tls_set(waitable_set.0)
|
||||
return CallbackCode::Yield.encode()
|
||||
}
|
||||
tls_set(waitable_set.0)
|
||||
arm_task_wakeup(waitable_set, task_state)
|
||||
CallbackCode::Wait(waitable_set.0).encode()
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
#doc(hidden)
|
||||
pub fn with_waitableset(f : async () -> Unit) -> Int {
|
||||
let waitable_set = WaitableSet::new()
|
||||
let lane = { blocking: 0, run_later: Deque([]), wakeup: None }
|
||||
tls_set(waitable_set.0)
|
||||
let task = spawn_owned(f, lane, None)
|
||||
let task_state = {
|
||||
lane,
|
||||
subscribers: Map([]),
|
||||
task,
|
||||
owned_coroutines: Set([]),
|
||||
resolution: Pending,
|
||||
cancellation_pending: false,
|
||||
}
|
||||
component_tasks.set(waitable_set, task_state)
|
||||
reschedule(lane)
|
||||
next_callback(waitable_set, task_state)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Record that the generated export wrapper has resolved the component-model
|
||||
/// task. One additional fair scheduling round lets the enclosing MoonBit task
|
||||
/// group observe its body completing without draining runnable background work.
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
#doc(hidden)
|
||||
pub fn task_returned() -> Unit {
|
||||
let waitable_set = current_waitableset()
|
||||
guard! component_task_state(waitable_set) is Some(task_state)
|
||||
guard! task_state.resolution is Pending
|
||||
task_state.resolution = FlushPending
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
#doc(hidden)
|
||||
pub fn cb(event : Int, waitable_id : Int, code : Int) -> Int {
|
||||
let waitable_set = current_waitableset()
|
||||
guard component_task_state(waitable_set) is Some(task_state) else { panic() }
|
||||
let events = Events::new(EventCode::from(event), waitable_id, code)
|
||||
let preserve_task_wakeup = match events {
|
||||
StreamRead(i, _) =>
|
||||
match task_state.lane.wakeup {
|
||||
Some(wakeup) => wakeup.reader == i
|
||||
None => false
|
||||
}
|
||||
_ => false
|
||||
}
|
||||
cancel_task_wakeup_read(task_state, preserve=preserve_task_wakeup)
|
||||
match events {
|
||||
None => {
|
||||
reschedule(task_state.lane)
|
||||
next_callback(waitable_set, task_state)
|
||||
}
|
||||
TaskCancelled => {
|
||||
task_state.cancellation_pending = true
|
||||
task_state.task.cancel()
|
||||
task_state.owned_coroutines.each(Coroutine::cancel)
|
||||
reschedule(task_state.lane)
|
||||
next_callback(waitable_set, task_state)
|
||||
}
|
||||
_ => {
|
||||
notify_subscriber(task_state, waitable_id, events)
|
||||
reschedule(task_state.lane)
|
||||
next_callback(waitable_set, task_state)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
let component_tasks : Map[WaitableSet, ComponentTaskState] = Map([])
|
||||
|
||||
///|
|
||||
/// Spawn a coroutine owned by the current component-model async task.
|
||||
///
|
||||
/// This is intended for runtime bridge work such as lowering local futures and
|
||||
/// streams to component-model handles. The coroutine does not participate in
|
||||
/// `TaskGroup` structured concurrency, but it is cancelled when the current
|
||||
/// component-model task is cancelled and keeps the waitable-set alive until it
|
||||
/// terminates.
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
#doc(hidden)
|
||||
pub fn spawn_component_task_current(f : async () -> Unit) -> Unit {
|
||||
let waitable_set = current_waitableset()
|
||||
guard! component_task_state(waitable_set) is Some(task_state)
|
||||
let coro = spawn_owned(
|
||||
async fn() -> Unit {
|
||||
let coro = current_coroutine()
|
||||
defer task_state.owned_coroutines.remove(coro)
|
||||
f()
|
||||
},
|
||||
task_state.lane,
|
||||
Some(spawn_component_task_current),
|
||||
)
|
||||
task_state.owned_coroutines.add(coro)
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
#doc(hidden)
|
||||
pub fn has_component_task_scope() -> Bool {
|
||||
let waitable_set = current_waitableset()
|
||||
component_task_state(waitable_set) is Some(_)
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
#doc(hidden)
|
||||
pub fn current_component_task_token() -> Int {
|
||||
current_waitableset().0
|
||||
}
|
||||
|
||||
///|
|
||||
fn detach_waitable(task_state : ComponentTaskState, waitable_id : Int) -> Unit {
|
||||
if task_state.subscribers.get(waitable_id) is Some(subscriber) {
|
||||
subscriber.coro.clear()
|
||||
task_state.subscribers.remove(waitable_id)
|
||||
}
|
||||
waitable_join(waitable_id, 0)
|
||||
}
|
||||
|
||||
///|
|
||||
fn task_wakeup(lane : TaskLane) -> TaskWakeup {
|
||||
match lane.wakeup {
|
||||
Some(wakeup) => wakeup
|
||||
None => {
|
||||
let pair = task_wakeup_stream_new()
|
||||
let wakeup = {
|
||||
reader: pair.to_int(),
|
||||
writer: (pair >> 32).to_int(),
|
||||
reading: false,
|
||||
signaled: false,
|
||||
}
|
||||
lane.wakeup = Some(wakeup)
|
||||
wakeup
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn arm_task_wakeup(
|
||||
waitable_set : WaitableSet,
|
||||
task_state : ComponentTaskState,
|
||||
) -> Unit {
|
||||
let wakeup = task_wakeup(task_state.lane)
|
||||
if wakeup.reading {
|
||||
return
|
||||
}
|
||||
let result = task_wakeup_stream_read(wakeup.reader, 0, 1)
|
||||
guard! result == -1
|
||||
let subscribers = task_state.subscribers
|
||||
guard! subscribers.get(wakeup.reader) is None
|
||||
subscribers.set(wakeup.reader, { event: None, coro: Set([]) })
|
||||
waitable_join(wakeup.reader, waitable_set.0)
|
||||
wakeup.reading = true
|
||||
wakeup.signaled = false
|
||||
}
|
||||
|
||||
///|
|
||||
fn signal_component_task(lane : TaskLane) -> Unit {
|
||||
guard lane.wakeup is Some(wakeup) else { return }
|
||||
if !wakeup.reading || wakeup.signaled {
|
||||
return
|
||||
}
|
||||
let result = StreamResult::from(task_wakeup_stream_write(wakeup.writer, 0, 1))
|
||||
guard! result.progress == 1 && result.copy_result is Completed
|
||||
wakeup.signaled = true
|
||||
}
|
||||
|
||||
///|
|
||||
fn cancel_task_wakeup_read(
|
||||
task_state : ComponentTaskState,
|
||||
preserve~ : Bool,
|
||||
) -> Unit {
|
||||
guard task_state.lane.wakeup is Some(wakeup) else { return }
|
||||
if !wakeup.reading || preserve {
|
||||
return
|
||||
}
|
||||
waitable_join(wakeup.reader, 0)
|
||||
task_state.subscribers.remove(wakeup.reader)
|
||||
ignore(task_wakeup_stream_cancel_read(wakeup.reader))
|
||||
wakeup.reading = false
|
||||
wakeup.signaled = false
|
||||
}
|
||||
|
||||
///|
|
||||
fn drop_task_wakeup(task_state : ComponentTaskState) -> Unit {
|
||||
guard task_state.lane.wakeup is Some(wakeup) else { return }
|
||||
if wakeup.reading {
|
||||
waitable_join(wakeup.reader, 0)
|
||||
task_state.subscribers.remove(wakeup.reader)
|
||||
ignore(task_wakeup_stream_cancel_read(wakeup.reader))
|
||||
}
|
||||
task_wakeup_stream_drop_readable(wakeup.reader)
|
||||
task_wakeup_stream_drop_writable(wakeup.writer)
|
||||
task_state.lane.wakeup = None
|
||||
}
|
||||
|
||||
///|
|
||||
fn cancel_waitable_event(
|
||||
owner_task : Int,
|
||||
waitable_id : Int,
|
||||
cancel : () -> Events,
|
||||
) -> Events {
|
||||
let waitable_set = WaitableSet(owner_task)
|
||||
guard! component_task_state(waitable_set) is Some(task_state)
|
||||
guard! task_state.subscribers.get(waitable_id) is Some(subscriber)
|
||||
|
||||
// Baseline cancel-read is synchronous and traps while its endpoint belongs
|
||||
// to a waitable set. Detach before invoking the generated intrinsic.
|
||||
waitable_join(waitable_id, 0)
|
||||
let event = match subscriber.event {
|
||||
Some(event) => event
|
||||
None => cancel()
|
||||
}
|
||||
subscriber.event = Some(event)
|
||||
subscriber.coro.each(Coroutine::wake)
|
||||
task_state.subscribers.remove(waitable_id)
|
||||
event
|
||||
}
|
||||
|
||||
///|
|
||||
/// Complete an operation immediately or suspend until its terminal waitable
|
||||
/// event arrives. This is the single owner of subscription registration and
|
||||
/// detachment for future and stream copy operations.
|
||||
async fn waitable_event(waitable_id : Int, immediate : Events?) -> Events {
|
||||
let waitable_set = current_waitableset()
|
||||
let task_state = component_task_state(waitable_set).unwrap()
|
||||
let subscribers = task_state.subscribers
|
||||
match immediate {
|
||||
Some(event) => {
|
||||
if subscribers.get(waitable_id) is Some(subscriber) {
|
||||
subscriber.event = Some(event)
|
||||
subscriber.coro.each(Coroutine::wake)
|
||||
subscriber.coro.clear()
|
||||
waitable_join(waitable_id, 0)
|
||||
}
|
||||
subscribers.remove(waitable_id)
|
||||
event
|
||||
}
|
||||
None => {
|
||||
let subscriber = if subscribers.get(waitable_id) is Some(subscriber) {
|
||||
subscriber
|
||||
} else {
|
||||
let subscriber = { event: None, coro: Set([]) }
|
||||
subscribers.set(waitable_id, subscriber)
|
||||
subscriber
|
||||
}
|
||||
guard! subscriber.event is None
|
||||
waitable_join(waitable_id, waitable_set.0)
|
||||
let coro = current_coroutine()
|
||||
subscriber.coro.add(coro)
|
||||
defer subscriber.coro.remove(coro)
|
||||
let event = match suspend_check_cancel() {
|
||||
Continue => subscriber.event.unwrap()
|
||||
Cancelled =>
|
||||
match subscriber.event {
|
||||
// Completion owns the canonical buffer once its event is
|
||||
// delivered, even if local cancellation wakes the same coroutine.
|
||||
Some(event) => event
|
||||
None => raise_cancellation_signal()
|
||||
}
|
||||
}
|
||||
subscribers.remove(waitable_id)
|
||||
event
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
#doc(hidden)
|
||||
pub async fn suspend_for_subtask(
|
||||
val : Int,
|
||||
settle_lowered_arguments : (Bool) -> Unit,
|
||||
drop_returned_result : () -> Unit,
|
||||
) -> Unit {
|
||||
let task = SubTask::from(val)
|
||||
let mut cleaned = false
|
||||
|
||||
// Once the subtask leaves Starting, canonical arguments are either
|
||||
// transferred or rejected. Generated code owns the corresponding action.
|
||||
fn settle_arguments(state : SubTaskState) -> Unit {
|
||||
if !cleaned && !(state is Starting) {
|
||||
cleaned = true
|
||||
settle_lowered_arguments(state is Cancelled_before_started)
|
||||
}
|
||||
}
|
||||
|
||||
// Immediate completion without a handle.
|
||||
if task.handle == 0 {
|
||||
settle_arguments(task.state)
|
||||
match task.state {
|
||||
Returned => return
|
||||
Cancelled_before_started => raise SubTaskCancelled(before_started=true)
|
||||
Cancelled_before_returned => raise SubTaskCancelled(before_started=false)
|
||||
_ => panic()
|
||||
}
|
||||
}
|
||||
|
||||
defer subtask_drop(task.handle)
|
||||
|
||||
// Initial state, return if finished
|
||||
settle_arguments(task.state)
|
||||
match task.state {
|
||||
Returned => return
|
||||
Cancelled_before_started => raise SubTaskCancelled(before_started=true)
|
||||
Cancelled_before_returned => raise SubTaskCancelled(before_started=false)
|
||||
_ => ()
|
||||
}
|
||||
|
||||
// A subtask can report intermediate states, so register the same subscriber
|
||||
// again after each callback until a terminal state arrives.
|
||||
let waitable_set = current_waitableset()
|
||||
let task_state = component_task_state(waitable_set).unwrap()
|
||||
let set = @set.Set([])
|
||||
let subscriber = { event: None, coro: set }
|
||||
let coro = current_coroutine()
|
||||
set.add(coro)
|
||||
defer {
|
||||
set.remove(coro)
|
||||
detach_waitable(task_state, task.handle)
|
||||
}
|
||||
for ;; {
|
||||
let subscribers = task_state.subscribers
|
||||
guard! subscribers.get(task.handle) is None
|
||||
subscribers.set(task.handle, subscriber)
|
||||
waitable_join(task.handle, waitable_set.0)
|
||||
if suspend_check_cancel() is Cancelled {
|
||||
protect_from_cancel(() => {
|
||||
detach_waitable(task_state, task.handle)
|
||||
// Consume a delivered terminal event before requesting cancellation:
|
||||
// cancelling an already terminal canonical operation traps.
|
||||
if subscriber.event is Some(Subtask(i, state)) {
|
||||
guard! i == task.handle
|
||||
settle_arguments(state)
|
||||
match state {
|
||||
Returned => {
|
||||
drop_returned_result()
|
||||
return
|
||||
}
|
||||
Cancelled_before_started | Cancelled_before_returned => return
|
||||
Starting | Started => subscriber.event = None
|
||||
}
|
||||
}
|
||||
let state = task.cancel()
|
||||
settle_arguments(state)
|
||||
match state {
|
||||
Returned => drop_returned_result()
|
||||
Cancelled_before_started | Cancelled_before_returned => ()
|
||||
Starting | Started => panic()
|
||||
}
|
||||
})
|
||||
raise_cancellation_signal()
|
||||
}
|
||||
|
||||
task_state.subscribers.remove(task.handle)
|
||||
|
||||
// Subsequent state, return if finished
|
||||
if subscriber.event is Some(Subtask(i, state)) {
|
||||
guard! i == task.handle
|
||||
settle_arguments(state)
|
||||
match state {
|
||||
Returned => return
|
||||
Cancelled_before_started => raise SubTaskCancelled(before_started=true)
|
||||
Cancelled_before_returned =>
|
||||
raise SubTaskCancelled(before_started=false)
|
||||
_ => subscriber.event = None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
#doc(hidden)
|
||||
pub async fn suspend_for_future_read(idx : Int, val : Int) -> Unit {
|
||||
let event = if val == -1 {
|
||||
waitable_event(idx, None)
|
||||
} else {
|
||||
let result = FutureReadResult::from(val)
|
||||
waitable_event(idx, Some(FutureRead(idx, result)))
|
||||
}
|
||||
guard! event is FutureRead(i, result) && i == idx
|
||||
match result {
|
||||
Completed => return
|
||||
Cancelled => raise FutureReadError::Cancelled
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
#doc(hidden)
|
||||
pub fn cancel_future_read(
|
||||
owner_task : Int,
|
||||
idx : Int,
|
||||
cancel : () -> Int,
|
||||
) -> Bool {
|
||||
let event = cancel_waitable_event(owner_task, idx, () => {
|
||||
FutureRead(idx, FutureReadResult::from(cancel()))
|
||||
})
|
||||
guard! event is FutureRead(i, result) && i == idx
|
||||
match result {
|
||||
Completed => true
|
||||
Cancelled => false
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
#doc(hidden)
|
||||
pub fn cancel_stream_read(
|
||||
owner_task : Int,
|
||||
idx : Int,
|
||||
cancel : () -> Int,
|
||||
) -> Int {
|
||||
let event = cancel_waitable_event(owner_task, idx, () => {
|
||||
StreamRead(idx, StreamResult::from(cancel()))
|
||||
})
|
||||
guard! event is StreamRead(i, result) && i == idx
|
||||
result.progress
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
#doc(hidden)
|
||||
pub fn cancel_stream_write(idx : Int, cancel : () -> Int) -> Int {
|
||||
let event = cancel_waitable_event(current_component_task_token(), idx, () => {
|
||||
StreamWrite(idx, StreamResult::from(cancel()))
|
||||
})
|
||||
guard! event is StreamWrite(i, result) && i == idx
|
||||
result.progress
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
#doc(hidden)
|
||||
pub async fn suspend_for_future_write_terminal(idx : Int, val : Int) -> Bool? {
|
||||
let event = if val == -1 {
|
||||
waitable_event(idx, None)
|
||||
} else {
|
||||
let result = FutureWriteResult::from(val)
|
||||
waitable_event(idx, Some(FutureWrite(idx, result)))
|
||||
}
|
||||
guard! event is FutureWrite(i, result) && i == idx
|
||||
match result {
|
||||
Completed => Some(true)
|
||||
Dropped => Some(false)
|
||||
Cancelled => None
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
#doc(hidden)
|
||||
pub async fn suspend_for_stream_read(idx : Int, val : Int) -> (Int, Bool) {
|
||||
let event = if val == -1 {
|
||||
waitable_event(idx, None)
|
||||
} else {
|
||||
let result = StreamResult::from(val)
|
||||
waitable_event(idx, Some(StreamRead(idx, result)))
|
||||
}
|
||||
guard! event is StreamRead(i, { progress, copy_result }) && i == idx
|
||||
match copy_result {
|
||||
Completed => return (progress, false)
|
||||
Dropped => return (progress, true)
|
||||
Cancelled =>
|
||||
if progress > 0 {
|
||||
return (progress, false)
|
||||
} else {
|
||||
raise StreamReadCancelled
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
#doc(hidden)
|
||||
pub async fn suspend_for_stream_write(idx : Int, val : Int) -> (Int, Bool) {
|
||||
let event = if val == -1 {
|
||||
waitable_event(idx, None)
|
||||
} else {
|
||||
let result = StreamResult::from(val)
|
||||
waitable_event(idx, Some(StreamWrite(idx, result)))
|
||||
}
|
||||
guard! event is StreamWrite(i, { progress, copy_result }) && i == idx
|
||||
match copy_result {
|
||||
Completed => return (progress, false)
|
||||
Dropped => return (progress, true)
|
||||
Cancelled => return (progress, false)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub suberror OpCancelled {
|
||||
SubTaskCancelled(before_started~ : Bool)
|
||||
StreamReadCancelled
|
||||
}
|
||||
|
||||
///|
|
||||
pub(all) suberror FutureReadError {
|
||||
Cancelled
|
||||
Dropped
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
pub(all) suberror EndpointBusy {
|
||||
Read
|
||||
Write
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Copyright 2025 International Digital Economy Academy
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
///|
|
||||
/// A mutex for synchronization between tasks.
|
||||
#valtype
|
||||
pub struct Mutex {
|
||||
priv semaphore : Semaphore
|
||||
}
|
||||
|
||||
///|
|
||||
/// Create a mutex in the released state.
|
||||
pub fn Mutex::Mutex() -> Mutex {
|
||||
{ semaphore: Semaphore(1) }
|
||||
}
|
||||
|
||||
///|
|
||||
/// Acquire the mutex in FIFO order.
|
||||
pub async fn Mutex::acquire(self : Mutex) -> Unit noraise {
|
||||
self.semaphore.acquire()
|
||||
}
|
||||
|
||||
///|
|
||||
/// Try to acquire the mutex without waiting.
|
||||
pub fn Mutex::try_acquire(self : Mutex) -> Bool {
|
||||
self.semaphore.try_acquire()
|
||||
}
|
||||
|
||||
///|
|
||||
/// Release the mutex. The mutex must already be acquired.
|
||||
pub fn Mutex::release(self : Mutex) -> Unit {
|
||||
self.semaphore.release()
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// Copyright 2025 International Digital Economy Academy
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
///|
|
||||
async fn[T] async_suspend(cb : ((T) -> Unit) -> Unit) -> T noraise + nocancel = "%async.suspend"
|
||||
|
||||
///|
|
||||
fn run_async(f : async () -> Unit noraise + nocancel) = "%async.run"
|
||||
|
||||
///|
|
||||
/// Deliver cancellation from the runtime, or resume it after boundary cleanup.
|
||||
#internal(wit_bindgen, "runtime and generated binding code only")
|
||||
#doc(hidden)
|
||||
pub async fn[X] raise_cancellation_signal() -> X noraise = "%async.raise_cancellation_signal"
|
||||
|
||||
///|
|
||||
async fn[X] capture_cancellation(
|
||||
f : async () -> X,
|
||||
handler~ : async () -> X nocancel,
|
||||
) -> X nocancel = "%async.capture_cancellation"
|
||||
@@ -0,0 +1,211 @@
|
||||
// Copyright 2025 International Digital Economy Academy
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
///|
|
||||
priv enum PromiseState[X] {
|
||||
Pending
|
||||
Completed(X)
|
||||
Failed(Error)
|
||||
Closed
|
||||
ReaderDropped
|
||||
Consumed
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct PromiseCell[X] {
|
||||
mut state : PromiseState[X]
|
||||
ready : Semaphore
|
||||
cleanup : ((X) -> Unit)?
|
||||
mut reading : Bool
|
||||
}
|
||||
|
||||
///|
|
||||
/// The local producer side of a one-shot `Future[X]`.
|
||||
///
|
||||
/// This is a MoonBit coordination value, not a component-model future writable
|
||||
/// endpoint. Conversion to a component future remains generated at an FFI site.
|
||||
pub struct Promise[X] {
|
||||
priv cell : Ref[PromiseCell[X]]
|
||||
}
|
||||
|
||||
///|
|
||||
pub(all) suberror PromiseClosed derive(Debug)
|
||||
|
||||
///|
|
||||
#deprecated
|
||||
pub extend PromiseClosed with Debug::{to_repr}
|
||||
|
||||
///|
|
||||
fn[X] new_future_promise(cleanup : ((X) -> Unit)?) -> (Future[X], Promise[X]) {
|
||||
let cell : Ref[PromiseCell[X]] = {
|
||||
val: {
|
||||
state: Pending,
|
||||
ready: Semaphore(1, initial_value=0),
|
||||
cleanup,
|
||||
reading: false,
|
||||
},
|
||||
}
|
||||
({ inner: Promised(cell) }, { cell, })
|
||||
}
|
||||
|
||||
///|
|
||||
/// Create a local one-shot Future/Promise pair.
|
||||
pub fn[X] Future::new() -> (Future[X], Promise[X]) {
|
||||
new_future_promise(None)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Create a local one-shot Future/Promise pair with value-discard cleanup.
|
||||
///
|
||||
/// The cleanup callback runs when the promise completed successfully but the
|
||||
/// future is dropped before consuming the value.
|
||||
pub fn[X] Future::new_with_cleanup(
|
||||
cleanup : (X) -> Unit,
|
||||
) -> (Future[X], Promise[X]) {
|
||||
new_future_promise(Some(cleanup))
|
||||
}
|
||||
|
||||
///|
|
||||
/// Complete the paired future with `value`.
|
||||
///
|
||||
/// `true` means the future accepted ownership. `false` means its reader was
|
||||
/// already dropped and the caller retains ownership of `value`.
|
||||
pub fn[X] Promise::complete(self : Promise[X], value : X) -> Bool {
|
||||
match self.cell.val.state {
|
||||
Pending => {
|
||||
self.cell.val.state = Completed(value)
|
||||
self.cell.val.ready.release()
|
||||
true
|
||||
}
|
||||
ReaderDropped => false
|
||||
Completed(_) | Failed(_) | Closed | Consumed =>
|
||||
abort("promise already settled")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Complete the paired future with an error raised by `Future::get`.
|
||||
pub fn[X] Promise::fail(self : Promise[X], error : Error) -> Bool {
|
||||
match self.cell.val.state {
|
||||
Pending => {
|
||||
self.cell.val.state = Failed(error)
|
||||
self.cell.val.ready.release()
|
||||
true
|
||||
}
|
||||
ReaderDropped => false
|
||||
Completed(_) | Failed(_) | Closed | Consumed =>
|
||||
abort("promise already settled")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Close the paired future without producing a value.
|
||||
///
|
||||
/// A local waiter observes `PromiseClosed`. An outgoing component future still
|
||||
/// cannot represent this terminal state and follows the bridge's no-value
|
||||
/// failure policy if it has already crossed an FFI boundary.
|
||||
pub fn[X] Promise::close(self : Promise[X]) -> Bool {
|
||||
match self.cell.val.state {
|
||||
Pending => {
|
||||
self.cell.val.state = Closed
|
||||
self.cell.val.ready.release()
|
||||
true
|
||||
}
|
||||
ReaderDropped => false
|
||||
Completed(_) | Failed(_) | Closed | Consumed =>
|
||||
abort("promise already settled")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] consume_promised_future(cell : Ref[PromiseCell[X]]) -> X raise {
|
||||
match cell.val.state {
|
||||
Completed(value) => {
|
||||
cell.val.state = Consumed
|
||||
value
|
||||
}
|
||||
Failed(error) => {
|
||||
cell.val.state = Consumed
|
||||
raise error
|
||||
}
|
||||
Closed => {
|
||||
cell.val.state = Consumed
|
||||
raise PromiseClosed
|
||||
}
|
||||
Pending => panic()
|
||||
ReaderDropped => raise FutureReadError::Dropped
|
||||
Consumed => abort("future already consumed")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
async fn[X] promised_future_get(cell : Ref[PromiseCell[X]]) -> X {
|
||||
if cell.val.reading {
|
||||
abort("future read already in progress")
|
||||
}
|
||||
match cell.val.state {
|
||||
Pending => {
|
||||
cell.val.reading = true
|
||||
{
|
||||
errdefer {
|
||||
cell.val.reading = false
|
||||
if cell.val.state is Pending {
|
||||
cell.val.state = ReaderDropped
|
||||
}
|
||||
}
|
||||
cell.val.ready.acquire()
|
||||
}
|
||||
cell.val.reading = false
|
||||
consume_promised_future(cell)
|
||||
}
|
||||
Completed(_) | Failed(_) | Closed => consume_promised_future(cell)
|
||||
ReaderDropped => consume_promised_future(cell)
|
||||
Consumed => abort("future already consumed")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] promised_future_drop(
|
||||
cell : Ref[PromiseCell[X]],
|
||||
fallback_cleanup : ((X) -> Unit)?,
|
||||
) -> Unit {
|
||||
if cell.val.reading {
|
||||
match cell.val.state {
|
||||
Pending => {
|
||||
cell.val.state = ReaderDropped
|
||||
cell.val.ready.release()
|
||||
}
|
||||
// Once settlement assigned a result, the waiting reader owns it.
|
||||
Completed(_) | Failed(_) | Closed => ()
|
||||
ReaderDropped | Consumed => ()
|
||||
}
|
||||
return
|
||||
}
|
||||
match cell.val.state {
|
||||
Pending => cell.val.state = ReaderDropped
|
||||
Completed(value) => {
|
||||
cell.val.state = Consumed
|
||||
match cell.val.cleanup {
|
||||
Some(cleanup) => cleanup(value)
|
||||
None =>
|
||||
match fallback_cleanup {
|
||||
Some(cleanup) => cleanup(value)
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
Failed(_) | Closed => cell.val.state = Consumed
|
||||
ReaderDropped | Consumed => ()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// Copyright 2025 International Digital Economy Academy
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
///|
|
||||
priv struct Scheduler {
|
||||
mut coro_id : Int
|
||||
mut curr_coro : Coroutine?
|
||||
}
|
||||
|
||||
///|
|
||||
/// The per-component-task part of the scheduler. Coroutines retain this lane,
|
||||
/// not `ComponentTaskState`, so a retired task cannot be kept alive by an RC
|
||||
/// cycle through its registry entry or subscribers.
|
||||
priv struct TaskLane {
|
||||
mut blocking : Int
|
||||
run_later : @deque.Deque[Coroutine]
|
||||
mut wakeup : TaskWakeup?
|
||||
}
|
||||
|
||||
///|
|
||||
let scheduler : Scheduler = { coro_id: 0, curr_coro: None }
|
||||
|
||||
///|
|
||||
fn current_coroutine() -> Coroutine {
|
||||
scheduler.curr_coro.unwrap()
|
||||
}
|
||||
|
||||
///|
|
||||
fn enqueue(coro : Coroutine) -> Unit {
|
||||
coro.lane.run_later.push_back(coro)
|
||||
}
|
||||
|
||||
///|
|
||||
fn has_immediately_ready_task(lane : TaskLane) -> Bool {
|
||||
!lane.run_later.is_empty()
|
||||
}
|
||||
|
||||
///|
|
||||
fn no_more_work(lane : TaskLane) -> Bool {
|
||||
lane.blocking == 0 && lane.run_later.is_empty()
|
||||
}
|
||||
|
||||
///|
|
||||
/// Run one fair scheduling round for a component task. Coroutines woken or
|
||||
/// spawned during this round are left for the next round so the component
|
||||
/// event loop gets a chance to poll completed waitables.
|
||||
fn reschedule(lane : TaskLane) -> Unit {
|
||||
let count = lane.run_later.length()
|
||||
for _ in 0..<count {
|
||||
guard lane.run_later.pop_front() is Some(coro) else { break }
|
||||
coro.ready = false
|
||||
guard coro.state is Suspend(cont) else { }
|
||||
coro.state = Running
|
||||
let last_coro = scheduler.curr_coro
|
||||
scheduler.curr_coro = Some(coro)
|
||||
if coro.cancelled && !coro.shielded {
|
||||
cont(Cancelled)
|
||||
} else {
|
||||
cont(Continue)
|
||||
}
|
||||
scheduler.curr_coro = last_coro
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// Copyright 2025 International Digital Economy Academy
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
///|
|
||||
priv struct SemaphoreWaiter {
|
||||
// Once a permit is assigned, cancellation must not lose it before the
|
||||
// waiter resumes. This matches moonbitlang/async's semaphore semantics.
|
||||
mut acquired : Bool
|
||||
mut coro : Coroutine?
|
||||
}
|
||||
|
||||
///|
|
||||
pub struct Semaphore {
|
||||
size : Int
|
||||
priv mut value : Int
|
||||
priv waiters : @deque.Deque[SemaphoreWaiter]
|
||||
}
|
||||
|
||||
///|
|
||||
/// Create a semaphore with at most `size` permits.
|
||||
///
|
||||
/// The initial number of available permits is `initial_value`, or `size` when
|
||||
/// omitted.
|
||||
#alias(new, deprecated)
|
||||
pub fn Semaphore::Semaphore(
|
||||
size : Int,
|
||||
initial_value? : Int = size,
|
||||
) -> Semaphore {
|
||||
if size <= 0 {
|
||||
abort("size of semaphore must be positive")
|
||||
}
|
||||
guard! initial_value >= 0 && initial_value <= size
|
||||
{ value: initial_value, size, waiters: Deque([]) }
|
||||
}
|
||||
|
||||
///|
|
||||
/// Release one permit. Waiting coroutines acquire permits in FIFO order.
|
||||
///
|
||||
/// Each call must correspond one-to-one with a successful `acquire`. Calling
|
||||
/// `release` without owning a permit is invalid.
|
||||
pub fn Semaphore::release(self : Semaphore) -> Unit {
|
||||
if self.value >= self.size {
|
||||
abort("semaphore: too many release")
|
||||
}
|
||||
while self.waiters.pop_front() is Some(waiter) {
|
||||
if waiter.coro is Some(coro) {
|
||||
waiter.acquired = true
|
||||
coro.wake()
|
||||
break
|
||||
}
|
||||
} nobreak {
|
||||
self.value += 1
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Acquire one permit, suspending in FIFO order when none is available.
|
||||
pub async fn Semaphore::acquire(self : Semaphore) -> Unit noraise {
|
||||
if self.value > 0 {
|
||||
self.value -= 1
|
||||
} else {
|
||||
let waiter = { coro: Some(current_coroutine()), acquired: false }
|
||||
self.waiters.push_back(waiter)
|
||||
match suspend_check_cancel() {
|
||||
Continue => ()
|
||||
Cancelled if waiter.acquired => ()
|
||||
Cancelled => {
|
||||
waiter.coro = None
|
||||
raise_cancellation_signal()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Try to acquire one permit without suspending.
|
||||
pub fn Semaphore::try_acquire(self : Semaphore) -> Bool {
|
||||
if self.value > 0 {
|
||||
self.value -= 1
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// Copyright 2025 International Digital Economy Academy
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
///|
|
||||
/// `Task[X]` represents a running task with result type `X`,
|
||||
/// it can be used to wait and retrieve the result value of the task.
|
||||
pub struct Task[X] {
|
||||
priv value : Ref[X?]
|
||||
priv coro : Coroutine
|
||||
}
|
||||
|
||||
///|
|
||||
/// An observed task terminated by cancellation. This is an ordinary error in
|
||||
/// the waiter, distinct from cancellation of the waiter itself.
|
||||
pub suberror TaskCancelled derive(Debug)
|
||||
|
||||
///|
|
||||
#deprecated
|
||||
pub extend TaskCancelled with Debug::{to_repr}
|
||||
|
||||
///|
|
||||
/// Wait for a task and retrieve its result value.
|
||||
/// If the task fails, `wait` will also fail with the same error.
|
||||
///
|
||||
/// If the target task was cancelled, `wait` raises `TaskCancelled`.
|
||||
/// Cancellation of the current task propagates as a cancellation signal.
|
||||
pub async fn[X] Task::wait(self : Task[X]) -> X {
|
||||
match self.coro.wait() {
|
||||
Continue => self.value.val.unwrap()
|
||||
Cancelled => raise TaskCancelled::TaskCancelled
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Try to obtain the result of the task.
|
||||
/// If the task already terminated, its result value will be returned.
|
||||
/// If the task already failed, `try_wait` will fail immediately.
|
||||
/// If the task is still running, `try_wait` returns `None`.
|
||||
/// `try_wait` is a synchoronous function: it never blocks.
|
||||
pub fn[X] Task::try_wait(self : Task[X]) -> X? raise {
|
||||
self.coro.check_error()
|
||||
self.value.val
|
||||
}
|
||||
|
||||
///|
|
||||
/// Cancel a running task. Cancelling a terminated task has no effect.
|
||||
/// Subsequent attempt to wait for a cancelled task will receive error.
|
||||
pub fn[X] Task::cancel(self : Task[X]) -> Unit {
|
||||
self.coro.cancel()
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
// Copyright 2025 International Digital Economy Academy
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
///|
|
||||
priv enum TaskGroupState {
|
||||
Done
|
||||
Fail(Error)
|
||||
Cancelled
|
||||
Running
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct GroupDeferBlock(async () -> Unit nocancel)
|
||||
|
||||
///|
|
||||
/// A `TaskGroup` can be used to spawn children tasks that run in parallel.
|
||||
/// Task groups implements *structured concurrency*:
|
||||
/// a task group will only return after all its children task terminates.
|
||||
///
|
||||
/// Task groups also handles *error propagation*:
|
||||
/// by default, if any child task raises error,
|
||||
/// the whole task group will also raise that error,
|
||||
/// and all other remaining child tasks will be cancelled.
|
||||
///
|
||||
/// The type parameter `X` in `TaskGroup[X]` is the result type of the group,
|
||||
/// see `with_task_group` for more detail.
|
||||
pub struct TaskGroup[X] {
|
||||
priv children : Set[Coroutine]
|
||||
priv parent : Coroutine
|
||||
priv mut waiting : Int
|
||||
priv mut state : TaskGroupState
|
||||
priv mut result : X?
|
||||
priv group_defer : Array[GroupDeferBlock]
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] TaskGroup::spawn_coroutine(
|
||||
self : TaskGroup[X],
|
||||
f : async () -> Unit,
|
||||
no_wait~ : Bool,
|
||||
allow_failure~ : Bool,
|
||||
) -> Coroutine {
|
||||
guard self.state is Running || !self.children.is_empty() else {
|
||||
abort("trying to spawn from a terminated task group")
|
||||
}
|
||||
if !no_wait {
|
||||
self.waiting += 1
|
||||
}
|
||||
async fn worker() {
|
||||
let coro = current_coroutine()
|
||||
defer {
|
||||
self.children.remove(coro)
|
||||
if !no_wait {
|
||||
self.waiting -= 1
|
||||
if self.waiting == 0 && self.state is Running {
|
||||
for child in self.children {
|
||||
child.cancel()
|
||||
}
|
||||
self.state = Done
|
||||
}
|
||||
}
|
||||
if self.children.is_empty() {
|
||||
self.parent.wake()
|
||||
}
|
||||
}
|
||||
f() catch {
|
||||
err if allow_failure => raise err
|
||||
err => {
|
||||
if self.state is Running {
|
||||
for child in self.children {
|
||||
child.cancel()
|
||||
}
|
||||
self.state = Fail(err)
|
||||
} else {
|
||||
self.state = Fail(err)
|
||||
}
|
||||
raise err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let coro = spawn(worker)
|
||||
self.children.add(coro)
|
||||
if !(self.state is Running) {
|
||||
coro.cancel()
|
||||
}
|
||||
coro
|
||||
}
|
||||
|
||||
///|
|
||||
/// Spawn a child task in a task group, and run it asynchronously in the background.
|
||||
///
|
||||
/// Unless `no_wait` (`false` by default) is `true`,
|
||||
/// the task group will wait for this task to complete before normal exit.
|
||||
/// No matter what the value of `no_wait` is,
|
||||
/// `with_task_group` will only return after all child tasks terminate.
|
||||
/// The task will be cancelled automatically if it is still running
|
||||
/// when the task group wishes to terminate.
|
||||
///
|
||||
/// Unless `allow_failure` (`false` by default) is `true`,
|
||||
/// the whole task group will also fail if the spawned task fails,
|
||||
/// other tasks in the group will be cancelled in this case.
|
||||
///
|
||||
/// Cancelled tasks are not considered failing. A normal error raised during
|
||||
/// cancellation cleanup is still considered a failure.
|
||||
///
|
||||
/// A task spawned while the group is cancelling still starts, but begins in a
|
||||
/// cancelled state so its entry cleanup can run. Spawning after the group has
|
||||
/// terminated or from a group defer is invalid and aborts.
|
||||
///
|
||||
/// It is undefined whether the child task will start running immediately
|
||||
/// before `spawn_bg` returns.
|
||||
pub fn[X] TaskGroup::spawn_bg(
|
||||
self : TaskGroup[X],
|
||||
f : async () -> Unit,
|
||||
no_wait? : Bool = false,
|
||||
allow_failure? : Bool = false,
|
||||
) -> Unit {
|
||||
ignore(self.spawn_coroutine(f, no_wait~, allow_failure~))
|
||||
}
|
||||
|
||||
///|
|
||||
/// Spawn a child task in a task group, compute a result asynchronously.
|
||||
/// A task handle will be returned, the result value of the task can be waited
|
||||
/// and retrieved using `.wait()`, or cancelled using `.cancel()`.
|
||||
///
|
||||
/// Unless `no_wait` (`false` by default) is `true`,
|
||||
/// the task group will wait for this task to complete before normal exit.
|
||||
/// No matter what the value of `no_wait` is,
|
||||
/// `with_task_group` will only return after all child tasks terminate.
|
||||
/// The task will be cancelled automatically if it is still running
|
||||
/// when the task group wishes to terminate.
|
||||
///
|
||||
/// Unless `allow_failure` (`false` by default) is `true`,
|
||||
/// the whole task group will also fail if the spawned task fails,
|
||||
/// other tasks in the group will be cancelled in this case.
|
||||
///
|
||||
/// Cancelled tasks are not considered failing. A normal error raised during
|
||||
/// cancellation cleanup is still considered a failure.
|
||||
///
|
||||
/// A task spawned while the group is cancelling still starts, but begins in a
|
||||
/// cancelled state so its entry cleanup can run. Spawning after the group has
|
||||
/// terminated or from a group defer is invalid and aborts.
|
||||
///
|
||||
/// It is undefined whether the child task will start running immediately
|
||||
/// before `spawn` returns.
|
||||
pub fn[G, X] TaskGroup::spawn(
|
||||
self : TaskGroup[G],
|
||||
f : async () -> X,
|
||||
no_wait? : Bool = false,
|
||||
allow_failure? : Bool = false,
|
||||
) -> Task[X] {
|
||||
let value = @ref.new(Option::None)
|
||||
let coro = self.spawn_coroutine(
|
||||
() => value.val = Some(f()),
|
||||
no_wait~,
|
||||
allow_failure~,
|
||||
)
|
||||
{ value, coro }
|
||||
}
|
||||
|
||||
///|
|
||||
/// Attach a defer block, represented as a cleanup function, to a task group.
|
||||
/// The cleanup function runs after every child task has terminated. Spawning a
|
||||
/// new child from a group defer is invalid and aborts.
|
||||
/// Group scoped defer blocks are executed in FILO order, just like normal `defer`.
|
||||
/// `with_task_group` will only exit after all group defer blocks terminate.
|
||||
///
|
||||
/// Group defer blocks must be `nocancel`. Use `protect_from_cancel` when
|
||||
/// running cancellable operations in a group defer.
|
||||
/// It is highly recommended to add a hard timeout to async defer block in this case,
|
||||
/// to avoid infinite hanging due to blocked operation.
|
||||
pub fn[X] TaskGroup::add_defer(
|
||||
self : TaskGroup[X],
|
||||
block : async () -> Unit nocancel,
|
||||
) -> Unit {
|
||||
guard self.state is Running else {
|
||||
abort("trying to attach defer to a terminated task group")
|
||||
}
|
||||
self.group_defer.push(GroupDeferBlock(block))
|
||||
}
|
||||
|
||||
///|
|
||||
/// `with_task_group(f)` creates a new task group and run `f` with the new group.
|
||||
/// `f` itself will be run in a child task of the new group.
|
||||
/// `with_task_group` exits after all the whole group terminates,
|
||||
/// which means all child tasks in the group have terminated, including `f`.
|
||||
///
|
||||
/// If all children task terminate successfully,
|
||||
/// `with_task_group` will return the result of `f`.
|
||||
pub async fn[X] with_task_group(f : async (TaskGroup[X]) -> X) -> X {
|
||||
let tg = {
|
||||
children: Set([]),
|
||||
parent: current_coroutine(),
|
||||
waiting: 0,
|
||||
state: Running,
|
||||
result: None,
|
||||
group_defer: [],
|
||||
}
|
||||
let curr = current_coroutine()
|
||||
let prev = curr.spawner
|
||||
curr.spawner = Some(fn(child) { tg.spawn_bg(child) })
|
||||
defer {
|
||||
curr.spawner = prev
|
||||
}
|
||||
tg.spawn_bg(() => {
|
||||
let value = f(tg)
|
||||
if tg.result is None {
|
||||
tg.result = Some(value)
|
||||
}
|
||||
})
|
||||
match suspend_check_cancel() {
|
||||
Continue => ()
|
||||
Cancelled => {
|
||||
if tg.state is Running {
|
||||
tg.state = Cancelled
|
||||
}
|
||||
if !tg.children.is_empty() {
|
||||
for child in tg.children {
|
||||
child.cancel()
|
||||
}
|
||||
protect_from_cancel(() => suspend())
|
||||
}
|
||||
}
|
||||
}
|
||||
guard! tg.children.is_empty()
|
||||
while tg.group_defer.pop() is Some(defer_block) {
|
||||
defer_block() catch {
|
||||
err => if tg.state is Done { tg.state = Fail(err) }
|
||||
}
|
||||
}
|
||||
match tg.state {
|
||||
Done => tg.result.unwrap()
|
||||
Fail(err) => raise err
|
||||
Cancelled => raise_cancellation_signal()
|
||||
Running => panic()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Force a task group to terminate immediately with the given result value.
|
||||
/// All child tasks in the group, including potentially the current one,
|
||||
/// will be cancelled.
|
||||
pub async fn[X] TaskGroup::return_immediately(
|
||||
self : TaskGroup[X],
|
||||
value : X,
|
||||
) -> Unit noraise {
|
||||
if self.result is None {
|
||||
self.result = Some(value)
|
||||
}
|
||||
if self.state is Running {
|
||||
self.state = Done
|
||||
for child in self.children {
|
||||
child.cancel()
|
||||
}
|
||||
}
|
||||
check_cancellation()
|
||||
}
|
||||
@@ -0,0 +1,964 @@
|
||||
///|
|
||||
pub struct Sink[X] {
|
||||
priv write : async (ArrayView[X]) -> Int
|
||||
priv close : async () -> Unit
|
||||
priv is_open : () -> Bool
|
||||
priv has_cleanup : () -> Bool
|
||||
priv cleanup : ((X) -> Unit)?
|
||||
priv write_window_size : Int
|
||||
}
|
||||
|
||||
///|
|
||||
let default_sink_write_window_size : Int = 64
|
||||
|
||||
///|
|
||||
/// The write callback must either raise before consuming any value or return
|
||||
/// the number consumed. It must not raise after partial consumption because
|
||||
/// `ArrayView` cannot carry an ownership offset through an exception.
|
||||
/// The close callback must be idempotent.
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
pub fn[X] Sink::from_callbacks(
|
||||
write : async (ArrayView[X]) -> Int,
|
||||
close : async () -> Unit,
|
||||
is_open : () -> Bool,
|
||||
cleanup : ((X) -> Unit)?,
|
||||
write_window_size : Int,
|
||||
) -> Sink[X] {
|
||||
guard! write_window_size > 0
|
||||
{
|
||||
write,
|
||||
close,
|
||||
is_open,
|
||||
has_cleanup: () => cleanup is Some(_),
|
||||
cleanup,
|
||||
write_window_size,
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Consumes up to one bounded window and returns the number of values consumed.
|
||||
///
|
||||
/// Consumption includes values accepted by the peer and values recursively
|
||||
/// cleaned after the peer closes. Check `is_open()` to distinguish those cases.
|
||||
pub async fn[X] Sink::write(self : Sink[X], data : ArrayView[X]) -> Int {
|
||||
if data.length() == 0 {
|
||||
return 0
|
||||
}
|
||||
let length = if data.length() < self.write_window_size {
|
||||
data.length()
|
||||
} else {
|
||||
self.write_window_size
|
||||
}
|
||||
// The callback may suspend, so it must not retain the caller's borrowed view.
|
||||
let buffer = FixedArray::from_array(data[:length])
|
||||
let written = (self.write)(buffer[:])
|
||||
guard! written >= 0 && written <= length
|
||||
if !(self.is_open)() && written < length && (self.has_cleanup)() {
|
||||
self.cleanup_unaccepted(buffer[:], written)
|
||||
return length
|
||||
}
|
||||
written
|
||||
}
|
||||
|
||||
///|
|
||||
/// Writes one bounded window from an immutable byte view.
|
||||
///
|
||||
/// This is the byte-stream counterpart of `write(ArrayView[T])`. MoonBit keeps
|
||||
/// `BytesView` and `ArrayView[Byte]` as distinct types, so byte strings need a
|
||||
/// separate entry point until the language provides a shared read-only view.
|
||||
pub async fn Sink::write_bytes(self : Sink[Byte], data : BytesView) -> Int {
|
||||
if data.length() == 0 {
|
||||
return 0
|
||||
}
|
||||
let length = if data.length() < self.write_window_size {
|
||||
data.length()
|
||||
} else {
|
||||
self.write_window_size
|
||||
}
|
||||
let buffer = data[:length].to_fixedarray()
|
||||
let written = (self.write)(buffer[:])
|
||||
guard! written >= 0 && written <= length
|
||||
if !(self.is_open)() && written < length && (self.has_cleanup)() {
|
||||
self.cleanup_unaccepted(buffer[:], written)
|
||||
return length
|
||||
}
|
||||
written
|
||||
}
|
||||
|
||||
///|
|
||||
/// Returns whether the sink can still accept values from its peer.
|
||||
pub fn[X] Sink::is_open(self : Sink[X]) -> Bool {
|
||||
(self.is_open)()
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] Sink::cleanup_unaccepted(
|
||||
self : Sink[X],
|
||||
data : ArrayView[X],
|
||||
offset : Int,
|
||||
) -> Unit {
|
||||
match self.cleanup {
|
||||
Some(cleanup) =>
|
||||
for i in offset..<data.length() {
|
||||
cleanup(data[i])
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Sink::cleanup_unaccepted_bytes(
|
||||
self : Sink[Byte],
|
||||
data : BytesView,
|
||||
offset : Int,
|
||||
) -> Unit {
|
||||
match self.cleanup {
|
||||
Some(cleanup) =>
|
||||
for i in offset..<data.length() {
|
||||
cleanup(data[i])
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Writes the entire slice to the sink unless the sink closes first.
|
||||
///
|
||||
/// Returns `true` if all items were written while the sink remained open and
|
||||
/// `false` if the endpoint closed during the operation. When the sink has a
|
||||
/// cleanup callback, every item was either accepted or cleaned and must not be
|
||||
/// retried. Producers of explicitly managed resources must use such a sink.
|
||||
pub async fn[X] Sink::write_all(self : Sink[X], data : ArrayView[X]) -> Bool {
|
||||
let mut offset = 0
|
||||
for ;; {
|
||||
if offset >= data.length() {
|
||||
return true
|
||||
}
|
||||
let written = {
|
||||
errdefer self.cleanup_unaccepted(data, offset)
|
||||
self.write(data[offset:])
|
||||
}
|
||||
offset = offset + written
|
||||
if !self.is_open() {
|
||||
self.cleanup_unaccepted(data, offset)
|
||||
return false
|
||||
}
|
||||
guard! written > 0
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Writes the entire byte view unless the sink closes first.
|
||||
pub async fn Sink::write_all_bytes(self : Sink[Byte], data : BytesView) -> Bool {
|
||||
let mut offset = 0
|
||||
for ;; {
|
||||
if offset >= data.length() {
|
||||
return true
|
||||
}
|
||||
let written = {
|
||||
errdefer self.cleanup_unaccepted_bytes(data, offset)
|
||||
self.write_bytes(data[offset:])
|
||||
}
|
||||
offset = offset + written
|
||||
if !self.is_open() {
|
||||
self.cleanup_unaccepted_bytes(data, offset)
|
||||
return false
|
||||
}
|
||||
guard! written > 0
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Closes the writable end of the stream.
|
||||
///
|
||||
/// Closing is idempotent. A peer waiting for values observes the end of the
|
||||
/// stream after any values already accepted by the sink have been read.
|
||||
pub async fn[X] Sink::close(self : Sink[X]) -> Unit {
|
||||
(self.close)()
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct LocalFutureState[X] {
|
||||
mut value : X?
|
||||
mut closed : Bool
|
||||
cleanup : ((X) -> Unit)?
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] local_future_close(
|
||||
state : Ref[LocalFutureState[X]],
|
||||
fallback_cleanup : ((X) -> Unit)?,
|
||||
) -> Unit {
|
||||
if state.val.closed {
|
||||
return
|
||||
}
|
||||
match state.val.value {
|
||||
Some(value) => {
|
||||
state.val.value = None
|
||||
match state.val.cleanup {
|
||||
Some(cleanup) => cleanup(value)
|
||||
None =>
|
||||
match fallback_cleanup {
|
||||
Some(cleanup) => cleanup(value)
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
state.val.closed = true
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] local_future_get(state : Ref[LocalFutureState[X]]) -> X raise {
|
||||
match state.val.value {
|
||||
Some(value) => {
|
||||
state.val.value = None
|
||||
state.val.closed = true
|
||||
value
|
||||
}
|
||||
None => raise FutureReadError::Dropped
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct StreamPipeReader[X] {
|
||||
max : Int
|
||||
mut value : FixedArray[X]?
|
||||
mut ended : Bool
|
||||
mut coro : Coroutine?
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct StreamPipeWriter[X] {
|
||||
mut value : FixedArray[X]?
|
||||
mut accepted : Int
|
||||
mut coro : Coroutine?
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct StreamPipe[X] {
|
||||
capacity : Int
|
||||
chunks : @deque.Deque[FixedArray[X]]
|
||||
mut buffered : Int
|
||||
mut writer_closed : Bool
|
||||
mut reader_dropped : Bool
|
||||
mut cleanup : ((X) -> Unit)?
|
||||
mut head : FixedArray[X]?
|
||||
mut head_pos : Int
|
||||
readers : @deque.Deque[StreamPipeReader[X]]
|
||||
writers : @deque.Deque[StreamPipeWriter[X]]
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] wake_stream_pipe_reader(
|
||||
reader : StreamPipeReader[X],
|
||||
value : FixedArray[X]?,
|
||||
ended : Bool,
|
||||
) -> Unit {
|
||||
match reader.coro {
|
||||
Some(coro) => {
|
||||
reader.value = value
|
||||
reader.ended = ended
|
||||
reader.coro = None
|
||||
coro.wake()
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] wake_stream_pipe_writer(
|
||||
writer : StreamPipeWriter[X],
|
||||
accepted : Int,
|
||||
) -> Unit {
|
||||
match writer.coro {
|
||||
Some(coro) => {
|
||||
writer.accepted = accepted
|
||||
writer.value = None
|
||||
writer.coro = None
|
||||
coro.wake()
|
||||
}
|
||||
None => writer.value = None
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] take_stream_pipe_reader(
|
||||
pipe : Ref[StreamPipe[X]],
|
||||
) -> StreamPipeReader[X]? {
|
||||
while pipe.val.readers.pop_front() is Some(reader) {
|
||||
if reader.coro is Some(_) {
|
||||
return Some(reader)
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] take_stream_pipe_writer(
|
||||
pipe : Ref[StreamPipe[X]],
|
||||
) -> StreamPipeWriter[X]? {
|
||||
while pipe.val.writers.pop_front() is Some(writer) {
|
||||
if writer.coro is Some(_) && writer.value is Some(_) {
|
||||
return Some(writer)
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] fill_stream_pipe_from_writers(pipe : Ref[StreamPipe[X]]) -> Unit {
|
||||
if pipe.val.capacity <= 0 || pipe.val.writer_closed || pipe.val.reader_dropped {
|
||||
return
|
||||
}
|
||||
for ;; {
|
||||
let available = pipe.val.capacity - pipe.val.buffered
|
||||
if available <= 0 {
|
||||
return
|
||||
}
|
||||
guard take_stream_pipe_writer(pipe) is Some(writer) else { return }
|
||||
guard writer.value is Some(data) else { continue }
|
||||
let take = if available < data.length() { available } else { data.length() }
|
||||
let chunk = FixedArray::from_array(data[:take])
|
||||
pipe.val.chunks.push_back(chunk)
|
||||
pipe.val.buffered = pipe.val.buffered + take
|
||||
wake_stream_pipe_writer(writer, take)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] stream_pipe_drop_reader(pipe : Ref[StreamPipe[X]]) -> Unit {
|
||||
stream_pipe_drop_reader_with_cleanup(pipe, pipe.val.cleanup)
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] stream_pipe_drop_reader_with_cleanup(
|
||||
pipe : Ref[StreamPipe[X]],
|
||||
cleanup : ((X) -> Unit)?,
|
||||
) -> Unit {
|
||||
if pipe.val.reader_dropped {
|
||||
return
|
||||
}
|
||||
match cleanup {
|
||||
Some(cleanup) => {
|
||||
match pipe.val.head {
|
||||
Some(head) =>
|
||||
for i in pipe.val.head_pos..<head.length() {
|
||||
cleanup(head[i])
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
while pipe.val.chunks.pop_front() is Some(chunk) {
|
||||
for value in chunk {
|
||||
cleanup(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
pipe.val.head = None
|
||||
pipe.val.head_pos = 0
|
||||
pipe.val.chunks.clear()
|
||||
pipe.val.buffered = 0
|
||||
pipe.val.reader_dropped = true
|
||||
while pipe.val.readers.pop_front() is Some(reader) {
|
||||
wake_stream_pipe_reader(reader, None, true)
|
||||
}
|
||||
while pipe.val.writers.pop_front() is Some(writer) {
|
||||
let consumed = match (cleanup, writer.value) {
|
||||
(Some(cleanup), Some(data)) => {
|
||||
for value in data {
|
||||
cleanup(value)
|
||||
}
|
||||
data.length()
|
||||
}
|
||||
_ => 0
|
||||
}
|
||||
wake_stream_pipe_writer(writer, consumed)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] stream_pipe_reject_reader(
|
||||
pipe : Ref[StreamPipe[X]],
|
||||
fallback : (X) -> Unit,
|
||||
) -> Unit {
|
||||
if pipe.val.cleanup is None {
|
||||
pipe.val.cleanup = Some(fallback)
|
||||
}
|
||||
stream_pipe_drop_reader(pipe)
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] stream_pipe_close_writer(pipe : Ref[StreamPipe[X]]) -> Unit {
|
||||
if pipe.val.writer_closed {
|
||||
return
|
||||
}
|
||||
pipe.val.writer_closed = true
|
||||
while pipe.val.writers.pop_front() is Some(writer) {
|
||||
wake_stream_pipe_writer(writer, 0)
|
||||
}
|
||||
if pipe.val.buffered == 0 {
|
||||
while pipe.val.readers.pop_front() is Some(reader) {
|
||||
wake_stream_pipe_reader(reader, None, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
async fn[X] stream_pipe_write(
|
||||
pipe : Ref[StreamPipe[X]],
|
||||
data : ArrayView[X],
|
||||
) -> Int {
|
||||
if data.length() == 0 || pipe.val.writer_closed || pipe.val.reader_dropped {
|
||||
return 0
|
||||
}
|
||||
match take_stream_pipe_reader(pipe) {
|
||||
Some(reader) => {
|
||||
let take = if reader.max < data.length() {
|
||||
reader.max
|
||||
} else {
|
||||
data.length()
|
||||
}
|
||||
let chunk = FixedArray::from_array(data[:take])
|
||||
wake_stream_pipe_reader(reader, Some(chunk), false)
|
||||
return take
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
if pipe.val.capacity > 0 && pipe.val.buffered < pipe.val.capacity {
|
||||
let available = pipe.val.capacity - pipe.val.buffered
|
||||
let take = if available < data.length() { available } else { data.length() }
|
||||
let chunk = FixedArray::from_array(data[:take])
|
||||
pipe.val.chunks.push_back(chunk)
|
||||
pipe.val.buffered = pipe.val.buffered + take
|
||||
return take
|
||||
}
|
||||
let writer = StreamPipeWriter::{
|
||||
value: Some(FixedArray::from_array(data)),
|
||||
accepted: 0,
|
||||
coro: Some(current_coroutine()),
|
||||
}
|
||||
pipe.val.writers.push_back(writer)
|
||||
match suspend_check_cancel() {
|
||||
Continue => ()
|
||||
Cancelled if writer.coro is None => return writer.accepted
|
||||
Cancelled => {
|
||||
writer.coro = None
|
||||
writer.value = None
|
||||
raise_cancellation_signal()
|
||||
}
|
||||
}
|
||||
writer.value = None
|
||||
writer.accepted
|
||||
}
|
||||
|
||||
///|
|
||||
async fn[X] stream_pipe_read(
|
||||
pipe : Ref[StreamPipe[X]],
|
||||
count : Int,
|
||||
) -> FixedArray[X]? {
|
||||
if count <= 0 {
|
||||
return Some([])
|
||||
}
|
||||
for ;; {
|
||||
if pipe.val.reader_dropped {
|
||||
return None
|
||||
}
|
||||
match pipe.val.head {
|
||||
Some(head) => {
|
||||
let available = head.length() - pipe.val.head_pos
|
||||
let take = if count < available { count } else { available }
|
||||
let result = FixedArray::from_array(
|
||||
head[pipe.val.head_pos:pipe.val.head_pos + take],
|
||||
)
|
||||
pipe.val.head_pos = pipe.val.head_pos + take
|
||||
pipe.val.buffered = pipe.val.buffered - take
|
||||
if pipe.val.head_pos >= head.length() {
|
||||
pipe.val.head = None
|
||||
pipe.val.head_pos = 0
|
||||
}
|
||||
fill_stream_pipe_from_writers(pipe)
|
||||
return Some(result)
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
if pipe.val.chunks.pop_front() is Some(chunk) {
|
||||
pipe.val.head = Some(chunk)
|
||||
pipe.val.head_pos = 0
|
||||
continue
|
||||
}
|
||||
match take_stream_pipe_writer(pipe) {
|
||||
Some(writer) => {
|
||||
guard writer.value is Some(data) else { continue }
|
||||
let take = if count < data.length() { count } else { data.length() }
|
||||
let result = FixedArray::from_array(data[:take])
|
||||
wake_stream_pipe_writer(writer, take)
|
||||
return Some(result)
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
if pipe.val.writer_closed {
|
||||
return None
|
||||
}
|
||||
let reader = StreamPipeReader::{
|
||||
max: count,
|
||||
value: None,
|
||||
ended: false,
|
||||
coro: Some(current_coroutine()),
|
||||
}
|
||||
pipe.val.readers.push_back(reader)
|
||||
if suspend_check_cancel() is Cancelled {
|
||||
reader.coro = None
|
||||
match reader.value {
|
||||
Some(value) => return Some(value)
|
||||
None if reader.ended => return None
|
||||
None => raise_cancellation_signal()
|
||||
}
|
||||
}
|
||||
match reader.value {
|
||||
Some(value) => return Some(value)
|
||||
None if reader.ended => return None
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct FutureSource[X] {
|
||||
get : async () -> X
|
||||
close : async () -> Unit
|
||||
close_sync : () -> Unit
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct FutureProducerState[X] {
|
||||
mut producer : (async () -> X)?
|
||||
mut on_unstarted_drop : (() -> Unit)?
|
||||
}
|
||||
|
||||
///|
|
||||
priv enum FutureState[X] {
|
||||
Source(FutureSource[X])
|
||||
Local(Ref[LocalFutureState[X]])
|
||||
Pending(Ref[FutureProducerState[X]])
|
||||
Promised(Ref[PromiseCell[X]])
|
||||
}
|
||||
|
||||
///|
|
||||
pub struct Future[X] {
|
||||
priv inner : FutureState[X]
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn[X] Future::ready_with_cleanup(
|
||||
value : X,
|
||||
cleanup : (X) -> Unit,
|
||||
) -> Future[X] {
|
||||
let state : Ref[LocalFutureState[X]] = {
|
||||
val: { value: Some(value), closed: false, cleanup: Some(cleanup) },
|
||||
}
|
||||
{ inner: Local(state) }
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn[X] Future::ready(value : X) -> Future[X] {
|
||||
let state : Ref[LocalFutureState[X]] = {
|
||||
val: { value: Some(value), closed: false, cleanup: None },
|
||||
}
|
||||
{ inner: Local(state) }
|
||||
}
|
||||
|
||||
///|
|
||||
/// Creates a lazy future from an async producer.
|
||||
///
|
||||
/// `on_unstarted_drop`, when present, releases resources captured by a producer
|
||||
/// that is discarded before its first `get`. Once the producer starts, it owns
|
||||
/// its runtime cleanup and this callback is never invoked.
|
||||
pub fn[X] Future::from(
|
||||
producer : async () -> X,
|
||||
on_unstarted_drop? : () -> Unit,
|
||||
) -> Future[X] {
|
||||
{ inner: Pending({ val: { producer: Some(producer), on_unstarted_drop } }) }
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
pub fn[X] Future::from_source(
|
||||
get : async () -> X,
|
||||
close : async () -> Unit,
|
||||
close_sync : () -> Unit,
|
||||
) -> Future[X] {
|
||||
{ inner: Source({ get, close, close_sync }) }
|
||||
}
|
||||
|
||||
///|
|
||||
/// Waits for and consumes the future's single value.
|
||||
///
|
||||
/// A `Future` is a one-shot value. Calling `get` again, or calling it after the
|
||||
/// readable end has been dropped, fails instead of replaying the value.
|
||||
pub async fn[X] Future::get(self : Future[X]) -> X {
|
||||
match self.inner {
|
||||
Source(source) => (source.get)()
|
||||
Local(state) => local_future_get(state)
|
||||
Pending(state) =>
|
||||
match state.val.producer {
|
||||
Some(producer) => {
|
||||
state.val.producer = None
|
||||
state.val.on_unstarted_drop = None
|
||||
producer()
|
||||
}
|
||||
None => raise FutureReadError::Dropped
|
||||
}
|
||||
Promised(cell) => promised_future_get(cell)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Releases the readable end without consuming its value.
|
||||
///
|
||||
/// If the value is already locally available, its registered cleanup callback
|
||||
/// runs. An unstarted lazy producer is discarded and runs
|
||||
/// `on_unstarted_drop`, when provided.
|
||||
pub async fn[X] Future::drop(self : Future[X]) -> Unit noraise {
|
||||
match self.inner {
|
||||
Source(source) => (source.close)() catch { _ => () }
|
||||
Local(state) => local_future_close(state, None)
|
||||
Pending(state) => {
|
||||
let cleanup = state.val.on_unstarted_drop
|
||||
state.val.producer = None
|
||||
state.val.on_unstarted_drop = None
|
||||
match cleanup {
|
||||
Some(cleanup) => cleanup()
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
Promised(cell) => promised_future_drop(cell, None)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
pub fn[X] Future::drop_sync(self : Future[X]) -> Unit {
|
||||
match self.inner {
|
||||
Source(source) => (source.close_sync)()
|
||||
Local(state) => local_future_close(state, None)
|
||||
Pending(state) => {
|
||||
let cleanup = state.val.on_unstarted_drop
|
||||
state.val.producer = None
|
||||
state.val.on_unstarted_drop = None
|
||||
match cleanup {
|
||||
Some(cleanup) => cleanup()
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
Promised(cell) => promised_future_drop(cell, None)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Rejects a future that was prepared for a component-model transfer but was
|
||||
/// never transferred. A locally available value uses its registered cleanup,
|
||||
/// falling back to the generated canonical-ABI cleanup. An unstarted producer
|
||||
/// is discarded without running it.
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
pub async fn[X] Future::reject(
|
||||
self : Future[X],
|
||||
cleanup : (X) -> Unit,
|
||||
) -> Unit noraise {
|
||||
match self.inner {
|
||||
Source(source) => (source.close)() catch { _ => () }
|
||||
Local(state) => local_future_close(state, Some(cleanup))
|
||||
Pending(state) => {
|
||||
let cleanup = state.val.on_unstarted_drop
|
||||
state.val.producer = None
|
||||
state.val.on_unstarted_drop = None
|
||||
match cleanup {
|
||||
Some(cleanup) => cleanup()
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
Promised(cell) => promised_future_drop(cell, Some(cleanup))
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct StreamProducerState[X] {
|
||||
mut producer : (async (Sink[X]) -> Unit)?
|
||||
mut cleanup : ((X) -> Unit)?
|
||||
mut on_unstarted_drop : (() -> Unit)?
|
||||
mut pipe : Ref[StreamPipe[X]]?
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct StreamSource[X] {
|
||||
read : async (Int) -> FixedArray[X]?
|
||||
close : async () -> Unit
|
||||
close_sync : () -> Unit
|
||||
}
|
||||
|
||||
///|
|
||||
priv enum StreamState[X] {
|
||||
Source(StreamSource[X])
|
||||
Local(Ref[StreamPipe[X]])
|
||||
Outgoing(Ref[StreamProducerState[X]])
|
||||
}
|
||||
|
||||
///|
|
||||
pub struct Stream[X] {
|
||||
priv inner : StreamState[X]
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] new_stream_pipe(
|
||||
capacity : Int,
|
||||
cleanup : ((X) -> Unit)?,
|
||||
) -> Ref[StreamPipe[X]] {
|
||||
if capacity < 0 {
|
||||
abort("stream capacity must not be negative")
|
||||
}
|
||||
{
|
||||
val: {
|
||||
capacity,
|
||||
chunks: Deque([]),
|
||||
buffered: 0,
|
||||
writer_closed: false,
|
||||
reader_dropped: false,
|
||||
cleanup,
|
||||
head: None,
|
||||
head_pos: 0,
|
||||
readers: Deque([]),
|
||||
writers: Deque([]),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] stream_pipe_sink(pipe : Ref[StreamPipe[X]]) -> Sink[X] {
|
||||
{
|
||||
write: (data : ArrayView[X]) => stream_pipe_write(pipe, data),
|
||||
close: () => stream_pipe_close_writer(pipe),
|
||||
is_open: () => !pipe.val.writer_closed && !pipe.val.reader_dropped,
|
||||
has_cleanup: () => pipe.val.cleanup is Some(_),
|
||||
cleanup: Some(fn(value) {
|
||||
match pipe.val.cleanup {
|
||||
Some(cleanup) => cleanup(value)
|
||||
None => ()
|
||||
}
|
||||
}),
|
||||
write_window_size: default_sink_write_window_size,
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] new_local_stream(
|
||||
capacity : Int,
|
||||
cleanup : ((X) -> Unit)?,
|
||||
) -> (Stream[X], Sink[X]) {
|
||||
let pipe = new_stream_pipe(capacity, cleanup)
|
||||
let stream = Stream::{ inner: Local(pipe) }
|
||||
let sink = stream_pipe_sink(pipe)
|
||||
(stream, sink)
|
||||
}
|
||||
|
||||
///|
|
||||
fn spawn_stream_producer(task : async () -> Unit) -> Unit {
|
||||
let current = current_coroutine()
|
||||
match current.spawner {
|
||||
Some(spawner) => spawner(task)
|
||||
None => ignore(spawn(task))
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn[X] materialize_stream_producer(
|
||||
state : Ref[StreamProducerState[X]],
|
||||
) -> Ref[StreamPipe[X]] {
|
||||
match state.val.pipe {
|
||||
Some(pipe) => pipe
|
||||
None => {
|
||||
let pipe = new_stream_pipe(0, state.val.cleanup)
|
||||
state.val.cleanup = None
|
||||
state.val.pipe = Some(pipe)
|
||||
match state.val.producer {
|
||||
Some(producer) => {
|
||||
state.val.producer = None
|
||||
state.val.on_unstarted_drop = None
|
||||
let sink = stream_pipe_sink(pipe)
|
||||
spawn_stream_producer(async fn() {
|
||||
defer stream_pipe_close_writer(pipe)
|
||||
producer(sink) catch {
|
||||
_ => ()
|
||||
}
|
||||
})
|
||||
}
|
||||
None => stream_pipe_close_writer(pipe)
|
||||
}
|
||||
pipe
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn[X] Stream::new(capacity? : Int = 0) -> (Stream[X], Sink[X]) {
|
||||
new_local_stream(capacity, None)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Creates a local stream whose unread values are cleaned up when its readable
|
||||
/// end is dropped.
|
||||
pub fn[X] Stream::new_with_cleanup(
|
||||
cleanup : (X) -> Unit,
|
||||
capacity? : Int = 0,
|
||||
) -> (Stream[X], Sink[X]) {
|
||||
new_local_stream(capacity, Some(cleanup))
|
||||
}
|
||||
|
||||
///|
|
||||
/// Creates a lazy stream from an async producer.
|
||||
///
|
||||
/// `cleanup`, when present, releases buffered or pending values if the readable
|
||||
/// end is dropped after the producer starts. Producers of explicitly managed
|
||||
/// resources should provide it.
|
||||
///
|
||||
/// `on_unstarted_drop`, when present, releases resources captured by a producer
|
||||
/// that is discarded before its first read or before a prepared component
|
||||
/// transfer commits. Once the producer starts, it owns its runtime cleanup and
|
||||
/// this callback is never invoked.
|
||||
pub fn[X] Stream::produce(
|
||||
producer : async (Sink[X]) -> Unit,
|
||||
cleanup? : (X) -> Unit,
|
||||
on_unstarted_drop? : () -> Unit,
|
||||
) -> Stream[X] {
|
||||
{
|
||||
inner: Outgoing({
|
||||
val: { producer: Some(producer), cleanup, on_unstarted_drop, pipe: None },
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
pub fn[X] Stream::from_source(
|
||||
read : async (Int) -> FixedArray[X]?,
|
||||
close : async () -> Unit,
|
||||
close_sync : () -> Unit,
|
||||
) -> Stream[X] {
|
||||
{ inner: Source({ read, close, close_sync }) }
|
||||
}
|
||||
|
||||
///|
|
||||
/// Reads at most `count` values from the stream.
|
||||
///
|
||||
/// `Some(values)` contains the next owned chunk and may be empty when the peer
|
||||
/// reports no progress. `None` means the writable end has closed and no
|
||||
/// buffered values remain. A non-positive count returns an empty chunk without
|
||||
/// waiting.
|
||||
pub async fn[X] Stream::read(self : Stream[X], count : Int) -> FixedArray[X]? {
|
||||
match self.inner {
|
||||
Source(source) => (source.read)(count)
|
||||
Local(pipe) => stream_pipe_read(pipe, count)
|
||||
Outgoing(state) =>
|
||||
stream_pipe_read(materialize_stream_producer(state), count)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Releases the readable end and discards unread values.
|
||||
///
|
||||
/// Registered cleanup callbacks run for locally buffered values. An unstarted
|
||||
/// lazy producer is discarded and runs `on_unstarted_drop`, when provided.
|
||||
pub async fn[X] Stream::drop(self : Stream[X]) -> Unit noraise {
|
||||
match self.inner {
|
||||
Source(source) => (source.close)() catch { _ => () }
|
||||
Local(pipe) => stream_pipe_drop_reader(pipe)
|
||||
Outgoing(state) =>
|
||||
match state.val.pipe {
|
||||
Some(pipe) => stream_pipe_drop_reader(pipe)
|
||||
None => {
|
||||
let cleanup = state.val.on_unstarted_drop
|
||||
state.val.producer = None
|
||||
state.val.cleanup = None
|
||||
state.val.on_unstarted_drop = None
|
||||
match cleanup {
|
||||
Some(cleanup) => cleanup()
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
pub fn[X] Stream::drop_sync(self : Stream[X]) -> Unit {
|
||||
match self.inner {
|
||||
Source(source) => (source.close_sync)()
|
||||
Local(pipe) => stream_pipe_drop_reader(pipe)
|
||||
Outgoing(state) =>
|
||||
match state.val.pipe {
|
||||
Some(pipe) => stream_pipe_drop_reader(pipe)
|
||||
None => {
|
||||
let cleanup = state.val.on_unstarted_drop
|
||||
state.val.producer = None
|
||||
state.val.cleanup = None
|
||||
state.val.on_unstarted_drop = None
|
||||
match cleanup {
|
||||
Some(cleanup) => cleanup()
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
pub fn[X] Stream::take_producer(self : Stream[X]) -> (async (Sink[X]) -> Unit)? {
|
||||
match self.inner {
|
||||
Outgoing(state) =>
|
||||
match state.val.pipe {
|
||||
Some(_) => None
|
||||
None => {
|
||||
let producer = state.val.producer
|
||||
state.val.producer = None
|
||||
state.val.cleanup = None
|
||||
state.val.on_unstarted_drop = None
|
||||
producer
|
||||
}
|
||||
}
|
||||
Source(_) | Local(_) => None
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Rejects a stream that was prepared for a component-model transfer but was
|
||||
/// never transferred. Component sources are closed immediately and buffered
|
||||
/// local values are cleaned synchronously. An unstarted producer is discarded
|
||||
/// without running it; its optional `on_unstarted_drop` callback owns cleanup of
|
||||
/// captured resources.
|
||||
#internal(wit_bindgen, "generated binding code only")
|
||||
pub async fn[X] Stream::reject(
|
||||
self : Stream[X],
|
||||
cleanup : (X) -> Unit,
|
||||
) -> Unit noraise {
|
||||
match self.inner {
|
||||
Source(source) => (source.close)() catch { _ => () }
|
||||
Local(pipe) => stream_pipe_reject_reader(pipe, cleanup)
|
||||
Outgoing(state) =>
|
||||
match state.val.pipe {
|
||||
Some(pipe) => stream_pipe_reject_reader(pipe, cleanup)
|
||||
None => {
|
||||
let cleanup = state.val.on_unstarted_drop
|
||||
state.val.producer = None
|
||||
state.val.cleanup = None
|
||||
state.val.on_unstarted_drop = None
|
||||
match cleanup {
|
||||
Some(cleanup) => cleanup()
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import {
|
||||
"moonbitlang/core/deque" @deque,
|
||||
"moonbitlang/core/ref" @ref,
|
||||
"moonbitlang/core/set" @set,
|
||||
}
|
||||
|
||||
warnings = "-44"
|
||||
supported_targets = "wasm"
|
||||
@@ -0,0 +1,148 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "moonplasma/desktop/async-core"
|
||||
|
||||
import {
|
||||
"moonbitlang/core/debug",
|
||||
}
|
||||
|
||||
// Values
|
||||
pub async fn check_cancellation() -> Unit noraise
|
||||
|
||||
pub async fn[X] handle_cancellation(async () -> X) -> X?
|
||||
|
||||
pub fn is_being_cancelled() -> Bool
|
||||
|
||||
pub async fn[X] protect_from_cancel(async () -> X) -> X nocancel
|
||||
|
||||
pub async fn[X] with_task_group(async (TaskGroup[X]) -> X) -> X
|
||||
|
||||
// Errors
|
||||
pub(all) suberror EndpointBusy {
|
||||
Read
|
||||
Write
|
||||
}
|
||||
|
||||
pub(all) suberror FutureReadError {
|
||||
Cancelled
|
||||
Dropped
|
||||
}
|
||||
|
||||
pub suberror OpCancelled {
|
||||
SubTaskCancelled(before_started~ : Bool)
|
||||
StreamReadCancelled
|
||||
}
|
||||
|
||||
#derive(@debug.Debug)
|
||||
pub(all) suberror PromiseClosed
|
||||
#deprecated
|
||||
pub fn PromiseClosed::to_repr(Self) -> @debug.Repr
|
||||
|
||||
#derive(@debug.Debug)
|
||||
pub suberror TaskCancelled
|
||||
#deprecated
|
||||
pub fn TaskCancelled::to_repr(Self) -> @debug.Repr
|
||||
|
||||
// Types and methods
|
||||
pub struct CondVar {
|
||||
// private fields
|
||||
}
|
||||
#alias(new, deprecated)
|
||||
pub fn CondVar::CondVar() -> Self
|
||||
pub fn CondVar::broadcast(Self) -> Unit
|
||||
pub fn CondVar::signal(Self) -> Unit
|
||||
pub async fn CondVar::wait(Self) -> Unit noraise
|
||||
|
||||
type Coroutine
|
||||
|
||||
pub struct Future[X] {
|
||||
// private fields
|
||||
}
|
||||
pub async fn[X] Future::drop(Self[X]) -> Unit noraise
|
||||
pub fn[X] Future::drop_sync(Self[X]) -> Unit
|
||||
pub fn[X] Future::from(async () -> X, on_unstarted_drop? : () -> Unit) -> Self[X]
|
||||
pub fn[X] Future::from_source(async () -> X, async () -> Unit, () -> Unit) -> Self[X]
|
||||
pub async fn[X] Future::get(Self[X]) -> X
|
||||
pub fn[X] Future::new() -> (Self[X], Promise[X])
|
||||
pub fn[X] Future::new_with_cleanup((X) -> Unit) -> (Self[X], Promise[X])
|
||||
pub fn[X] Future::ready(X) -> Self[X]
|
||||
pub fn[X] Future::ready_with_cleanup(X, (X) -> Unit) -> Self[X]
|
||||
pub async fn[X] Future::reject(Self[X], (X) -> Unit) -> Unit noraise
|
||||
|
||||
pub struct Mutex {
|
||||
// private fields
|
||||
}
|
||||
pub fn Mutex::Mutex() -> Self
|
||||
pub async fn Mutex::acquire(Self) -> Unit noraise
|
||||
pub fn Mutex::release(Self) -> Unit
|
||||
pub fn Mutex::try_acquire(Self) -> Bool
|
||||
|
||||
pub struct Promise[X] {
|
||||
// private fields
|
||||
}
|
||||
pub fn[X] Promise::close(Self[X]) -> Bool
|
||||
pub fn[X] Promise::complete(Self[X], X) -> Bool
|
||||
pub fn[X] Promise::fail(Self[X], Error) -> Bool
|
||||
|
||||
pub struct Semaphore {
|
||||
size : Int32
|
||||
// private fields
|
||||
}
|
||||
#alias(new, deprecated)
|
||||
pub fn Semaphore::Semaphore(Int32, initial_value? : Int32) -> Self
|
||||
pub async fn Semaphore::acquire(Self) -> Unit noraise
|
||||
pub fn Semaphore::release(Self) -> Unit
|
||||
pub fn Semaphore::try_acquire(Self) -> Bool
|
||||
|
||||
pub struct Sink[X] {
|
||||
// private fields
|
||||
}
|
||||
pub async fn[X] Sink::close(Self[X]) -> Unit
|
||||
pub fn[X] Sink::from_callbacks(async (ArrayView[X]) -> Int32, async () -> Unit, () -> Bool, ((X) -> Unit)?, Int32) -> Self[X]
|
||||
pub fn[X] Sink::is_open(Self[X]) -> Bool
|
||||
pub async fn[X] Sink::write(Self[X], ArrayView[X]) -> Int32
|
||||
pub async fn[X] Sink::write_all(Self[X], ArrayView[X]) -> Bool
|
||||
pub async fn Sink::write_all_bytes(Self[Byte], BytesView) -> Bool
|
||||
pub async fn Sink::write_bytes(Self[Byte], BytesView) -> Int32
|
||||
|
||||
pub struct Stream[X] {
|
||||
// private fields
|
||||
}
|
||||
pub async fn[X] Stream::drop(Self[X]) -> Unit noraise
|
||||
pub fn[X] Stream::drop_sync(Self[X]) -> Unit
|
||||
pub fn[X] Stream::from_source(async (Int32) -> FixedArray[X]?, async () -> Unit, () -> Unit) -> Self[X]
|
||||
pub fn[X] Stream::new(capacity? : Int32) -> (Self[X], Sink[X])
|
||||
pub fn[X] Stream::new_with_cleanup((X) -> Unit, capacity? : Int32) -> (Self[X], Sink[X])
|
||||
pub fn[X] Stream::produce(async (Sink[X]) -> Unit, cleanup? : (X) -> Unit, on_unstarted_drop? : () -> Unit) -> Self[X]
|
||||
pub async fn[X] Stream::read(Self[X], Int32) -> FixedArray[X]?
|
||||
pub async fn[X] Stream::reject(Self[X], (X) -> Unit) -> Unit noraise
|
||||
pub fn[X] Stream::take_producer(Self[X]) -> (async (Sink[X]) -> Unit)?
|
||||
|
||||
pub struct Task[X] {
|
||||
// private fields
|
||||
}
|
||||
pub fn[X] Task::cancel(Self[X]) -> Unit
|
||||
pub fn[X] Task::try_wait(Self[X]) -> X? raise
|
||||
pub async fn[X] Task::wait(Self[X]) -> X
|
||||
|
||||
pub struct TaskGroup[X] {
|
||||
// private fields
|
||||
}
|
||||
pub fn[X] TaskGroup::add_defer(Self[X], async () -> Unit nocancel) -> Unit
|
||||
pub async fn[X] TaskGroup::return_immediately(Self[X], X) -> Unit noraise
|
||||
pub fn[G, X] TaskGroup::spawn(Self[G], async () -> X, no_wait? : Bool, allow_failure? : Bool) -> Task[X]
|
||||
pub fn[X] TaskGroup::spawn_bg(Self[X], async () -> Unit, no_wait? : Bool, allow_failure? : Bool) -> Unit
|
||||
|
||||
#derive(Eq, Hash)
|
||||
type WaitableSet
|
||||
#deprecated
|
||||
pub fn WaitableSet::equal(Self, Self) -> Bool
|
||||
#deprecated
|
||||
pub fn WaitableSet::hash(Self) -> Int32
|
||||
#deprecated
|
||||
pub fn WaitableSet::hash_combine(Self, Hasher) -> Unit
|
||||
#deprecated
|
||||
pub fn WaitableSet::not_equal(Self, Self) -> Bool
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
@@ -0,0 +1,70 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
|
||||
///|
|
||||
pub fn mbt_ffi_cabi_realloc(
|
||||
src_offset : Int,
|
||||
src_size : Int,
|
||||
_dst_alignment : Int,
|
||||
dst_size : Int,
|
||||
) -> Int {
|
||||
// malloc
|
||||
if src_offset == 0 && src_size == 0 {
|
||||
return mbt_ffi_malloc(dst_size)
|
||||
}
|
||||
// free
|
||||
if dst_size == 0 {
|
||||
mbt_ffi_free(src_offset)
|
||||
return 0
|
||||
}
|
||||
// realloc
|
||||
let dst = mbt_ffi_malloc(dst_size)
|
||||
mbt_ffi_copy(dst, src_offset, if src_size < dst_size { src_size } else { dst_size })
|
||||
mbt_ffi_free(src_offset)
|
||||
dst
|
||||
}
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_copy(dest : Int, src : Int, len : Int) =
|
||||
#|(func (param i32) (param i32) (param i32) local.get 0 local.get 1 local.get 2 memory.copy)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
|
||||
#|(func (param i32) (result i32) (local i32)
|
||||
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
|
||||
#| local.tee 1 i32.const 0 call $moonbit.init_array8
|
||||
#| local.get 1)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_free(position : Int) =
|
||||
#|(func (param i32) local.get 0 call $moonbit.decref)
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportInitGui(p0 : Int, p1 : Int) -> Unit {
|
||||
@gui-loader.wasmExportInitGui(p0, p1)
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportOnKey(p0 : Int, p1 : Int, p2 : Int) -> Unit {
|
||||
@gui-loader.wasmExportOnKey(p0, p1, p2)
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportRenderFrame() -> Unit {
|
||||
@gui-loader.wasmExportRenderFrame()
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportOnResize(p0 : Int, p1 : Int) -> Unit {
|
||||
@gui-loader.wasmExportOnResize(p0, p1)
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportOnPointer(p0 : Int, p1 : Double, p2 : Double) -> Unit {
|
||||
@gui-loader.wasmExportOnPointer(p0, p1, p2)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import {
|
||||
"moonplasma/desktop/components/gfx-gui/gen/world/gui-loader" @gui-loader,
|
||||
}
|
||||
|
||||
warnings = "-44"
|
||||
supported_targets = "wasm"
|
||||
|
||||
pkgtype(kind: "foreign_library")
|
||||
|
||||
options(
|
||||
link: {
|
||||
"wasm": {
|
||||
"export-memory-name": "memory",
|
||||
"heap-start-address": 16,
|
||||
"exports": [
|
||||
"mbt_ffi_cabi_realloc:cabi_realloc",
|
||||
"wasmExportInitGui:init-gui",
|
||||
"wasmExportOnKey:on-key",
|
||||
"wasmExportOnPointer:on-pointer",
|
||||
"wasmExportOnResize:on-resize",
|
||||
"wasmExportRenderFrame:render-frame"
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "moonplasma/desktop/components/gfx-gui/gen"
|
||||
|
||||
// Values
|
||||
pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,51 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportInitGui(p0 : Int, p1 : Int) -> Unit {
|
||||
|
||||
let _ = init_gui((p0).reinterpret_as_uint(), (p1).reinterpret_as_uint());
|
||||
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportRenderFrame() -> Unit {
|
||||
|
||||
let _ = render_frame();
|
||||
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportOnResize(p0 : Int, p1 : Int) -> Unit {
|
||||
|
||||
let _ = on_resize((p0).reinterpret_as_uint(), (p1).reinterpret_as_uint());
|
||||
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportOnPointer(p0 : Int, p1 : Double, p2 : Double) -> Unit {
|
||||
|
||||
let _ = on_pointer((p0).to_byte(), p1, p2);
|
||||
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportOnKey(p0 : Int, p1 : Int, p2 : Int) -> Unit {
|
||||
|
||||
let result = mbt_ffi_ptr2str(p1, p2)
|
||||
|
||||
let _ = on_key((p0 != 0), result);
|
||||
|
||||
}
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
|
||||
#|(func (param i32) (param i32) (result i32)
|
||||
#| local.get 0
|
||||
#| local.get 1 call $moonbit.init_array16
|
||||
#| local.get 0)
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import {
|
||||
"moonplasma/desktop/interface/wasi-gfx/surface/surface" @surface,
|
||||
"moonplasma/desktop/interface/wasi-gfx/surface/surface-frame-buffer" @sfb,
|
||||
"moonplasma/desktop/compositor/scene" @scene,
|
||||
"moonplasma/desktop/compositor/renderer" @renderer,
|
||||
}
|
||||
|
||||
warnings = "-44"
|
||||
@@ -0,0 +1,21 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "moonplasma/desktop/components/gfx-gui/gen/world/gui-loader"
|
||||
|
||||
// Values
|
||||
pub fn init_gui(UInt32, UInt32) -> Unit
|
||||
|
||||
pub fn on_key(Bool, String) -> Unit
|
||||
|
||||
pub fn on_pointer(Byte, Double, Double) -> Unit
|
||||
|
||||
pub fn on_resize(UInt32, UInt32) -> Unit
|
||||
|
||||
pub fn render_frame() -> Unit
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,164 @@
|
||||
///| Moon-Plasma GUI loader component backed by wasi-gfx (surface + frame-buffer).
|
||||
|
||||
priv struct GfxGuiState {
|
||||
mut surface : @surface.Surface?
|
||||
mut context : @sfb.Context?
|
||||
mut width : Int
|
||||
mut height : Int
|
||||
mut launcher_open : Bool
|
||||
mut pointer_x : Double
|
||||
mut pointer_y : Double
|
||||
mut last_key : String
|
||||
mut frame_count : Int
|
||||
}
|
||||
|
||||
let state : GfxGuiState = {
|
||||
surface: None,
|
||||
context: None,
|
||||
width: 640,
|
||||
height: 360,
|
||||
launcher_open: false,
|
||||
pointer_x: 0.0,
|
||||
pointer_y: 0.0,
|
||||
last_key: "",
|
||||
frame_count: 0,
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn init_gui(width : UInt, height : UInt) -> Unit {
|
||||
let w = if width < 1U { 1U } else { width }
|
||||
let h = if height < 1U { 1U } else { height }
|
||||
state.width = w.reinterpret_as_int()
|
||||
state.height = h.reinterpret_as_int()
|
||||
let surf = @surface.Surface::surface({
|
||||
height: Some(h),
|
||||
width: Some(w),
|
||||
})
|
||||
let ctx = @sfb.Context::context(surf)
|
||||
state.surface = Some(surf)
|
||||
state.context = Some(ctx)
|
||||
render_frame()
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn render_frame() -> Unit {
|
||||
match state.context {
|
||||
None => ()
|
||||
Some(ctx) => {
|
||||
state.frame_count = state.frame_count + 1
|
||||
let w = state.width
|
||||
let h = state.height
|
||||
let theme = @scene.ThemeTokens::moon_night()
|
||||
let sg = @scene.SceneGraph::new(w, h)
|
||||
let titles : Array[String] = ["wasi-gfx Desktop"]
|
||||
let (bg_ops, panel_ops) = @scene.build_shell_ops(
|
||||
w,
|
||||
h,
|
||||
theme,
|
||||
"wasi-gfx",
|
||||
titles,
|
||||
)
|
||||
sg.background_ops = bg_ops
|
||||
sg.panel_ops = panel_ops
|
||||
|
||||
// Add a sample Breeze-decorated window so the GUI surface is rich and verifiable.
|
||||
let win_w = if w > 320 { w / 2 } else { w - 32 }
|
||||
let win_h = if h > 220 { h / 2 } else { h - 64 }
|
||||
let (insets, deco_ops) = @scene.build_breeze_decoration(
|
||||
"moon-plasma (wasi-gfx)",
|
||||
"org.moonplasma.gfx",
|
||||
true,
|
||||
false,
|
||||
win_w + 4,
|
||||
win_h + 34,
|
||||
theme,
|
||||
)
|
||||
sg.windows.push({
|
||||
id: 1UL,
|
||||
title: "moon-plasma (wasi-gfx)",
|
||||
app_id: "org.moonplasma.gfx",
|
||||
focused: true,
|
||||
fullscreen: false,
|
||||
geometry: @scene.Rect::new(24, 24, win_w, win_h),
|
||||
deco_insets: insets,
|
||||
deco_ops,
|
||||
surface: None,
|
||||
})
|
||||
|
||||
if state.launcher_open {
|
||||
sg.widgets.push({
|
||||
id: "launcher",
|
||||
rect: @scene.Rect::new(8, h - theme.panel_height - 168, 220, 160),
|
||||
ops: [
|
||||
@scene.DrawOp::FillRect(
|
||||
@scene.Rect::new(0, 0, 220, 160),
|
||||
theme.palette.surface_popup,
|
||||
theme.radius,
|
||||
),
|
||||
@scene.DrawOp::StrokeRect(
|
||||
@scene.Rect::new(0, 0, 220, 160),
|
||||
theme.palette.border,
|
||||
theme.radius,
|
||||
1,
|
||||
),
|
||||
@scene.DrawOp::Text(
|
||||
14,
|
||||
24,
|
||||
"Applications (wasi-gfx)",
|
||||
theme.font_size,
|
||||
theme.palette.foreground,
|
||||
@scene.TextAlign::Left,
|
||||
true,
|
||||
),
|
||||
],
|
||||
popup: None,
|
||||
})
|
||||
}
|
||||
|
||||
let pixmap = @renderer.render_scene(sg)
|
||||
let buf = ctx.get_current_buffer()
|
||||
buf.set_with_copy(pixmap.data)
|
||||
ctx.present()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn on_resize(width : UInt, height : UInt) -> Unit {
|
||||
let w = if width < 1U { 1U } else { width }
|
||||
let h = if height < 1U { 1U } else { height }
|
||||
state.width = w.reinterpret_as_int()
|
||||
state.height = h.reinterpret_as_int()
|
||||
match state.surface {
|
||||
Some(surf) => surf.request_set_size(Some(h), Some(w))
|
||||
None => ()
|
||||
}
|
||||
render_frame()
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn on_pointer(kind : Byte, x : Double, y : Double) -> Unit {
|
||||
state.pointer_x = x
|
||||
state.pointer_y = y
|
||||
// kind == 1: pointer down
|
||||
if kind == b'\x01' {
|
||||
let theme = @scene.ThemeTokens::moon_night()
|
||||
if y.to_int() >= state.height - theme.panel_height && x.to_int() <= 120 {
|
||||
state.launcher_open = !state.launcher_open
|
||||
}
|
||||
render_frame()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn on_key(pressed : Bool, text : String) -> Unit {
|
||||
if pressed {
|
||||
state.last_key = text
|
||||
if text == "Escape" {
|
||||
state.launcher_open = false
|
||||
} else if text == "Super" || text == "Meta" {
|
||||
state.launcher_open = !state.launcher_open
|
||||
}
|
||||
render_frame()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
///|
|
||||
declare pub fn init_gui(width : UInt, height : UInt) -> Unit
|
||||
///|
|
||||
declare pub fn render_frame() -> Unit
|
||||
///|
|
||||
declare pub fn on_resize(width : UInt, height : UInt) -> Unit
|
||||
///|
|
||||
declare pub fn on_pointer(kind : Byte, x : Double, y : Double) -> Unit
|
||||
///|
|
||||
declare pub fn on_key(pressed : Bool, text : String) -> Unit
|
||||
|
||||
+22
-2
@@ -1,10 +1,11 @@
|
||||
///| Standalone native MoonBit Wayland compositor entrypoint.
|
||||
///| Standalone native MoonBit Wayland compositor entrypoint with wasi-gfx presentation.
|
||||
|
||||
///|
|
||||
fn main {
|
||||
let args = @env.args()
|
||||
let mut socket_path = "/tmp/wayland-moon-0"
|
||||
let mut theme_path = "config/themes/moon-night.json"
|
||||
let mut gfx_out = ""
|
||||
let width = 1280
|
||||
let height = 720
|
||||
|
||||
@@ -17,6 +18,9 @@ fn main {
|
||||
} else if a == "--theme" && i + 1 < args.length() {
|
||||
theme_path = args[i + 1]
|
||||
i = i + 2
|
||||
} else if a == "--gfx-out" && i + 1 < args.length() {
|
||||
gfx_out = args[i + 1]
|
||||
i = i + 2
|
||||
} else {
|
||||
i = i + 1
|
||||
}
|
||||
@@ -33,11 +37,27 @@ fn main {
|
||||
@scene.ThemeTokens::moon_night()
|
||||
}
|
||||
|
||||
let gfx_surface = @gfx.Surface::new({
|
||||
width: Some(width),
|
||||
height: Some(height),
|
||||
})
|
||||
let gfx_ctx = @gfx.SurfaceFrameBufferContext::new(gfx_surface)
|
||||
|
||||
match @host.MoonPlasmaCompositor::new(socket_path, theme, width, height) {
|
||||
Some(comp) => {
|
||||
println("moon-plasma compositor listening on " + socket_path)
|
||||
if gfx_out.length() > 0 {
|
||||
let pixmap = comp.present_to_gfx(gfx_ctx)
|
||||
let png = @renderer.encode_png(pixmap)
|
||||
ignore(@sys.write_file_bytes(gfx_out, png))
|
||||
comp.close()
|
||||
println("wasi-gfx frame written to " + gfx_out)
|
||||
return
|
||||
}
|
||||
println("moon-plasma compositor listening on " + socket_path + " (wasi-gfx surface active)")
|
||||
while true {
|
||||
comp.step()
|
||||
comp.handle_gfx_events(gfx_surface)
|
||||
ignore(comp.present_to_gfx(gfx_ctx))
|
||||
@sys.sleep_ms(16)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
"moonbitlang/core/env",
|
||||
"moonplasma/desktop/compositor/sys" @sys,
|
||||
"moonplasma/desktop/compositor/scene" @scene,
|
||||
"moonplasma/desktop/compositor/renderer" @renderer,
|
||||
"moonplasma/desktop/compositor/gfx" @gfx,
|
||||
"moonplasma/desktop/compositor/host" @host,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
///| Pure-MoonBit implementation of wasi-gfx:surface@0.2.0,
|
||||
/// wasi-gfx:surface/surface-frame-buffer@0.2.0, and
|
||||
/// wasi-gfx:frame-buffer/frame-buffer@0.2.0 for loading & presenting GUIs.
|
||||
|
||||
///|
|
||||
pub(all) struct CreateDesc {
|
||||
width : Int?
|
||||
height : Int?
|
||||
}
|
||||
|
||||
///|
|
||||
pub(all) struct ResizeEvent {
|
||||
width : Int
|
||||
height : Int
|
||||
}
|
||||
|
||||
///|
|
||||
pub(all) struct FrameEvent {
|
||||
nothing : Bool
|
||||
}
|
||||
|
||||
///|
|
||||
pub(all) struct PointerEvent {
|
||||
x : Double
|
||||
y : Double
|
||||
}
|
||||
|
||||
///|
|
||||
pub(all) struct KeyEvent {
|
||||
key : String?
|
||||
text : String?
|
||||
alt_key : Bool
|
||||
ctrl_key : Bool
|
||||
meta_key : Bool
|
||||
shift_key : Bool
|
||||
}
|
||||
|
||||
///|
|
||||
/// Equivalent to `wasi-gfx:frame-buffer/frame-buffer.buffer`.
|
||||
pub(all) struct FrameBuffer {
|
||||
mut width : Int
|
||||
mut height : Int
|
||||
mut bytes : FixedArray[Byte]
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn FrameBuffer::new(width : Int, height : Int) -> FrameBuffer {
|
||||
let w = if width < 1 { 1 } else { width }
|
||||
let h = if height < 1 { 1 } else { height }
|
||||
{ width: w, height: h, bytes: FixedArray::make(w * h * 4, b'\x00') }
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn FrameBuffer::get_with_copy(self : FrameBuffer) -> FixedArray[Byte] {
|
||||
let out = FixedArray::make(self.bytes.length(), b'\x00')
|
||||
for i = 0; i < self.bytes.length(); i = i + 1 {
|
||||
out[i] = self.bytes[i]
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn FrameBuffer::set_with_copy(
|
||||
self : FrameBuffer,
|
||||
val : FixedArray[Byte],
|
||||
) -> Unit {
|
||||
let n = val.length()
|
||||
let next = FixedArray::make(n, b'\x00')
|
||||
for i = 0; i < n; i = i + 1 {
|
||||
next[i] = val[i]
|
||||
}
|
||||
self.bytes = next
|
||||
}
|
||||
|
||||
///|
|
||||
/// Equivalent to `wasi-gfx:surface/surface.surface`.
|
||||
pub(all) struct Surface {
|
||||
mut width : Int
|
||||
mut height : Int
|
||||
resize_events : Array[ResizeEvent]
|
||||
frame_events : Array[FrameEvent]
|
||||
pointer_down_events : Array[PointerEvent]
|
||||
pointer_up_events : Array[PointerEvent]
|
||||
pointer_move_events : Array[PointerEvent]
|
||||
key_down_events : Array[KeyEvent]
|
||||
key_up_events : Array[KeyEvent]
|
||||
mut presented_frames : Int
|
||||
mut last_presented : FixedArray[Byte]?
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::new(desc : CreateDesc) -> Surface {
|
||||
let w = match desc.width {
|
||||
Some(v) => if v < 1 { 1 } else { v }
|
||||
None => 1280
|
||||
}
|
||||
let h = match desc.height {
|
||||
Some(v) => if v < 1 { 1 } else { v }
|
||||
None => 720
|
||||
}
|
||||
{
|
||||
width: w,
|
||||
height: h,
|
||||
resize_events: [],
|
||||
frame_events: [],
|
||||
pointer_down_events: [],
|
||||
pointer_up_events: [],
|
||||
pointer_move_events: [],
|
||||
key_down_events: [],
|
||||
key_up_events: [],
|
||||
presented_frames: 0,
|
||||
last_presented: None,
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::width(self : Surface) -> Int {
|
||||
self.width
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::height(self : Surface) -> Int {
|
||||
self.height
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::request_set_size(
|
||||
self : Surface,
|
||||
height : Int?,
|
||||
width : Int?,
|
||||
) -> Unit {
|
||||
let nw = match width {
|
||||
Some(v) => if v < 1 { 1 } else { v }
|
||||
None => self.width
|
||||
}
|
||||
let nh = match height {
|
||||
Some(v) => if v < 1 { 1 } else { v }
|
||||
None => self.height
|
||||
}
|
||||
if nw != self.width || nh != self.height {
|
||||
self.width = nw
|
||||
self.height = nh
|
||||
self.resize_events.push({ width: nw, height: nh })
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::push_frame(self : Surface) -> Unit {
|
||||
self.frame_events.push({ nothing: false })
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::push_pointer_down(
|
||||
self : Surface,
|
||||
x : Double,
|
||||
y : Double,
|
||||
) -> Unit {
|
||||
self.pointer_down_events.push({ x, y })
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::push_pointer_up(
|
||||
self : Surface,
|
||||
x : Double,
|
||||
y : Double,
|
||||
) -> Unit {
|
||||
self.pointer_up_events.push({ x, y })
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::push_pointer_move(
|
||||
self : Surface,
|
||||
x : Double,
|
||||
y : Double,
|
||||
) -> Unit {
|
||||
self.pointer_move_events.push({ x, y })
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::push_key_down(self : Surface, ev : KeyEvent) -> Unit {
|
||||
self.key_down_events.push(ev)
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::push_key_up(self : Surface, ev : KeyEvent) -> Unit {
|
||||
self.key_up_events.push(ev)
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::drain_resize(self : Surface) -> Array[ResizeEvent] {
|
||||
let out = self.resize_events.copy()
|
||||
self.resize_events.clear()
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::drain_pointer_down(self : Surface) -> Array[PointerEvent] {
|
||||
let out = self.pointer_down_events.copy()
|
||||
self.pointer_down_events.clear()
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::drain_pointer_up(self : Surface) -> Array[PointerEvent] {
|
||||
let out = self.pointer_up_events.copy()
|
||||
self.pointer_up_events.clear()
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::drain_pointer_move(self : Surface) -> Array[PointerEvent] {
|
||||
let out = self.pointer_move_events.copy()
|
||||
self.pointer_move_events.clear()
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Surface::drain_key_down(self : Surface) -> Array[KeyEvent] {
|
||||
let out = self.key_down_events.copy()
|
||||
self.key_down_events.clear()
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
/// Equivalent to `wasi-gfx:surface/surface-frame-buffer.context`.
|
||||
pub(all) struct SurfaceFrameBufferContext {
|
||||
surface : Surface
|
||||
back_buffer : FrameBuffer
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn SurfaceFrameBufferContext::new(
|
||||
surface : Surface,
|
||||
) -> SurfaceFrameBufferContext {
|
||||
{
|
||||
surface,
|
||||
back_buffer: FrameBuffer::new(surface.width, surface.height),
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn SurfaceFrameBufferContext::get_current_buffer(
|
||||
self : SurfaceFrameBufferContext,
|
||||
) -> FrameBuffer {
|
||||
if self.back_buffer.width != self.surface.width ||
|
||||
self.back_buffer.height != self.surface.height {
|
||||
self.back_buffer.width = self.surface.width
|
||||
self.back_buffer.height = self.surface.height
|
||||
self.back_buffer.bytes = FixedArray::make(
|
||||
self.surface.width * self.surface.height * 4,
|
||||
b'\x00',
|
||||
)
|
||||
}
|
||||
self.back_buffer
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn SurfaceFrameBufferContext::present(
|
||||
self : SurfaceFrameBufferContext,
|
||||
) -> Unit {
|
||||
let copy = self.back_buffer.get_with_copy()
|
||||
self.surface.last_presented = Some(copy)
|
||||
self.surface.presented_frames = self.surface.presented_frames + 1
|
||||
}
|
||||
|
||||
///|
|
||||
/// Present a rendered `Pixmap` through a `wasi-gfx` `SurfaceFrameBufferContext`.
|
||||
pub fn present_pixmap(
|
||||
ctx : SurfaceFrameBufferContext,
|
||||
pixmap : @renderer.Pixmap,
|
||||
) -> Unit {
|
||||
let buf = ctx.get_current_buffer()
|
||||
buf.set_with_copy(pixmap.data)
|
||||
ctx.present()
|
||||
}
|
||||
|
||||
///|
|
||||
/// Render a `SceneGraph` and present it onto a `wasi-gfx` `SurfaceFrameBufferContext`.
|
||||
pub fn present_scene(
|
||||
ctx : SurfaceFrameBufferContext,
|
||||
sg : @scene.SceneGraph,
|
||||
) -> @renderer.Pixmap {
|
||||
let pixmap = @renderer.render_scene(sg)
|
||||
present_pixmap(ctx, pixmap)
|
||||
pixmap
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
///| Unit tests for pure-MoonBit wasi-gfx surface & frame-buffer presentation.
|
||||
|
||||
test "wasi-gfx surface, frame-buffer, and present_scene" {
|
||||
let surf = @gfx.Surface::new({ width: Some(160), height: Some(90) })
|
||||
assert_eq(surf.width(), 160)
|
||||
assert_eq(surf.height(), 90)
|
||||
|
||||
let ctx = @gfx.SurfaceFrameBufferContext::new(surf)
|
||||
let theme = @scene.ThemeTokens::moon_night()
|
||||
let sg = @scene.SceneGraph::new(160, 90)
|
||||
let (bg, panel) = @scene.build_shell_ops(160, 90, theme, "Tiling", [
|
||||
"Terminal",
|
||||
])
|
||||
sg.background_ops = bg
|
||||
sg.panel_ops = panel
|
||||
|
||||
let pixmap = @gfx.present_scene(ctx, sg)
|
||||
assert_eq(surf.presented_frames, 1)
|
||||
match surf.last_presented {
|
||||
Some(bytes) => {
|
||||
assert_eq(bytes.length(), 160 * 90 * 4)
|
||||
assert_eq(bytes[0], pixmap.data[0])
|
||||
assert_eq(bytes[3], b'\xff')
|
||||
}
|
||||
None => abort("expected presented frame bytes")
|
||||
}
|
||||
}
|
||||
|
||||
test "wasi-gfx surface resize and pointer/key event queues" {
|
||||
let surf = @gfx.Surface::new({ width: Some(320), height: Some(200) })
|
||||
surf.request_set_size(Some(240), Some(400))
|
||||
assert_eq(surf.width(), 400)
|
||||
assert_eq(surf.height(), 240)
|
||||
let resizes = surf.drain_resize()
|
||||
assert_eq(resizes.length(), 1)
|
||||
assert_eq(resizes[0].width, 400)
|
||||
assert_eq(resizes[0].height, 240)
|
||||
|
||||
surf.push_pointer_down(12.5, 34.5)
|
||||
let ptrs = surf.drain_pointer_down()
|
||||
assert_eq(ptrs.length(), 1)
|
||||
assert_eq(ptrs[0].x, 12.5)
|
||||
assert_eq(ptrs[0].y, 34.5)
|
||||
|
||||
surf.push_key_down({
|
||||
key: Some("Escape"),
|
||||
text: Some("Escape"),
|
||||
alt_key: false,
|
||||
ctrl_key: false,
|
||||
meta_key: false,
|
||||
shift_key: false,
|
||||
})
|
||||
let keys = surf.drain_key_down()
|
||||
assert_eq(keys.length(), 1)
|
||||
assert_eq(keys[0].text, Some("Escape"))
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import {
|
||||
"moonbitlang/core/builtin",
|
||||
"moonplasma/desktop/compositor/scene" @scene,
|
||||
"moonplasma/desktop/compositor/renderer" @renderer,
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "moonplasma/desktop/compositor/gfx"
|
||||
|
||||
import {
|
||||
"moonplasma/desktop/compositor/renderer",
|
||||
"moonplasma/desktop/compositor/scene",
|
||||
}
|
||||
|
||||
// Values
|
||||
pub fn present_pixmap(SurfaceFrameBufferContext, @renderer.Pixmap) -> Unit
|
||||
|
||||
pub fn present_scene(SurfaceFrameBufferContext, @scene.SceneGraph) -> @renderer.Pixmap
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
pub(all) struct CreateDesc {
|
||||
width : Int32?
|
||||
height : Int32?
|
||||
}
|
||||
|
||||
pub(all) struct FrameBuffer {
|
||||
mut width : Int32
|
||||
mut height : Int32
|
||||
mut bytes : FixedArray[Byte]
|
||||
}
|
||||
pub fn FrameBuffer::get_with_copy(Self) -> FixedArray[Byte]
|
||||
pub fn FrameBuffer::new(Int32, Int32) -> Self
|
||||
pub fn FrameBuffer::set_with_copy(Self, FixedArray[Byte]) -> Unit
|
||||
|
||||
pub(all) struct FrameEvent {
|
||||
nothing : Bool
|
||||
}
|
||||
|
||||
pub(all) struct KeyEvent {
|
||||
key : String?
|
||||
text : String?
|
||||
alt_key : Bool
|
||||
ctrl_key : Bool
|
||||
meta_key : Bool
|
||||
shift_key : Bool
|
||||
}
|
||||
|
||||
pub(all) struct PointerEvent {
|
||||
x : Double
|
||||
y : Double
|
||||
}
|
||||
|
||||
pub(all) struct ResizeEvent {
|
||||
width : Int32
|
||||
height : Int32
|
||||
}
|
||||
|
||||
pub(all) struct Surface {
|
||||
mut width : Int32
|
||||
mut height : Int32
|
||||
resize_events : Array[ResizeEvent]
|
||||
frame_events : Array[FrameEvent]
|
||||
pointer_down_events : Array[PointerEvent]
|
||||
pointer_up_events : Array[PointerEvent]
|
||||
pointer_move_events : Array[PointerEvent]
|
||||
key_down_events : Array[KeyEvent]
|
||||
key_up_events : Array[KeyEvent]
|
||||
mut presented_frames : Int32
|
||||
mut last_presented : FixedArray[Byte]?
|
||||
}
|
||||
pub fn Surface::drain_key_down(Self) -> Array[KeyEvent]
|
||||
pub fn Surface::drain_pointer_down(Self) -> Array[PointerEvent]
|
||||
pub fn Surface::drain_pointer_move(Self) -> Array[PointerEvent]
|
||||
pub fn Surface::drain_pointer_up(Self) -> Array[PointerEvent]
|
||||
pub fn Surface::drain_resize(Self) -> Array[ResizeEvent]
|
||||
pub fn Surface::height(Self) -> Int32
|
||||
pub fn Surface::new(CreateDesc) -> Self
|
||||
pub fn Surface::push_frame(Self) -> Unit
|
||||
pub fn Surface::push_key_down(Self, KeyEvent) -> Unit
|
||||
pub fn Surface::push_key_up(Self, KeyEvent) -> Unit
|
||||
pub fn Surface::push_pointer_down(Self, Double, Double) -> Unit
|
||||
pub fn Surface::push_pointer_move(Self, Double, Double) -> Unit
|
||||
pub fn Surface::push_pointer_up(Self, Double, Double) -> Unit
|
||||
pub fn Surface::request_set_size(Self, Int32?, Int32?) -> Unit
|
||||
pub fn Surface::width(Self) -> Int32
|
||||
|
||||
pub(all) struct SurfaceFrameBufferContext {
|
||||
surface : Surface
|
||||
back_buffer : FrameBuffer
|
||||
}
|
||||
pub fn SurfaceFrameBufferContext::get_current_buffer(Self) -> FrameBuffer
|
||||
pub fn SurfaceFrameBufferContext::new(Surface) -> Self
|
||||
pub fn SurfaceFrameBufferContext::present(Self) -> Unit
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -274,3 +274,50 @@ pub fn MoonPlasmaCompositor::compose_frame(
|
||||
ignore(self.damage.take_damage(self.output_w, self.output_h))
|
||||
@renderer.render_scene(scene)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Compose the current desktop GUI frame and present it onto a wasi-gfx
|
||||
/// `SurfaceFrameBufferContext`.
|
||||
pub fn MoonPlasmaCompositor::present_to_gfx(
|
||||
self : MoonPlasmaCompositor,
|
||||
ctx : @gfx.SurfaceFrameBufferContext,
|
||||
) -> @renderer.Pixmap {
|
||||
let pixmap = self.compose_frame()
|
||||
@gfx.present_pixmap(ctx, pixmap)
|
||||
pixmap
|
||||
}
|
||||
|
||||
///|
|
||||
/// Process pending wasi-gfx surface input events (pointer clicks for focus).
|
||||
pub fn MoonPlasmaCompositor::handle_gfx_events(
|
||||
self : MoonPlasmaCompositor,
|
||||
surface : @gfx.Surface,
|
||||
) -> Unit {
|
||||
let downs = surface.drain_pointer_down()
|
||||
for ev in downs {
|
||||
let px = ev.x.to_int()
|
||||
let py = ev.y.to_int()
|
||||
let order = self.wm.stacking_order()
|
||||
// Top-most window hit-test (iterate reverse Z-order).
|
||||
let mut i = order.length() - 1
|
||||
while i >= 0 {
|
||||
let wid = order[i]
|
||||
match self.windows.get(wid) {
|
||||
Some(win) =>
|
||||
if px >= win.geometry.x &&
|
||||
px < win.geometry.x + win.geometry.w &&
|
||||
py >= win.geometry.y - 32 &&
|
||||
py < win.geometry.y + win.geometry.h {
|
||||
self.apply_actions([
|
||||
@wm.WmAction::Focus(wid),
|
||||
@wm.WmAction::Raise(wid),
|
||||
])
|
||||
break
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
i = i - 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
"moonplasma/desktop/compositor/shell" @shell,
|
||||
"moonplasma/desktop/compositor/renderer" @renderer,
|
||||
"moonplasma/desktop/compositor/wayland" @wayland,
|
||||
"moonplasma/desktop/compositor/gfx" @gfx,
|
||||
}
|
||||
|
||||
supported_targets = "-all+native"
|
||||
@@ -366,3 +366,27 @@ pub struct WmState {
|
||||
}
|
||||
```
|
||||
All layout math (`compute_bsp_rects`, `insert_leaf`, `remove_leaf`, `focus_direction`, `hit_test_stack`) lives in `lib/wm/` as pure functions over `WmState`, unit-tested via `moon test` and integrated directly into `compositor/host/`.
|
||||
|
||||
---
|
||||
|
||||
## 9. `wasi-gfx` GUI Loading & Presentation Architecture
|
||||
|
||||
To load and present the `moon-plasma` GUI portably across both the native MoonBit compositor and WebAssembly/browser hosts, `moon-plasma` integrates the [wasi-gfx](https://wasi-gfx.dev/) WIT specification (`wasi-gfx:surface@0.2.0` and `wasi-gfx:frame-buffer@0.2.0`):
|
||||
|
||||
1. **WIT Contracts (`wit/gfx/`):**
|
||||
- `wit/gfx/deps/wasi-gfx-frame-buffer-0.2.0/frame-buffer.wit`: `wasi-gfx:frame-buffer/frame-buffer@0.2.0` (`buffer` resource with `get-with-copy` / `set-with-copy`).
|
||||
- `wit/gfx/deps/wasi-gfx-surface-0.2.0/surface.wit`: `wasi-gfx:surface/surface@0.2.0` (`surface` resource, `create-desc`, `resize-event`, `frame-event`, `pointer-event`, `key-event`, and `stream<...>` event channels).
|
||||
- `wit/gfx/deps/wasi-gfx-surface-0.2.0/surface-frame-buffer.wit`: `wasi-gfx:surface/surface-frame-buffer@0.2.0` (`context` resource binding a `surface` to `get-current-buffer()` + `present()`).
|
||||
- `wit/gfx/worlds.wit`: `moonplasma:gfx@0.2.0/gui-loader` world importing `wasi-gfx` and exporting `init-gui`, `render-frame`, `on-resize`, `on-pointer`, and `on-key`.
|
||||
|
||||
2. **MoonBit `wasi-gfx` GUI Component (`components/gfx-gui/`):**
|
||||
- Built with `wit-bindgen moonbit wit/gfx --world gui-loader` and `scripts/build-gfx.sh`.
|
||||
- Uses `@surface.Surface::surface`, `@sfb.Context::context`, `@scene.SceneGraph`, and `@renderer.render_scene` to render the desktop shell, Breeze-decorated windows, and launcher overlay into RGBA8888 pixel buffers and present them through `wasi-gfx`.
|
||||
|
||||
3. **Pure-MoonBit Native `wasi-gfx` Runtime (`compositor/gfx/`):**
|
||||
- Implements `Surface`, `FrameBuffer`, `SurfaceFrameBufferContext`, `present_pixmap`, and `present_scene` in pure MoonBit.
|
||||
- `MoonPlasmaCompositor::present_to_gfx` and `MoonPlasmaCompositor::handle_gfx_events` in `compositor/host/` connect the native Wayland compositor to `wasi-gfx` surfaces (also exposed via `--gfx-out <path.png>` in `compositor/bin/main.mbt`).
|
||||
|
||||
4. **JS / Browser `wasi-gfx` Host Adapter (`host/src/wasi-gfx.mjs`, `host/web/main.mjs`):**
|
||||
- Provides `WasiGfxSurface`, `WasiGfxBuffer`, `WasiGfxFrameBufferContext`, and `createWasiGfxHost()` for both `jco`-transpiled `wasi-gfx` components and the browser desktop shell (`host/web/main.mjs`), routing input streams and presenting RGBA8888 frames onto the `<canvas>`.
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
// Pure JS host implementation of the wasi-gfx WIT interfaces:
|
||||
// - wasi-gfx:frame-buffer/frame-buffer@0.2.0
|
||||
// - wasi-gfx:surface/surface@0.2.0
|
||||
// - wasi-gfx:surface/surface-frame-buffer@0.2.0
|
||||
//
|
||||
// Works in both Browser (HTMLCanvasElement + Canvas2D ImageData) and Node/headless.
|
||||
|
||||
export class WasiGfxBuffer {
|
||||
constructor(width = 1, height = 1) {
|
||||
this.width = Math.max(1, width | 0);
|
||||
this.height = Math.max(1, height | 0);
|
||||
this._data = new Uint8Array(this.width * this.height * 4);
|
||||
}
|
||||
|
||||
getWithCopy() {
|
||||
return new Uint8Array(this._data);
|
||||
}
|
||||
|
||||
setWithCopy(val) {
|
||||
if (!(val instanceof Uint8Array)) {
|
||||
this._data = new Uint8Array(val);
|
||||
} else {
|
||||
this._data = new Uint8Array(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function makeEventStream(subscribe) {
|
||||
let unsubscribe = null;
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
unsubscribe = subscribe((ev) => controller.enqueue(ev));
|
||||
},
|
||||
cancel() {
|
||||
if (unsubscribe) unsubscribe();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export class WasiGfxSurface {
|
||||
constructor(desc = {}, options = {}) {
|
||||
this._width = Math.max(1, (desc.width ?? options.width ?? 1280) | 0);
|
||||
this._height = Math.max(1, (desc.height ?? options.height ?? 720) | 0);
|
||||
this.canvas = options.canvas ?? null;
|
||||
this.onPresent = options.onPresent ?? null;
|
||||
this.presentedFrames = 0;
|
||||
this.lastPresented = null;
|
||||
this._listeners = {
|
||||
resize: new Set(),
|
||||
frame: new Set(),
|
||||
pointerUp: new Set(),
|
||||
pointerDown: new Set(),
|
||||
pointerMove: new Set(),
|
||||
keyUp: new Set(),
|
||||
keyDown: new Set(),
|
||||
};
|
||||
|
||||
if (this.canvas) {
|
||||
this.canvas.width = this._width;
|
||||
this.canvas.height = this._height;
|
||||
this._ctx2d = this.canvas.getContext('2d');
|
||||
this._bindCanvasEvents();
|
||||
} else {
|
||||
this._ctx2d = null;
|
||||
}
|
||||
}
|
||||
|
||||
_bindCanvasEvents() {
|
||||
const c = this.canvas;
|
||||
const pos = (e) => {
|
||||
const r = c.getBoundingClientRect();
|
||||
return {
|
||||
x: (e.clientX - r.left) * (c.width / (r.width || c.width)),
|
||||
y: (e.clientY - r.top) * (c.height / (r.height || c.height)),
|
||||
};
|
||||
};
|
||||
c.addEventListener('pointerup', (e) => this._emit('pointerUp', pos(e)));
|
||||
c.addEventListener('pointerdown', (e) => this._emit('pointerDown', pos(e)));
|
||||
c.addEventListener('pointermove', (e) => this._emit('pointerMove', pos(e)));
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('keyup', (e) => this._emit('keyUp', {
|
||||
key: undefined,
|
||||
text: e.key,
|
||||
altKey: e.altKey,
|
||||
ctrlKey: e.ctrlKey,
|
||||
metaKey: e.metaKey,
|
||||
shiftKey: e.shiftKey,
|
||||
}));
|
||||
window.addEventListener('keydown', (e) => this._emit('keyDown', {
|
||||
key: undefined,
|
||||
text: e.key,
|
||||
altKey: e.altKey,
|
||||
ctrlKey: e.ctrlKey,
|
||||
metaKey: e.metaKey,
|
||||
shiftKey: e.shiftKey,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
_emit(channel, event) {
|
||||
for (const fn of this._listeners[channel]) fn(event);
|
||||
}
|
||||
|
||||
_subscribe(channel, fn) {
|
||||
this._listeners[channel].add(fn);
|
||||
return () => this._listeners[channel].delete(fn);
|
||||
}
|
||||
|
||||
height() { return this._height; }
|
||||
width() { return this._width; }
|
||||
|
||||
requestSetSize(height, width) {
|
||||
const nw = width != null ? Math.max(1, width | 0) : this._width;
|
||||
const nh = height != null ? Math.max(1, height | 0) : this._height;
|
||||
if (nw !== this._width || nh !== this._height) {
|
||||
this._width = nw;
|
||||
this._height = nh;
|
||||
if (this.canvas) {
|
||||
this.canvas.width = nw;
|
||||
this.canvas.height = nh;
|
||||
}
|
||||
this._emit('resize', { width: nw, height: nh });
|
||||
}
|
||||
}
|
||||
|
||||
onResize() { return makeEventStream((fn) => this._subscribe('resize', fn)); }
|
||||
onFrame() { return makeEventStream((fn) => this._subscribe('frame', fn)); }
|
||||
onPointerUp() { return makeEventStream((fn) => this._subscribe('pointerUp', fn)); }
|
||||
onPointerDown() { return makeEventStream((fn) => this._subscribe('pointerDown', fn)); }
|
||||
onPointerMove() { return makeEventStream((fn) => this._subscribe('pointerMove', fn)); }
|
||||
onKeyUp() { return makeEventStream((fn) => this._subscribe('keyUp', fn)); }
|
||||
onKeyDown() { return makeEventStream((fn) => this._subscribe('keyDown', fn)); }
|
||||
|
||||
_commitFrame(rgbaBytes) {
|
||||
this.lastPresented = new Uint8Array(rgbaBytes);
|
||||
this.presentedFrames += 1;
|
||||
if (this._ctx2d && typeof ImageData !== 'undefined') {
|
||||
const expected = this._width * this._height * 4;
|
||||
if (this.lastPresented.length === expected) {
|
||||
const img = new ImageData(
|
||||
new Uint8ClampedArray(this.lastPresented.buffer, this.lastPresented.byteOffset, expected),
|
||||
this._width,
|
||||
this._height,
|
||||
);
|
||||
this._ctx2d.putImageData(img, 0, 0);
|
||||
}
|
||||
}
|
||||
if (this.onPresent) this.onPresent(this.lastPresented, this._width, this._height);
|
||||
}
|
||||
}
|
||||
|
||||
export class WasiGfxFrameBufferContext {
|
||||
constructor(surface) {
|
||||
this.surface = surface;
|
||||
this._buffer = new WasiGfxBuffer(surface.width(), surface.height());
|
||||
}
|
||||
|
||||
getCurrentBuffer() {
|
||||
if (this._buffer.width !== this.surface.width() || this._buffer.height !== this.surface.height()) {
|
||||
this._buffer = new WasiGfxBuffer(this.surface.width(), this.surface.height());
|
||||
}
|
||||
return this._buffer;
|
||||
}
|
||||
|
||||
present() {
|
||||
this.surface._commitFrame(this._buffer.getWithCopy());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a wasi-gfx host state & import table for jco-transpiled components.
|
||||
* Tracks all created surfaces and contexts so hosts/tests can inspect presented frames.
|
||||
*/
|
||||
export function createWasiGfxHost(options = {}) {
|
||||
const surfaces = [];
|
||||
const contexts = [];
|
||||
|
||||
class Surface extends WasiGfxSurface {
|
||||
constructor(desc) {
|
||||
super(desc, options);
|
||||
surfaces.push(this);
|
||||
}
|
||||
}
|
||||
|
||||
class Context extends WasiGfxFrameBufferContext {
|
||||
constructor(surface) {
|
||||
super(surface);
|
||||
contexts.push(this);
|
||||
}
|
||||
}
|
||||
|
||||
const imports = {
|
||||
'wasi-gfx:frame-buffer/frame-buffer': { Buffer: WasiGfxBuffer },
|
||||
'wasi-gfx:frame-buffer/frame-buffer@0.2.0': { Buffer: WasiGfxBuffer },
|
||||
'wasi-gfx:surface/surface': { Surface },
|
||||
'wasi-gfx:surface/surface@0.2.0': { Surface },
|
||||
'wasi-gfx:surface/surface-frame-buffer': { Context },
|
||||
'wasi-gfx:surface/surface-frame-buffer@0.2.0': { Context },
|
||||
};
|
||||
|
||||
return {
|
||||
Surface,
|
||||
Context,
|
||||
Buffer: WasiGfxBuffer,
|
||||
surfaces,
|
||||
contexts,
|
||||
imports,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { createWasiGfxHost } from '../src/wasi-gfx.mjs';
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||
const BUILD = join(HERE, '..', '..', 'build');
|
||||
|
||||
test('wasi-gfx host: Surface, Buffer, Context, and event streams', async () => {
|
||||
const gfx = createWasiGfxHost();
|
||||
const surf = new gfx.Surface({ width: 100, height: 50 });
|
||||
assert.equal(surf.width(), 100);
|
||||
assert.equal(surf.height(), 50);
|
||||
|
||||
const resizes = [];
|
||||
const reader = surf.onResize().getReader();
|
||||
surf.requestSetSize(80, 120);
|
||||
const { value } = await reader.read();
|
||||
resizes.push(value);
|
||||
await reader.cancel();
|
||||
assert.deepEqual(resizes, [{ width: 120, height: 80 }]);
|
||||
|
||||
const ctx = new gfx.Context(surf);
|
||||
const buf = ctx.getCurrentBuffer();
|
||||
const pixels = new Uint8Array(120 * 80 * 4);
|
||||
pixels[0] = 0x11;
|
||||
pixels[1] = 0x22;
|
||||
pixels[2] = 0x33;
|
||||
pixels[3] = 0xff;
|
||||
buf.setWithCopy(pixels);
|
||||
ctx.present();
|
||||
|
||||
assert.equal(surf.presentedFrames, 1);
|
||||
assert.equal(surf.lastPresented[0], 0x11);
|
||||
assert.equal(surf.lastPresented[3], 0xff);
|
||||
});
|
||||
|
||||
test('wasi-gfx component (gfx-gui.wasm): loads GUI, handles pointer/resize/key, presents RGBA frames', async () => {
|
||||
const gfx = createWasiGfxHost();
|
||||
const jcoDir = join(BUILD, 'jco', 'gfx-gui');
|
||||
const mod = await import(pathToFileURL(join(jcoDir, 'gfx-gui.js')).href);
|
||||
const getCoreModule = async (p) => WebAssembly.compile(await readFile(join(jcoDir, p)));
|
||||
|
||||
const inst = await mod.instantiate(getCoreModule, gfx.imports);
|
||||
await inst.initGui(320, 180);
|
||||
|
||||
assert.equal(gfx.surfaces.length, 1);
|
||||
assert.equal(gfx.contexts.length, 1);
|
||||
const surf = gfx.surfaces[0];
|
||||
assert.equal(surf.width(), 320);
|
||||
assert.equal(surf.height(), 180);
|
||||
assert.equal(surf.presentedFrames, 1);
|
||||
assert.equal(surf.lastPresented.length, 320 * 180 * 4);
|
||||
|
||||
// Verify non-empty rendered GUI pixels (alpha=255 and multiple distinct colors).
|
||||
const colors = new Set();
|
||||
for (let i = 0; i < surf.lastPresented.length; i += 4) {
|
||||
assert.equal(surf.lastPresented[i + 3], 255);
|
||||
colors.add((surf.lastPresented[i] << 16) | (surf.lastPresented[i + 1] << 8) | surf.lastPresented[i + 2]);
|
||||
}
|
||||
assert.ok(colors.size > 5, `expected rich GUI palette, got ${colors.size} colors`);
|
||||
|
||||
// Pointer click on launcher area -> opens launcher popup and presents new frame.
|
||||
await inst.onPointer(1, 20, 170);
|
||||
assert.equal(surf.presentedFrames, 2);
|
||||
|
||||
// Resize -> updates surface size and presents resized frame.
|
||||
await inst.onResize(400, 240);
|
||||
assert.equal(surf.width(), 400);
|
||||
assert.equal(surf.height(), 240);
|
||||
assert.equal(surf.presentedFrames, 3);
|
||||
assert.equal(surf.lastPresented.length, 400 * 240 * 4);
|
||||
|
||||
// Escape key -> dismisses launcher and presents frame.
|
||||
await inst.onKey(true, 'Escape');
|
||||
assert.equal(surf.presentedFrames, 4);
|
||||
});
|
||||
+53
-12
@@ -2,6 +2,7 @@ import { Desktop } from '../src/desktop.mjs';
|
||||
import { createPlatform } from '../src/platform.mjs';
|
||||
import { tokensFromJson } from '../src/theme.mjs';
|
||||
import { webLoader } from '../src/loader-web.mjs';
|
||||
import { WasiGfxSurface, WasiGfxFrameBufferContext } from '../src/wasi-gfx.mjs';
|
||||
import { paint } from './canvas.mjs';
|
||||
|
||||
const base = new URL('../../', import.meta.url).href.replace(/\/$/, '');
|
||||
@@ -12,6 +13,15 @@ const getJson = async (p) => {
|
||||
return r.json();
|
||||
};
|
||||
|
||||
async function drainStream(stream, handler) {
|
||||
const reader = stream.getReader();
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
handler(value);
|
||||
}
|
||||
}
|
||||
|
||||
const status = document.getElementById('status');
|
||||
try {
|
||||
const config = await getJson(`config/${q.get('config') ?? 'desktop.json'}`);
|
||||
@@ -21,23 +31,54 @@ try {
|
||||
const platform = createPlatform({ apps, tokens, now: fixed ? () => fixed : undefined });
|
||||
const desktop = await new Desktop({ config, loader: webLoader(base), platform }).start();
|
||||
|
||||
// Present the desktop GUI through a wasi-gfx Surface + FrameBuffer Context.
|
||||
const canvas = document.getElementById('screen');
|
||||
canvas.width = desktop.screen.w; canvas.height = desktop.screen.h;
|
||||
const ctx = canvas.getContext('2d');
|
||||
const redraw = () => paint(ctx, desktop.frame().ops, desktop.screen);
|
||||
const pos = (e) => { const r = canvas.getBoundingClientRect(); return [Math.round((e.clientX - r.left) * canvas.width / r.width), Math.round((e.clientY - r.top) * canvas.height / r.height)]; };
|
||||
for (const [ev, kind] of [['pointermove', 'move'], ['pointerdown', 'down'], ['pointerup', 'up']]) {
|
||||
canvas.addEventListener(ev, (e) => { const [x, y] = pos(e); if (desktop.pointer(kind, x, y)) redraw(); });
|
||||
}
|
||||
window.addEventListener('keydown', (e) => {
|
||||
const k = e.key.length === 1 || ['Backspace', 'Enter', 'Escape'].includes(e.key) ? e.key : null;
|
||||
if (k && desktop.key(k)) { e.preventDefault(); redraw(); }
|
||||
const gfxSurface = new WasiGfxSurface(
|
||||
{ width: desktop.screen.w, height: desktop.screen.h },
|
||||
{ canvas },
|
||||
);
|
||||
const gfxContext = new WasiGfxFrameBufferContext(gfxSurface);
|
||||
const offscreen = document.createElement('canvas');
|
||||
offscreen.width = desktop.screen.w;
|
||||
offscreen.height = desktop.screen.h;
|
||||
const offCtx = offscreen.getContext('2d');
|
||||
|
||||
const redraw = () => {
|
||||
paint(offCtx, desktop.frame().ops, desktop.screen);
|
||||
const img = offCtx.getImageData(0, 0, desktop.screen.w, desktop.screen.h);
|
||||
const buf = gfxContext.getCurrentBuffer();
|
||||
buf.setWithCopy(new Uint8Array(img.data.buffer, img.data.byteOffset, img.data.byteLength));
|
||||
gfxContext.present();
|
||||
};
|
||||
|
||||
// Route input events from wasi-gfx Surface streams into Desktop.
|
||||
drainStream(gfxSurface.onPointerMove(), (e) => {
|
||||
if (desktop.pointer('move', Math.round(e.x), Math.round(e.y))) redraw();
|
||||
});
|
||||
drainStream(gfxSurface.onPointerDown(), (e) => {
|
||||
if (desktop.pointer('down', Math.round(e.x), Math.round(e.y))) redraw();
|
||||
});
|
||||
drainStream(gfxSurface.onPointerUp(), (e) => {
|
||||
if (desktop.pointer('up', Math.round(e.x), Math.round(e.y))) redraw();
|
||||
});
|
||||
drainStream(gfxSurface.onKeyDown(), (e) => {
|
||||
const k = e.text && (e.text.length === 1 || ['Backspace', 'Enter', 'Escape'].includes(e.text)) ? e.text : null;
|
||||
if (k && desktop.key(k)) redraw();
|
||||
});
|
||||
|
||||
redraw();
|
||||
if (!fixed) setInterval(redraw, 1000);
|
||||
status.textContent = `${desktop.widgets.map((w) => `${w.id}=${w.componentName}`).join(' ')} | theme: ${platform.tokens.name}`;
|
||||
status.textContent = `${desktop.widgets.map((w) => `${w.id}=${w.componentName}`).join(' ')} | theme: ${platform.tokens.name} | wasi-gfx`;
|
||||
// Handle for automation / the browser console.
|
||||
window.moonPlasma = { desktop, platform, redraw, swap: async (id, c) => { await desktop.swap(id, c); redraw(); }, ready: true };
|
||||
window.moonPlasma = {
|
||||
desktop,
|
||||
platform,
|
||||
gfxSurface,
|
||||
gfxContext,
|
||||
redraw,
|
||||
swap: async (id, c) => { await desktop.swap(id, c); redraw(); },
|
||||
ready: true,
|
||||
};
|
||||
} catch (e) {
|
||||
status.textContent = `ERROR: ${e.message}`;
|
||||
status.style.color = '#f66';
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
|
||||
///|
|
||||
fn wasmImportResourceDropBuffer(resource : Int) = "wasi-gfx:frame-buffer/frame-buffer@0.2.0" "[resource-drop]buffer"
|
||||
|
||||
///|
|
||||
fn wasmImportMethodBufferGetWithCopy(p0 : Int, p1 : Int) = "wasi-gfx:frame-buffer/frame-buffer@0.2.0" "[method]buffer.get-with-copy"
|
||||
|
||||
///|
|
||||
fn wasmImportMethodBufferSetWithCopy(p0 : Int, p1 : Int, p2 : Int) = "wasi-gfx:frame-buffer/frame-buffer@0.2.0" "[method]buffer.set-with-copy"
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] =
|
||||
#|(func (param i32) (param i32) (result i32)
|
||||
#| local.get 0
|
||||
#| local.get 1 call $moonbit.init_array8
|
||||
#| local.get 0)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
|
||||
#|(func (param i32) (result i32) (local i32)
|
||||
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
|
||||
#| local.tee 1 i32.const 0 call $moonbit.init_array8
|
||||
#| local.get 1)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
|
||||
#|(func (param i32) (result i32) local.get 0 i32.load)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_free(position : Int) =
|
||||
#|(func (param i32) local.get 0 call $moonbit.decref)
|
||||
|
||||
///|
|
||||
#owned(bytes)
|
||||
extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int =
|
||||
#|(func (param i32) (result i32) local.get 0)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
warnings = "-44"
|
||||
@@ -0,0 +1,16 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "moonplasma/desktop/interface/wasi-gfx/frame-buffer/frame-buffer"
|
||||
|
||||
// Values
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
pub(all) struct Buffer(Int32)
|
||||
pub fn Buffer::drop(Self) -> Unit
|
||||
pub fn Buffer::get_with_copy(Self) -> FixedArray[Byte]
|
||||
pub fn Buffer::set_with_copy(Self, FixedArray[Byte]) -> Unit
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,36 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
///|
|
||||
pub(all) struct Buffer(Int) derive()
|
||||
|
||||
///|
|
||||
/// Drops a resource handle.
|
||||
pub fn Buffer::drop(self : Buffer) -> Unit {
|
||||
let Buffer(resource) = self
|
||||
wasmImportResourceDropBuffer(resource)
|
||||
}
|
||||
///|
|
||||
/// TODO: This should be replaced with something that doesn't require a copy.
|
||||
pub fn Buffer::get_with_copy(self : Buffer) -> FixedArray[Byte] {
|
||||
|
||||
let Buffer(handle) = self
|
||||
let return_area = mbt_ffi_malloc(8)
|
||||
wasmImportMethodBufferGetWithCopy(handle, return_area);
|
||||
|
||||
let result = mbt_ffi_ptr2bytes(mbt_ffi_load32((return_area) + 0), mbt_ffi_load32((return_area) + 4))
|
||||
let ret = result
|
||||
mbt_ffi_free(return_area)
|
||||
return ret
|
||||
|
||||
}
|
||||
///|
|
||||
pub fn Buffer::set_with_copy(self : Buffer, val : FixedArray[Byte]) -> Unit {
|
||||
|
||||
let Buffer(handle) = self
|
||||
|
||||
let ptr = mbt_ffi_bytes2ptr(val)
|
||||
|
||||
wasmImportMethodBufferSetWithCopy(handle, ptr, val.length());
|
||||
mbt_ffi_free(ptr)
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
|
||||
///|
|
||||
fn wasmImportResourceDropContext(resource : Int) = "wasi-gfx:surface/surface-frame-buffer@0.2.0" "[resource-drop]context"
|
||||
|
||||
///|
|
||||
fn wasmImportConstructorContext(p0 : Int) -> Int = "wasi-gfx:surface/surface-frame-buffer@0.2.0" "[constructor]context"
|
||||
|
||||
///|
|
||||
fn wasmImportMethodContextGetCurrentBuffer(p0 : Int) -> Int = "wasi-gfx:surface/surface-frame-buffer@0.2.0" "[method]context.get-current-buffer"
|
||||
|
||||
///|
|
||||
fn wasmImportMethodContextPresent(p0 : Int) = "wasi-gfx:surface/surface-frame-buffer@0.2.0" "[method]context.present"
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import {
|
||||
"moonplasma/desktop/interface/wasi-gfx/frame-buffer/frame-buffer" @frame-buffer,
|
||||
"moonplasma/desktop/interface/wasi-gfx/surface/surface" @surface,
|
||||
}
|
||||
|
||||
warnings = "-44"
|
||||
@@ -0,0 +1,22 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "moonplasma/desktop/interface/wasi-gfx/surface/surface-frame-buffer"
|
||||
|
||||
import {
|
||||
"moonplasma/desktop/interface/wasi-gfx/frame-buffer/frame-buffer",
|
||||
"moonplasma/desktop/interface/wasi-gfx/surface/surface",
|
||||
}
|
||||
|
||||
// Values
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
pub(all) struct Context(Int32)
|
||||
pub fn Context::context(@surface.Surface) -> Self
|
||||
pub fn Context::drop(Self) -> Unit
|
||||
pub fn Context::get_current_buffer(Self) -> @frame-buffer.Buffer
|
||||
pub fn Context::present(Self) -> Unit
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,37 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
///|
|
||||
pub(all) struct Context(Int) derive()
|
||||
|
||||
///|
|
||||
/// Drops a resource handle.
|
||||
pub fn Context::drop(self : Context) -> Unit {
|
||||
let Context(resource) = self
|
||||
wasmImportResourceDropContext(resource)
|
||||
}
|
||||
///|
|
||||
pub fn Context::context(surface : @surface.Surface) -> Context {
|
||||
|
||||
let @surface.Surface(handle) = surface
|
||||
let result : Int = wasmImportConstructorContext(handle);
|
||||
let ret = Context::Context(result)
|
||||
return ret
|
||||
|
||||
}
|
||||
///|
|
||||
pub fn Context::get_current_buffer(self : Context) -> @frame-buffer.Buffer {
|
||||
|
||||
let Context(handle) = self
|
||||
let result : Int = wasmImportMethodContextGetCurrentBuffer(handle);
|
||||
let ret = @frame-buffer.Buffer::Buffer(result)
|
||||
return ret
|
||||
|
||||
}
|
||||
///|
|
||||
/// TODO: consider if needed
|
||||
pub fn Context::present(self : Context) -> Unit {
|
||||
|
||||
let Context(handle) = self
|
||||
wasmImportMethodContextPresent(handle);
|
||||
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,6 @@
|
||||
import {
|
||||
"moonplasma/desktop/async-core" @async-core,
|
||||
}
|
||||
|
||||
warnings = "-44"
|
||||
supported_targets = "wasm"
|
||||
@@ -0,0 +1,233 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "moonplasma/desktop/interface/wasi-gfx/surface/surface"
|
||||
|
||||
import {
|
||||
"moonplasma/desktop/async-core",
|
||||
}
|
||||
|
||||
// Values
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
pub(all) struct CreateDesc {
|
||||
height : UInt32?
|
||||
width : UInt32?
|
||||
}
|
||||
|
||||
pub(all) struct FrameEvent {
|
||||
nothing : Bool
|
||||
}
|
||||
|
||||
pub(all) enum Key {
|
||||
BACKQUOTE
|
||||
BACKSLASH
|
||||
BRACKET_LEFT
|
||||
BRACKET_RIGHT
|
||||
COMMA
|
||||
DIGIT0
|
||||
DIGIT1
|
||||
DIGIT2
|
||||
DIGIT3
|
||||
DIGIT4
|
||||
DIGIT5
|
||||
DIGIT6
|
||||
DIGIT7
|
||||
DIGIT8
|
||||
DIGIT9
|
||||
EQUAL
|
||||
INTL_BACKSLASH
|
||||
INTL_RO
|
||||
INTL_YEN
|
||||
KEY_A
|
||||
KEY_B
|
||||
KEY_C
|
||||
KEY_D
|
||||
KEY_E
|
||||
KEY_F
|
||||
KEY_G
|
||||
KEY_H
|
||||
KEY_I
|
||||
KEY_J
|
||||
KEY_K
|
||||
KEY_L
|
||||
KEY_M
|
||||
KEY_N
|
||||
KEY_O
|
||||
KEY_P
|
||||
KEY_Q
|
||||
KEY_R
|
||||
KEY_S
|
||||
KEY_T
|
||||
KEY_U
|
||||
KEY_V
|
||||
KEY_W
|
||||
KEY_X
|
||||
KEY_Y
|
||||
KEY_Z
|
||||
MINUS
|
||||
PERIOD
|
||||
QUOTE
|
||||
SEMICOLON
|
||||
SLASH
|
||||
ALT_LEFT
|
||||
ALT_RIGHT
|
||||
BACKSPACE
|
||||
CAPS_LOCK
|
||||
CONTEXT_MENU
|
||||
CONTROL_LEFT
|
||||
CONTROL_RIGHT
|
||||
ENTER
|
||||
META_LEFT
|
||||
META_RIGHT
|
||||
SHIFT_LEFT
|
||||
SHIFT_RIGHT
|
||||
SPACE
|
||||
TAB
|
||||
CONVERT
|
||||
KANA_MODE
|
||||
LANG1
|
||||
LANG2
|
||||
LANG3
|
||||
LANG4
|
||||
LANG5
|
||||
NON_CONVERT
|
||||
DELETE
|
||||
END
|
||||
HELP
|
||||
HOME
|
||||
INSERT
|
||||
PAGE_DOWN
|
||||
PAGE_UP
|
||||
ARROW_DOWN
|
||||
ARROW_LEFT
|
||||
ARROW_RIGHT
|
||||
ARROW_UP
|
||||
NUM_LOCK
|
||||
NUMPAD0
|
||||
NUMPAD1
|
||||
NUMPAD2
|
||||
NUMPAD3
|
||||
NUMPAD4
|
||||
NUMPAD5
|
||||
NUMPAD6
|
||||
NUMPAD7
|
||||
NUMPAD8
|
||||
NUMPAD9
|
||||
NUMPAD_ADD
|
||||
NUMPAD_BACKSPACE
|
||||
NUMPAD_CLEAR
|
||||
NUMPAD_CLEAR_ENTRY
|
||||
NUMPAD_COMMA
|
||||
NUMPAD_DECIMAL
|
||||
NUMPAD_DIVIDE
|
||||
NUMPAD_ENTER
|
||||
NUMPAD_EQUAL
|
||||
NUMPAD_HASH
|
||||
NUMPAD_MEMORY_ADD
|
||||
NUMPAD_MEMORY_CLEAR
|
||||
NUMPAD_MEMORY_RECALL
|
||||
NUMPAD_MEMORY_STORE
|
||||
NUMPAD_MEMORY_SUBTRACT
|
||||
NUMPAD_MULTIPLY
|
||||
NUMPAD_PAREN_LEFT
|
||||
NUMPAD_PAREN_RIGHT
|
||||
NUMPAD_STAR
|
||||
NUMPAD_SUBTRACT
|
||||
ESCAPE
|
||||
F1
|
||||
F2
|
||||
F3
|
||||
F4
|
||||
F5
|
||||
F6
|
||||
F7
|
||||
F8
|
||||
F9
|
||||
F10
|
||||
F11
|
||||
F12
|
||||
FN
|
||||
FN_LOCK
|
||||
PRINT_SCREEN
|
||||
SCROLL_LOCK
|
||||
PAUSE
|
||||
BROWSER_BACK
|
||||
BROWSER_FAVORITES
|
||||
BROWSER_FORWARD
|
||||
BROWSER_HOME
|
||||
BROWSER_REFRESH
|
||||
BROWSER_SEARCH
|
||||
BROWSER_STOP
|
||||
EJECT
|
||||
LAUNCH_APP1
|
||||
LAUNCH_APP2
|
||||
LAUNCH_MAIL
|
||||
MEDIA_PLAY_PAUSE
|
||||
MEDIA_SELECT
|
||||
MEDIA_STOP
|
||||
MEDIA_TRACK_NEXT
|
||||
MEDIA_TRACK_PREVIOUS
|
||||
POWER
|
||||
SLEEP
|
||||
AUDIO_VOLUME_DOWN
|
||||
AUDIO_VOLUME_MUTE
|
||||
AUDIO_VOLUME_UP
|
||||
WAKE_UP
|
||||
HYPER
|
||||
SUPER
|
||||
TURBO
|
||||
ABORT
|
||||
RESUME
|
||||
SUSPEND
|
||||
AGAIN
|
||||
COPY
|
||||
CUT
|
||||
FIND
|
||||
OPEN
|
||||
PASTE
|
||||
PROPS
|
||||
SELECT
|
||||
UNDO
|
||||
HIRAGANA
|
||||
KATAKANA
|
||||
}
|
||||
pub fn Key::from(Int32) -> Self
|
||||
pub fn Key::ordinal(Self) -> Int32
|
||||
|
||||
pub(all) struct KeyEvent {
|
||||
key : Key?
|
||||
text : String?
|
||||
alt_key : Bool
|
||||
ctrl_key : Bool
|
||||
meta_key : Bool
|
||||
shift_key : Bool
|
||||
}
|
||||
|
||||
pub(all) struct PointerEvent {
|
||||
x : Double
|
||||
y : Double
|
||||
}
|
||||
|
||||
pub(all) struct ResizeEvent {
|
||||
height : UInt32
|
||||
width : UInt32
|
||||
}
|
||||
|
||||
pub(all) struct Surface(Int32)
|
||||
pub fn Surface::drop(Self) -> Unit
|
||||
pub fn Surface::height(Self) -> UInt32
|
||||
pub fn Surface::on_frame(Self) -> @async-core.Stream[FrameEvent]
|
||||
pub fn Surface::on_key_down(Self) -> @async-core.Stream[KeyEvent]
|
||||
pub fn Surface::on_key_up(Self) -> @async-core.Stream[KeyEvent]
|
||||
pub fn Surface::on_pointer_down(Self) -> @async-core.Stream[PointerEvent]
|
||||
pub fn Surface::on_pointer_move(Self) -> @async-core.Stream[PointerEvent]
|
||||
pub fn Surface::on_pointer_up(Self) -> @async-core.Stream[PointerEvent]
|
||||
pub fn Surface::on_resize(Self) -> @async-core.Stream[ResizeEvent]
|
||||
pub fn Surface::request_set_size(Self, UInt32?, UInt32?) -> Unit
|
||||
pub fn Surface::surface(CreateDesc) -> Self
|
||||
pub fn Surface::width(Self) -> UInt32
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,545 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
///|
|
||||
pub(all) struct CreateDesc {
|
||||
height : UInt?; width : UInt?
|
||||
}
|
||||
///|
|
||||
pub(all) struct Surface(Int) derive()
|
||||
|
||||
///|
|
||||
/// Drops a resource handle.
|
||||
pub fn Surface::drop(self : Surface) -> Unit {
|
||||
let Surface(resource) = self
|
||||
wasmImportResourceDropSurface(resource)
|
||||
}
|
||||
///|
|
||||
pub(all) struct ResizeEvent {
|
||||
height : UInt; width : UInt
|
||||
}
|
||||
///|
|
||||
pub(all) struct FrameEvent {
|
||||
nothing : Bool
|
||||
}
|
||||
///|
|
||||
pub(all) struct PointerEvent {
|
||||
x : Double; y : Double
|
||||
}
|
||||
///|
|
||||
/// corresponds with https://w3c.github.io/uievents-code/#code-value-tables
|
||||
/// `Unidentified` is not included, use `option<key>` instead.
|
||||
pub(all) enum Key {
|
||||
BACKQUOTE; BACKSLASH; BRACKET_LEFT; BRACKET_RIGHT; COMMA; DIGIT0; DIGIT1; DIGIT2; DIGIT3; DIGIT4; DIGIT5; DIGIT6; DIGIT7; DIGIT8; DIGIT9; EQUAL; INTL_BACKSLASH; INTL_RO; INTL_YEN; KEY_A; KEY_B; KEY_C; KEY_D; KEY_E; KEY_F; KEY_G; KEY_H; KEY_I; KEY_J; KEY_K; KEY_L; KEY_M; KEY_N; KEY_O; KEY_P; KEY_Q; KEY_R; KEY_S; KEY_T; KEY_U; KEY_V; KEY_W; KEY_X; KEY_Y; KEY_Z; MINUS; PERIOD; QUOTE; SEMICOLON; SLASH; ALT_LEFT; ALT_RIGHT; BACKSPACE; CAPS_LOCK; CONTEXT_MENU; CONTROL_LEFT; CONTROL_RIGHT; ENTER; META_LEFT; META_RIGHT; SHIFT_LEFT; SHIFT_RIGHT; SPACE; TAB; CONVERT; KANA_MODE; LANG1; LANG2; LANG3; LANG4; LANG5; NON_CONVERT; DELETE; END; HELP; HOME; INSERT; PAGE_DOWN; PAGE_UP; ARROW_DOWN; ARROW_LEFT; ARROW_RIGHT; ARROW_UP; NUM_LOCK; NUMPAD0; NUMPAD1; NUMPAD2; NUMPAD3; NUMPAD4; NUMPAD5; NUMPAD6; NUMPAD7; NUMPAD8; NUMPAD9; NUMPAD_ADD; NUMPAD_BACKSPACE; NUMPAD_CLEAR; NUMPAD_CLEAR_ENTRY; NUMPAD_COMMA; NUMPAD_DECIMAL; NUMPAD_DIVIDE; NUMPAD_ENTER; NUMPAD_EQUAL; NUMPAD_HASH; NUMPAD_MEMORY_ADD; NUMPAD_MEMORY_CLEAR; NUMPAD_MEMORY_RECALL; NUMPAD_MEMORY_STORE; NUMPAD_MEMORY_SUBTRACT; NUMPAD_MULTIPLY; NUMPAD_PAREN_LEFT; NUMPAD_PAREN_RIGHT; NUMPAD_STAR; NUMPAD_SUBTRACT; ESCAPE; F1; F2; F3; F4; F5; F6; F7; F8; F9; F10; F11; F12; FN; FN_LOCK; PRINT_SCREEN; SCROLL_LOCK; PAUSE; BROWSER_BACK; BROWSER_FAVORITES; BROWSER_FORWARD; BROWSER_HOME; BROWSER_REFRESH; BROWSER_SEARCH; BROWSER_STOP; EJECT; LAUNCH_APP1; LAUNCH_APP2; LAUNCH_MAIL; MEDIA_PLAY_PAUSE; MEDIA_SELECT; MEDIA_STOP; MEDIA_TRACK_NEXT; MEDIA_TRACK_PREVIOUS; POWER; SLEEP; AUDIO_VOLUME_DOWN; AUDIO_VOLUME_MUTE; AUDIO_VOLUME_UP; WAKE_UP; HYPER; SUPER; TURBO; ABORT; RESUME; SUSPEND; AGAIN; COPY; CUT; FIND; OPEN; PASTE; PROPS; SELECT; UNDO; HIRAGANA; KATAKANA
|
||||
} derive()
|
||||
|
||||
///|
|
||||
pub fn Key::ordinal(self : Key) -> Int {
|
||||
match self {
|
||||
BACKQUOTE => 0
|
||||
BACKSLASH => 1
|
||||
BRACKET_LEFT => 2
|
||||
BRACKET_RIGHT => 3
|
||||
COMMA => 4
|
||||
DIGIT0 => 5
|
||||
DIGIT1 => 6
|
||||
DIGIT2 => 7
|
||||
DIGIT3 => 8
|
||||
DIGIT4 => 9
|
||||
DIGIT5 => 10
|
||||
DIGIT6 => 11
|
||||
DIGIT7 => 12
|
||||
DIGIT8 => 13
|
||||
DIGIT9 => 14
|
||||
EQUAL => 15
|
||||
INTL_BACKSLASH => 16
|
||||
INTL_RO => 17
|
||||
INTL_YEN => 18
|
||||
KEY_A => 19
|
||||
KEY_B => 20
|
||||
KEY_C => 21
|
||||
KEY_D => 22
|
||||
KEY_E => 23
|
||||
KEY_F => 24
|
||||
KEY_G => 25
|
||||
KEY_H => 26
|
||||
KEY_I => 27
|
||||
KEY_J => 28
|
||||
KEY_K => 29
|
||||
KEY_L => 30
|
||||
KEY_M => 31
|
||||
KEY_N => 32
|
||||
KEY_O => 33
|
||||
KEY_P => 34
|
||||
KEY_Q => 35
|
||||
KEY_R => 36
|
||||
KEY_S => 37
|
||||
KEY_T => 38
|
||||
KEY_U => 39
|
||||
KEY_V => 40
|
||||
KEY_W => 41
|
||||
KEY_X => 42
|
||||
KEY_Y => 43
|
||||
KEY_Z => 44
|
||||
MINUS => 45
|
||||
PERIOD => 46
|
||||
QUOTE => 47
|
||||
SEMICOLON => 48
|
||||
SLASH => 49
|
||||
ALT_LEFT => 50
|
||||
ALT_RIGHT => 51
|
||||
BACKSPACE => 52
|
||||
CAPS_LOCK => 53
|
||||
CONTEXT_MENU => 54
|
||||
CONTROL_LEFT => 55
|
||||
CONTROL_RIGHT => 56
|
||||
ENTER => 57
|
||||
META_LEFT => 58
|
||||
META_RIGHT => 59
|
||||
SHIFT_LEFT => 60
|
||||
SHIFT_RIGHT => 61
|
||||
SPACE => 62
|
||||
TAB => 63
|
||||
CONVERT => 64
|
||||
KANA_MODE => 65
|
||||
LANG1 => 66
|
||||
LANG2 => 67
|
||||
LANG3 => 68
|
||||
LANG4 => 69
|
||||
LANG5 => 70
|
||||
NON_CONVERT => 71
|
||||
DELETE => 72
|
||||
END => 73
|
||||
HELP => 74
|
||||
HOME => 75
|
||||
INSERT => 76
|
||||
PAGE_DOWN => 77
|
||||
PAGE_UP => 78
|
||||
ARROW_DOWN => 79
|
||||
ARROW_LEFT => 80
|
||||
ARROW_RIGHT => 81
|
||||
ARROW_UP => 82
|
||||
NUM_LOCK => 83
|
||||
NUMPAD0 => 84
|
||||
NUMPAD1 => 85
|
||||
NUMPAD2 => 86
|
||||
NUMPAD3 => 87
|
||||
NUMPAD4 => 88
|
||||
NUMPAD5 => 89
|
||||
NUMPAD6 => 90
|
||||
NUMPAD7 => 91
|
||||
NUMPAD8 => 92
|
||||
NUMPAD9 => 93
|
||||
NUMPAD_ADD => 94
|
||||
NUMPAD_BACKSPACE => 95
|
||||
NUMPAD_CLEAR => 96
|
||||
NUMPAD_CLEAR_ENTRY => 97
|
||||
NUMPAD_COMMA => 98
|
||||
NUMPAD_DECIMAL => 99
|
||||
NUMPAD_DIVIDE => 100
|
||||
NUMPAD_ENTER => 101
|
||||
NUMPAD_EQUAL => 102
|
||||
NUMPAD_HASH => 103
|
||||
NUMPAD_MEMORY_ADD => 104
|
||||
NUMPAD_MEMORY_CLEAR => 105
|
||||
NUMPAD_MEMORY_RECALL => 106
|
||||
NUMPAD_MEMORY_STORE => 107
|
||||
NUMPAD_MEMORY_SUBTRACT => 108
|
||||
NUMPAD_MULTIPLY => 109
|
||||
NUMPAD_PAREN_LEFT => 110
|
||||
NUMPAD_PAREN_RIGHT => 111
|
||||
NUMPAD_STAR => 112
|
||||
NUMPAD_SUBTRACT => 113
|
||||
ESCAPE => 114
|
||||
F1 => 115
|
||||
F2 => 116
|
||||
F3 => 117
|
||||
F4 => 118
|
||||
F5 => 119
|
||||
F6 => 120
|
||||
F7 => 121
|
||||
F8 => 122
|
||||
F9 => 123
|
||||
F10 => 124
|
||||
F11 => 125
|
||||
F12 => 126
|
||||
FN => 127
|
||||
FN_LOCK => 128
|
||||
PRINT_SCREEN => 129
|
||||
SCROLL_LOCK => 130
|
||||
PAUSE => 131
|
||||
BROWSER_BACK => 132
|
||||
BROWSER_FAVORITES => 133
|
||||
BROWSER_FORWARD => 134
|
||||
BROWSER_HOME => 135
|
||||
BROWSER_REFRESH => 136
|
||||
BROWSER_SEARCH => 137
|
||||
BROWSER_STOP => 138
|
||||
EJECT => 139
|
||||
LAUNCH_APP1 => 140
|
||||
LAUNCH_APP2 => 141
|
||||
LAUNCH_MAIL => 142
|
||||
MEDIA_PLAY_PAUSE => 143
|
||||
MEDIA_SELECT => 144
|
||||
MEDIA_STOP => 145
|
||||
MEDIA_TRACK_NEXT => 146
|
||||
MEDIA_TRACK_PREVIOUS => 147
|
||||
POWER => 148
|
||||
SLEEP => 149
|
||||
AUDIO_VOLUME_DOWN => 150
|
||||
AUDIO_VOLUME_MUTE => 151
|
||||
AUDIO_VOLUME_UP => 152
|
||||
WAKE_UP => 153
|
||||
HYPER => 154
|
||||
SUPER => 155
|
||||
TURBO => 156
|
||||
ABORT => 157
|
||||
RESUME => 158
|
||||
SUSPEND => 159
|
||||
AGAIN => 160
|
||||
COPY => 161
|
||||
CUT => 162
|
||||
FIND => 163
|
||||
OPEN => 164
|
||||
PASTE => 165
|
||||
PROPS => 166
|
||||
SELECT => 167
|
||||
UNDO => 168
|
||||
HIRAGANA => 169
|
||||
KATAKANA => 170
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Key::from(self : Int) -> Key {
|
||||
match self {
|
||||
0 => BACKQUOTE
|
||||
1 => BACKSLASH
|
||||
2 => BRACKET_LEFT
|
||||
3 => BRACKET_RIGHT
|
||||
4 => COMMA
|
||||
5 => DIGIT0
|
||||
6 => DIGIT1
|
||||
7 => DIGIT2
|
||||
8 => DIGIT3
|
||||
9 => DIGIT4
|
||||
10 => DIGIT5
|
||||
11 => DIGIT6
|
||||
12 => DIGIT7
|
||||
13 => DIGIT8
|
||||
14 => DIGIT9
|
||||
15 => EQUAL
|
||||
16 => INTL_BACKSLASH
|
||||
17 => INTL_RO
|
||||
18 => INTL_YEN
|
||||
19 => KEY_A
|
||||
20 => KEY_B
|
||||
21 => KEY_C
|
||||
22 => KEY_D
|
||||
23 => KEY_E
|
||||
24 => KEY_F
|
||||
25 => KEY_G
|
||||
26 => KEY_H
|
||||
27 => KEY_I
|
||||
28 => KEY_J
|
||||
29 => KEY_K
|
||||
30 => KEY_L
|
||||
31 => KEY_M
|
||||
32 => KEY_N
|
||||
33 => KEY_O
|
||||
34 => KEY_P
|
||||
35 => KEY_Q
|
||||
36 => KEY_R
|
||||
37 => KEY_S
|
||||
38 => KEY_T
|
||||
39 => KEY_U
|
||||
40 => KEY_V
|
||||
41 => KEY_W
|
||||
42 => KEY_X
|
||||
43 => KEY_Y
|
||||
44 => KEY_Z
|
||||
45 => MINUS
|
||||
46 => PERIOD
|
||||
47 => QUOTE
|
||||
48 => SEMICOLON
|
||||
49 => SLASH
|
||||
50 => ALT_LEFT
|
||||
51 => ALT_RIGHT
|
||||
52 => BACKSPACE
|
||||
53 => CAPS_LOCK
|
||||
54 => CONTEXT_MENU
|
||||
55 => CONTROL_LEFT
|
||||
56 => CONTROL_RIGHT
|
||||
57 => ENTER
|
||||
58 => META_LEFT
|
||||
59 => META_RIGHT
|
||||
60 => SHIFT_LEFT
|
||||
61 => SHIFT_RIGHT
|
||||
62 => SPACE
|
||||
63 => TAB
|
||||
64 => CONVERT
|
||||
65 => KANA_MODE
|
||||
66 => LANG1
|
||||
67 => LANG2
|
||||
68 => LANG3
|
||||
69 => LANG4
|
||||
70 => LANG5
|
||||
71 => NON_CONVERT
|
||||
72 => DELETE
|
||||
73 => END
|
||||
74 => HELP
|
||||
75 => HOME
|
||||
76 => INSERT
|
||||
77 => PAGE_DOWN
|
||||
78 => PAGE_UP
|
||||
79 => ARROW_DOWN
|
||||
80 => ARROW_LEFT
|
||||
81 => ARROW_RIGHT
|
||||
82 => ARROW_UP
|
||||
83 => NUM_LOCK
|
||||
84 => NUMPAD0
|
||||
85 => NUMPAD1
|
||||
86 => NUMPAD2
|
||||
87 => NUMPAD3
|
||||
88 => NUMPAD4
|
||||
89 => NUMPAD5
|
||||
90 => NUMPAD6
|
||||
91 => NUMPAD7
|
||||
92 => NUMPAD8
|
||||
93 => NUMPAD9
|
||||
94 => NUMPAD_ADD
|
||||
95 => NUMPAD_BACKSPACE
|
||||
96 => NUMPAD_CLEAR
|
||||
97 => NUMPAD_CLEAR_ENTRY
|
||||
98 => NUMPAD_COMMA
|
||||
99 => NUMPAD_DECIMAL
|
||||
100 => NUMPAD_DIVIDE
|
||||
101 => NUMPAD_ENTER
|
||||
102 => NUMPAD_EQUAL
|
||||
103 => NUMPAD_HASH
|
||||
104 => NUMPAD_MEMORY_ADD
|
||||
105 => NUMPAD_MEMORY_CLEAR
|
||||
106 => NUMPAD_MEMORY_RECALL
|
||||
107 => NUMPAD_MEMORY_STORE
|
||||
108 => NUMPAD_MEMORY_SUBTRACT
|
||||
109 => NUMPAD_MULTIPLY
|
||||
110 => NUMPAD_PAREN_LEFT
|
||||
111 => NUMPAD_PAREN_RIGHT
|
||||
112 => NUMPAD_STAR
|
||||
113 => NUMPAD_SUBTRACT
|
||||
114 => ESCAPE
|
||||
115 => F1
|
||||
116 => F2
|
||||
117 => F3
|
||||
118 => F4
|
||||
119 => F5
|
||||
120 => F6
|
||||
121 => F7
|
||||
122 => F8
|
||||
123 => F9
|
||||
124 => F10
|
||||
125 => F11
|
||||
126 => F12
|
||||
127 => FN
|
||||
128 => FN_LOCK
|
||||
129 => PRINT_SCREEN
|
||||
130 => SCROLL_LOCK
|
||||
131 => PAUSE
|
||||
132 => BROWSER_BACK
|
||||
133 => BROWSER_FAVORITES
|
||||
134 => BROWSER_FORWARD
|
||||
135 => BROWSER_HOME
|
||||
136 => BROWSER_REFRESH
|
||||
137 => BROWSER_SEARCH
|
||||
138 => BROWSER_STOP
|
||||
139 => EJECT
|
||||
140 => LAUNCH_APP1
|
||||
141 => LAUNCH_APP2
|
||||
142 => LAUNCH_MAIL
|
||||
143 => MEDIA_PLAY_PAUSE
|
||||
144 => MEDIA_SELECT
|
||||
145 => MEDIA_STOP
|
||||
146 => MEDIA_TRACK_NEXT
|
||||
147 => MEDIA_TRACK_PREVIOUS
|
||||
148 => POWER
|
||||
149 => SLEEP
|
||||
150 => AUDIO_VOLUME_DOWN
|
||||
151 => AUDIO_VOLUME_MUTE
|
||||
152 => AUDIO_VOLUME_UP
|
||||
153 => WAKE_UP
|
||||
154 => HYPER
|
||||
155 => SUPER
|
||||
156 => TURBO
|
||||
157 => ABORT
|
||||
158 => RESUME
|
||||
159 => SUSPEND
|
||||
160 => AGAIN
|
||||
161 => COPY
|
||||
162 => CUT
|
||||
163 => FIND
|
||||
164 => OPEN
|
||||
165 => PASTE
|
||||
166 => PROPS
|
||||
167 => SELECT
|
||||
168 => UNDO
|
||||
169 => HIRAGANA
|
||||
170 => KATAKANA
|
||||
_ => panic()
|
||||
}
|
||||
}
|
||||
///|
|
||||
pub(all) struct KeyEvent {
|
||||
key : Key?; text : String?; alt_key : Bool; ctrl_key : Bool; meta_key : Bool; shift_key : Bool
|
||||
}
|
||||
///|
|
||||
pub fn Surface::surface(desc : CreateDesc) -> Surface {
|
||||
|
||||
let (lowered, lowered1) = match ((desc).height) {
|
||||
None => {
|
||||
|
||||
((0), 0)
|
||||
}
|
||||
Some(payload0) => {
|
||||
|
||||
((1), (payload0).reinterpret_as_int())
|
||||
}
|
||||
}
|
||||
|
||||
let (lowered4, lowered5) = match ((desc).width) {
|
||||
None => {
|
||||
|
||||
((0), 0)
|
||||
}
|
||||
Some(payload3) => {
|
||||
|
||||
((1), (payload3).reinterpret_as_int())
|
||||
}
|
||||
}
|
||||
let result : Int = wasmImportConstructorSurface(lowered, lowered1, lowered4, lowered5);
|
||||
let ret = Surface::Surface(result)
|
||||
return ret
|
||||
|
||||
}
|
||||
///|
|
||||
pub fn Surface::height(self : Surface) -> UInt {
|
||||
|
||||
let Surface(handle) = self
|
||||
let result : Int = wasmImportMethodSurfaceHeight(handle);
|
||||
let ret = (result).reinterpret_as_uint()
|
||||
return ret
|
||||
|
||||
}
|
||||
///|
|
||||
pub fn Surface::width(self : Surface) -> UInt {
|
||||
|
||||
let Surface(handle) = self
|
||||
let result : Int = wasmImportMethodSurfaceWidth(handle);
|
||||
let ret = (result).reinterpret_as_uint()
|
||||
return ret
|
||||
|
||||
}
|
||||
///|
|
||||
pub fn Surface::request_set_size(self : Surface, height : UInt?, width : UInt?) -> Unit {
|
||||
|
||||
let Surface(handle) = self
|
||||
|
||||
let (lowered, lowered1) = match (height) {
|
||||
None => {
|
||||
|
||||
((0), 0)
|
||||
}
|
||||
Some(payload0) => {
|
||||
|
||||
((1), (payload0).reinterpret_as_int())
|
||||
}
|
||||
}
|
||||
|
||||
let (lowered4, lowered5) = match (width) {
|
||||
None => {
|
||||
|
||||
((0), 0)
|
||||
}
|
||||
Some(payload3) => {
|
||||
|
||||
((1), (payload3).reinterpret_as_int())
|
||||
}
|
||||
}
|
||||
wasmImportMethodSurfaceRequestSetSize(handle, lowered, lowered1, lowered4, lowered5);
|
||||
|
||||
}
|
||||
///|
|
||||
pub fn Surface::on_resize(self : Surface) -> @async-core.Stream[ResizeEvent] {
|
||||
|
||||
let Surface(handle) = self
|
||||
let lower_arg = handle
|
||||
let result : Int = wasmImportMethodSurfaceOnResize(lower_arg);
|
||||
let result0 = wasmWasiGfxSurfaceSurface020MethodSurfaceOnResizeStream0StreamLift(result)
|
||||
let ret = result0
|
||||
return ret
|
||||
|
||||
}
|
||||
///|
|
||||
pub fn Surface::on_frame(self : Surface) -> @async-core.Stream[FrameEvent] {
|
||||
|
||||
let Surface(handle) = self
|
||||
let lower_arg = handle
|
||||
let result : Int = wasmImportMethodSurfaceOnFrame(lower_arg);
|
||||
let result0 = wasmWasiGfxSurfaceSurface020MethodSurfaceOnFrameStream0StreamLift(result)
|
||||
let ret = result0
|
||||
return ret
|
||||
|
||||
}
|
||||
///|
|
||||
pub fn Surface::on_pointer_up(self : Surface) -> @async-core.Stream[PointerEvent] {
|
||||
|
||||
let Surface(handle) = self
|
||||
let lower_arg = handle
|
||||
let result : Int = wasmImportMethodSurfaceOnPointerUp(lower_arg);
|
||||
let result0 = wasmWasiGfxSurfaceSurface020MethodSurfaceOnPointerUpStream0StreamLift(result)
|
||||
let ret = result0
|
||||
return ret
|
||||
|
||||
}
|
||||
///|
|
||||
pub fn Surface::on_pointer_down(self : Surface) -> @async-core.Stream[PointerEvent] {
|
||||
|
||||
let Surface(handle) = self
|
||||
let lower_arg = handle
|
||||
let result : Int = wasmImportMethodSurfaceOnPointerDown(lower_arg);
|
||||
let result0 = wasmWasiGfxSurfaceSurface020MethodSurfaceOnPointerDownStream0StreamLift(result)
|
||||
let ret = result0
|
||||
return ret
|
||||
|
||||
}
|
||||
///|
|
||||
pub fn Surface::on_pointer_move(self : Surface) -> @async-core.Stream[PointerEvent] {
|
||||
|
||||
let Surface(handle) = self
|
||||
let lower_arg = handle
|
||||
let result : Int = wasmImportMethodSurfaceOnPointerMove(lower_arg);
|
||||
let result0 = wasmWasiGfxSurfaceSurface020MethodSurfaceOnPointerMoveStream0StreamLift(result)
|
||||
let ret = result0
|
||||
return ret
|
||||
|
||||
}
|
||||
///|
|
||||
pub fn Surface::on_key_up(self : Surface) -> @async-core.Stream[KeyEvent] {
|
||||
|
||||
let Surface(handle) = self
|
||||
let lower_arg = handle
|
||||
let result : Int = wasmImportMethodSurfaceOnKeyUp(lower_arg);
|
||||
let result0 = wasmWasiGfxSurfaceSurface020MethodSurfaceOnKeyUpStream0StreamLift(result)
|
||||
let ret = result0
|
||||
return ret
|
||||
|
||||
}
|
||||
///|
|
||||
pub fn Surface::on_key_down(self : Surface) -> @async-core.Stream[KeyEvent] {
|
||||
|
||||
let Surface(handle) = self
|
||||
let lower_arg = handle
|
||||
let result : Int = wasmImportMethodSurfaceOnKeyDown(lower_arg);
|
||||
let result0 = wasmWasiGfxSurfaceSurface020MethodSurfaceOnKeyDownStream0StreamLift(result)
|
||||
let ret = result0
|
||||
return ret
|
||||
|
||||
}
|
||||
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build wasi-gfx GUI loader MoonBit component from wit/gfx/ and transpile with jco.
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT"
|
||||
export PATH="$ROOT/.tools/bin:$HOME/.moon/bin:$PATH"
|
||||
JCO="$ROOT/host/node_modules/.bin/jco"
|
||||
[ -x "$JCO" ] || { echo "error: jco missing; run: (cd host && npm ci)" >&2; exit 1; }
|
||||
|
||||
wasm-tools component wit wit/gfx >/dev/null
|
||||
moon build --target wasm --release components/gfx-gui/gen 2>&1 | grep -v -E 'Warning|^\s*$|[│╭╰─]' || true
|
||||
[ "${PIPESTATUS[0]}" -eq 0 ] || { echo "error: moon build failed" >&2; exit 1; }
|
||||
|
||||
mkdir -p build/components build/jco
|
||||
core="_build/wasm/release/build/components/gfx-gui/gen/gen.wasm"
|
||||
[ -f "$core" ] || { echo "error: $core missing" >&2; exit 1; }
|
||||
out="build/components/gfx-gui.wasm"
|
||||
wasm-tools component embed wit/gfx "$core" --world gui-loader --encoding utf16 -o "build/components/gfx-gui.embed.wasm"
|
||||
wasm-tools component new "build/components/gfx-gui.embed.wasm" -o "$out"
|
||||
rm -f "build/components/gfx-gui.embed.wasm"
|
||||
wasm-tools validate --features component-model "$out"
|
||||
wasm-tools component targets --world gui-loader wit/gfx "$out" >/dev/null
|
||||
|
||||
rm -rf "build/jco/gfx-gui"
|
||||
"$JCO" transpile "$out" -o "build/jco/gfx-gui" --instantiation async --no-typescript --name gfx-gui >/dev/null
|
||||
echo '{"type":"module"}' > "build/jco/gfx-gui/package.json"
|
||||
printf ' %-18s %-20s %7s bytes\n' "gfx-gui" "gui-loader" "$(stat -c %s "$out")"
|
||||
echo "ok (gfx)"
|
||||
@@ -25,6 +25,10 @@ generate() { # <out-dir> <ignore-stub: 0|1>
|
||||
--gen-dir "components/$name/gen" --project-name moonplasma/desktop \
|
||||
--ignore-module-file "${extra[@]}" >/dev/null 2>"$log" || { cat "$log" >&2; exit 1; }
|
||||
done < scripts/components.txt
|
||||
extra=(); [ "$ignore" = 1 ] && extra+=(--ignore-stub)
|
||||
wit-bindgen moonbit wit/gfx --world gui-loader --out-dir "$out" \
|
||||
--gen-dir "components/gfx-gui/gen" --project-name moonplasma/desktop \
|
||||
--ignore-module-file "${extra[@]}" >/dev/null 2>"$log" || { cat "$log" >&2; exit 1; }
|
||||
}
|
||||
|
||||
if [ "${1:-}" = "--check" ]; then
|
||||
|
||||
+5
-2
@@ -22,6 +22,9 @@ scripts/build.sh
|
||||
step "build wm & decoration components"
|
||||
scripts/build-wm.sh
|
||||
|
||||
step "build wasi-gfx GUI loader component"
|
||||
scripts/build-gfx.sh
|
||||
|
||||
if command -v wasmtime >/dev/null; then
|
||||
step "wasmtime accepts every component (compile only; hosts supply the imports)"
|
||||
for f in build/components/*.wasm; do
|
||||
@@ -32,6 +35,6 @@ fi
|
||||
step "host integration tests (jco + Node)"
|
||||
(cd host && npm test)
|
||||
|
||||
step "pure-MoonBit native Wayland compositor + e2e tests (compositor/)"
|
||||
moon test --target native --warn-list -a compositor/renderer compositor/host
|
||||
step "pure-MoonBit native Wayland compositor + wasi-gfx + e2e tests (compositor/)"
|
||||
moon test --target native --warn-list -a compositor/renderer compositor/gfx compositor/host
|
||||
moon build --target native --warn-list -a compositor/bin
|
||||
@@ -0,0 +1,13 @@
|
||||
package wasi-gfx:frame-buffer@0.2.0;
|
||||
|
||||
world imports {
|
||||
import frame-buffer;
|
||||
}
|
||||
|
||||
interface frame-buffer {
|
||||
resource buffer {
|
||||
// TODO: This should be replaced with something that doesn't require a copy.
|
||||
get-with-copy: func() -> list<u8>;
|
||||
set-with-copy: func(val: list<u8>);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
interface surface-frame-buffer {
|
||||
use wasi-gfx:frame-buffer/frame-buffer@0.2.0.{buffer};
|
||||
use surface.{surface};
|
||||
|
||||
resource context {
|
||||
constructor(surface: borrow<surface>);
|
||||
get-current-buffer: func() -> buffer;
|
||||
// TODO: consider if needed
|
||||
present: func();
|
||||
}
|
||||
}
|
||||
|
||||
world frame-buffer-imports {
|
||||
import surface-frame-buffer;
|
||||
import wasi-gfx:frame-buffer/frame-buffer@0.2.0;
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package wasi-gfx:surface@0.2.0;
|
||||
|
||||
world imports {
|
||||
import surface;
|
||||
}
|
||||
|
||||
interface surface {
|
||||
record create-desc {
|
||||
height: option<u32>,
|
||||
width: option<u32>,
|
||||
}
|
||||
|
||||
resource surface {
|
||||
constructor(desc: create-desc);
|
||||
|
||||
height: func() -> u32;
|
||||
width: func() -> u32;
|
||||
|
||||
request-set-size: func(height: option<u32>, width: option<u32>);
|
||||
|
||||
on-resize: func() -> stream<resize-event>;
|
||||
on-frame: func() -> stream<frame-event>;
|
||||
on-pointer-up: func() -> stream<pointer-event>;
|
||||
on-pointer-down: func() -> stream<pointer-event>;
|
||||
on-pointer-move: func() -> stream<pointer-event>;
|
||||
on-key-up: func() -> stream<key-event>;
|
||||
on-key-down: func() -> stream<key-event>;
|
||||
}
|
||||
|
||||
record resize-event {
|
||||
height: u32,
|
||||
width: u32,
|
||||
}
|
||||
|
||||
record frame-event {
|
||||
/// TODO: This field doesn't mean anything.
|
||||
/// Can't have empty record. Would like to have a way around this.
|
||||
nothing: bool,
|
||||
}
|
||||
|
||||
record pointer-event {
|
||||
x: f64,
|
||||
y: f64,
|
||||
}
|
||||
|
||||
record key-event {
|
||||
key: option<key>,
|
||||
text: option<string>,
|
||||
alt-key: bool,
|
||||
ctrl-key: bool,
|
||||
meta-key: bool,
|
||||
shift-key: bool,
|
||||
}
|
||||
|
||||
// corresponds with https://w3c.github.io/uievents-code/#code-value-tables
|
||||
// `Unidentified` is not included, use `option<key>` instead.
|
||||
enum key {
|
||||
backquote,
|
||||
backslash,
|
||||
bracket-left,
|
||||
bracket-right,
|
||||
comma,
|
||||
digit0,
|
||||
digit1,
|
||||
digit2,
|
||||
digit3,
|
||||
digit4,
|
||||
digit5,
|
||||
digit6,
|
||||
digit7,
|
||||
digit8,
|
||||
digit9,
|
||||
equal,
|
||||
intl-backslash,
|
||||
intl-ro,
|
||||
intl-yen,
|
||||
key-a,
|
||||
key-b,
|
||||
key-c,
|
||||
key-d,
|
||||
key-e,
|
||||
key-f,
|
||||
key-g,
|
||||
key-h,
|
||||
key-i,
|
||||
key-j,
|
||||
key-k,
|
||||
key-l,
|
||||
key-m,
|
||||
key-n,
|
||||
key-o,
|
||||
key-p,
|
||||
key-q,
|
||||
key-r,
|
||||
key-s,
|
||||
key-t,
|
||||
key-u,
|
||||
key-v,
|
||||
key-w,
|
||||
key-x,
|
||||
key-y,
|
||||
key-z,
|
||||
minus,
|
||||
period,
|
||||
quote,
|
||||
semicolon,
|
||||
slash,
|
||||
alt-left,
|
||||
alt-right,
|
||||
backspace,
|
||||
caps-lock,
|
||||
context-menu,
|
||||
control-left,
|
||||
control-right,
|
||||
enter,
|
||||
meta-left,
|
||||
meta-right,
|
||||
shift-left,
|
||||
shift-right,
|
||||
space,
|
||||
tab,
|
||||
convert,
|
||||
kana-mode,
|
||||
lang1,
|
||||
lang2,
|
||||
lang3,
|
||||
lang4,
|
||||
lang5,
|
||||
non-convert,
|
||||
delete,
|
||||
end,
|
||||
help,
|
||||
home,
|
||||
insert,
|
||||
page-down,
|
||||
page-up,
|
||||
arrow-down,
|
||||
arrow-left,
|
||||
arrow-right,
|
||||
arrow-up,
|
||||
num-lock,
|
||||
numpad0,
|
||||
numpad1,
|
||||
numpad2,
|
||||
numpad3,
|
||||
numpad4,
|
||||
numpad5,
|
||||
numpad6,
|
||||
numpad7,
|
||||
numpad8,
|
||||
numpad9,
|
||||
numpad-add,
|
||||
numpad-backspace,
|
||||
numpad-clear,
|
||||
numpad-clear-entry,
|
||||
numpad-comma,
|
||||
numpad-decimal,
|
||||
numpad-divide,
|
||||
numpad-enter,
|
||||
numpad-equal,
|
||||
numpad-hash,
|
||||
numpad-memory-add,
|
||||
numpad-memory-clear,
|
||||
numpad-memory-recall,
|
||||
numpad-memory-store,
|
||||
numpad-memory-subtract,
|
||||
numpad-multiply,
|
||||
numpad-paren-left,
|
||||
numpad-paren-right,
|
||||
numpad-star,
|
||||
numpad-subtract,
|
||||
escape,
|
||||
f1,
|
||||
f2,
|
||||
f3,
|
||||
f4,
|
||||
f5,
|
||||
f6,
|
||||
f7,
|
||||
f8,
|
||||
f9,
|
||||
f10,
|
||||
f11,
|
||||
f12,
|
||||
fn,
|
||||
fn-lock,
|
||||
print-screen,
|
||||
scroll-lock,
|
||||
pause,
|
||||
browser-back,
|
||||
browser-favorites,
|
||||
browser-forward,
|
||||
browser-home,
|
||||
browser-refresh,
|
||||
browser-search,
|
||||
browser-stop,
|
||||
eject,
|
||||
launch-app1,
|
||||
launch-app2,
|
||||
launch-mail,
|
||||
media-play-pause,
|
||||
media-select,
|
||||
media-stop,
|
||||
media-track-next,
|
||||
media-track-previous,
|
||||
power,
|
||||
sleep,
|
||||
audio-volume-down,
|
||||
audio-volume-mute,
|
||||
audio-volume-up,
|
||||
wake-up,
|
||||
hyper,
|
||||
super,
|
||||
turbo,
|
||||
abort,
|
||||
resume,
|
||||
suspend,
|
||||
again,
|
||||
copy,
|
||||
cut,
|
||||
find,
|
||||
open,
|
||||
paste,
|
||||
props,
|
||||
select,
|
||||
undo,
|
||||
hiragana,
|
||||
katakana,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package moonplasma:gfx@0.2.0;
|
||||
|
||||
/// Host-agnostic GUI loader world backed by wasi-gfx surfaces & frame-buffers.
|
||||
world gui-loader {
|
||||
import wasi-gfx:surface/surface@0.2.0;
|
||||
import wasi-gfx:surface/surface-frame-buffer@0.2.0;
|
||||
import wasi-gfx:frame-buffer/frame-buffer@0.2.0;
|
||||
|
||||
export init-gui: func(width: u32, height: u32);
|
||||
export render-frame: func();
|
||||
export on-resize: func(width: u32, height: u32);
|
||||
export on-pointer: func(kind: u8, x: f64, y: f64);
|
||||
export on-key: func(pressed: bool, text: string);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
Host-agnostic GUI loader world backed by wasi-gfx surfaces & frame-buffers.
|
||||
@@ -0,0 +1,2 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
warnings = "-44"
|
||||
@@ -0,0 +1,12 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "moonplasma/desktop/world/gui-loader"
|
||||
|
||||
// Values
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
Reference in new issue
Block a user