File: RDTableView.cpp

package info (click to toggle)
renderdoc 1.2%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 79,584 kB
  • sloc: cpp: 491,671; ansic: 285,823; python: 12,617; java: 11,345; cs: 7,181; makefile: 6,703; yacc: 5,682; ruby: 4,648; perl: 3,461; php: 2,119; sh: 2,068; lisp: 1,835; tcl: 1,068; ml: 747; xml: 137
file content (489 lines) | stat: -rw-r--r-- 15,209 bytes parent folder | download
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2016-2018 Baldur Karlsson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

#include "RDTableView.h"
#include <QAbstractButton>
#include <QApplication>
#include <QClipboard>
#include <QHeaderView>
#include <QMouseEvent>
#include <QPainter>
#include <QPen>
#include <QScrollBar>
#include "Code/QRDUtils.h"
#include "RDHeaderView.h"

RDTableView::RDTableView(QWidget *parent) : QTableView(parent)
{
  m_horizontalHeader = new RDHeaderView(Qt::Horizontal, this);
  m_horizontalHeader->setCustomSizing(true);
  setHorizontalHeader(m_horizontalHeader);

  QObject::connect(m_horizontalHeader, &QHeaderView::sectionResized,
                   [this](int, int, int) { viewport()->update(); });
}

int RDTableView::columnViewportPosition(int column) const
{
  return horizontalHeader()->sectionViewportPosition(column);
}

int RDTableView::columnAt(int x) const
{
  return horizontalHeader()->visualIndexAt(x);
}

int RDTableView::columnWidth(int column) const
{
  return horizontalHeader()->sectionSize(column);
}

void RDTableView::setColumnWidth(int column, int width)
{
  horizontalHeader()->resizeSection(column, width);

  updateGeometries();
}

void RDTableView::setColumnWidths(const QList<int> &widths)
{
  horizontalHeader()->resizeSections(widths);

  updateGeometries();
}

void RDTableView::resizeColumnsToContents()
{
  horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);

  updateGeometries();
}

QRect RDTableView::visualRect(const QModelIndex &index) const
{
  if(!index.isValid())
    return QRect();

  const int row = index.row();
  const int col = index.column();

  const int gridWidth = showGrid() ? 1 : 0;

  return QRect(columnViewportPosition(col), rowViewportPosition(row), columnWidth(col) - gridWidth,
               rowHeight(row) - gridWidth);
}

QRegion RDTableView::visualRegionForSelection(const QItemSelection &selection) const
{
  QRegion selectionRegion;
  const QRect viewRect = viewport()->rect();

  QAbstractItemModel *m = model();

  for(const QItemSelectionRange &selRange : selection)
  {
    for(int row = selRange.top(); row <= selRange.bottom(); row++)
    {
      for(int col = selRange.left(); col <= selRange.right(); col++)
      {
        const QRect &rangeRect = visualRect(m->index(row, col));
        if(viewRect.intersects(rangeRect))
          selectionRegion += rangeRect;
      }
    }
  }

  return selectionRegion;
}

QModelIndex RDTableView::indexAt(const QPoint &p) const
{
  int row = rowAt(p.y());
  int col = columnAt(p.x());

  if(row < 0 || col < 0)
    return QModelIndex();

  return model()->index(row, col);
}

void RDTableView::setColumnGroupRole(int role)
{
  m_columnGroupRole = role;
  m_horizontalHeader->setColumnGroupRole(role);
}

void RDTableView::setPinnedColumns(int numColumns)
{
  m_pinnedColumns = numColumns;
  m_horizontalHeader->setPinnedColumns(numColumns);
}

