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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! This crate is wrapper of curses games like rogue and nethack, for AI making.
//!
//! What this crate provie is spawning CUI game as child process and emulation of vt100 control
//! sequence(helped by vte crate).
//!
//! To run AI, You have to implement ```Reactor``` trait to your AI object.
//! The result of vt100 emulation are stored as ```Vec<Vec<u8>>``` and AI recieves it as
//! ```Changed(Vec<Vec<u8>>)```.
//! # Examples
//! ```no_run
//! extern crate curses_game_wrapper as cgw;
//! use cgw::{Reactor, ActionResult, AsciiChar, GameSetting, Severity};
//! use std::time::Duration;
//! fn main() {
//!     struct EmptyAI {
//!         loopnum: usize,
//!     };
//!     impl Reactor for EmptyAI {
//!         fn action(&mut self, _screen: ActionResult, turn: usize) -> Option<Vec<u8>> {
//!             let mut res = Vec::new();
//!             match turn {
//!                 val if val == self.loopnum - 1 => res.push(AsciiChar::CarriageReturn.as_byte()),
//!                 val if val == self.loopnum - 2 => res.push(b'y'),
//!                 val if val == self.loopnum - 3 => res.push(b'Q'),
//!                 _ => {
//!                     let c = match (turn % 4) as u8 {
//!                         0u8 => b'h',
//!                         1u8 => b'j',
//!                         2u8 => b'k',
//!                         _ => b'l',
//!                     };
//!                     res.push(c);
//!                 }
//!             };
//!             Some(res)
//!         }
//!     }
//!     let loopnum = 50;
//!     let gs = GameSetting::new("rogue")
//!         .env("ROGUEUSER", "EmptyAI")
//!         .lines(24)
//!         .columns(80)
//!         .debug_file("debug.txt")
//!         .max_loop(loopnum + 1)
//!         .draw_on(Duration::from_millis(200));
//!     let game = gs.build();
//!     let mut ai = EmptyAI { loopnum: loopnum };
//!     game.play(&mut ai);
//! }
//! ```

#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]

extern crate ascii;
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate slog;
extern crate sloggers;
extern crate termion;
extern crate vte;

mod term_data;

/// It's imported from ```ascii``` crate for convinience.
pub use ascii::AsciiChar;
pub use sloggers::types::Severity;
use termion::async_stdin;
use termion::raw::IntoRawMode;
use vte::Parser;

use term_data::TermData;
use std::error::Error;
use std::fmt::{self, Debug, Formatter};
use std::io;
use std::process::{Child, Command, Stdio};
use std::env;
use std::io::{BufReader, Read, Write};
use std::str;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::thread::{self, JoinHandle};
use std::time::Duration;

#[derive(Clone, Debug)]
struct LogInfo {
    fname: String,
    sev: Severity,
}

impl Default for LogInfo {
    fn default() -> LogInfo {
        LogInfo {
            fname: String::new(),
            sev: Severity::Debug,
        }
    }
}

#[derive(Copy, Clone, Debug)]
enum DrawType {
    Terminal(Duration),
    Null,
}

