pepper 0.15.1

A simple and opinionated modal code editor for your terminal
Documentation
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use std::{
    io,
    os::unix::{
        io::{AsRawFd, RawFd},
        net::{UnixListener, UnixStream},
    },
    time::Duration,
};

use crate::{
    application::{ApplicationConfig, ClientApplication, ServerApplication},
    client::ClientHandle,
    platform::{Key, PlatformEvent, PlatformProcessHandle, PlatformRequest},
    Args,
};

mod unix_utils;
use unix_utils::{
    is_pipped, read, read_from_connection, run, suspend_process, write_all_bytes, Process, Terminal,
};

const MAX_CLIENT_COUNT: usize = 20;
const MAX_PROCESS_COUNT: usize = 43;
const MAX_TRIGGERED_EVENT_COUNT: usize = 32;

pub fn try_launching_debugger() {}

pub fn main(config: ApplicationConfig) {
    run(config, run_server, run_client);
}

fn errno() -> libc::c_int {
    unsafe { *libc::__errno_location() }
}

struct SignalFd(RawFd);
impl SignalFd {
    pub fn new(signal: libc::c_int) -> Self {
        unsafe {
            let mut signals = std::mem::zeroed();
            let result = libc::sigemptyset(&mut signals);
            if result == -1 {
                panic!("could not create signal fd");
            }
            let result = libc::sigaddset(&mut signals, signal);
            if result == -1 {
                panic!("could not create signal fd");
            }
            let result = libc::sigprocmask(libc::SIG_BLOCK, &signals, std::ptr::null_mut());
            if result == -1 {
                panic!("could not create signal fd");
            }
            let fd = libc::signalfd(-1, &signals, 0);
            if fd == -1 {
                panic!("could not create signal fd");
            }
            Self(fd)
        }
    }

    pub fn read(&self) {
        let mut buf = [0; std::mem::size_of::<libc::signalfd_siginfo>()];
        if read(self.0, &mut buf) != Ok(buf.len()) {
            panic!("could not read from signal fd");
        }
    }
}
impl AsRawFd for SignalFd {
    fn as_raw_fd(&self) -> RawFd {
        self.0
    }
}
impl Drop for SignalFd {
    fn drop(&mut self) {
        unsafe { libc::close(self.0) };
    }
}

struct EpollEvents([libc::epoll_event; MAX_TRIGGERED_EVENT_COUNT]);
impl EpollEvents {
    pub fn new() -> Self {
        const DEFAULT_EVENT: libc::epoll_event = libc::epoll_event { events: 0, u64: 0 };
        Self([DEFAULT_EVENT; MAX_TRIGGERED_EVENT_COUNT])
    }
}
struct Epoll(RawFd);
impl Epoll {
    pub fn new() -> Self {
        let fd = unsafe { libc::epoll_create1(0) };
        if fd == -1 {
            panic!("could not create epoll");
        }
        Self(fd)
    }

    pub fn add(&self, fd: RawFd, index: usize) {
        let mut event = libc::epoll_event {
            events: (libc::EPOLLIN | libc::EPOLLERR | libc::EPOLLRDHUP | libc::EPOLLHUP) as _,
            u64: index as _,
        };
        let result = unsafe { libc::epoll_ctl(self.0, libc::EPOLL_CTL_ADD, fd, &mut event) };
        if result == -1 {
            panic!("could not add event");
        }
    }

    pub fn remove(&self, fd: RawFd) {
        let mut event = libc::epoll_event { events: 0, u64: 0 };
        unsafe { libc::epoll_ctl(self.0, libc::EPOLL_CTL_DEL, fd, &mut event) };
    }

    pub fn wait<'a>(
        &self,
        events: &'a mut EpollEvents,
        timeout: Option<Duration>,
    ) -> impl 'a + ExactSizeIterator<Item = usize> {
        let timeout = match timeout {
            Some(duration) => duration.as_millis() as _,
            None => -1,
        };
        let mut len = unsafe {
            libc::epoll_wait(self.0, events.0.as_mut_ptr(), events.0.len() as _, timeout)
        };
        if len == -1 {
            if errno() == libc::EINTR {
                len = 0;
            } else {
                panic!("could not wait for events");
            }
        }

        events.0[..len as usize].iter().map(|e| e.u64 as _)
    }
}
impl Drop for Epoll {
    fn drop(&mut self) {
        unsafe { libc::close(self.0) };
    }
}