void RDTableView::keyPressEvent(QKeyEvent *e)
{
  if(e == QKeySequence::Copy)
  {
    QModelIndexList sel = selectionModel()->selectedIndexes();

    if(!sel.isEmpty())
    {
      int stackWidths[16];
      int *heapWidths = NULL;

      int colCount = model()->columnCount();

      if(colCount >= 16)
        heapWidths = new int[colCount];

      int *widths = heapWidths ? heapWidths : stackWidths;

      for(int i = 0; i < colCount; i++)
        widths[i] = 0;

      int top = sel[0].row(), bottom = sel[0].row();
      int left = sel[0].column(), right = sel[0].column();

      // align the copied data so that each column is the same width
      for(QModelIndex idx : sel)
      {
        QString text = model()->data(idx).toString();
        widths[idx.column()] = qMax(widths[idx.column()], text.count());

        top = qMin(top, idx.row());
        bottom = qMax(bottom, idx.row());
        left = qMin(left, idx.column());
        right = qMax(right, idx.column());
      }

      // only align up to 50 characters so one really long item doesn't mess up the whole thing
      for(int i = 0; i < colCount; i++)
        widths[i] = qMin(50, widths[i]);

      QString clipData;
      for(int row = top; row <= bottom; row++)
      {
        for(int col = left; col <= right; col++)
        {
          QString format = col == left ? lit("%1") : lit(" %1");
          QString text = model()->data(model()->index(row, col)).toString();

          clipData += format.arg(text, -widths[col]);
        }

        clipData += lit("\n");
      }

      QClipboard *clipboard = QApplication::clipboard();
      clipboard->setText(clipData.trimmed());

      delete[] heapWidths;
    }

    e->accept();
    return;
  }

  return QTableView::keyPressEvent(e);
}

void RDTableView::paintEvent(QPaintEvent *e)
{
  const int gridWidth = showGrid() ? 1 : 0;
  QStyleOptionViewItem opt = viewOptions();

  QPainter painter(viewport());

  if(model()->rowCount() == 0 || model()->columnCount() == 0)
    return;

  int firstRow = qMax(verticalHeader()->visualIndexAt(0), 0);
  int lastRow = verticalHeader()->visualIndexAt(viewport()->height());
  if(lastRow < 0)
    lastRow = verticalHeader()->count() - 1;
  lastRow = qMin(lastRow, verticalHeader()->count() - 1);

  int firstCol = qMax(horizontalHeader()->visualIndexAt(horizontalHeader()->pinnedWidth() + 1), 0);
  int lastCol = horizontalHeader()->visualIndexAt(viewport()->width());
  if(lastCol < 0)
    lastCol = horizontalHeader()->count() - 1;
  lastCol = qMin(lastCol, horizontalHeader()->count() - 1);

  firstCol = qMax(m_pinnedColumns, firstCol);

  for(int row = firstRow; row <= lastRow; row++)
  {
    for(int col = firstCol; col <= lastCol; col++)
    {
      const QModelIndex index = model()->index(row, col);
      if(index.isValid())
        paintCell(&painter, index, opt);
    }
    for(int col = 0; col < m_pinnedColumns; col++)
    {
      const QModelIndex index = model()->index(row, col);
      if(index.isValid())
        paintCell(&painter, index, opt);
    }
  }

  if(gridWidth)
  {
    QPen prevPen = painter.pen();
    QBrush prevBrush = painter.brush();

    QColor gridCol(QRgb(style()->styleHint(QStyle::SH_Table_GridLineColor, &opt, this)));

    painter.setPen(QPen(gridCol, 0, gridStyle()));
    painter.setBrush(QBrush(gridCol));

    // draw bottom line of each row
    for(int row = firstRow; row <= lastRow; row++)
    {
      int y = rowViewportPosition(row) + rowHeight(row) - gridWidth;
      painter.drawLine(viewport()->rect().left(), y, viewport()->rect().right(), y);
    }

    int gapSize = m_horizontalHeader->groupGapSize();

    // draw lines for each column, and group gaps
    for(int col = firstCol; col <= lastCol; col++)
    {
      int x = columnViewportPosition(col) + columnWidth(col) - gridWidth;

      if(m_horizontalHeader->hasGroupGap(col))
        painter.drawRect(x, viewport()->rect().top(), gapSize, viewport()->rect().height());
      else
        painter.drawLine(x, viewport()->rect().top(), x, viewport()->rect().bottom());
    }
    for(int col = 0; col < m_pinnedColumns; col++)
    {
      int x = columnViewportPosition(col) + columnWidth(col) - gridWidth;

      if(m_horizontalHeader->hasGroupGap(col))
        painter.drawRect(x, viewport()->rect().top(), gapSize, viewport()->rect().height());
      else
        painter.drawLine(x, viewport()->rect().top(), x, viewport()->rect().bottom());
    }

    painter.setPen(prevPen);
    painter.setBrush(prevBrush);
  }
}

