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
//! A table of widgets with static number of columns.
//!
//! Use by implementing `TableRow` and adding instances of that type to a `Table` using `rows_mut`.
use base::basic_types::*;
use base::{StyleModifier, Window};
use input::Scrollable;
use input::{Behavior, Input, Navigatable, OperationResult};
use widget::{
    layout_linearly, ColDemand, Demand, Demand2D, RenderingHints, RowDemand, SeparatingStyle,
    Widget,
};

/// A single column in a `Table`.
///
/// This does not store any data, but rather how to access a cell in a single column of a table
/// and how it reacts to input.
///
/// In a sense this is only necessary because we do not have variadic generics.
pub struct Column<T: ?Sized> {
    /// Immutable widget access.
    pub access: fn(&T) -> &dyn Widget,
    /// Mutable widget access.
    pub access_mut: fn(&mut T) -> &mut dyn Widget,
    /// Input processing
    pub behavior: fn(&mut T, Input) -> Option<Input>,
}

/// This trait both (statically) describes the layout of the table (`COLUMNS`) and represents a
/// single row in the table.
///
/// Implement this trait, if you want to create a `Table`!
pub trait TableRow: 'static {
    /// Define the behavior of individual columns of the table.
    const COLUMNS: &'static [Column<Self>];

    /// Convenient access using `COLUMNS`. (Do not reimplement this.)
    fn num_columns() -> usize {
        Self::COLUMNS.len()
    }

    /// Calculate the vertical space demand of the current row. (Default: max of all cells.)
    fn height_demand(&self) -> RowDemand {
        let mut y_demand = Demand::zero();
        for col in Self::COLUMNS.iter() {
            let demand2d = (col.access)(self).space_demand();
            y_demand.max_assign(demand2d.height);
        }
        y_demand
    }
}

/// Mutable row access mapper to enforce invariants after mutation.
pub struct RowsMut<'a, R: 'static + TableRow> {
    table: &'a mut Table<R>,
}

impl<'a, R: 'static + TableRow> ::std::ops::Drop for RowsMut<'a, R> {
    fn drop(&mut self) {
        let _ = self.table.validate_row_pos();
    }
}

impl<'a, R: 'static + TableRow> ::std::ops::Deref for RowsMut<'a, R> {
    type Target = Vec<R>;
    fn deref(&self) -> &Self::Target {
        &self.table.rows
    }
}

impl<'a, R: 'static + TableRow> ::std::ops::DerefMut for RowsMut<'a, R> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.table.rows
    }
}

/// A table of widgets with static number of `Columns`.
///
/// In order to create a table, you have to define a type for a row in the table and implement
/// `TableRow` for it. Then add instances of that type using `rows_mut`.
///
/// At any time, a single cell of the table is active. Send user input to the cell by adding the
/// result of `current_cell_behavior()` to an `InputChain`.
/// A table is also `Navigatable` by which the user can change which cell is the currently active
/// one.
pub struct Table<R: TableRow> {
    rows: Vec<R>,
    row_sep_style: SeparatingStyle,
    col_sep_style: SeparatingStyle,
    focused_style: StyleModifier,
    row_pos: u32,
    col_pos: u32,
}

impl<R: TableRow + 'static> Table<R> {
    /// Create an empty table and specify how rows/columns and the currently active cell will be
    /// distinguished.
    pub fn new(
        row_sep_style: SeparatingStyle,
        col_sep_style: SeparatingStyle,
        focused_style: StyleModifier,
    ) -> Self {
        Table {
            rows: Vec::new(),
            row_sep_style: row_sep_style,
            col_sep_style: col_sep_style,
            focused_style: focused_style,
            row_pos: 0,
            col_pos: 0,
        }
    }

    /// Access the content of the table mutably.
    pub fn rows_mut<'a>(&'a mut self) -> RowsMut<'a, R> {
        RowsMut { table: self }
    }

    /// Access the content of the table immutably.
    pub fn rows(&mut self) -> &Vec<R> {
        &self.rows
    }

    fn layout_columns(&self, window: &Window) -> Box<[Width]> {
        let mut x_demands = vec![Demand::zero(); R::num_columns()];
        for row in self.rows.iter() {
            for (col_num, col) in R::COLUMNS.iter().enumerate() {
                let demand2d = (col.access)(row).space_demand();
                x_demands[col_num].max_assign(demand2d.width);
            }
        }
        let separator_width = self.col_sep_style.width();
        layout_linearly(window.get_width(), separator_width, &x_demands)
    }

    fn validate_row_pos(&mut self) -> Result<(), ()> {
        let max_pos = (self.rows.len() as u32).checked_sub(1).unwrap_or(0);
        if self.row_pos > max_pos {
            self.row_pos = max_pos;
            Err(())
        } else {
            Ok(())
        }
    }

    fn validate_col_pos(&mut self) -> Result<(), ()> {
        let max_pos = R::num_columns() as u32 - 1;
        if self.col_pos > max_pos {
            self.col_pos = max_pos;
            Err(())
        } else {
            Ok(())
        }
    }

    /// Get access to the currently active row.
    pub fn current_row(&self) -> Option<&R> {
        self.rows.get(self.row_pos as usize)
    }

    /// Get mutable access to the currently active row.
    pub fn current_row_mut(&mut self) -> Option<&mut R> {
        self.rows.get_mut(self.row_pos as usize)
    }

    /// Get the currently active column.
    pub fn current_col(&self) -> &'static Column<R> {
        &R::COLUMNS[self.col_pos as usize]
    }

    fn pass_event_to_current_cell(&mut self, i: Input) -> Option<Input> {
        let col_behavior = self.current_col().behavior;
        if let Some(row) = self.current_row_mut() {
            col_behavior(row, i)
        } else {
            Some(i)
        }
    }

    /// Create a `Behavior` which can be used to send input directly to the currently active cell
    /// by adding it to an `InputChain`.
    pub fn current_cell_behavior<'a>(&'a mut self) -> CurrentCellBehavior<'a, R> {
        CurrentCellBehavior { table: self }
    }
}

