Last active
December 19, 2015 16:18
-
-
Save metajack/5982180 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub struct Context { | |
chan: SharedChan<Msg>, | |
} | |
enum Msg { | |
CreateWindow(Context, uint, uint, ~str, WindowMode, Chan<Option<Window>>), | |
DetachCurrentContext, | |
// window messages | |
GetShouldClose(*c_void, Chan<bool>), | |
SetShouldClose(*c_void, bool), | |
Show(*c_void), | |
SetKeyCallback(*c_void, Chan<KeyEvent>), | |
} | |
// ... | |
impl Context { | |
pub fn new() { | |
let (port, chan) = SharedChan::new(); | |
do task::spawn_sched(task::PlatformThread) { | |
loop { | |
match port.recv() { | |
CreateWindow(ctx, width, height, title, mode, result_chan) => { | |
let result = unsafe { | |
do ll::glfwCreateWindow( | |
width as c_int, | |
height as c_int, | |
title.as_c_str(|a| a), | |
mode.to_ptr(), | |
ptr::null() | |
).to_option().map |&ptr| { | |
// ... | |
Window { | |
ctx: ctx, | |
ptr: cast::transmute(ptr), | |
} | |
} | |
}; | |
result_chan.send(result); | |
} | |
GetShoudlClose(win, result_chan) => { | |
let result = unsafe { ll::glfwWindowShouldClose(win) as bool }; | |
result_chan.send(result); | |
} | |
SetKeyCallback(win, chan) => { | |
let callback = |win, key, scancode, action, mods| { | |
chan.send(Event { ... }); | |
}; | |
set_window_callback!(setter: glfwSetKeyCallback, | |
callback: callback, | |
field: key_fun); | |
} | |
// ... | |
} | |
poll_events(); | |
yield(); | |
} | |
} | |
Context { chan: chan } | |
} | |
} | |
impl Window { | |
pub fn create(ctx: Context, width: uint, height: uint, title: &str, mode: WindowMode) -> Option<Window> { | |
let (port, chan) = comm::stream(); | |
ctx.chan.send(CreateWindow(ctx, width, height, title.to_owned(), mode, chan)); | |
port.recv() | |
} | |
pub fn should_close(&self) -> bool { | |
let (port, chan) = comm::stream(); | |
self.ctx.chan.send(GetShouldClose(self.ptr, chan)); | |
port.recv() | |
} | |
pub fn set_should_close(&self, value: bool) { | |
self.ctx.chan.send(SetShoudlClose(self.ptr, value)); | |
} | |
pub fn show(&self) { | |
self.ctx.chan.send(Show(self.ptr)); | |
} | |
pub fn set_key_callback(&self, cbfun: KeyFun) { | |
let (port, chan) = comm::stream(); | |
self.key_cb = Some(KeyCallback { port: port, fun: cbfun})); | |
self.ctx.chan.send(SetKeyCallback(self.ptr, chan)); | |
} | |
pub fn poll_events(&self) { | |
if self.key_cb.port.peek() { | |
self.key_cb.fun(self.key_cb.port.recv()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment