diff --git a/src/nvim.rs b/src/nvim.rs index 1960389..af1ef9e 100644 --- a/src/nvim.rs +++ b/src/nvim.rs @@ -1,7 +1,46 @@ use neovim_lib::{Neovim, NeovimApi, Session}; use std::io::{Result, Error, ErrorKind}; +use std::cell::UnsafeCell; +use std::thread; +use std::sync::Arc; use rmp::Value; use ui::Ui; +use gtk; + +pub struct MainLoopMutex { + data: UnsafeCell, + main_thread_name: Option, +} + +unsafe impl Sync for MainLoopMutex {} + +impl MainLoopMutex { + pub fn new(t: T) -> MainLoopMutex { + MainLoopMutex { + data: UnsafeCell::new(t), + main_thread_name: thread::current().name().map(|v| v.to_owned()), + } + } + + // TODO: return some sort of ref guard here + pub fn get(&self) -> &mut T { + if thread::current().name().map(|v| v.to_owned()) != self.main_thread_name { + panic!("Can access value only from main thread"); + } + + unsafe { &mut *self.data.get() } + } + + pub fn safe_call(mutex: Arc>, cb: F) + where I: 'static, + F: Fn(&MainLoopMutex) + 'static + { + gtk::idle_add(move || { + cb(&*mutex); + gtk::Continue(false) + }); + } +} pub struct Nvim { nvim: Neovim,