void RDTableView::paintCell(QPainter *painter, const QModelIndex &index,
                            const QStyleOptionViewItem &opt)
{
  QStyleOptionViewItem cellopt = opt;

  cellopt.rect = QRect(columnViewportPosition(index.column()), rowViewportPosition(index.row()),
                       columnWidth(index.column()), rowHeight(index.row()));

  // erase the rect here since we need to draw over any overlapping non-pinned cells and
  // there's no way to just clip the above painting :(
  if(index.column() < m_pinnedColumns)
    painter->eraseRect(cellopt.rect);

  if(selectionModel() && selectionModel()->isSelected(index))
    cellopt.state |= QStyle::State_Selected;

  // draw the background, then the cell
  style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &cellopt, painter, this);
  itemDelegate(index)->paint(painter, cellopt, index);
}

void RDTableView::scrollTo(const QModelIndex &index, ScrollHint hint)
{
  if(!index.isValid())
    return;

  QRect cellRect = QRect(columnViewportPosition(index.column()), rowViewportPosition(index.row()),
                         columnWidth(index.column()), rowHeight(index.row()));

  QRect dataRect = viewport()->rect();
  dataRect.setLeft(horizontalHeader()->pinnedWidth());

  // if it's already visible then just bail, common case
  if(dataRect.contains(cellRect) && hint == QAbstractItemView::EnsureVisible)
    return;

  // assume per-item vertical scrolling and per-pixel horizontal scrolling

  // for any hint except position at center, we just ensure it's visible horizontally
  if(hint != QAbstractItemView::PositionAtCenter)
  {
    // scroll into view from the left
    if(dataRect.left() > cellRect.left())
    {
      horizontalScrollBar()->setValue(horizontalScrollBar()->value() -
                                      (dataRect.left() - cellRect.left()));
    }

    // scroll into view from the right
    if(dataRect.right() < cellRect.right())
    {
      horizontalScrollBar()->setValue(horizontalScrollBar()->value() +
                                      (cellRect.right() - dataRect.right()));
    }
  }
  else
  {
    // center it horizontally from the left
    QPoint dataCenter = dataRect.center();
    QPoint cellCenter = cellRect.center();

    if(dataCenter.x() > cellCenter.x())
    {
      horizontalScrollBar()->setValue(horizontalScrollBar()->value() -
                                      (dataCenter.x() - cellCenter.x()));
    }

    // center it horizontally from the right
    if(dataCenter.x() < cellCenter.x())
    {
      horizontalScrollBar()->setValue(horizontalScrollBar()->value() +
                                      (cellCenter.x() - dataCenter.x()));
    }
  }

  // collapse EnsureVisible to either PositionAtTop or PositionAtBottom depending on which side it's
  // on, or just return if we only had to make it visible horizontally
  if(hint == QAbstractItemView::EnsureVisible)
  {
    if(dataRect.bottom() < cellRect.bottom())
      hint = QAbstractItemView::PositionAtBottom;
    else if(dataRect.top() > cellRect.top())
      hint = QAbstractItemView::PositionAtTop;
    else
      return;
  }

  int firstRow = qMax(verticalHeader()->visualIndexAt(0), 0);
  int lastRow = verticalHeader()->visualIndexAt(viewport()->height());
  if(lastRow == -1)
    lastRow = verticalHeader()->count();

  int visibleRows = lastRow - firstRow + 1;

  // a partially displayed row doesn't count
  if(verticalHeader()->sectionViewportPosition(lastRow) + verticalHeader()->sectionSize(lastRow) >
     viewport()->height())
    visibleRows--;

  if(hint == QAbstractItemView::PositionAtTop)
  {
    verticalScrollBar()->setValue(index.row());
  }
  else if(hint == QAbstractItemView::PositionAtBottom)
  {
    verticalScrollBar()->setValue(index.row() - visibleRows + 1);
  }
  else if(hint == QAbstractItemView::PositionAtCenter)
  {
    verticalScrollBar()->setValue(index.row() - (visibleRows + 1) / 2);
  }

  update(index);
}