/// Pass all behavior to the currently active cell.
pub struct CurrentCellBehavior<'a, R: TableRow + 'static> {
    table: &'a mut Table<R>,
}

impl<'a, R: TableRow + 'static> Behavior for CurrentCellBehavior<'a, R> {
    fn input(self, i: Input) -> Option<Input> {
        self.table.pass_event_to_current_cell(i)
    }
}

impl<R: TableRow + 'static> Widget for Table<R> {
    fn space_demand(&self) -> Demand2D {
        let mut x_demands = vec![Demand::exact(0); R::num_columns()];
        let mut y_demand = Demand::zero();

        let mut row_iter = self.rows.iter().peekable();
        while let Some(row) = row_iter.next() {
            let mut row_max_y = Demand::exact(0);
            for (col_num, col) in R::COLUMNS.iter().enumerate() {
                let demand2d = (col.access)(row).space_demand();
                x_demands[col_num].max_assign(demand2d.width);
                row_max_y.max_assign(demand2d.height)
            }
            y_demand += row_max_y;
            if row_iter.peek().is_some() {
                y_demand += Demand::exact(self.row_sep_style.height());
            }
        }

        //Account all separators between cols
        let x_demand = x_demands.iter().sum::<ColDemand>()
            + ColDemand::exact(
                (self.col_sep_style.width() * (x_demands.len() as i32 - 1)).positive_or_zero(),
            );
        Demand2D {
            width: x_demand,
            height: y_demand,
        }
    }
    fn draw(&self, window: Window, hints: RenderingHints) {
        let column_widths = self.layout_columns(&window);

        let mut window = Some(window);
        let mut row_iter = self.rows.iter().enumerate().peekable();
        while let Some((row_index, row)) = row_iter.next() {
            if window.is_none() {
                break;
            }
            let height = row.height_demand().min;
            let (mut row_window, rest_window) = match window.unwrap().split(height.from_origin()) {
                Ok((row_window, rest_window)) => (row_window, Some(rest_window)),
                Err(row_window) => (row_window, None),
            };
            window = rest_window;

            if let (1, &SeparatingStyle::AlternatingStyle(modifier)) =
                (row_index % 2, &self.row_sep_style)
            {
                row_window.modify_default_style(modifier);
            }

            let mut iter = R::COLUMNS
                .iter()
                .zip(column_widths.iter())
                .enumerate()
                .peekable();
            while let Some((col_index, (col, &pos))) = iter.next() {
                let (mut cell_window, r) = row_window
                    .split(pos.from_origin())
                    .expect("valid split pos from layout");
                row_window = r;

                if let (1, &SeparatingStyle::AlternatingStyle(modifier)) =
                    (col_index % 2, &self.col_sep_style)
                {
                    cell_window.modify_default_style(modifier);
                }

                let cell_draw_hints =
                    if row_index as u32 == self.row_pos && col_index as u32 == self.col_pos {
                        cell_window.modify_default_style(self.focused_style);
                        hints
                    } else {
                        hints.active(false)
                    };

                cell_window.clear(); // Fill background using new style
                (col.access)(row).draw(cell_window, cell_draw_hints);
                if let (Some(_), &SeparatingStyle::Draw(ref c)) = (iter.peek(), &self.col_sep_style)
                {
                    if row_window.get_width() > 0 {
                        let (mut sep_window, r) = row_window
                            .split(Width::from(c.width()).from_origin())
                            .expect("valid split pos from layout");
                        row_window = r;
                        sep_window.fill(c.clone());
                    }
                }
            }
            if let (Some(_), &SeparatingStyle::Draw(ref c)) = (row_iter.peek(), &self.row_sep_style)
            {
                if window.is_none() {
                    break;
                }
                let (mut sep_window, rest_window) =
                    match window.unwrap().split(height.from_origin()) {
                        Ok((row_window, rest_window)) => (row_window, Some(rest_window)),
                        Err(row_window) => (row_window, None),
                    };
                window = rest_window;
                sep_window.fill(c.clone());
            }
        }
    }
}

impl<R: TableRow + 'static> Navigatable for Table<R> {
    fn move_up(&mut self) -> OperationResult {
        if self.row_pos > 0 {
            self.row_pos -= 1;
            Ok(())
        } else {
            Err(())
        }
    }
    fn move_down(&mut self) -> OperationResult {
        self.row_pos += 1;
        self.validate_row_pos()
    }
    fn move_left(&mut self) -> OperationResult {
        if self.col_pos != 0 {
            self.col_pos -= 1;
            Ok(())
        } else {
            Err(())
        }
    }
    fn move_right(&mut self) -> OperationResult {
        self.col_pos += 1;
        self.validate_col_pos()
    }
}

impl<R: TableRow + 'static> Scrollable for Table<R> {
    fn scroll_backwards(&mut self) -> OperationResult {
        self.move_up()
    }
    fn scroll_forwards(&mut self) -> OperationResult {
        self.move_down()
    }
    fn scroll_to_beginning(&mut self) -> OperationResult {
        if self.row_pos != 0 {
            self.row_pos = 0;
            Ok(())
        } else {
            Err(())
        }
    }
    fn scroll_to_end(&mut self) -> OperationResult {
        let end = self.rows.len().saturating_sub(1) as u32;
        if self.row_pos != end {
            self.row_pos = end;
            Ok(())
        } else {
            Err(())
        }
    }
}