Skip to content

Commit 5d0d3ea

Browse files
first crack at adding SyncGuard from Funami580
Co-authored-by: Funami580 <63090225+Funami580@users.noreply.github.com>
1 parent 3915728 commit 5d0d3ea

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, RwLock};
@@ -78,6 +79,19 @@ impl<'a> TermFeatures<'a> {
7879
is_a_color_terminal(self.0)
7980
}
8081

82+
#[inline]
83+
pub fn is_synchronized_output_supported(&self) -> bool {
84+
#[cfg(unix)]
85+
{
86+
supports_synchronized_output()
87+
}
88+
#[cfg(not(unix))]
89+
{
90+
// TODO
91+
false
92+
}
93+
}
94+
8195
/// Check if this terminal is an msys terminal.
8296
///
8397
/// This is sometimes useful to disable features that are known to not
@@ -656,6 +670,42 @@ impl<'a> Read for &'a Term {
656670
}
657671
}
658672

673+
pub struct SyncGuard<'a> {
674+
term: Cell<Option<&'a Term>>,
675+
}
676+
677+
impl<'a> SyncGuard<'a> {
678+
pub fn begin_sync(term: &'a Term) -> io::Result<Self> {
679+
let ret = if term.features().is_synchronized_output_supported() {
680+
term.write_str("\x1b[?2026h")?;
681+
Some(term)
682+
} else {
683+
None
684+
};
685+
686+
Ok(Self {
687+
term: Cell::new(ret),
688+
})
689+
}
690+
691+
pub fn finish_sync(self) -> io::Result<()> {
692+
self.finish_sync_inner()
693+
}
694+
695+
fn finish_sync_inner(&self) -> io::Result<()> {
696+
if let Some(term) = self.term.take() {
697+
term.write_str("\x1b[?2026l")?;
698+
}
699+
Ok(())
700+
}
701+
}
702+
703+
impl Drop for SyncGuard<'_> {
704+
fn drop(&mut self) {
705+
let _ = self.finish_sync_inner();
706+
}
707+
}
708+
659709
#[cfg(all(unix, not(target_arch = "wasm32")))]
660710
pub use crate::unix_term::*;
661711
#[cfg(target_arch = "wasm32")]

0 commit comments

Comments
 (0)