/// Game process builder, providing control over how a new process
/// should be spawned.
///
/// Like ```std::process::Command```, A default configuration can be
/// generated using Gamesetting::new(command name) and other settings
/// can be added by builder methods.
/// # Example
/// ```no_run
/// extern crate curses_game_wrapper as cgw;
/// use cgw::{Reactor, ActionResult, AsciiChar, GameSetting, Severity};
/// use std::time::Duration;
/// fn main() {
///     let loopnum = 50;
///     let gs = GameSetting::new("rogue")
///         .env("ROGUEUSER", "EmptyAI")
///         .lines(24)
///         .columns(80)
///         .debug_file("debug.txt")
///         .max_loop(loopnum + 1)
///         .draw_on(Duration::from_millis(200));
///     let game = gs.build();
/// }
/// ```
#[derive(Clone, Debug)]
pub struct GameSetting<'a> {
    cmdname: String,
    lines: usize,
    columns: usize,
    envs: Vec<(&'a str, &'a str)>,
    args: Vec<&'a str>,
    log_info: LogInfo,
    timeout: Duration,
    draw_type: DrawType,
    max_loop: usize,
}
impl<'a> GameSetting<'a> {
    /// Build GameSetting object with command name(like ```rogue```).
    pub fn new(command_name: &str) -> Self {
        GameSetting {
            cmdname: String::from(command_name),
            lines: 24,
            columns: 80,
            envs: Vec::new(),
            args: Vec::new(),
            log_info: LogInfo::default(),
            timeout: Duration::from_millis(100),
            draw_type: DrawType::Null,
            max_loop: 100,
        }
    }
    /// Set screen width of curses widow
    pub fn columns(mut self, u: usize) -> Self {
        self.columns = u;
        self
    }
    /// Set screen height of curses window
    pub fn lines(mut self, u: usize) -> Self {
        self.lines = u;
        self
    }
    /// Add command line argument
    pub fn arg(mut self, s: &'a str) -> Self {
        self.args.push(s);
        self
    }
    /// Set environmental variable
    pub fn env(mut self, s: &'a str, t: &'a str) -> Self {
        self.envs.push((s, t));
        self
    }
    /// Set multiple command line arguments
    pub fn args<I>(mut self, i: I) -> Self
    where
        I: IntoIterator<Item = &'a str>,
    {
        let v: Vec<_> = i.into_iter().collect();
        self.args = v;
        self
    }
    /// Set multiple environmental variables
    pub fn envs<I>(mut self, i: I) -> Self
    where
        I: IntoIterator<Item = (&'a str, &'a str)>,
    {
        let v: Vec<_> = i.into_iter().collect();
        self.envs = v;
        self
    }
    /// Draw game on terminal(Default: off).
    /// You hanve to set duration of drawing.
    pub fn draw_on(mut self, d: Duration) -> Self {
        self.draw_type = DrawType::Terminal(d);
        self
    }
    /// You can set debug file of this crate.
    /// This is mainly for developper of this crate:)
    pub fn debug_file(mut self, s: &str) -> Self {
        self.log_info.fname = s.to_owned();
        self
    }
    /// You can set debug level of this crate.
    /// This is mainly for developper of this crate:)
    pub fn debug_level(mut self, s: Severity) -> Self {
        self.log_info.sev = s;
        self
    }
    /// You can set timeout to game output.
    /// It's setted to 0.1s by default.
    pub fn timeout(mut self, d: Duration) -> Self {
        self.timeout = d;
        self
    }
    /// You can set max_loop of game.
    /// It's setted to 100 by default.
    pub fn max_loop(mut self, t: usize) -> Self {
        self.max_loop = t;
        self
    }
    /// Consume game setting and build GameEnv
    pub fn build(self) -> GameEnv {
        let dat = TermData::from_setting(&self);
        let t = self.timeout;
        let m = self.max_loop;
        let d = self.draw_type;
        GameEnv {
            process: ProcHandler::from_setting(self),
            term_data: dat,
            timeout: t,
            max_loop: m,
            draw_type: d,
        }
    }
}

/// Result of the game action.
/// ```Changed(Vec<Vec<u8>>)``` contains virtual terminal as buffer.
#[derive(Clone)]
pub enum ActionResult {
    Changed(Vec<Vec<u8>>),
    NotChanged,
    GameEnded,
}
impl Debug for ActionResult {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        match *self {
            ActionResult::Changed(ref buf) => {
                write!(f, "ActionResult::Changed\n")?;
                write!(f, "--------------------\n")?;
                for v in buf {
                    let s = str::from_utf8(v).unwrap();
                    write!(f, "{}\n", s)?;
                }
                write!(f, "--------------------")
            }
            ActionResult::NotChanged => write!(f, "ActionResult::NotChanged"),
            ActionResult::GameEnded => write!(f, "ActionResult::GameEnded"),
        }
    }
}

