-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathlib.rs
More file actions
275 lines (250 loc) · 6.36 KB
/
lib.rs
File metadata and controls
275 lines (250 loc) · 6.36 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
use std::{
cell::RefCell,
io::{self, Read, StdinLock, StdoutLock, Write},
process::{Child, ChildStdin, ChildStdout},
result,
};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::Value;
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("postcard error: {0}")]
Postcard(#[from] postcard::Error),
#[error("io error: {0}")]
Io(#[from] io::Error),
#[error("pipe failed")]
MissingPipe,
#[error("failed to ping server")]
PingFailed,
#[error("Invalid size of message (is the pipeline really speaking lens?): {0}")]
InvalidMessageSize(u32),
}
type Result<T, E = Error> = result::Result<T, E>;
#[derive(Debug, Serialize, Deserialize)]
pub struct DistortOutput {
pub red: [f32; 2],
pub green: [f32; 2],
pub blue: [f32; 2],
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LeftRightTopBottom {
pub left: f32,
pub right: f32,
pub top: f32,
pub bottom: f32,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[repr(u32)]
pub enum Eye {
Left = 0,
Right = 1,
}
mod json {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
pub fn serialize<S>(value: &Value, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let str = serde_json::to_string(&value).unwrap();
str.serialize(serializer)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Value, D::Error>
where
D: Deserializer<'de>,
{
let str = String::deserialize(deserializer).unwrap();
Ok(serde_json::from_str(&str).unwrap())
}
}
#[derive(Debug, Serialize, Deserialize)]
pub enum Request {
Init(#[serde(with = "json")] Value),
Ping(u32),
Distort(Eye, [f32; 2]),
ProjectionRaw(Eye),
Exit,
}
pub trait LensClient {
fn ping(&self, v: u32) -> Result<u32>;
fn project(&self, eye: Eye) -> Result<LeftRightTopBottom>;
fn matrix_needs_inversion(&self) -> Result<bool>;
fn distort(&self, eye: Eye, uv: [f32; 2]) -> Result<DistortOutput>;
fn set_config(&self, config: Value) -> Result<()>;
fn exit(&self) -> Result<()>;
}
pub struct StubClient;
impl LensClient for StubClient {
fn ping(&self, v: u32) -> Result<u32> {
Ok(v)
}
fn project(&self, eye: Eye) -> Result<LeftRightTopBottom> {
Ok(match eye {
Eye::Left => LeftRightTopBottom {
left: -1.667393,
right: 0.821432,
top: -1.116938,
bottom: 1.122846,
},
Eye::Right => LeftRightTopBottom {
left: -0.822435,
right: 1.635135,
top: -1.138235,
bottom: 1.107449,
},
})
}
fn matrix_needs_inversion(&self) -> Result<bool> {
Ok(true)
}
fn distort(&self, _eye: Eye, uv: [f32; 2]) -> Result<DistortOutput> {
Ok(DistortOutput {
red: uv,
green: uv,
blue: uv,
})
}
fn set_config(&self, _config: Value) -> Result<()> {
Ok(())
}
fn exit(&self) -> Result<()> {
Ok(())
}
}
pub struct ServerClientInner {
stdin: ChildStdin,
stdout: ChildStdout,
child: Child,
}
impl ServerClientInner {
fn request<R: DeserializeOwned>(&mut self, request: &Request) -> Result<R> {
self.send(request)?;
let data = read_message(&mut self.stdout)?;
Ok(postcard::from_bytes(&data)?)
}
pub fn send(&mut self, request: &Request) -> Result<()> {
let data = postcard::to_stdvec(&request)?;
write_message(&mut self.stdin, &data)?;
self.stdin.flush()?;
Ok(())
}
}
pub struct ServerClient(RefCell<ServerClientInner>);
impl LensClient for ServerClient {
fn ping(&self, v: u32) -> Result<u32> {
self.0.borrow_mut().request(&Request::Ping(v))
}
fn project(&self, eye: Eye) -> Result<LeftRightTopBottom> {
self.0.borrow_mut().request(&Request::ProjectionRaw(eye))
}
fn matrix_needs_inversion(&self) -> Result<bool> {
let v = self.project(Eye::Left)?;
Ok(v.top > v.bottom)
}
fn distort(&self, eye: Eye, uv: [f32; 2]) -> Result<DistortOutput> {
self.0.borrow_mut().request(&Request::Distort(eye, uv))
}
fn set_config(&self, config: Value) -> Result<()> {
self.0.borrow_mut().send(&Request::Init(config))?;
Ok(())
}
fn exit(&self) -> Result<()> {
// Flush may fail in case if exit succeeded
let _ = self.0.borrow_mut().send(&Request::Exit);
self.0.borrow_mut().child.wait().unwrap();
Ok(())
}
}
impl ServerClient {
pub fn open(mut child: Child, config: Value) -> Result<Self> {
let res = Self(RefCell::new(ServerClientInner {
stdin: child.stdin.take().ok_or(Error::MissingPipe)?,
stdout: child.stdout.take().ok_or(Error::MissingPipe)?,
child,
}));
if res.ping(0x12345678)? != 0x12345678 {
return Err(Error::MissingPipe);
}
res.set_config(config)?;
Ok(res)
}
pub fn exit(&mut self) {}
}
impl Drop for ServerClient {
fn drop(&mut self) {
self.exit()
}
}
#[cfg(target_os = "windows")]
#[link(name = "msvcrt")]
extern "C" {
fn _setmode(fd: i32, mode: i32) -> i32;
}
pub fn read_message(read: &mut impl Read) -> Result<Vec<u8>> {
let mut len_buf = [0; 4];
read.read_exact(&mut len_buf)?;
let len = u32::from_be_bytes(len_buf);
if len < 0 || len > 0xFFFFFF {
return Err(Error::InvalidMessageSize(len));
}
// This protocol isn't talkative, its ok to allocate here.
let mut data = vec![0; len as usize];
read.read_exact(&mut data)?;
Ok(data)
}
pub fn write_message(write: &mut impl Write, v: &[u8]) -> Result<()> {
write.write_all(&u32::to_be_bytes(v.len() as u32))?;
write.write_all(v)?;
Ok(())
}
pub struct Server {
stdin: StdinLock<'static>,
stdout: StdoutLock<'static>,
#[cfg(target_os = "windows")]
modes: (i32, i32),
}
impl Server {
pub fn listen() -> Self {
#[cfg(target_os = "windows")]
let modes = {
let stdout = unsafe { _setmode(0, 0x8000) };
let stdin = unsafe { _setmode(1, 0x8000) };
assert!(
stdout != -1 && stdin != -1,
"binary mode should be accepted, and fds are correct"
);
(stdout, stdin)
};
let stdin = io::stdin().lock();
let stdout = io::stdout().lock();
Self {
stdin,
stdout,
#[cfg(target_os = "windows")]
modes,
}
}
pub fn recv(&mut self) -> Result<Request> {
let data = read_message(&mut self.stdin)?;
Ok(postcard::from_bytes(&data)?)
}
pub fn send(&mut self, v: &impl Serialize) -> Result<()> {
let data = postcard::to_stdvec(&v)?;
write_message(&mut self.stdout, &data)?;
self.stdout.flush()?;
Ok(())
}
}
impl Drop for Server {
fn drop(&mut self) {
#[cfg(target_os = "windows")]
{
let stdout = unsafe { _setmode(0, self.modes.0) };
let stdin = unsafe { _setmode(1, self.modes.1) };
assert!(
stdout != -1 && stdin != -1,
"previous mode and fds should be correct"
);
}
}
}