-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
lib.rs
2221 lines (1994 loc) · 69.2 KB
/
lib.rs
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
This crate provides a cross platform abstraction for writing colored text to
a terminal. Colors are written using either ANSI escape sequences or by
communicating with a Windows console. Much of this API was motivated by use
inside command line applications, where colors or styles can be configured
by the end user and/or the environment.
This crate also provides platform independent support for writing colored text
to an in memory buffer. While this is easy to do with ANSI escape sequences
(because they are in the buffer themselves), it is trickier to do with the
Windows console API, which requires synchronous communication.
# Organization
The `WriteColor` trait extends the `io::Write` trait with methods for setting
colors or resetting them.
`StandardStream` and `StandardStreamLock` both satisfy `WriteColor` and are
analogous to `std::io::Stdout` and `std::io::StdoutLock`, or `std::io::Stderr`
and `std::io::StderrLock`.
`Buffer` is an in memory buffer that supports colored text. In a parallel
program, each thread might write to its own buffer. A buffer can be printed to
using a `BufferWriter`. The advantage of this design is that each thread can
work in parallel on a buffer without having to synchronize access to global
resources such as the Windows console. Moreover, this design also prevents
interleaving of buffer output.
`Ansi` and `NoColor` both satisfy `WriteColor` for arbitrary implementors of
`io::Write`. These types are useful when you know exactly what you need. An
analogous type for the Windows console is not provided since it cannot exist.
# Example: using `StandardStream`
The `StandardStream` type in this crate works similarly to `std::io::Stdout`,
except it is augmented with methods for coloring by the `WriteColor` trait.
For example, to write some green text:
```rust,no_run
# fn test() -> Result<(), Box<::std::error::Error>> {
use std::io::Write;
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
let mut stdout = StandardStream::stdout(ColorChoice::Always);
stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?;
writeln!(&mut stdout, "green text!")?;
# Ok(()) }
```
Note that any text written to the terminal now will be colored
green when using ANSI escape sequences, even if it is written via
stderr, and even if stderr had previously been set to `Color::Red`.
Users will need to manage any color changes themselves by calling
[`WriteColor::set_color`](trait.WriteColor.html#tymethod.set_color), and this
may include calling [`WriteColor::reset`](trait.WriteColor.html#tymethod.reset)
before the program exits to a shell.
# Example: using `BufferWriter`
A `BufferWriter` can create buffers and write buffers to stdout or stderr. It
does *not* implement `io::Write` or `WriteColor` itself. Instead, `Buffer`
implements `io::Write` and `io::WriteColor`.
This example shows how to print some green text to stderr.
```rust,no_run
# fn test() -> Result<(), Box<::std::error::Error>> {
use std::io::Write;
use termcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};
let mut bufwtr = BufferWriter::stderr(ColorChoice::Always);
let mut buffer = bufwtr.buffer();
buffer.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?;
writeln!(&mut buffer, "green text!")?;
bufwtr.print(&buffer)?;
# Ok(()) }
```
# Detecting presence of a terminal
In many scenarios when using color, one often wants to enable colors
automatically when writing to a terminal and disable colors automatically when
writing to anything else. The typical way to achieve this in Unix environments
is via libc's
[`isatty`](http://man7.org/linux/man-pages/man3/isatty.3.html)
function.
Unfortunately, this notoriously does not work well in Windows environments. To
work around that, the currently recommended solution is to use the
[`atty`](https://crates.io/crates/atty)
crate, which goes out of its way to get this as right as possible in Windows
environments.
For example, in a command line application that exposes a `--color` flag,
your logic for how to enable colors might look like this:
```rust,ignore
use atty;
use termcolor::{ColorChoice, StandardStream};
let preference = argv.get_flag("color").unwrap_or("auto");
let choice = match preference {
"always" => ColorChoice::Always,
"ansi" => ColorChoice::AlwaysAnsi,
"auto" => {
if atty::is(atty::Stream::Stdout) {
ColorChoice::Auto
} else {
ColorChoice::Never
}
}
_ => ColorChoice::Never,
};
let stdout = StandardStream::stdout(choice);
// ... write to stdout
```
Currently, `termcolor` does not provide anything to do this for you.
*/
#![deny(missing_docs)]
#[cfg(doctest)]
use doc_comment::doctest;
#[cfg(doctest)]
doctest!("../README.md");
use std::env;
use std::error;
use std::fmt;
use std::io::{self, Write};
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(windows)]
use std::sync::{Mutex, MutexGuard};
#[cfg(windows)]
use winapi_util::console as wincon;
/// This trait describes the behavior of writers that support colored output.
pub trait WriteColor: io::Write {
/// Returns true if and only if the underlying writer supports colors.
fn supports_color(&self) -> bool;
/// Set the color settings of the writer.
///
/// Subsequent writes to this writer will use these settings until either
/// `reset` is called or new color settings are set.
///
/// If there was a problem setting the color settings, then an error is
/// returned.
fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()>;
/// Reset the current color settings to their original settings.
///
/// If there was a problem resetting the color settings, then an error is
/// returned.
fn reset(&mut self) -> io::Result<()>;
/// Returns true if and only if the underlying writer must synchronously
/// interact with an end user's device in order to control colors. By
/// default, this always returns `false`.
///
/// In practice, this should return `true` if the underlying writer is
/// manipulating colors using the Windows console APIs.
///
/// This is useful for writing generic code (such as a buffered writer)
/// that can perform certain optimizations when the underlying writer
/// doesn't rely on synchronous APIs. For example, ANSI escape sequences
/// can be passed through to the end user's device as is.
fn is_synchronous(&self) -> bool {
false
}
}
impl<'a, T: ?Sized + WriteColor> WriteColor for &'a mut T {
fn supports_color(&self) -> bool {
(&**self).supports_color()
}
fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> {
(&mut **self).set_color(spec)
}
fn reset(&mut self) -> io::Result<()> {
(&mut **self).reset()
}
fn is_synchronous(&self) -> bool {
(&**self).is_synchronous()
}
}
impl<T: ?Sized + WriteColor> WriteColor for Box<T> {
fn supports_color(&self) -> bool {
(&**self).supports_color()
}
fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> {
(&mut **self).set_color(spec)
}
fn reset(&mut self) -> io::Result<()> {
(&mut **self).reset()
}
fn is_synchronous(&self) -> bool {
(&**self).is_synchronous()
}
}
/// ColorChoice represents the color preferences of an end user.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ColorChoice {
/// Try very hard to emit colors. This includes emitting ANSI colors
/// on Windows if the console API is unavailable.
Always,
/// AlwaysAnsi is like Always, except it never tries to use anything other
/// than emitting ANSI color codes.
AlwaysAnsi,
/// Try to use colors, but don't force the issue. If the console isn't
/// available on Windows, or if TERM=dumb, or if `NO_COLOR` is defined, for
/// example, then don't use colors.
Auto,
/// Never emit colors.
Never,
}
impl ColorChoice {
/// Returns true if we should attempt to write colored output.
fn should_attempt_color(&self) -> bool {
match *self {
ColorChoice::Always => true,
ColorChoice::AlwaysAnsi => true,
ColorChoice::Never => false,
ColorChoice::Auto => self.env_allows_color(),
}
}
#[cfg(not(windows))]
fn env_allows_color(&self) -> bool {
match env::var_os("TERM") {
// If TERM isn't set, then we are in a weird environment that
// probably doesn't support colors.
None => return false,
Some(k) => {
if k == "dumb" {
return false;
}
}
}
// If TERM != dumb, then the only way we don't allow colors at this
// point is if NO_COLOR is set.
if env::var_os("NO_COLOR").is_some() {
return false;
}
true
}
#[cfg(windows)]
fn env_allows_color(&self) -> bool {
// On Windows, if TERM isn't set, then we shouldn't automatically
// assume that colors aren't allowed. This is unlike Unix environments
// where TERM is more rigorously set.
if let Some(k) = env::var_os("TERM") {
if k == "dumb" {
return false;
}
}
// If TERM != dumb, then the only way we don't allow colors at this
// point is if NO_COLOR is set.
if env::var_os("NO_COLOR").is_some() {
return false;
}
true
}
/// Returns true if this choice should forcefully use ANSI color codes.
///
/// It's possible that ANSI is still the correct choice even if this
/// returns false.
#[cfg(windows)]
fn should_ansi(&self) -> bool {
match *self {
ColorChoice::Always => false,
ColorChoice::AlwaysAnsi => true,
ColorChoice::Never => false,
ColorChoice::Auto => {
match env::var("TERM") {
Err(_) => false,
// cygwin doesn't seem to support ANSI escape sequences
// and instead has its own variety. However, the Windows
// console API may be available.
Ok(k) => k != "dumb" && k != "cygwin",
}
}
}
}
}
/// `std::io` implements `Stdout` and `Stderr` (and their `Lock` variants) as
/// separate types, which makes it difficult to abstract over them. We use
/// some simple internal enum types to work around this.
enum StandardStreamType {
Stdout,
Stderr,
StdoutBuffered,
StderrBuffered,
}
enum IoStandardStream {
Stdout(io::Stdout),
Stderr(io::Stderr),
StdoutBuffered(io::BufWriter<io::Stdout>),
StderrBuffered(io::BufWriter<io::Stderr>),
}
impl IoStandardStream {
fn new(sty: StandardStreamType) -> IoStandardStream {
match sty {
StandardStreamType::Stdout => {
IoStandardStream::Stdout(io::stdout())
}
StandardStreamType::Stderr => {
IoStandardStream::Stderr(io::stderr())
}
StandardStreamType::StdoutBuffered => {
let wtr = io::BufWriter::new(io::stdout());
IoStandardStream::StdoutBuffered(wtr)
}
StandardStreamType::StderrBuffered => {
let wtr = io::BufWriter::new(io::stderr());
IoStandardStream::StderrBuffered(wtr)
}
}
}
fn lock(&self) -> IoStandardStreamLock<'_> {
match *self {
IoStandardStream::Stdout(ref s) => {
IoStandardStreamLock::StdoutLock(s.lock())
}
IoStandardStream::Stderr(ref s) => {
IoStandardStreamLock::StderrLock(s.lock())
}
IoStandardStream::StdoutBuffered(_)
| IoStandardStream::StderrBuffered(_) => {
// We don't permit this case to ever occur in the public API,
// so it's OK to panic.
panic!("cannot lock a buffered standard stream")
}
}
}
}
impl io::Write for IoStandardStream {
#[inline(always)]
fn write(&mut self, b: &[u8]) -> io::Result<usize> {
match *self {
IoStandardStream::Stdout(ref mut s) => s.write(b),
IoStandardStream::Stderr(ref mut s) => s.write(b),
IoStandardStream::StdoutBuffered(ref mut s) => s.write(b),
IoStandardStream::StderrBuffered(ref mut s) => s.write(b),
}
}
#[inline(always)]
fn flush(&mut self) -> io::Result<()> {
match *self {
IoStandardStream::Stdout(ref mut s) => s.flush(),
IoStandardStream::Stderr(ref mut s) => s.flush(),
IoStandardStream::StdoutBuffered(ref mut s) => s.flush(),
IoStandardStream::StderrBuffered(ref mut s) => s.flush(),
}
}
}
// Same rigmarole for the locked variants of the standard streams.
enum IoStandardStreamLock<'a> {
StdoutLock(io::StdoutLock<'a>),
StderrLock(io::StderrLock<'a>),
}
impl<'a> io::Write for IoStandardStreamLock<'a> {
#[inline(always)]
fn write(&mut self, b: &[u8]) -> io::Result<usize> {
match *self {
IoStandardStreamLock::StdoutLock(ref mut s) => s.write(b),
IoStandardStreamLock::StderrLock(ref mut s) => s.write(b),
}
}
#[inline(always)]
fn flush(&mut self) -> io::Result<()> {
match *self {
IoStandardStreamLock::StdoutLock(ref mut s) => s.flush(),
IoStandardStreamLock::StderrLock(ref mut s) => s.flush(),
}
}
}
/// Satisfies `io::Write` and `WriteColor`, and supports optional coloring
/// to either of the standard output streams, stdout and stderr.
pub struct StandardStream {
wtr: LossyStandardStream<WriterInner<IoStandardStream>>,
}
/// `StandardStreamLock` is a locked reference to a `StandardStream`.
///
/// This implements the `io::Write` and `WriteColor` traits, and is constructed
/// via the `Write::lock` method.
///
/// The lifetime `'a` refers to the lifetime of the corresponding
/// `StandardStream`.
pub struct StandardStreamLock<'a> {
wtr: LossyStandardStream<WriterInnerLock<'a, IoStandardStreamLock<'a>>>,
}
/// Like `StandardStream`, but does buffered writing.
pub struct BufferedStandardStream {
wtr: LossyStandardStream<WriterInner<IoStandardStream>>,
}
/// WriterInner is a (limited) generic representation of a writer. It is
/// limited because W should only ever be stdout/stderr on Windows.
enum WriterInner<W> {
NoColor(NoColor<W>),
Ansi(Ansi<W>),
#[cfg(windows)]
Windows {
wtr: W,
console: Mutex<wincon::Console>,
},
}
/// WriterInnerLock is a (limited) generic representation of a writer. It is
/// limited because W should only ever be stdout/stderr on Windows.
enum WriterInnerLock<'a, W> {
NoColor(NoColor<W>),
Ansi(Ansi<W>),
/// What a gross hack. On Windows, we need to specify a lifetime for the
/// console when in a locked state, but obviously don't need to do that
/// on Unix, which makes the `'a` unused. To satisfy the compiler, we need
/// a PhantomData.
#[allow(dead_code)]
Unreachable(::std::marker::PhantomData<&'a ()>),
#[cfg(windows)]
Windows {
wtr: W,
console: MutexGuard<'a, wincon::Console>,
},
}
impl StandardStream {
/// Create a new `StandardStream` with the given color preferences that
/// writes to standard output.
///
/// On Windows, if coloring is desired and a Windows console could not be
/// found, then ANSI escape sequences are used instead.
///
/// The specific color/style settings can be configured when writing via
/// the `WriteColor` trait.
pub fn stdout(choice: ColorChoice) -> StandardStream {
let wtr = WriterInner::create(StandardStreamType::Stdout, choice);
StandardStream { wtr: LossyStandardStream::new(wtr) }
}
/// Create a new `StandardStream` with the given color preferences that
/// writes to standard error.
///
/// On Windows, if coloring is desired and a Windows console could not be
/// found, then ANSI escape sequences are used instead.
///
/// The specific color/style settings can be configured when writing via
/// the `WriteColor` trait.
pub fn stderr(choice: ColorChoice) -> StandardStream {
let wtr = WriterInner::create(StandardStreamType::Stderr, choice);
StandardStream { wtr: LossyStandardStream::new(wtr) }
}
/// Lock the underlying writer.
///
/// The lock guard returned also satisfies `io::Write` and
/// `WriteColor`.
///
/// This method is **not reentrant**. It may panic if `lock` is called
/// while a `StandardStreamLock` is still alive.
pub fn lock(&self) -> StandardStreamLock<'_> {
StandardStreamLock::from_stream(self)
}
}
impl<'a> StandardStreamLock<'a> {
#[cfg(not(windows))]
fn from_stream(stream: &StandardStream) -> StandardStreamLock<'_> {
let locked = match *stream.wtr.get_ref() {
WriterInner::NoColor(ref w) => {
WriterInnerLock::NoColor(NoColor(w.0.lock()))
}
WriterInner::Ansi(ref w) => {
WriterInnerLock::Ansi(Ansi(w.0.lock()))
}
};
StandardStreamLock { wtr: stream.wtr.wrap(locked) }
}
#[cfg(windows)]
fn from_stream(stream: &StandardStream) -> StandardStreamLock {
let locked = match *stream.wtr.get_ref() {
WriterInner::NoColor(ref w) => {
WriterInnerLock::NoColor(NoColor(w.0.lock()))
}
WriterInner::Ansi(ref w) => {
WriterInnerLock::Ansi(Ansi(w.0.lock()))
}
#[cfg(windows)]
WriterInner::Windows { ref wtr, ref console } => {
WriterInnerLock::Windows {
wtr: wtr.lock(),
console: console.lock().unwrap(),
}
}
};
StandardStreamLock { wtr: stream.wtr.wrap(locked) }
}
}
impl BufferedStandardStream {
/// Create a new `BufferedStandardStream` with the given color preferences
/// that writes to standard output via a buffered writer.
///
/// On Windows, if coloring is desired and a Windows console could not be
/// found, then ANSI escape sequences are used instead.
///
/// The specific color/style settings can be configured when writing via
/// the `WriteColor` trait.
pub fn stdout(choice: ColorChoice) -> BufferedStandardStream {
let wtr =
WriterInner::create(StandardStreamType::StdoutBuffered, choice);
BufferedStandardStream { wtr: LossyStandardStream::new(wtr) }
}
/// Create a new `BufferedStandardStream` with the given color preferences
/// that writes to standard error via a buffered writer.
///
/// On Windows, if coloring is desired and a Windows console could not be
/// found, then ANSI escape sequences are used instead.
///
/// The specific color/style settings can be configured when writing via
/// the `WriteColor` trait.
pub fn stderr(choice: ColorChoice) -> BufferedStandardStream {
let wtr =
WriterInner::create(StandardStreamType::StderrBuffered, choice);
BufferedStandardStream { wtr: LossyStandardStream::new(wtr) }
}
}
impl WriterInner<IoStandardStream> {
/// Create a new inner writer for a standard stream with the given color
/// preferences.
#[cfg(not(windows))]
fn create(
sty: StandardStreamType,
choice: ColorChoice,
) -> WriterInner<IoStandardStream> {
if choice.should_attempt_color() {
WriterInner::Ansi(Ansi(IoStandardStream::new(sty)))
} else {
WriterInner::NoColor(NoColor(IoStandardStream::new(sty)))
}
}
/// Create a new inner writer for a standard stream with the given color
/// preferences.
///
/// If coloring is desired and a Windows console could not be found, then
/// ANSI escape sequences are used instead.
#[cfg(windows)]
fn create(
sty: StandardStreamType,
choice: ColorChoice,
) -> WriterInner<IoStandardStream> {
let mut con = match sty {
StandardStreamType::Stdout => wincon::Console::stdout(),
StandardStreamType::Stderr => wincon::Console::stderr(),
StandardStreamType::StdoutBuffered => wincon::Console::stdout(),
StandardStreamType::StderrBuffered => wincon::Console::stderr(),
};
let is_console_virtual = con
.as_mut()
.map(|con| con.set_virtual_terminal_processing(true).is_ok())
.unwrap_or(false);
if choice.should_attempt_color() {
if choice.should_ansi() || is_console_virtual {
WriterInner::Ansi(Ansi(IoStandardStream::new(sty)))
} else if let Ok(console) = con {
WriterInner::Windows {
wtr: IoStandardStream::new(sty),
console: Mutex::new(console),
}
} else {
WriterInner::Ansi(Ansi(IoStandardStream::new(sty)))
}
} else {
WriterInner::NoColor(NoColor(IoStandardStream::new(sty)))
}
}
}
impl io::Write for StandardStream {
#[inline]
fn write(&mut self, b: &[u8]) -> io::Result<usize> {
self.wtr.write(b)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.wtr.flush()
}
}
impl WriteColor for StandardStream {
#[inline]
fn supports_color(&self) -> bool {
self.wtr.supports_color()
}
#[inline]
fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> {
self.wtr.set_color(spec)
}
#[inline]
fn reset(&mut self) -> io::Result<()> {
self.wtr.reset()
}
#[inline]
fn is_synchronous(&self) -> bool {
self.wtr.is_synchronous()
}
}
impl<'a> io::Write for StandardStreamLock<'a> {
#[inline]
fn write(&mut self, b: &[u8]) -> io::Result<usize> {
self.wtr.write(b)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.wtr.flush()
}
}
impl<'a> WriteColor for StandardStreamLock<'a> {
#[inline]
fn supports_color(&self) -> bool {
self.wtr.supports_color()
}
#[inline]
fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> {
self.wtr.set_color(spec)
}
#[inline]
fn reset(&mut self) -> io::Result<()> {
self.wtr.reset()
}
#[inline]
fn is_synchronous(&self) -> bool {
self.wtr.is_synchronous()
}
}
impl io::Write for BufferedStandardStream {
#[inline]
fn write(&mut self, b: &[u8]) -> io::Result<usize> {
self.wtr.write(b)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.wtr.flush()
}
}
impl WriteColor for BufferedStandardStream {
#[inline]
fn supports_color(&self) -> bool {
self.wtr.supports_color()
}
#[inline]
fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> {
if self.is_synchronous() {
self.wtr.flush()?;
}
self.wtr.set_color(spec)
}
#[inline]
fn reset(&mut self) -> io::Result<()> {
self.wtr.reset()
}
#[inline]
fn is_synchronous(&self) -> bool {
self.wtr.is_synchronous()
}
}
impl<W: io::Write> io::Write for WriterInner<W> {
#[inline(always)]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match *self {
WriterInner::NoColor(ref mut wtr) => wtr.write(buf),
WriterInner::Ansi(ref mut wtr) => wtr.write(buf),
#[cfg(windows)]
WriterInner::Windows { ref mut wtr, .. } => wtr.write(buf),
}
}
#[inline(always)]
fn flush(&mut self) -> io::Result<()> {
match *self {
WriterInner::NoColor(ref mut wtr) => wtr.flush(),
WriterInner::Ansi(ref mut wtr) => wtr.flush(),
#[cfg(windows)]
WriterInner::Windows { ref mut wtr, .. } => wtr.flush(),
}
}
}
impl<W: io::Write> WriteColor for WriterInner<W> {
fn supports_color(&self) -> bool {
match *self {
WriterInner::NoColor(_) => false,
WriterInner::Ansi(_) => true,
#[cfg(windows)]
WriterInner::Windows { .. } => true,
}
}
fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> {
match *self {
WriterInner::NoColor(ref mut wtr) => wtr.set_color(spec),
WriterInner::Ansi(ref mut wtr) => wtr.set_color(spec),
#[cfg(windows)]
WriterInner::Windows { ref mut wtr, ref console } => {
wtr.flush()?;
let mut console = console.lock().unwrap();
spec.write_console(&mut *console)
}
}
}
fn reset(&mut self) -> io::Result<()> {
match *self {
WriterInner::NoColor(ref mut wtr) => wtr.reset(),
WriterInner::Ansi(ref mut wtr) => wtr.reset(),
#[cfg(windows)]
WriterInner::Windows { ref mut wtr, ref mut console } => {
wtr.flush()?;
console.lock().unwrap().reset()?;
Ok(())
}
}
}
fn is_synchronous(&self) -> bool {
match *self {
WriterInner::NoColor(_) => false,
WriterInner::Ansi(_) => false,
#[cfg(windows)]
WriterInner::Windows { .. } => true,
}
}
}
impl<'a, W: io::Write> io::Write for WriterInnerLock<'a, W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match *self {
WriterInnerLock::Unreachable(_) => unreachable!(),
WriterInnerLock::NoColor(ref mut wtr) => wtr.write(buf),
WriterInnerLock::Ansi(ref mut wtr) => wtr.write(buf),
#[cfg(windows)]
WriterInnerLock::Windows { ref mut wtr, .. } => wtr.write(buf),
}
}
fn flush(&mut self) -> io::Result<()> {
match *self {
WriterInnerLock::Unreachable(_) => unreachable!(),
WriterInnerLock::NoColor(ref mut wtr) => wtr.flush(),
WriterInnerLock::Ansi(ref mut wtr) => wtr.flush(),
#[cfg(windows)]
WriterInnerLock::Windows { ref mut wtr, .. } => wtr.flush(),
}
}
}
impl<'a, W: io::Write> WriteColor for WriterInnerLock<'a, W> {
fn supports_color(&self) -> bool {
match *self {
WriterInnerLock::Unreachable(_) => unreachable!(),
WriterInnerLock::NoColor(_) => false,
WriterInnerLock::Ansi(_) => true,
#[cfg(windows)]
WriterInnerLock::Windows { .. } => true,
}
}
fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> {
match *self {
WriterInnerLock::Unreachable(_) => unreachable!(),
WriterInnerLock::NoColor(ref mut wtr) => wtr.set_color(spec),
WriterInnerLock::Ansi(ref mut wtr) => wtr.set_color(spec),
#[cfg(windows)]
WriterInnerLock::Windows { ref mut wtr, ref mut console } => {
wtr.flush()?;
spec.write_console(console)
}
}
}
fn reset(&mut self) -> io::Result<()> {
match *self {
WriterInnerLock::Unreachable(_) => unreachable!(),
WriterInnerLock::NoColor(ref mut wtr) => wtr.reset(),
WriterInnerLock::Ansi(ref mut wtr) => wtr.reset(),
#[cfg(windows)]
WriterInnerLock::Windows { ref mut wtr, ref mut console } => {
wtr.flush()?;
console.reset()?;
Ok(())
}
}
}
fn is_synchronous(&self) -> bool {
match *self {
WriterInnerLock::Unreachable(_) => unreachable!(),
WriterInnerLock::NoColor(_) => false,
WriterInnerLock::Ansi(_) => false,
#[cfg(windows)]
WriterInnerLock::Windows { .. } => true,
}
}
}
/// Writes colored buffers to stdout or stderr.
///
/// Writable buffers can be obtained by calling `buffer` on a `BufferWriter`.
///
/// This writer works with terminals that support ANSI escape sequences or
/// with a Windows console.
///
/// It is intended for a `BufferWriter` to be put in an `Arc` and written to
/// from multiple threads simultaneously.
pub struct BufferWriter {
stream: LossyStandardStream<IoStandardStream>,
printed: AtomicBool,
separator: Option<Vec<u8>>,
color_choice: ColorChoice,
#[cfg(windows)]
console: Option<Mutex<wincon::Console>>,
}
impl BufferWriter {
/// Create a new `BufferWriter` that writes to a standard stream with the
/// given color preferences.
///
/// The specific color/style settings can be configured when writing to
/// the buffers themselves.
#[cfg(not(windows))]
fn create(sty: StandardStreamType, choice: ColorChoice) -> BufferWriter {
BufferWriter {
stream: LossyStandardStream::new(IoStandardStream::new(sty)),
printed: AtomicBool::new(false),
separator: None,
color_choice: choice,
}
}
/// Create a new `BufferWriter` that writes to a standard stream with the
/// given color preferences.
///
/// If coloring is desired and a Windows console could not be found, then
/// ANSI escape sequences are used instead.
///
/// The specific color/style settings can be configured when writing to
/// the buffers themselves.
#[cfg(windows)]
fn create(sty: StandardStreamType, choice: ColorChoice) -> BufferWriter {
let mut con = match sty {
StandardStreamType::Stdout => wincon::Console::stdout(),
StandardStreamType::Stderr => wincon::Console::stderr(),
StandardStreamType::StdoutBuffered => wincon::Console::stdout(),
StandardStreamType::StderrBuffered => wincon::Console::stderr(),
}
.ok();
let is_console_virtual = con
.as_mut()
.map(|con| con.set_virtual_terminal_processing(true).is_ok())
.unwrap_or(false);
// If we can enable ANSI on Windows, then we don't need the console
// anymore.
if is_console_virtual {
con = None;
}
let stream = LossyStandardStream::new(IoStandardStream::new(sty));
BufferWriter {
stream: stream,
printed: AtomicBool::new(false),
separator: None,
color_choice: choice,
console: con.map(Mutex::new),
}
}
/// Create a new `BufferWriter` that writes to stdout with the given
/// color preferences.
///
/// On Windows, if coloring is desired and a Windows console could not be
/// found, then ANSI escape sequences are used instead.
///
/// The specific color/style settings can be configured when writing to
/// the buffers themselves.
pub fn stdout(choice: ColorChoice) -> BufferWriter {
BufferWriter::create(StandardStreamType::Stdout, choice)
}
/// Create a new `BufferWriter` that writes to stderr with the given
/// color preferences.
///
/// On Windows, if coloring is desired and a Windows console could not be
/// found, then ANSI escape sequences are used instead.
///
/// The specific color/style settings can be configured when writing to
/// the buffers themselves.
pub fn stderr(choice: ColorChoice) -> BufferWriter {
BufferWriter::create(StandardStreamType::Stderr, choice)
}
/// If set, the separator given is printed between buffers. By default, no
/// separator is printed.
///
/// The default value is `None`.
pub fn separator(&mut self, sep: Option<Vec<u8>>) {
self.separator = sep;
}
/// Creates a new `Buffer` with the current color preferences.
///
/// A `Buffer` satisfies both `io::Write` and `WriteColor`. A `Buffer` can
/// be printed using the `print` method.
#[cfg(not(windows))]
pub fn buffer(&self) -> Buffer {
Buffer::new(self.color_choice)
}
/// Creates a new `Buffer` with the current color preferences.
///
/// A `Buffer` satisfies both `io::Write` and `WriteColor`. A `Buffer` can
/// be printed using the `print` method.
#[cfg(windows)]
pub fn buffer(&self) -> Buffer {
Buffer::new(self.color_choice, self.console.is_some())
}
/// Prints the contents of the given buffer.
///
/// It is safe to call this from multiple threads simultaneously. In
/// particular, all buffers are written atomically. No interleaving will
/// occur.
pub fn print(&self, buf: &Buffer) -> io::Result<()> {
if buf.is_empty() {
return Ok(());
}
let mut stream = self.stream.wrap(self.stream.get_ref().lock());
if let Some(ref sep) = self.separator {
if self.printed.load(Ordering::SeqCst) {
stream.write_all(sep)?;
stream.write_all(b"\n")?;
}
}
match buf.0 {
BufferInner::NoColor(ref b) => stream.write_all(&b.0)?,
BufferInner::Ansi(ref b) => stream.write_all(&b.0)?,
#[cfg(windows)]
BufferInner::Windows(ref b) => {
// We guarantee by construction that we have a console here.
// Namely, a BufferWriter is the only way to produce a Buffer.
let console_mutex = self
.console
.as_ref()
.expect("got Windows buffer but have no Console");
let mut console = console_mutex.lock().unwrap();
b.print(&mut *console, &mut stream)?;
}
}
self.printed.store(true, Ordering::SeqCst);