void RDTableView::updateGeometries()
{
  static bool recurse = false;
  if(recurse)
    return;
  recurse = true;

  QAbstractButton *cornerButton = findChild<QAbstractButton *>();
  cornerButton->setVisible(false);

  QRect geom = viewport()->geometry();

  // assume no vertical header

  int horizHeight =
      qBound(horizontalHeader()->minimumHeight(), horizontalHeader()->sizeHint().height(),
             horizontalHeader()->maximumHeight());

  setViewportMargins(0, horizHeight, 0, 0);

  horizontalHeader()->setGeometry(geom.left(), geom.top() - horizHeight, geom.width(), horizHeight);

  // even though it's not visible we need to set the geometry right so that it looks up rows by
  // position properly.
  verticalHeader()->setGeometry(0, horizHeight, 0, geom.height());

  // if the headers are hidden nothing else will update their geometries and some things like
  // scrolling etc depend on it being up to date, so hackily call the protected slot. Yuk!
  if(verticalHeader()->isHidden())
    QMetaObject::invokeMethod(verticalHeader(), "updateGeometries");
  if(horizontalHeader()->isHidden())
    QMetaObject::invokeMethod(horizontalHeader(), "updateGeometries");

  // assume per-item vertical scrolling and per-pixel horizontal scrolling

  // vertical scroll bar
  {
    int firstRow = qMax(verticalHeader()->visualIndexAt(0), 0);
    int lastRow = verticalHeader()->visualIndexAt(viewport()->height());
    bool last = false;
    if(lastRow == -1)
    {
      last = true;
      lastRow = verticalHeader()->count();
    }

    int visibleRows = lastRow - firstRow + 1;

    // a partially displayed row doesn't count
    if(verticalHeader()->sectionViewportPosition(lastRow) + verticalHeader()->sectionSize(lastRow) >
       viewport()->height())
      visibleRows--;

    verticalScrollBar()->setRange(0, verticalHeader()->count() - visibleRows);
    verticalScrollBar()->setSingleStep(1);
    verticalScrollBar()->setPageStep(visibleRows);
    if(visibleRows >= verticalHeader()->count())
      verticalHeader()->setOffset(0);
    else if(last)
      verticalHeader()->setOffsetToLastSection();
  }

  // horizontal scroll bar
  {
    int totalWidth = horizontalHeader()->sizeHint().width();

    horizontalScrollBar()->setPageStep(viewport()->width() - horizontalHeader()->pinnedWidth());
    horizontalScrollBar()->setRange(0, totalWidth - viewport()->width());
    horizontalScrollBar()->setSingleStep(qMax(totalWidth / (horizontalHeader()->count() + 1), 2));
  }

  recurse = false;
  QAbstractItemView::updateGeometries();
}

void RDTableView::scrollContentsBy(int dx, int dy)
{
  QTableView::scrollContentsBy(dx, dy);

  viewport()->update();
}