/// You have to implement ```Reactor``` for your AI to work.
pub trait Reactor {
    fn action(&mut self, action_result: ActionResult, turn: usize) -> Option<Vec<u8>>;
}

/// This is for spawning curses game as child process.
///
/// It stores inputs from the game and sends result to AI when its input handler timeouts.
///
/// The only usage is
/// # Example
/// ```no_run
/// extern crate curses_game_wrapper as cgw;
/// use cgw::{Reactor, ActionResult, AsciiChar, GameSetting};
/// use std::time::Duration;
/// fn main() {
///     struct EmptyAI;
///     impl Reactor for EmptyAI {
///         fn action(&mut self, _screen: ActionResult, _turn: usize) -> Option<Vec<u8>> {
///              None
///         }
///     }
///     let gs = GameSetting::new("rogue")
///         .env("ROGUEUSER", "EmptyAI")
///         .lines(24)
///         .columns(80)
///         .debug_file("debug.txt")
///         .max_loop(10)
///         .draw_on(Duration::from_millis(200));
///     let game = gs.build();
///     let mut ai = EmptyAI { };
///     game.play(&mut ai);
/// }
/// ```
pub struct GameEnv {
    process: ProcHandler,
    term_data: TermData,
    timeout: Duration,
    max_loop: usize,
    draw_type: DrawType,
}
impl GameEnv {
    /// Start process and run AI.
    ///
    pub fn play<R: Reactor>(mut self, ai: &mut R) {
        use mpsc::RecvTimeoutError;
        macro_rules! send_or {
            ($to:expr, $handle:expr) => (
                if let Err(why) = $to.send_bytes($handle) {
                    debug!(
                        self.term_data.logger,
                        concat!("can't send to ", stringify!($to), ": {}"),
                        why.description()
                    );
                }
            )
        }
        let proc_handle = self.process.run();
        let mut viewer: Box<GameViewer> = match self.draw_type {
            DrawType::Terminal(d) => Box::new(TerminalViewer::new(d)),
            DrawType::Null => Box::new(EmptyViewer {}),
        };
        let viewer_handle = viewer.run();
        let mut stdin = async_stdin().bytes();
        let mut ctrl_c = false;

        let mut parser = Parser::new();
        let mut proc_dead = false;
        let mut stored_map = None;
        let mut cnt = 0;
        while cnt < self.max_loop {
            macro_rules! do_action {
                ($act:expr) => {{
                    cnt += 1;
                    if let Some(bytes) = ai.action($act, cnt) {
                        send_or!(self.process, &bytes);
                    }
                }}
            }
            let action_res = match self.process.rx.recv_timeout(self.timeout) {
                Ok(rec) => match rec {
                    Handle::Panicked => {
                        send_or!(viewer, Handle::Panicked);
                        panic!("panicked in child thread")
                    }
                    Handle::Zero => {
                        debug!(self.term_data.logger, "read zero bytes");
                        send_or!(viewer, Handle::Zero);
                        proc_dead = true;
                        ActionResult::GameEnded
                    }
                    Handle::Valid(ref r) => {
                        send_or!(viewer, Handle::Valid(r));
                        for c in r {
                            parser.advance(&mut self.term_data, *c);
                        }
                        ActionResult::Changed(self.term_data.ret_screen())
                    }
                },
                Err(err) => match err {
                    RecvTimeoutError::Timeout => ActionResult::NotChanged,
                    RecvTimeoutError::Disconnected => panic!("disconnected"),
                },
            };
            trace!(self.term_data.logger, "{:?}, turn: {}", action_res, cnt);
            match action_res {
                ActionResult::GameEnded => do_action!(ActionResult::GameEnded),
                // store inputs until timeout occurs
                ActionResult::Changed(map) => stored_map = Some(map),
                ActionResult::NotChanged => if let Some(map) = stored_map {
                    do_action!(ActionResult::Changed(map));
                    stored_map = None;
                } else {
                    do_action!(ActionResult::NotChanged);
                },
            }
            if proc_dead {
                trace!(self.term_data.logger, "Game ended in turn {}", cnt);
                break;
            }
            if let Some(Ok(3)) = stdin.next() {
                ctrl_c = true;
                break;
            }
        }
        if !proc_dead {
            debug!(
                self.term_data.logger,
                "Game not ended and killed process forcibly"
            );
            self.process.kill();
            send_or!(viewer, Handle::Zero);
            let _ = ai.action(ActionResult::GameEnded, self.max_loop);
        }
        if !ctrl_c {
            proc_handle.join().unwrap();
            viewer_handle.join().unwrap();
        }
    }
}

