要在 Piston + Conrod 的環境中實作 更完整的事件處理(包含滑鼠點擊、拖曳等互動),重點是:
- 正確轉換 piston_window 的事件成 conrod 可識別的事件(
conrod_core::event::Input)
- 在主事件迴圈中將所有事件傳給 conrod UI
- 利用 conrod 的 widget 回傳事件(例如按鈕點擊、滑桿拖曳)
完整事件處理示範重點
以下示範一個縮小版範例,涵蓋滑鼠點擊與拖曳事件,示範以下流程:
- piston_window 接收鍵盤和鼠標事件
- 轉換成 conrod 事件並注入 UI
- conrod 根據事件回饋互動結果(例如按下、拖曳)
- 彈窗裡有按鈕和滑桿可互動
環境設定(Cargo.toml)
[dependencies]
piston_window = "0.127"
conrod_core = "0.76"
conrod_piston = "0.76"
find_folder = "0.3"
lazy_static = "1.4"
事件轉換函式(支援鍵盤、滑鼠點擊、滑鼠拖曳)
fn convert_event(event: &piston_window::Event) -> Option<conrod_core::event::Input> {
use conrod_core::event::{Input, Button as CButton, Motion, Key, MouseButton, Press, Release};
use piston_window::{Event, Button, Motion as PMotion, Key as PKey, MouseCursorEvent};
match event {
Event::Input(input, _) => match input {
piston_window::Input::Button(button_args) => {
let state = match button_args.state {
piston_window::ButtonState::Press => Press,
piston_window::ButtonState::Release => Release,
};
match button_args.button {
Button::Keyboard(key) => {
let key = match key {
PKey::Backspace => Key::Backspace,
PKey::Delete => Key::Delete,
PKey::Down => Key::Down,
PKey::End => Key::End,
PKey::Enter => Key::Return,
PKey::Escape => Key::Escape,
PKey::Left => Key::Left,
PKey::Home => Key::Home,
PKey::Return => Key::Return,
PKey::Right => Key::Right,
PKey::Space => Key::Space,
PKey::Tab => Key::Tab,
PKey::Up => Key::Up,
_ => return None,
};
Some(Input::Button(CButton::Keyboard(key), state))
}
Button::Mouse(mouse_btn) => {
let mouse_btn = match mouse_btn {
piston_window::MouseButton::Left => MouseButton::Left,
piston_window::MouseButton::Right => MouseButton::Right,
piston_window::MouseButton::Middle => MouseButton::Middle,
};
Some(Input::Button(CButton::Mouse(mouse_btn), state))
}
_ => None,
}
}
piston_window::Input::Move(motion) => {
// 轉換滑鼠游標移動
match motion {
PMotion::MouseCursor{x, y} => {
Some(Input::Motion(Motion::MouseCursor([*x, *y])))
}
_ => None,
}
}
_ => None,
},
_ => None,
}
}
基本應用示範程式碼(整合上述事件處理)
以下範例內含:
- 主頁面:用按鈕開啟 Modal
- Modal 視窗裡:有按鈕與滑桿,支援滑鼠點擊與拖拽互動
extern crate piston_window;
extern crate conrod_core;
extern crate conrod_piston;
extern crate find_folder;
#[macro_use] extern crate lazy_static;
use piston_window::*;
use conrod_core::{widget, Colorable, Positionable, Sizeable, Widget};
use conrod_core::widget_ids;
widget_ids! {
struct Ids {
button,
slider,
text,
}
}
trait State {
fn input(&mut self, event: &piston_window::Event, stack: &mut StateStack);
fn update(&mut self);
fn render(&mut self, c: piston_window::Context, g: &mut G2d);
}
struct StateStack {
stack: Vec<Box<dyn State>>,
}
impl StateStack {
fn new(initial: Box<dyn State>) -> Self {
Self { stack: vec![initial] }
}
fn push(&mut self, state: Box<dyn State>) {
self.stack.push(state);
}
fn pop(&mut self) {
self.stack.pop();
}
fn input(&mut self, e: &piston_window::Event) {
if let Some(top) = self.stack.last_mut() {
top.input(e, self);
}
}
fn update(&mut self) {
if let Some(top) = self.stack.last_mut() {
top.update();
}
}
fn render(&mut self, c: piston_window::Context, g: &mut G2d) {
if let Some(top) = self.stack.last_mut() {
top.render(c, g);
}
}
}
struct MainPage {
slider_val: f64,
}
impl MainPage {
fn new() -> Self {
MainPage {
slider_val: 0.5,
}
}
}
impl State for MainPage {
fn input(&mut self, event: &piston_window::Event, stack: &mut StateStack) {
if let Some(Button::Keyboard(key)) = event.press_args() {
if key == Key::M {
stack.push(Box::new(ModalWindow::new(self.slider_val)));
}
}
}
fn update(&mut self) {}
fn render(&mut self, c: piston_window::Context, g: &mut G2d) {
clear([0.9, 0.9, 0.9, 1.0], g);
let text = format!("主頁面(按 M 彈出 Modal)\n滑桿值:{:.2}", self.slider_val);
piston_window::text::Text::new_color([0., 0., 0., 1.], 24)
.draw(
&text,
&mut FONT_CACHE.lock().unwrap(),
&DrawState::default(),
c.transform.trans(50.0, 100.0),
g,
).unwrap();
}
}
struct ModalWindow {
ui: conrod_core::Ui,
ids: Ids,
slider_value: f64,
close_requested: bool,
}
impl ModalWindow {
fn new(init_val: f64) -> Self {
let mut ui = conrod_core::UiBuilder::new([640.0, 480.0]).build();
let ids = Ids::new(ui.widget_id_generator());
ModalWindow {
ui,
ids,
slider_value: init_val,
close_requested: false,
}
}
}
impl State for ModalWindow {
fn input(&mut self, event: &piston_window::Event, stack: &mut StateStack) {
if let Some(input) = convert_event(event) {
self.ui.handle_event(input);
}
// ESC 關閉
if let Some(Button::Keyboard(key)) = event.press_args() {
if key == Key::Escape {
self.close_requested = true;
}
}
}
fn update(&mut self) {
let slider_val = &mut self.slider_value;
let ids = &self.ids;
self.ui.set_widgets(|mut ui| {
use conrod_core::widget;
widget::Canvas::new()
.color(conrod_core::color::rgba(0.0, 0.0, 0.0, 0.5))
.set(ui.widget_id_generator().next(), &mut ui);
widget::Canvas::new()
.color(conrod_core::color::WHITE)
.w_h(400.0, 200.0)
.mid_top_of(ui.window)
.set(ui.widget_id_generator().next(), &mut ui);
if widget::Button::new()
.w_h(120.0, 40.0)
.mid_bottom_with_margin_on(ui.window, 20.0)
.label("Close (Esc)")
.set(ids.button, &mut ui)
.was_pressed()
{
self.close_requested = true;
}
*slider_val = widget::Slider::new(*slider_val, 0.0..=1.0)
.w_h(300.0, 40.0)
.mid_top_with_margin_on(ui.window, 30.0)
.label("Value")
.set(ids.slider, &mut ui)
.get();
widget::Text::new(&format!("Value = {:.2}", *slider_val))
.down(10.0)
.mid_top_with_margin_on(ui.window, 80.0)
.set(ids.text, &mut ui);
})
}
fn render(&mut self, c: piston_window::Context, g: &mut G2d) {
use conrod_piston::draw::primitives;
clear([0.0, 0.0, 0.0, 0.5], g);
let primitives = self.ui.draw();
primitives.draw(c, g, self.ui.image_map());
// 字形緩存刷新等(依整合情況調整)
}
}
fn main() {
let mut window: PistonWindow = WindowSettings::new("Piston+Conrod 完整事件", [640, 480])
.exit_on_esc(true)
.build()
.unwrap();
lazy_static::lazy_static! {
static ref FONT_CACHE: std::sync::Mutex<piston_window::Glyphs> = {
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").unwrap();
let font_path = assets.join("FiraSans-Regular.ttf");
std::sync::Mutex::new(window.load_font(font_path).unwrap())
};
}
let mut state_stack = StateStack::new(Box::new(MainPage::new()));
while let Some(event) = window.next() {
state_stack.input(&event);
state_stack.update();
window.draw_2d(&event, |c, g, device| {
state_stack.render(c, g);
FONT_CACHE.lock().unwrap().factory.encoder.flush(device);
});
if let Some(modal) = state_stack.stack.last() {
// 如果彈窗關閉請移除
if let Some(modal) = modal.as_any().downcast_ref::<ModalWindow>() {
if modal.close_requested {
state_stack.pop();
}
}
}
}
}
// 事件轉換函式 (同前)
fn convert_event(event: &piston_window::Event) -> Option<conrod_core::event::Input> {
use conrod_core::event::{Input, Button as CButton, Motion, Key, MouseButton, Press, Release};
use piston_window::{Event, Button, Key as PKey, Motion as PMotion};
match event {
Event::Input(input, _) => match input {
piston_window::Input::Button(button_args) => {
let state = match button_args.state {
piston_window::ButtonState::Press => Press,
piston_window::ButtonState::Release => Release,
};
match button_args.button {
Button::Keyboard(key) => {
let key = match key {
PKey::Backspace => Key::Backspace,
PKey::Delete => Key::Delete,
PKey::Down => Key::Down,
PKey::End => Key::End,
PKey::Enter => Key::Return,
PKey::Escape => Key::Escape,
PKey::Left => Key::Left,
PKey::Home => Key::Home,
PKey::Return => Key::Return,
PKey::Right => Key::Right,
PKey::Space => Key::Space,
PKey::Tab => Key::Tab,
PKey::Up => Key::Up,
_ => return None,
};
Some(Input::Button(CButton::Keyboard(key), state))
}
Button::Mouse(mouse_btn) => {
let mouse_btn = match mouse_btn {
piston_window::MouseButton::Left => MouseButton::Left,
piston_window::MouseButton::Right => MouseButton::Right,
piston_window::MouseButton::Middle => MouseButton::Middle,
};
Some(Input::Button(CButton::Mouse(mouse_btn), state))
}
_ => None,
}
}
piston_window::Input::Move(motion) => {
match motion {
PMotion::MouseCursor { x, y } => Some(Input::Motion(Motion::MouseCursor([*x, *y]))),
_ => None,
}
}
_ => None,
},
_ => None,
}
}
// trait object downcast helper
use std::any::Any;
trait AsAny {
fn as_any(&self) -> &dyn Any;
}
impl<T: State + 'static> AsAny for T {
fn as_any(&self) -> &dyn Any {
self
}
}
impl dyn State {
fn as_any(&self) -> &dyn Any {
self
}
}
重點說明
- 事件轉換:
convert_event 將 piston_window 的滑鼠移動(MouseCursor)、滑鼠按鍵(MouseButton)與鍵盤按鍵(Keyboard)訊息轉成 conrod 使用的事件。
- UI 處理:conrod
Ui 物件呼叫 handle_event() 來注入事件,保持內部事件隊列的正確狀態。
- widget 行為:
Button::was_pressed()、Slider::get() 等取得用戶輸入互動結果。
- 狀態堆疊管理:管理彈窗的壓入彈出。
- 字型快取:採用
lazy_static 靜態字型資源。
- 彈窗關閉邏輯:從堆疊中移除狀態。
如果要讓此範例順利運作,需要:
- 將字型檔(如
FiraSans-Regular.ttf)放至 assets 資料夾或改成你可用的字型路徑。
- 確保 Cargo.toml 的 crate 版本對應。
這樣你就會有很完整的滑鼠點擊和拖曳事件支援,能操作 Modal 窗口內的 GUI。你還能自由擴展其他 widget,例如輸入框、下拉選單等。
有需要我也能示範:
- 如何自訂 widget 樣式
- 使用其他 Rust GUI crate(如 egui、druid)與 piston/window 整合
- 複雜事件流程設計
隨時跟我說!