fn run_server(config: ApplicationConfig, listener: UnixListener) {
    use io::Write;

    const NONE_PROCESS: Option<Process> = None;

    let mut application = match ServerApplication::new(config) {
        Some(application) => application,
        None => return,
    };

    let mut client_connections: [Option<UnixStream>; MAX_CLIENT_COUNT] = Default::default();
    let mut processes = [NONE_PROCESS; MAX_PROCESS_COUNT];

    let mut events = Vec::new();
    let mut timeout = None;

    const CLIENTS_START_INDEX: usize = 1;
    const CLIENTS_LAST_INDEX: usize = CLIENTS_START_INDEX + MAX_CLIENT_COUNT - 1;
    const PROCESSES_START_INDEX: usize = CLIENTS_LAST_INDEX + 1;
    const PROCESSES_LAST_INDEX: usize = PROCESSES_START_INDEX + MAX_PROCESS_COUNT - 1;

    let epoll = Epoll::new();
    epoll.add(listener.as_raw_fd(), 0);
    let mut epoll_events = EpollEvents::new();

    loop {
        let epoll_events = epoll.wait(&mut epoll_events, timeout);
        if epoll_events.len() == 0 {
            match timeout {
                Some(Duration::ZERO) => timeout = Some(ServerApplication::idle_duration()),
                Some(_) => {
                    events.push(PlatformEvent::Idle);
                    timeout = None;
                }
                None => unreachable!(),
            }
        }

        for event_index in epoll_events {
            match event_index {
                0 => match listener.accept() {
                    Ok((connection, _)) => {
                        for (i, c) in client_connections.iter_mut().enumerate() {
                            if c.is_none() {
                                epoll.add(connection.as_raw_fd(), CLIENTS_START_INDEX + i);
                                *c = Some(connection);
                                let handle = ClientHandle::from_index(i).unwrap();
                                events.push(PlatformEvent::ConnectionOpen { handle });
                                break;
                            }
                        }
                    }
                    Err(error) => panic!("could not accept connection {}", error),
                },
                CLIENTS_START_INDEX..=CLIENTS_LAST_INDEX => {
                    let index = event_index - CLIENTS_START_INDEX;
                    if let Some(ref mut connection) = client_connections[index] {
                        let handle = ClientHandle::from_index(index).unwrap();
                        match read_from_connection(
                            connection,
                            &mut application.ctx.platform.buf_pool,
                            ServerApplication::connection_buffer_len(),
                        ) {
                            Ok(buf) => events.push(PlatformEvent::ConnectionOutput { handle, buf }),
                            Err(()) => {
                                epoll.remove(connection.as_raw_fd());
                                client_connections[index] = None;
                                events.push(PlatformEvent::ConnectionClose { handle });
                            }
                        }
                    }
                }
                PROCESSES_START_INDEX..=PROCESSES_LAST_INDEX => {
                    let index = event_index - PROCESSES_START_INDEX;
                    if let Some(ref mut process) = processes[index] {
                        let tag = process.tag();
                        match process.read(&mut application.ctx.platform.buf_pool) {
                            Ok(None) => (),
                            Ok(Some(buf)) => events.push(PlatformEvent::ProcessOutput { tag, buf }),
                            Err(()) => {
                                if let Some(fd) = process.try_as_raw_fd() {
                                    epoll.remove(fd);
                                }
                                process.kill();
                                processes[index] = None;
                                events.push(PlatformEvent::ProcessExit { tag });
                            }
                        }
                    }
                }
                _ => unreachable!(),
            }
        }

        application.update(events.drain(..));
        let mut requests = application.ctx.platform.requests.drain();
        while let Some(request) = requests.next() {
            match request {
                PlatformRequest::Quit => {
                    for request in requests {
                        if let PlatformRequest::WriteToClient { buf, .. }
                        | PlatformRequest::WriteToProcess { buf, .. } = request
                        {
                            application.ctx.platform.buf_pool.release(buf);
                        }
                    }
                    return;
                }
                PlatformRequest::Redraw => timeout = Some(Duration::ZERO),
                PlatformRequest::WriteToClient { handle, buf } => {
                    let index = handle.into_index();
                    if let Some(ref mut connection) = client_connections[index] {
                        if connection.write_all(buf.as_bytes()).is_err() {
                            epoll.remove(connection.as_raw_fd());
                            client_connections[index] = None;
                            events.push(PlatformEvent::ConnectionClose { handle });
                        }
                    }
                    application.ctx.platform.buf_pool.release(buf);
                }
                PlatformRequest::CloseClient { handle } => {
                    let index = handle.into_index();
                    if let Some(connection) = client_connections[index].take() {
                        epoll.remove(connection.as_raw_fd());
                    }
                    events.push(PlatformEvent::ConnectionClose { handle });
                }
                PlatformRequest::SpawnProcess {
                    tag,
                    mut command,
                    buf_len,
                } => {
                    let mut spawned = false;
                    for (i, p) in processes.iter_mut().enumerate() {
                        if p.is_some() {
                            continue;
                        }

                        let handle = PlatformProcessHandle(i as _);
                        if let Ok(child) = command.spawn() {
                            let process = Process::new(child, tag, buf_len);
                            if let Some(fd) = process.try_as_raw_fd() {
                                epoll.add(fd, PROCESSES_START_INDEX + i);
                            }
                            *p = Some(process);
                            events.push(PlatformEvent::ProcessSpawned { tag, handle });
                            spawned = true;
                        }
                        break;
                    }
                    if !spawned {
                        events.push(PlatformEvent::ProcessExit { tag });
                    }
                }
                PlatformRequest::WriteToProcess { handle, buf } => {
                    let index = handle.0 as usize;
                    if let Some(ref mut process) = processes[index] {
                        if !process.write(buf.as_bytes()) {
                            if let Some(fd) = process.try_as_raw_fd() {
                                epoll.remove(fd);
                            }
                            let tag = process.tag();
                            process.kill();
                            processes[index] = None;
                            events.push(PlatformEvent::ProcessExit { tag });
                        }
                    }
                    application.ctx.platform.buf_pool.release(buf);
                }
                PlatformRequest::CloseProcessInput { handle } => {
                    if let Some(ref mut process) = processes[handle.0 as usize] {
                        process.close_input();
                    }
                }
                PlatformRequest::KillProcess { handle } => {
                    let index = handle.0 as usize;
                    if let Some(ref mut process) = processes[index] {
                        if let Some(fd) = process.try_as_raw_fd() {
                            epoll.remove(fd);
                        }
                        let tag = process.tag();
                        process.kill();
                        processes[index] = None;
                        events.push(PlatformEvent::ProcessExit { tag });
                    }
                }
            }
        }

        if !events.is_empty() {
            timeout = Some(Duration::ZERO);
        }
    }
}