// handles Sender and Reciever
enum Handle<T> {
    Panicked, // thread panicked
    Zero,     // read 0 bytes (probably game ended)
    Valid(T), // read 1 or more bytes
}

trait GameViewer {
    fn run(&mut self) -> JoinHandle<()>;
    fn send_bytes(&mut self, bytes: Handle<&[u8]>) -> Result<(), ViewerError>;
}

#[derive(Debug)]
struct ViewerError(String);
impl fmt::Display for ViewerError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}
impl Error for ViewerError {
    fn description(&self) -> &str {
        &self.0
    }
}
impl From<mpsc::SendError<Handle<Vec<u8>>>> for ViewerError {
    fn from(e: mpsc::SendError<Handle<Vec<u8>>>) -> Self {
        ViewerError(e.description().to_owned())
    }
}

struct EmptyViewer {}

impl GameViewer for EmptyViewer {
    fn run(&mut self) -> JoinHandle<()> {
        thread::spawn(move || {})
    }
    fn send_bytes(&mut self, _bytes: Handle<&[u8]>) -> Result<(), ViewerError> {
        Ok(())
    }
}

#[derive(Debug)]
struct TerminalViewer {
    tx: mpsc::Sender<Handle<Vec<u8>>>,
    rx: Arc<Mutex<Receiver<Handle<Vec<u8>>>>>,
    sleep_time: Arc<Duration>,
}

impl TerminalViewer {
    fn new(d: Duration) -> Self {
        let (tx, rx) = mpsc::channel();
        let wrapped_recv = Arc::new(Mutex::new(rx));
        TerminalViewer {
            tx: tx,
            rx: wrapped_recv,
            sleep_time: Arc::new(d),
        }
    }
}
impl GameViewer for TerminalViewer {
    fn run(&mut self) -> JoinHandle<()> {
        let rx = Arc::clone(&self.rx);
        let sleep = Arc::clone(&self.sleep_time);
        env::set_var("TERM", "vt100");
        thread::spawn(move || {
            let receiver = rx.lock().unwrap();
            while let Ok(game_input) = (*receiver).recv() {
                match game_input {
                    Handle::Valid(ref bytes) => {
                        let s = str::from_utf8(bytes).unwrap();
                        let mut stdout = io::stdout()
                            .into_raw_mode()
                            .expect("Couldn't get raw stdin");
                        write!(stdout, "{}", s).expect("Couldn't write to stdin");
                        stdout.flush().expect("Could not flush stdout");
                    }
                    Handle::Zero => break,
                    Handle::Panicked => panic!("main thread panicked"),
                }
                thread::sleep(*sleep);
            }
        })
    }
    fn send_bytes(&mut self, b: Handle<&[u8]>) -> Result<(), ViewerError> {
        let txclone = self.tx.clone();
        let res = match b {
            Handle::Zero => Handle::Zero,
            Handle::Panicked => Handle::Panicked,
            Handle::Valid(b) => Handle::Valid(b.to_owned()),
        };
        txclone.send(res)?;
        Ok(())
    }
}

#[derive(Debug)]
struct ProcessError(String);

impl fmt::Display for ProcessError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Error for ProcessError {
    fn description(&self) -> &str {
        &self.0
    }
}

impl From<io::Error> for ProcessError {
    fn from(why: io::Error) -> Self {
        ProcessError(why.description().to_owned())
    }
}

