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
use crate::layout::{LineLayout, SegmentLayout};
use crate::position::AbsolutePosition;
use crate::segment::{Segment, SegmentId};
use crate::terminal::Terminal;
use crate::{Error, Result};
use std::collections::HashMap;
use std::mem::swap;
use std::sync::atomic::{AtomicUsize, Ordering};

/// A unique line identifier.
#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)]
pub struct LineId(usize);

/// The greatest provisioned line identifier.
static ID_VALUE: AtomicUsize = AtomicUsize::new(0);

impl LineId {
    /// Create a new, unique line identifier.
    fn new() -> Self {
        Self(ID_VALUE.fetch_add(1, Ordering::Relaxed))
    }
}

/// A line composed of text segments. Accumulates changes until applied by its parent `Interface`.
/// May be obtained from the `Interface` API.
#[derive(Debug)]
pub struct Line {
    /// This line's immutable, unique identifier.
    identifier: LineId,

    /// The currently-rendered state.
    current: LineState,

    /// If changed, the state with queued and unapplied changes.
    alternate: Option<LineState>,

    /// The segment value store. Ordering information is stored in the state.
    segments: HashMap<SegmentId, Segment>,
}

impl Line {
    /// Create a new line with no text segments.
    pub(crate) fn new() -> Line {
        Line {
            identifier: LineId::new(),
            current: LineState::default(),
            alternate: None,
            segments: HashMap::new(),
        }
    }

    /// This line's unique identifier.
    pub fn identifier(&self) -> LineId {
        self.identifier
    }

    /// This line's text segment identifiers. Reflects the latest state, even if staged changes have
    /// not yet been applied to the interface.
    pub fn segment_ids(&self) -> &Vec<SegmentId> {
        match self.alternate {
            Some(ref alternate) => &alternate.segments,
            None => &self.current.segments,
        }
    }

    /// This line's text segments. Reflects the latest state, even if staged changes have not yet
    /// been applied to the interface.
    pub fn segments(&self) -> Vec<&Segment> {
        self.segment_ids()
            .iter()
            .map(|id| self.segments.get(id).unwrap())
            .collect()
    }

    /// Retrieves several segment references by their identifiers.
    pub fn get_segments(&self, ids: &Vec<SegmentId>) -> Result<Vec<&Segment>> {
        ids.iter()
            .map(|id| self.segments.get(id).ok_or(Error::SegmentIdInvalid))
            .collect()
    }

    /// Retrieves a segment reference by its identifier.
    pub fn get_segment(&self, id: &SegmentId) -> Result<&Segment> {
        self.segments.get(&id).ok_or(Error::SegmentIdInvalid)
    }

    /// Retrieves a mutable segment reference by its identifier.
    pub fn get_segment_mut(&mut self, id: &SegmentId) -> Result<&mut Segment> {
        self.segments.get_mut(&id).ok_or(Error::SegmentIdInvalid)
    }

    /// Determines the specified segment's index in this line.
    pub fn get_segment_index(&self, id: &SegmentId) -> Result<usize> {
        self.segment_ids()
            .iter()
            .position(|oth| oth == id)
            .ok_or(Error::SegmentIdInvalid)
    }

    /// Appends a new text segment to this line. The text segment addition will be staged until
    /// changes are applied for this line's `Interface`. Note that the returned segment may have
    /// other changes staged against it for the same update.
    pub fn add_segment(&mut self) -> &mut Segment {
        let segment_id = self.create_segment();

        let alternate = self.get_alternate_mut();
        alternate.segments.push(segment_id);

        self.get_segment_mut(&segment_id).unwrap()
    }

