summary refs log tree commit diff
path: root/src/subtitles/state.rs
blob: 6b1ebdab20d0221c7a375a81cf3bb52746abd6e3 (plain)
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
use crate::{
    subtitles::{SUBTITLE_TRACKS, StreamIndex},
    translation::TRANSLATIONS,
    util::Tracker,
};

#[derive(Default)]
pub struct SubtitleState {
    pub stream_ix: Option<StreamIndex>,
    pub last_started_cue_ix: Tracker<Option<usize>>,
    pub last_ended_cue_ix: Tracker<Option<usize>>,
}

#[derive(Clone, Copy, Debug)]
pub struct CueAddress(pub StreamIndex, pub usize);

impl SubtitleState {
    pub fn active_cue(&self) -> Option<CueAddress> {
        if let Some(stream_ix) = self.stream_ix {
            match (*self.last_started_cue_ix, *self.last_ended_cue_ix) {
                (None, _) => None,
                (Some(started_ix), None) => Some(CueAddress(stream_ix, started_ix)),
                (Some(started_ix), Some(ended_ix)) => {
                    if started_ix > ended_ix {
                        Some(CueAddress(stream_ix, started_ix))
                    } else {
                        None
                    }
                }
            }
        } else {
            None
        }
    }

    pub fn is_dirty(&self) -> bool {
        self.last_started_cue_ix.is_dirty() || self.last_ended_cue_ix.is_dirty()
    }

    pub fn reset(&mut self) {
        self.last_started_cue_ix.reset();
        self.last_ended_cue_ix.reset();
    }

    pub fn set_stream_ix(&mut self, stream_ix: Option<StreamIndex>) {
        self.stream_ix = stream_ix;
        self.last_started_cue_ix.set(None);
        self.last_ended_cue_ix.set(None);
    }
}

impl CueAddress {
    pub fn resolve_text(&self) -> String {
        SUBTITLE_TRACKS.read().get(&self.0).unwrap().texts[self.1].clone()
    }

    pub fn resolve_translation(&self) -> Option<String> {
        TRANSLATIONS
            .read()
            .get(&self.0)
            .and_then(|tln| tln.get(self.1).cloned())
    }
}