fn run_client(args: Args, mut connection: UnixStream) {
    use io::{Read, Write};

    let terminal = if args.quit {
        None
    } else {
        Some(Terminal::new())
    };

    let mut application = ClientApplication::new(terminal.as_ref().map(Terminal::to_file));
    let bytes = application.init(args);
    if connection.write_all(bytes).is_err() {
        return;
    }

    let epoll = Epoll::new();
    epoll.add(connection.as_raw_fd(), 1);
    if is_pipped(libc::STDIN_FILENO) {
        epoll.add(libc::STDIN_FILENO, 3);
    }

    let mut epoll_events = EpollEvents::new();

    let resize_signal;
    if let Some(terminal) = &terminal {
        terminal.enter_raw_mode();
        epoll.add(terminal.as_raw_fd(), 0);

        let signal = SignalFd::new(libc::SIGWINCH);
        epoll.add(signal.as_raw_fd(), 2);
        resize_signal = Some(signal);

        let size = terminal.get_size();
        let (_, bytes) = application.update(Some(size), &[Key::None], None, &[]);
        if connection.write_all(bytes).is_err() {
            return;
        }
    } else {
        resize_signal = None;
    }

    if is_pipped(libc::STDOUT_FILENO) {
        let (_, bytes) = application.update(None, &[], Some(&[]), &[]);
        if connection.write_all(bytes).is_err() {
            return;
        }
    }

    let mut keys = Vec::new();

    const BUF_LEN: usize =
        if ClientApplication::connection_buffer_len() > ClientApplication::stdin_buffer_len() {
            ClientApplication::connection_buffer_len()
        } else {
            ClientApplication::stdin_buffer_len()
        };
    let mut buf = [0; BUF_LEN];

    'main_loop: loop {
        for event_index in epoll.wait(&mut epoll_events, None) {
            let mut resize = None;
            let mut stdin_bytes = None;
            let mut server_bytes = &[][..];

            keys.clear();

            match event_index {
                0 => {
                    if let Some(terminal) = &terminal {
                        match read(terminal.as_raw_fd(), &mut buf) {
                            Ok(0) | Err(()) => break 'main_loop,
                            Ok(len) => terminal.parse_keys(&buf[..len], &mut keys),
                        }
                    }
                }
                1 => match connection.read(&mut buf) {
                    Ok(0) | Err(_) => break 'main_loop,
                    Ok(len) => server_bytes = &buf[..len],
                },
                2 => {
                    if let Some(ref signal) = resize_signal {
                        signal.read();
                        resize = terminal.as_ref().map(Terminal::get_size);
                    }
                }
                3 => match read(libc::STDIN_FILENO, &mut buf) {
                    Ok(0) | Err(()) => {
                        epoll.remove(libc::STDIN_FILENO);
                        stdin_bytes = Some(&[][..]);
                    }
                    Ok(len) => stdin_bytes = Some(&buf[..len]),
                },
                _ => unreachable!(),
            }

            let (suspend, bytes) = application.update(resize, &keys, stdin_bytes, server_bytes);
            if connection.write_all(bytes).is_err() {
                break;
            }
            if suspend {
                suspend_process(&mut application, &terminal);
            }
        }
    }

    if is_pipped(libc::STDOUT_FILENO) {
        let bytes = application.get_stdout_bytes();
        write_all_bytes(libc::STDOUT_FILENO, bytes);
    }

    drop(terminal);
    drop(application);
}