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
extern crate termbox_sys as ffi;
extern crate try_from;
pub mod attributes;
pub mod keys;
mod internal;
pub use self::attributes::*;
pub use self::keys::*;
use std::char;
use std::error;
use std::fmt::{
self,
Display,
Formatter,
};
use std::mem;
use std::os::raw::c_int;
use std::result;
use std::slice;
use try_from::TryFrom;
use internal::Lock;
pub type Cell = ffi::RawCell;
pub type Coord = c_int;
pub type Result<T> = result::Result<T, Error>;
pub type Time = c_int;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Error {
Locked,
UnsupportedTerminal,
FailedToOpenTty,
PipeTrapError,
}
impl Error {
pub fn as_str (self) -> &'static str {
match self {
Error::Locked => "locked",
Error::UnsupportedTerminal => "unsupported terminal",
Error::FailedToOpenTty => "failed to open tty",
Error::PipeTrapError => "pipe trap error",
}
}
}
impl Error {
fn from_raw (raw: c_int) -> Option<Error> {
match raw {
ffi::TB_EUNSUPPORTED_TERMINAL => Some(Error::UnsupportedTerminal),
ffi::TB_EFAILED_TO_OPEN_TTY => Some(Error::FailedToOpenTty),
ffi::TB_EPIPE_TRAP_ERROR => Some(Error::PipeTrapError),
_ => None,
}
}
}
impl Display for Error {
fn fmt (&self, f: &mut Formatter) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl error::Error for Error {
fn description (&self) -> &str {
self.as_str()
}
}
#[derive(Clone, Copy, Debug)]
pub enum Event {
Key(KeyEvent),
Resize(ResizeEvent),
Mouse(MouseEvent),
}
impl Event {
fn from_raw (raw: ffi::RawEvent) -> Option<Event> {
match raw.etype {
ffi::TB_EVENT_KEY => Some(Event::Key(KeyEvent::from_raw(raw).unwrap())),
ffi::TB_EVENT_RESIZE => Some(Event::Resize(ResizeEvent::from_raw(raw).unwrap())),
ffi::TB_EVENT_MOUSE => Some(Event::Mouse(MouseEvent::from_raw(raw).unwrap())),
_ => None,
}
}
}
const INPUT_MODE_MASK: c_int = 3;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum InputMode {
Esc,
Alt,
}
impl InputMode {
fn from_raw (raw: c_int) -> Option<InputMode> {
match raw & INPUT_MODE_MASK {
ffi::TB_INPUT_ESC => Some(InputMode::Esc),
ffi::TB_INPUT_ALT => Some(InputMode::Alt),
_ => None,
}
}
fn to_raw (self) -> c_int {
match self {
InputMode::Esc => ffi::TB_INPUT_ESC,
InputMode::Alt => ffi::TB_INPUT_ALT,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct KeyEvent {
pub key: Key,
pub ch: Option<char>,
pub alt: bool,
}
impl KeyEvent {
fn from_raw (raw: ffi::RawEvent) -> Option<KeyEvent> {
if raw.etype == ffi::TB_EVENT_KEY {
Some(KeyEvent {
key: raw.key,
ch: char::from_u32(raw.ch),
alt: (raw.emod & ffi::TB_MOD_ALT) != 0,
})
} else {
None
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum MouseButton {
Left,
Right,
Middle,
Release,
WheelUp,
WheelDown,
}
impl MouseButton {
fn from_raw (raw: u16) -> Option<MouseButton> {
match raw {
ffi::TB_KEY_MOUSE_LEFT => Some(MouseButton::Left),
ffi::TB_KEY_MOUSE_RIGHT => Some(MouseButton::Right),
ffi::TB_KEY_MOUSE_MIDDLE => Some(MouseButton::Middle),
ffi::TB_KEY_MOUSE_RELEASE => Some(MouseButton::Release),
ffi::TB_KEY_MOUSE_WHEEL_UP => Some(MouseButton::WheelUp),
ffi::TB_KEY_MOUSE_WHEEL_DOWN => Some(MouseButton::WheelDown),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct MouseEvent {
pub button: MouseButton,
pub x: Coord,
pub y: Coord,
}
impl MouseEvent {
fn from_raw (raw: ffi::RawEvent) -> Option<MouseEvent> {
if raw.etype == ffi::TB_EVENT_MOUSE {
Some(MouseEvent {
button: MouseButton::from_raw(raw.key).unwrap(),
x: Coord::try_from(raw.x).unwrap(),
y: Coord::try_from(raw.y).unwrap(),
})
} else {
None
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum OutputMode {
Normal,
Color256,
Color216,
Grayscale,
}
impl OutputMode {
fn from_raw (raw: c_int) -> Option<OutputMode> {
match raw {
ffi::TB_OUTPUT_NORMAL => Some(OutputMode::Normal),
ffi::TB_OUTPUT_256 => Some(OutputMode::Color256),
ffi::TB_OUTPUT_216 => Some(OutputMode::Color216),
ffi::TB_OUTPUT_GRAYSCALE => Some(OutputMode::Grayscale),
_ => None,
}
}
fn to_raw (self) -> c_int {
match self {
OutputMode::Normal => ffi::TB_OUTPUT_NORMAL,
OutputMode::Color256 => ffi::TB_OUTPUT_256,
OutputMode::Color216 => ffi::TB_OUTPUT_216,
OutputMode::Grayscale => ffi::TB_OUTPUT_GRAYSCALE,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct ResizeEvent {
pub w: Coord,
pub h: Coord,
}
impl ResizeEvent {
fn from_raw (raw: ffi::RawEvent) -> Option<ResizeEvent> {
if raw.etype == ffi::TB_EVENT_RESIZE {
Some(ResizeEvent {
w: Coord::try_from(raw.w).unwrap(),
h: Coord::try_from(raw.h).unwrap(),
})
} else {
None
}
}
}
pub struct Termbox {
#[allow(dead_code)]
lock: Lock,
}
impl Termbox {
pub fn blit (&mut self, x: Coord, y: Coord, w: Coord, h: Coord, cells: &[Cell]) {
unsafe {
let uwidth = usize::try_from(w).unwrap();
let uheight = usize::try_from(h).unwrap();
let min_len = uwidth.checked_mul(uheight).unwrap();
assert!(cells.len() >= min_len);
ffi::tb_blit(x, y, w, h, &cells[0]);
}
}
pub fn cell_buffer<'a> (&'a self) -> &'a [Cell] {
unsafe {
let w = usize::try_from(ffi::tb_width()).unwrap();
let h = usize::try_from(ffi::tb_height()).unwrap();
let len = w.checked_mul(h).unwrap();
let ptr = ffi::tb_cell_buffer() as *const Cell;
return slice::from_raw_parts(ptr, len);
}
}
pub fn cell_buffer_mut<'a> (&'a mut self) -> &'a mut [Cell] {
unsafe {
let w = usize::try_from(ffi::tb_width()).unwrap();
let h = usize::try_from(ffi::tb_height()).unwrap();
let len = w.checked_mul(h).unwrap();
let ptr = ffi::tb_cell_buffer();
return slice::from_raw_parts_mut(ptr, len);
}
}
pub fn change_cell (&mut self, x: Coord, y: Coord, ch: char, fg: Attribute, bg: Attribute) {
unsafe {
ffi::tb_change_cell(x, y, ch as u32, fg, bg);
}
}
pub fn clear (&mut self) {
unsafe {
ffi::tb_clear();
}
}
pub fn height (&self) -> Coord {
unsafe {
ffi::tb_height()
}
}
pub fn hide_cursor (&mut self) {
unsafe {
ffi::tb_set_cursor(ffi::TB_HIDE_CURSOR, ffi::TB_HIDE_CURSOR);
}
}
pub fn input_mode (&self) -> InputMode {
unsafe {
let raw_mode = ffi::tb_select_input_mode(ffi::TB_INPUT_CURRENT);
return InputMode::from_raw(raw_mode).unwrap();
}
}
pub fn is_mouse_enabled (&self) -> bool {
unsafe {
let mode = ffi::tb_select_input_mode(ffi::TB_INPUT_CURRENT);
return (mode & ffi::TB_INPUT_MOUSE) != 0;
}
}
pub fn open () -> Result<Termbox> {
unsafe {
let lock;
match Lock::acquire() {
Some(l) => { lock = l; },
None => { return Err(Error::Locked); },
}
match ffi::tb_init() {
0 => { return Ok(Termbox { lock: lock }); },
n => { return Err(Error::from_raw(n).unwrap()); },
}
}
}
pub fn output_mode (&self) -> OutputMode {
unsafe {
let raw_mode = ffi::tb_select_output_mode(ffi::TB_OUTPUT_CURRENT);
return OutputMode::from_raw(raw_mode).unwrap();
}
}
pub fn peek_event (&mut self, timeout: Time) -> Option<Event> {
unsafe {
let mut raw: ffi::RawEvent = mem::uninitialized();
let result = ffi::tb_peek_event(&mut raw, timeout);
if result < 0 {
panic!("tb_peek_event returned {}", result);
} else if result == 0 {
return None;
} else {
return Some(Event::from_raw(raw).unwrap());
}
}
}
pub fn poll_event (&mut self) -> Event {
unsafe {
let mut raw: ffi::RawEvent = mem::uninitialized();
let result = ffi::tb_poll_event(&mut raw);
if result <= 0 {
panic!("tb_poll_event returned {}", result);
} else {
return Event::from_raw(raw).unwrap();
}
}
}
pub fn present (&mut self) {
unsafe {
ffi::tb_present();
}
}
pub fn put_cell (&mut self, x: Coord, y: Coord, cell: Cell) {
unsafe {
ffi::tb_put_cell(x, y, &cell);
}
}
pub fn put_str (&mut self, x: Coord, y: Coord, msg: &str, fg: Attribute, bg: Attribute) {
unsafe {
let mut x = x;
for ch in msg.chars() {
ffi::tb_change_cell(x, y, ch as u32, fg, bg);
x += 1;
}
}
}
pub fn set_clear_attributes (&mut self, fg: Attribute, bg: Attribute) {
unsafe {
ffi::tb_set_clear_attributes(fg, bg);
}
}
pub fn set_cursor (&mut self, x: Coord, y: Coord) {
unsafe {
ffi::tb_set_cursor(x, y);
}
}
pub fn set_input_mode (&mut self, mode: InputMode) {
unsafe {
let prev_mode = ffi::tb_select_input_mode(ffi::TB_INPUT_CURRENT);
let flags = prev_mode & !INPUT_MODE_MASK;
ffi::tb_select_input_mode(mode.to_raw() | flags);
}
}
pub fn set_mouse_enabled (&mut self, enabled: bool) {
unsafe {
let prev_mode = ffi::tb_select_input_mode(ffi::TB_INPUT_CURRENT);
let new_mode;
if enabled {
new_mode = prev_mode | ffi::TB_INPUT_MOUSE;
} else {
new_mode = prev_mode & !ffi::TB_INPUT_MOUSE;
}
if new_mode != prev_mode {
ffi::tb_select_input_mode(new_mode);
}
}
}
pub fn set_output_mode (&mut self, mode: OutputMode) {
unsafe {
ffi::tb_select_output_mode(mode.to_raw());
}
}
pub fn width (&self) -> Coord {
unsafe {
ffi::tb_width()
}
}
}
impl Drop for Termbox {
fn drop (&mut self) {
unsafe {
ffi::tb_shutdown();
}
}
}