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
use {NodeIndex, Scalar, Widget};
use widget;


/// Reaction params.
pub type WidgetNum = usize;
pub type ColNum = usize;
pub type RowNum = usize;
pub type Width = Scalar;
pub type Height = Scalar;
pub type PosX = Scalar;
pub type PosY = Scalar;

/// Draw a matrix of any rectangular widget type, where the matrix will provide a function with
/// the widget number, it's `rows` and `cols` position, the width and height for the widget and
/// the location at which the widget should be drawn.
#[derive(Copy, Clone)]
pub struct Matrix<F> {
    common: widget::CommonBuilder,
    style: Style,
    cols: usize,
    rows: usize,
    maybe_each_widget: Option<F>,
}

/// The state of the Matrix, to be cached within the `Ui`'s widget `Graph`.
#[derive(Clone, Debug, PartialEq)]
pub struct State {
    /// A `NodeIndex` for every Widget in the Matrix.
    /// This matrix is column major, meaning the outer-most Vec represents each column, and each
    /// inner Vec represents a row.
    indices: Vec<Vec<NodeIndex>>,
}

widget_style!{
    /// Unique styling for the `Matrix`.
    style Style {
        /// The width of the padding for each matrix element's "cell".
        - cell_pad_w: Scalar { 0.0 }
        /// The height of the padding for each matrix element's "cell".
        - cell_pad_h: Scalar { 0.0 }
    }
}

impl<F> Matrix<F> {

    /// Create a widget matrix context.
    pub fn new(cols: usize, rows: usize) -> Matrix<F> {
        Matrix {
            common: widget::CommonBuilder::new(),
            style: Style::new(),
            cols: cols,
            rows: rows,
            maybe_each_widget: None,
        }
    }

    /// The function that will be called for each and every element in the Matrix.
    /// The function should return the widget that will be displayed in the element associated with
    /// the given row and column number.
    /// Note that the returned Widget's position and dimensions will be overridden with the
    /// dimensions and position of the matrix element's rectangle.
    pub fn each_widget(mut self, each_widget: F) -> Matrix<F> {
        self.maybe_each_widget = Some(each_widget);
        self
    }

    /// A builder method for adding padding to the cell.
    pub fn cell_padding(mut self, w: Scalar, h: Scalar) -> Matrix<F> {
        self.style.cell_pad_w = Some(w);
        self.style.cell_pad_h = Some(h);
        self
    }

}


impl<'a, F, W> Widget for Matrix<F>
    where W: Widget,
          F: FnMut(WidgetNum, ColNum, RowNum) -> W
{
    type State = State;
    type Style = Style;

    fn common(&self) -> &widget::CommonBuilder {
        &self.common
    }

    fn common_mut(&mut self) -> &mut widget::CommonBuilder {
        &mut self.common
    }

    fn init_state(&self) -> State {
        State { indices: Vec::new() }
    }

    fn style(&self) -> Style {
        self.style.clone()
    }

    /// Update the state of the Matrix.
    fn update(self, args: widget::UpdateArgs<Self>) {
        let widget::UpdateArgs { idx, state, rect, style, mut ui, .. } = args;
        let Matrix { cols, rows, maybe_each_widget, .. } = self;

        // First, check that we have the correct number of columns and rows.
        let num_cols = state.indices.len();
        let num_rows = state.indices.get(0).map(|col| col.len()).unwrap_or(0);
        let maybe_new_indices = if num_cols < cols || num_rows < rows {
            let mut total_cols: Vec<_> = state.indices.iter()
                .map(|col| col.clone())
                .chain((num_cols..cols).map(|_| Vec::with_capacity(rows)))
                .collect();
            for col in total_cols.iter_mut() {
                let rows_in_col = col.len();
                if rows_in_col < rows {
                    col.extend((rows_in_col..rows).map(|_| ui.new_unique_node_index()));
                }
            }
            Some(total_cols)
        } else {
            None
        };

        // A function to simplify getting the current slice of indices.
        fn get_indices<'a>(maybe_new: &'a Option<Vec<Vec<NodeIndex>>>,
                           state: &'a widget::State<State>) -> &'a [Vec<NodeIndex>] {
            maybe_new.as_ref().map(|is| &is[..]).unwrap_or_else(|| &state.indices[..])
        }

        // We only need to worry about element calculations if we actually have rows and columns.
        if rows > 0 && cols > 0 {
            // Likewise, there must also be some function to give us the widgets.
            if let Some(mut each_widget) = maybe_each_widget {

                let cell_pad_w = style.cell_pad_w(ui.theme());
                let cell_pad_h = style.cell_pad_h(ui.theme());
                let (w, h) = rect.w_h();
                let widget_w = w / cols as Scalar;
                let widget_h = h / rows as Scalar;
                let (half_w, half_h) = (w / 2.0, h / 2.0);
                let x_min = -half_w + widget_w / 2.0;
                let x_max = half_w + widget_w / 2.0;
                let y_min = -half_h - widget_h / 2.0;
                let y_max = half_h - widget_h / 2.0;

                let mut widget_num = 0;
                let indices = get_indices(&maybe_new_indices, state);
                for col in 0..cols {
                    for row in 0..rows {
                        use position::{Positionable, Sizeable};
                        use utils::map_range;
                        let rel_x = map_range(col as Scalar, 0.0, cols as Scalar, x_min, x_max);
                        let rel_y = map_range(row as Scalar, 0.0, rows as Scalar, y_max, y_min);
                        let w = widget_w - cell_pad_w * 2.0;
                        let h = widget_h - cell_pad_h * 2.0;
                        let widget_idx = indices[col][row];
                        each_widget(widget_num, col, row)
                            .wh([w, h])
                            .x_y_relative_to(idx, rel_x, rel_y)
                            .set(widget_idx, &mut ui);
                        widget_num += 1;
                    }
                }
            }
        }

        if let Some(new_indices) = maybe_new_indices {
            state.update(|state| state.indices = new_indices);
        }
    }

}