Skip to content

Commit d997294

Browse files
first crack at adding SyncGuard from Funami580
1 parent f978a21 commit d997294

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@
7878
7979
pub use crate::kb::Key;
8080
pub use crate::term::{
81-
user_attended, user_attended_stderr, Term, TermFamily, TermFeatures, TermTarget,
81+
user_attended, user_attended_stderr, SyncGuard, Term, TermFamily, TermFeatures, TermTarget,
8282
};
8383
pub use crate::utils::{
8484
colors_enabled, colors_enabled_stderr, measure_text_width, pad_str, pad_str_with,

src/term.rs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::cell::Cell;
12
use std::fmt::{Debug, Display};
23
use std::io::{self, Read, Write};
34
use std::sync::{Arc, Mutex};
@@ -76,6 +77,19 @@ impl<'a> TermFeatures<'a> {
7677
is_a_color_terminal(self.0)
7778
}
7879

80+
#[inline]
81+
pub fn is_synchronized_output_supported(&self) -> bool {
82+
#[cfg(unix)]
83+
{
84+
supports_synchronized_output()
85+
}
86+
#[cfg(not(unix))]
87+
{
88+
// TODO
89+
false
90+
}
91+
}
92+
7993
/// Check if this terminal is an msys terminal.
8094
///
8195
/// This is sometimes useful to disable features that are known to not
@@ -624,6 +638,42 @@ impl<'a> Read for &'a Term {
624638
}
625639
}
626640

641+
pub struct SyncGuard<'a> {
642+
term: Cell<Option<&'a Term>>,
643+
}
644+
645+
impl<'a> SyncGuard<'a> {
646+
pub fn begin_sync(term: &'a Term) -> io::Result<Self> {
647+
let ret = if term.features().is_synchronized_output_supported() {
648+
term.write_str("\x1b[?2026h")?;
649+
Some(term)
650+
} else {
651+
None
652+
};
653+
654+
Ok(Self {
655+
term: Cell::new(ret),
656+
})
657+
}
658+
659+
pub fn finish_sync(self) -> io::Result<()> {
660+
self.finish_sync_inner()
661+
}
662+
663+
fn finish_sync_inner(&self) -> io::Result<()> {
664+
if let Some(term) = self.term.take() {
665+
term.write_str("\x1b[?2026l")?;
666+
}
667+
Ok(())
668+
}
669+
}
670+
671+
impl Drop for SyncGuard<'_> {
672+
fn drop(&mut self) {
673+
let _ = self.finish_sync_inner();
674+
}
675+
}
676+
627677
#[cfg(unix)]
628678
pub use crate::unix_term::*;
629679
#[cfg(target_arch = "wasm32")]

0 commit comments

Comments
 (0)