name: gpui-context description: GPUI中的上下文管理,包括App、Window和AsyncApp。当处理上下文、实体更新或窗口操作时使用。不同的上下文类型提供不同的UI渲染、实体管理和异步操作能力。
概述
GPUI针对不同场景使用不同的上下文类型:
上下文类型:
App:全局应用状态,实体创建Window:窗口特定操作,绘画,布局Context<T>:组件T的实体特定上下文AsyncApp:用于前台任务的异步上下文AsyncWindowContext:具有窗口访问的异步上下文
快速开始
Context<T> - 组件上下文
impl MyComponent {
fn update_state(&mut self, cx: &mut Context<Self>) {
self.value = 42;
cx.notify(); // 触发重新渲染
// 生成异步任务
cx.spawn(async move |cx| {
// 异步工作
}).detach();
// 获取当前实体
let entity = cx.entity();
}
}
App - 全局上下文
fn main() {
let app = Application::new();
app.run(|cx: &mut App| {
// 创建实体
let entity = cx.new(|cx| MyState::default());
// 打开窗口
cx.open_window(WindowOptions::default(), |window, cx| {
cx.new(|cx| Root::new(view, window, cx))
});
});
}
Window - 窗口上下文
impl Render for MyView {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// 窗口操作
let is_focused = window.is_window_focused();
let bounds = window.bounds();
div().child("内容")
}
}
AsyncApp - 异步上下文
cx.spawn(async move |cx: &mut AsyncApp| {
let data = fetch_data().await;
entity.update(cx, |state, inner_cx| {
state.data = data;
inner_cx.notify();
}).ok();
}).detach();
常见操作
实体操作
// 创建实体
let entity = cx.new(|cx| MyState::default());
// 更新实体
entity.update(cx, |state, cx| {
state.value = 42;
cx.notify();
});
// 读取实体
let value = entity.read(cx).value;
通知和事件
// 触发重新渲染
cx.notify();
// 发射事件
cx.emit(MyEvent::Updated);
// 观察实体
cx.observe(&entity, |this, observed, cx| {
// 响应变化
}).detach();
// 订阅事件
cx.subscribe(&entity, |this, source, event, cx| {
// 处理事件
}).detach();
窗口操作
// 窗口状态
let focused = window.is_window_focused();
let bounds = window.bounds();
let scale = window.scale_factor();
// 关闭窗口
window.remove_window();
异步操作
// 生成前台任务
cx.spawn(async move |cx| {
// 具有实体访问的异步工作
}).detach();
// 生成后台任务
cx.background_spawn(async move {
// 繁重计算
}).detach();
上下文层次结构
App (全局)
└─ Window (每窗口)
└─ Context<T> (每组件)
└─ AsyncApp (在异步任务中)
└─ AsyncWindowContext (异步 + 窗口)
参考文档
- API 参考:参见 api-reference.md
- 完整上下文API,方法,转换
- 实体操作,窗口操作
- 异步上下文,最佳实践