    /// Inserts a new text segment in this line at a specified index. The segment insertion will be
    /// staged until changes are applied for this line's `Interface`. Note that the returned
    /// segment may have other changes staged against it for the same update.
    pub fn insert_segment(&mut self, index: usize) -> Result<&mut Segment> {
        if index > self.get_alternate().segments.len() {
            return Err(Error::SegmentOutOfBounds);
        }

        let segment_id = self.create_segment();

        let alternate = self.get_alternate_mut();
        alternate.segments.insert(index, segment_id);

        Ok(self.get_segment_mut(&segment_id).unwrap())
    }

    /// Removes a text segment with the specified identifier from this line. The segment removal
    /// will be staged until changes are applied for this line's `Interface`.
    pub fn remove_segment(&mut self, id: &SegmentId) -> Result<()> {
        let index = self.get_segment_index(id)?;

        let alternate = self.get_alternate_mut();
        alternate.segments.remove(index);

        Ok(())
    }

    /// Removes a text segment from this line at the specified index. The segment removal will be
    /// staged until changes are applied for this line's `Interface`.
    pub fn remove_segment_at(&mut self, index: usize) -> Result<SegmentId> {
        let alternate = self.get_alternate_mut();

        if index > alternate.segments.len() - 1 {
            return Err(Error::SegmentOutOfBounds);
        }

        let segment_id = alternate.segments.remove(index);

        Ok(segment_id)
    }

    /// Whether this line or its text segments have any staged changes.
    pub fn has_changes(&self) -> bool {
        self.alternate.is_some()
            || self
                .current
                .segments
                .iter()
                .map(|id| self.segments.get(id).unwrap())
                .any(|segment| segment.has_changes())
    }

    /// Removes the specified text segment from this line and returns a clone of it.
    pub(crate) fn take_segment(&mut self, segment_id: &SegmentId) -> Result<Segment> {
        let segment = self.get_segment(segment_id)?;
        let clone = segment.clone();
        self.remove_segment(segment_id)?;
        Ok(clone)
    }

    /// Inserts the provided text segment in this line at a specified index. The segment insertion
    /// will be staged until changes are applied for this line's `Interface`. Note that the returned
    /// segment may have other changes staged against it for the same update.
    pub(crate) fn append_given_segment(&mut self, segment: Segment) -> &mut Segment {
        let segment_id = segment.identifier();
        self.segments.insert(segment_id, segment);

        let alternate = self.get_alternate_mut();
        alternate.segments.push(segment_id);

        self.get_segment_mut(&segment_id).unwrap()
    }

    /// Render this at the specified `location`. Unless `force_render`, assumes the previous state
    /// is still valid and performs an optimized render applying staged updates if available. If
    /// `force_render`, the line and its segments are fully re-rendered.
    pub(crate) fn update(
        &mut self,
        terminal: &mut Terminal,
        location: AbsolutePosition,
        force_render: bool,
    ) -> Result<LineLayout> {
        if !force_render && !self.has_changes() {
            return if self.current.segments.is_empty() {
                Ok(LineLayout::new(self.identifier, Vec::default()))
            } else {
                Ok(self.current.layout.clone().unwrap())
            };
        }

        let previous_layout = self.current.layout.as_ref();
        let previous_end = previous_layout.and_then(|l| l.end_position());

        let segment_layouts = if self.has_alternate() {
            let alternate = self.swap_alternate();
            self.prune_segments(&alternate.segments);
            self.render(terminal, location, force_render, &alternate.segments)?
        } else {
            let current_segments = self.current.segments.clone();
            self.render(terminal, location, force_render, &current_segments)?
        };

        let new_layout = LineLayout::new(self.identifier, segment_layouts);

        let new_end = new_layout.end_position();

        let line_is_shorter = match (previous_end, new_end) {
            (Some(previous), Some(new)) => {
                new.row() == previous.row() && new.column() < previous.column()
            }
            (Some(_), None) => true,
            _ => false,
        };

        if force_render || line_is_shorter {
            if let Some(position) = new_layout.end_position() {
                terminal.move_cursor(position)?;
            }
            terminal.clear_rest_of_line()?;
        }

        self.current.layout = Some(new_layout.clone());

        Ok(new_layout)
    }

