summaryrefslogtreecommitdiff
path: root/src/widget/table.c
blob: 7a0ea03dd95e79aba73bcf7f44683a297f4f4565 (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
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
#include "table.h"

#include "widget.h"

const uiCell* GetCell(const uiTable* table, int row, int col) {
  assert(table);
  return &table->cells[row][col];
}

uiCell* GetCellMut(uiTable* table, int row, int col) {
  assert(table);
  return (uiCell*)GetCell(table, row, col);
}

uiCell** GetLastRow(uiTable* table) {
  assert(table);
  assert(table->rows > 0);
  return &table->cells[table->rows - 1];
}

uiTable* uiMakeTable(int rows, int cols, const char** header) {
  uiTable* table = UI_NEW(uiTable);

  *table = (uiTable){
      .widget = (uiWidget){.type = uiTypeTable},
      .rows   = rows,
      .cols   = cols,
      .widths = (cols > 0) ? calloc(cols, sizeof(int)) : 0,
      .header = header ? calloc(cols, sizeof(uiCell)) : 0,
      .cells  = (rows * cols > 0) ? calloc(rows, sizeof(uiCell*)) : 0,
      .flags  = {0},
  };

  if (header) {
    for (int col = 0; col < cols; ++col) {
      table->header[col].child = (uiWidget*)uiMakeLabel(header[col]);
    }
  }

  return table;
}

void uiTableClear(uiTable* table) {
  assert(table);

  // Free row data.
  if (table->cells) {
    for (int row = 0; row < table->rows; ++row) {
      for (int col = 0; col < table->cols; ++col) {
        DestroyWidget(&table->cells[row][col].child);
      }
      free(table->cells[row]);
    }
    free(table->cells);
    table->cells = 0;
  }
  table->rows = 0;

  // Clear row widths.
  for (int i = 0; i < table->cols; ++i) {
    table->widths[i] = 0;
  }

  table->offset = 0;

  table->flags.vertical_overflow = 0;
}

void uiTableAddRow(uiTable* table, const char** row) {
  assert(table);

  table->rows++;

  uiCell** cells = realloc(table->cells, table->rows * sizeof(uiCell*));
  ASSERT(cells);
  table->cells = cells;

  uiCell** pLastRow = GetLastRow(table);
  *pLastRow         = calloc(table->cols, sizeof(uiCell));
  ASSERT(*pLastRow);
  uiCell* lastRow = *pLastRow;

  for (int col = 0; col < table->cols; ++col) {
    lastRow[col].child = (uiWidget*)uiMakeLabel(row[col]);
  }
}

void uiTableSet(uiTable* table, int row, int col, uiPtr child) {
  assert(table);
  assert(child.widget);

  GetCellMut(table, row, col)->child = child.widget;
}

const uiWidget* uiTableGet(const uiTable* table, int row, int col) {
  assert(table);
  return GetCell(table, row, col)->child;
}

uiWidget* uiTableGetMut(uiTable* table, int row, int col) {
  assert(table);
  return GetCellMut(table, row, col)->child;
}