use super::*;
pub(crate) struct StagedTurn {
file: String,
pub(crate) prior_seen: Option<String>,
prior_comment_only: bool,
prior_target: Option<String>,
stage_gen: u64,
}
impl PairState {
pub(crate) fn new(
session: CollabSession,
events: Option<Sender<crate::pair_host::PairEvent>>,
) -> Self {
Self {
session,
region: None,
discarding: false,
cancelled: false,
can_interrupt: false,
turn_active: false,
target_file: None,
pending_note: None,
stage_gen: 0,
notes: Vec::new(),
next_note_id: 1,
note_in_flight: None,
events,
comment_only: false,
pending_caret: None,
last_seen: std::collections::HashMap::new(),
}
}
pub(crate) fn doc_lines(&self, file: &str) -> Option<Vec<String>> {
self.session
.doc_text(file)
.map(|t| t.split('\n').map(String::from).collect())
}
pub(crate) fn turn_active(&self) -> bool {
self.turn_active
}
pub(crate) fn begin_turn(
&mut self,
file: &str,
content: &str,
comment_only: bool,
) -> Option<String> {
self.comment_only = comment_only;
self.target_file = Some(file.to_string());
self.session.request_file(file);
self.last_seen.insert(file.to_string(), content.to_string())
}
pub(crate) fn stage_turn(
&mut self,
file: &str,
content: &str,
comment_only: bool,
) -> StagedTurn {
let prior_comment_only = self.comment_only;
let prior_target = self.target_file.clone();
let prior_seen = self.begin_turn(file, content, comment_only);
self.stage_gen += 1;
StagedTurn {
file: file.to_string(),
prior_seen,
prior_comment_only,
prior_target,
stage_gen: self.stage_gen,
}
}
pub(crate) fn unstage_turn(&mut self, staged: StagedTurn) {
if self.stage_gen != staged.stage_gen {
return;
}
self.stage_gen = staged.stage_gen - 1;
self.comment_only = staged.prior_comment_only;
self.target_file = staged.prior_target;
match staged.prior_seen {
Some(old) => {
self.last_seen.insert(staged.file, old);
}
None => {
self.last_seen.remove(&staged.file);
}
}
}
pub(crate) fn last_seen_of(&self, file: &str) -> Option<String> {
self.last_seen.get(file).cloned()
}
}
pub(crate) fn lock_briefly(
state: &Mutex<PairState>,
) -> Option<std::sync::MutexGuard<'_, PairState>> {
let deadline = std::time::Instant::now() + Duration::from_millis(100);
loop {
if let Ok(guard) = state.try_lock() {
return Some(guard);
}
if std::time::Instant::now() > deadline {
return None;
}
std::thread::sleep(Duration::from_millis(1));
}
}