1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
use std::result;
use std::net::TcpStream;
use std::io::Result;
use std::io::{Error, ErrorKind};
use std::process::Stdio;
use std::process::{Command, Child, ChildStdin, ChildStdout};
use std::thread::JoinHandle;
use std::time::Duration;
use rpc::value::Value;
use rpc::Client;
pub struct Session {
client: ClientConnection,
timeout: Option<Duration>,
}
macro_rules! call_args {
() => (Vec::new());
($($e:expr), *) => {{
let mut vec = Vec::new();
$(
vec.push($e.into_val());
)*
vec
}};
}
impl Session {
pub fn new_tcp(addr: &str) -> Result<Session> {
let stream = TcpStream::connect(addr)?;
let read = stream.try_clone()?;
Ok(Session {
client: ClientConnection::Tcp(Client::new(stream, read)),
timeout: Some(Duration::new(5, 0)),
})
}
pub fn new_child() -> Result<Session> {
if cfg!(target_os = "linux") || cfg!(target_os = "freebsd") {
Self::new_child_path("nvim")
} else {
Self::new_child_path("nvim.exe")
}
}
pub fn new_child_path(program: &str) -> Result<Session> {
let mut child = Command::new(program).arg("--embed")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;
let stdout = child.stdout
.take()
.ok_or_else(|| Error::new(ErrorKind::Other, "Can't open stdout"))?;
let stdin = child.stdin
.take()
.ok_or_else(|| Error::new(ErrorKind::Other, "Can't open stdin"))?;
Ok(Session {
client: ClientConnection::Child(Client::new(stdout, stdin), child),
timeout: Some(Duration::new(5, 0)),
})
}
pub fn set_timeout(&mut self, timeout: Duration) {
self.timeout = Some(timeout);
}
pub fn set_infinity_timeout(&mut self) {
self.timeout = None;
}
pub fn start_event_loop_cb<F: FnMut(&str, Vec<Value>) + Send + 'static>(&mut self, cb: F) {
match self.client {
ClientConnection::Child(ref mut client, _) => client.start_event_loop_cb(cb),
ClientConnection::Tcp(ref mut client) => client.start_event_loop_cb(cb),
}
}
pub fn start_event_loop(&mut self) {
match self.client {
ClientConnection::Child(ref mut client, _) => client.start_event_loop(),
ClientConnection::Tcp(ref mut client) => client.start_event_loop(),
}
}
pub fn call(&mut self, method: &str, args: &Vec<Value>) -> result::Result<Value, Value> {
match self.client {
ClientConnection::Child(ref mut client, _) => client.call(method, args, self.timeout),
ClientConnection::Tcp(ref mut client) => client.call(method, args, self.timeout),
}
}
pub fn take_dispatch_guard(&mut self) -> JoinHandle<()> {
match self.client {
ClientConnection::Child(ref mut client, _) => client.take_dispatch_guard(),
ClientConnection::Tcp(ref mut client) => client.take_dispatch_guard(),
}
}
}
enum ClientConnection {
Child(Client<ChildStdout, ChildStdin>, Child),
Tcp(Client<TcpStream, TcpStream>),
}