// exec process
struct ProcHandler {
    my_proc: Child,
    tx: Sender<Handle<Vec<u8>>>,
    // note : Reciever blocks until some bytes wrote
    rx: Receiver<Handle<Vec<u8>>>,
    killed: Arc<AtomicBool>,
}

impl ProcHandler {
    fn from_setting(g: GameSetting) -> ProcHandler {
        let mut cmd = Command::new(&g.cmdname);
        let cmd = cmd.args(g.args);
        let cmd = cmd.env("LINES", format!("{}", g.lines));
        let cmd = cmd.env("COLUMNS", format!("{}", g.columns));
        let cmd = cmd.env("TERM", "vt100"); // You can override it by env
        let cmd = cmd.envs(g.envs);
        let cmd = cmd.stdin(Stdio::piped()).stdout(Stdio::piped());
        let process = match cmd.spawn() {
            Ok(p) => p,
            Err(why) => panic!("couldn't spawn game: {}", why.description()),
        };
        let (tx, rx) = mpsc::channel();
        ProcHandler {
            my_proc: process,
            tx: tx,
            rx: rx,
            killed: Arc::new(AtomicBool::new(false)),
        }
    }

    fn run(&mut self) -> JoinHandle<()> {
        let proc_out = self.my_proc.stdout.take().unwrap();
        let txclone = self.tx.clone();
        let ac = Arc::clone(&self.killed);
        thread::spawn(move || {
            let mut proc_reader = BufReader::new(proc_out);
            const BUFSIZE: usize = 4096;
            let mut readbuf = vec![0u8; BUFSIZE];
            while !ac.load(Ordering::Relaxed) {
                match proc_reader.read(&mut readbuf) {
                    Err(why) => {
                        txclone.send(Handle::Panicked).ok();
                        panic!("couldn't read child stdout: {}", why.description())
                    }
                    Ok(0) => {
                        txclone.send(Handle::Zero).ok();
                        break;
                    }
                    Ok(BUFSIZE) => {
                        txclone.send(Handle::Panicked).ok();
                        panic!("Buffer is too small.")
                    }
                    Ok(n) => {
                        txclone.send(Handle::Valid(readbuf[0..n].to_owned())).ok();
                    }
                }
            }
        })
    }

    fn send_bytes(&mut self, buf: &[u8]) -> Result<(), ProcessError> {
        let stdin = self.my_proc.stdin.as_mut().unwrap();
        stdin.write_all(buf)?;
        Ok(())
    }

    fn kill(&mut self) {
        self.my_proc.kill().unwrap();
        let ac = Arc::clone(&self.killed);
        ac.store(true, Ordering::Relaxed)
    }
}

// Destractor (kill proc)
impl Drop for ProcHandler {
    fn drop(&mut self) {
        self.my_proc.kill().unwrap();
    }
}

#[cfg(test)]
mod tests {
    #[test]
    #[ignore]
    fn test_gameplay() {
        use super::*;
        struct EmptyAI {
            loopnum: usize,
        };
        impl Reactor for EmptyAI {
            fn action(&mut self, _screen: ActionResult, turn: usize) -> Option<Vec<u8>> {
                let mut res = Vec::new();
                match turn {
                    val if val == self.loopnum - 1 => res.push(AsciiChar::CarriageReturn.as_byte()),
                    val if val == self.loopnum - 2 => res.push(b'y'),
                    val if val == self.loopnum - 3 => res.push(b'Q'),
                    _ => res.push(b'j'),
                };
                Some(res)
            }
        }
        let loopnum = 10;
        let gs = GameSetting::new("rogue")
            .env("ROGUEUSER", "EmptyAI")
            .lines(24)
            .columns(80)
            .debug_file("debug.txt")
            .debug_level(Severity::Trace)
            .max_loop(loopnum + 1)
            .draw_on(Duration::from_millis(100));
        let game = gs.build();
        let mut ai = EmptyAI { loopnum: loopnum };
        game.play(&mut ai);
    }
}