    /// Renders the current line state at the `location`. Attempts to optimize the update using the
    /// current state or `previous_segments`, if available. If `force_render`, no optimizations are
    /// made and the line is fully re-rendered.
    fn render(
        &mut self,
        terminal: &mut Terminal,
        location: AbsolutePosition,
        mut force_render: bool,
        previous_segments: &Vec<SegmentId>,
    ) -> Result<Vec<SegmentLayout>> {
        let mut segment_layouts = Vec::new();

        terminal.move_cursor(location)?;

        let mut segment_cursor = location;
        for (index, segment_id) in self.current.segments.iter().enumerate() {
            let mut previous_layout = None;
            if previous_segments.get(index) == Some(segment_id) {
                let current_segments = self.current.layout.as_ref().unwrap().segments();
                previous_layout = Some(current_segments[index].clone());
            }

            if previous_layout.is_none() {
                force_render = true;
            }

            let segment = self.segments.get_mut(segment_id).unwrap();

            let segment_layout =
                if !force_render && previous_layout.is_some() && !segment.has_changes() {
                    previous_layout.clone().unwrap()
                } else {
                    segment.update(terminal, segment_cursor, force_render)?
                };

            if let Some(last_part) = segment_layout.parts().last() {
                segment_cursor = last_part.end_position();
            }

            if let Some(previous_layout) = previous_layout {
                if previous_layout.end_position() != segment_layout.end_position() {
                    force_render = true;
                }
            } else {
                force_render = true;
            }

            segment_layouts.push(segment_layout);
        }

        Ok(segment_layouts)
    }

    /// Prune any segment values whose IDs are no longer included in this line.
    fn prune_segments(&mut self, segment_ids: &Vec<SegmentId>) {
        let segment_id_iter = segment_ids.iter();
        let removed_segment_ids = segment_id_iter.filter(|id| !self.current.segments.contains(id));

        removed_segment_ids.for_each(|id| {
            self.segments.remove(id);
        });
    }

    /// Create a new segment, add it to the map, and return its identifier. Note that the returned
    /// identifier still needs to be ordered in state.
    fn create_segment(&mut self) -> SegmentId {
        let segment = Segment::new();
        let segment_id = segment.identifier();
        self.segments.insert(segment_id, segment);
        segment_id
    }

    /// Whether this line has an alternate state, which may contain added or removed text segments.
    fn has_alternate(&self) -> bool {
        self.alternate.is_some()
    }

    /// Get a reference to this line's alternate state, creating it and dirtying the line if
    /// necessary.
    fn get_alternate(&mut self) -> &LineState {
        if self.alternate.is_none() {
            self.alternate = Some(self.current.clone());
        }

        &self.alternate.as_ref().unwrap()
    }

    /// Get a mutable reference to this line's alternate state, creating it and dirtying the line
    /// if necessary.
    fn get_alternate_mut(&mut self) -> &mut LineState {
        if self.alternate.is_none() {
            self.alternate = Some(self.current.clone());
        }

        self.alternate.as_mut().unwrap()
    }

    /// Swaps this line's alternate state out for its current and returns the previous-current
    /// state. This line must have an alternate for this to be called.
    fn swap_alternate(&mut self) -> LineState {
        let mut alternate = self.alternate.take().unwrap();
        swap(&mut self.current, &mut alternate);
        alternate
    }
}

/// The line's segment ordering and, if rendered, layout.
#[derive(Clone, Debug)]
struct LineState {
    /// Segment ordering. Note that these IDs must also be present in the `Line`'s `segments` map.
    segments: Vec<SegmentId>,

    /// This line's layout on screen, if it has been rendered.
    layout: Option<LineLayout>,
}

impl Default for LineState {
    /// An empty state with no segments or layout.
    fn default() -> Self {
        Self {
            segments: Vec::new(),
            layout: None,
        }
    }
}