File: spreadmodel.cpp

package info (click to toggle)
qt6-declarative 6.9.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 308,920 kB
  • sloc: cpp: 775,911; javascript: 514,247; xml: 10,855; python: 2,806; ansic: 2,253; java: 810; sh: 262; makefile: 41; php: 27
file content (731 lines) | stat: -rw-r--r-- 25,361 bytes parent folder | download | duplicates (2)
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include "spreadformula.h"
#include "spreadmodel.h"
#include "spreadrole.h"

#include <QPoint>
#include <QRegularExpression>

int SpreadModel::columnNumberFromName(const QString &text)
{
    if (text.size() == 1)
        return getModelColumn(text[0].toLatin1() - 'A');
    else if (text.size() == 2)
        return getModelColumn((text[0].toLatin1() - 'A' + 1) * 26 + (text[1].toLatin1() - 'A'));
    return 0;
}

int SpreadModel::rowNumberFromName(const QString &text)
{
    return getModelRow(text.toInt() - 1);
}

SpreadModel *SpreadModel::instance()
{
    return s_instance;
}

SpreadModel *SpreadModel::create(QQmlEngine *, QJSEngine *)
{
    if (!s_instance)
        s_instance = new SpreadModel {nullptr};
    return s_instance;
}

void SpreadModel::update(int row, int column)
{
    if (!m_updateMutex.tryLock())
        return;
    column = getModelColumn(column);
    row = getModelRow(row);
    const QModelIndex index = this->index(row, column);
    emit dataChanged(index, index, {spread::Role::Display,});
    m_updateMutex.unlock();
}

void SpreadModel::clearHighlight()
{
    if (m_dataModel.empty())
        return;

    const auto [top_left, bottom_right] = m_dataModel.clearHighlight();

    emit dataChanged(index(top_left.first, top_left.second),
                     index(bottom_right.first, bottom_right.second),
                     {spread::Role::Hightlight,});
}

void SpreadModel::setHighlight(const QModelIndex &index, bool highlight)
{
    if (!index.isValid())
        return;
    if (m_dataModel.setHighlight(SpreadKey{index.row(), index.column()}, highlight))
        emit dataChanged(index, index, {spread::Role::Hightlight,});
}

int SpreadModel::rowCount(const QModelIndex &parent) const
{
    return m_size.first;
}

int SpreadModel::columnCount(const QModelIndex &parent) const
{
    return m_size.second;
}

QVariant SpreadModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant{};

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

    return m_dataModel.getData(SpreadKey{row, column}, role);
}

bool SpreadModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid())
        return false;

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

    if (m_dataModel.setData(SpreadKey{row, column}, value, role))
        emit dataChanged(index, index);

    return true;
}

bool SpreadModel::clearItemData(const QModelIndex &index)
{
    if (!index.isValid())
        return false;
    if (m_dataModel.clearData(SpreadKey{index.row(), index.column()})) {
        emit dataChanged(index, index);
        return true;
    }
    return false;
}

Qt::ItemFlags SpreadModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::NoItemFlags;
    return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;
}

QHash<int, QByteArray> SpreadModel::roleNames() const
{
    return {{spread::Role::Display, "display"},
            {spread::Role::Edit, "edit"},
            {spread::Role::ColumnName, "columnName"},
            {spread::Role::RowName, "rowName"},
            {spread::Role::Hightlight, "highlight"}};

}

QVariant SpreadModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    switch (role) {
    case spread::Role::ColumnName:
    case spread::Role::RowName:
        break;
    default:
        return QVariant{};
    }

    switch (orientation) {
    case Qt::Horizontal: {
        constexpr char A = 'A';
        const int view_section = getViewColumn(section);
        if (view_section < 26) {
            return QString{static_cast<char>(view_section + A)};
        } else {
            const int first = view_section / 26 - 1;
            const int second = view_section % 26;
            QString title{static_cast<char>(first + A)};
            title += static_cast<char>(second + A);
            return title;
        }
    }
    case Qt::Vertical: {
        return getViewRow(section) + 1;
    }
    }

    return QVariant{};
}

bool SpreadModel::insertColumns(int column, int count, const QModelIndex &parent)
{
    if (count != 1)  // TODO: implement inserting more than 1 columns
        return false;

    beginInsertColumns(QModelIndex{}, column, column + count - 1);
    m_size.second += count;

    // update model
    m_dataModel.shiftColumns(column, count);

    QMap<int, int> old_columns;
    std::swap(old_columns, m_viewColumns);
    for (auto it = old_columns.begin(); it != old_columns.end(); ++it) {
        const int new_view_column = (it.value() < column) ? it.value() : it.value() + count;
        const int new_model_column = (it.key() < column) ? it.key() : it.key() + count;
        m_viewColumns.insert(new_model_column, new_view_column);
    }

    endInsertColumns();
    return true;
}

bool SpreadModel::insertRows(int row, int count, const QModelIndex &parent)
{
    if (count != 1)  // TODO: implement inserting more than 1 rows
        return false;

    beginInsertRows(QModelIndex{}, row, row + count - 1);
    m_size.first += count;

    // update model
    m_dataModel.shiftRows(row, count);

    endInsertRows();
    return true;
}

bool SpreadModel::removeColumns(int column, int count, const QModelIndex &parent)
{
    if (count != 1)  // TODO: implement removing more than 1 columns
        return false;

    beginRemoveColumns(QModelIndex{}, column, column + count - 1);
    m_size.second -= count;

    // update model
    m_dataModel.removeColumnCells(column);
    m_dataModel.shiftColumns(column + 1, -count);

    endRemoveColumns();
    return true;
}

bool SpreadModel::removeRows(int row, int count, const QModelIndex &parent)
{
    if (count != 1)  // TODO: implement removing more than 1 rows
        return false;

    beginRemoveRows(QModelIndex{}, row, row + count - 1);
    m_size.first -= count;

    // update model
    m_dataModel.removeRowCells(row);
    m_dataModel.shiftRows(row + 1, -count);

    endRemoveRows();
    return true;
}

bool SpreadModel::clearItemData(const QModelIndexList &indexes)
{
    bool ok = true;
    for (const QModelIndex &index : indexes)
        ok &= clearItemData(index);
    return ok;
}

bool SpreadModel::removeColumns(QModelIndexList indexes)
{
    auto greater = [](const QModelIndex &lhs, const QModelIndex &rhs)
    {
        return lhs.column() > rhs.column();
    };
    std::sort(indexes.begin(), indexes.end(), greater);
    for (const QModelIndex &index : indexes)
        removeColumn(index.column());
    return true;
}

bool SpreadModel::removeRows(QModelIndexList indexes)
{
    auto greater = [](const QModelIndex &lhs, const QModelIndex &rhs)
    {
        return lhs.row() > rhs.row();
    };
    std::sort(indexes.begin(), indexes.end(), greater);
    for (const QModelIndex &index : indexes)
        removeRow(index.row());
    return true;
}

void SpreadModel::mapColumn(int model, int view)
{
    if (model == view)
        m_viewColumns.remove(model);
    else
        m_viewColumns[model] = view;
    emit headerDataChanged(Qt::Horizontal, model, view);
}

void SpreadModel::mapRow(int model, int view)
{
    if (model == view)
        m_viewRows.remove(model);
    else
        m_viewRows[model] = view;
    emit headerDataChanged(Qt::Vertical, model, view);
}

Formula SpreadModel::parseFormulaString(const QString &qText)
{
    if (qText.isEmpty())
        return Formula{};

    QRegularExpression pattern_re;

    // is formula
    pattern_re.setPattern("^\\s*=.*");
    QRegularExpressionMatch match = pattern_re.match(qText);
    if (!match.hasMatch())
        return Formula{};

    // is Assignment: e.g. =A1
    pattern_re.setPattern("^\\s*=\\s*([a-zA-Z]+)([1-9][0-9]*)\\s*$");
    match = pattern_re.match(qText);
    if (match.hasMatch()) {
        const QString column_label = match.captured(1);
        const QString row_label = match.captured(2);
        const int column = columnNumberFromName(column_label);
        const int row = rowNumberFromName(row_label);
        const int cell_id = m_dataModel.createId(SpreadKey{row, column});
        return Formula::create(Formula::Operator::Assign, cell_id, 0);
    }

    // is Addition: e.g. =A1+A2
    pattern_re.setPattern("^\\s*=\\s*([a-zA-Z]+)([1-9][0-9]*)\\s*\\+\\s*([a-zA-Z]+)([1-9][0-9]*)\\s*$");
    match = pattern_re.match(qText);
    if (match.hasMatch()) {
        // first argument
        QString column_label = match.captured(1);
        QString row_label = match.captured(2);
        int column = columnNumberFromName(column_label);
        int row = rowNumberFromName(row_label);
        const int cell_id_1 = m_dataModel.createId(SpreadKey{row, column});
        // second argument
        column_label = match.captured(3);
        row_label = match.captured(4);
        column = columnNumberFromName(column_label);
        row = rowNumberFromName(row_label);
        const int cell_id_2 = m_dataModel.createId(SpreadKey{row, column});
        // create formula
        return Formula::create(Formula::Operator::Add, cell_id_1, cell_id_2);
    }

    // is Subtraction: e.g. =A1-A2
    pattern_re.setPattern("^\\s*=\\s*([a-zA-Z]+)([1-9][0-9]*)\\s*\\-\\s*([a-zA-Z]+)([1-9][0-9]*)\\s*$");
    match = pattern_re.match(qText);
    if (match.hasMatch()) {
        // first argument
        QString column_label = match.captured(1);
        QString row_label = match.captured(2);
        int column = columnNumberFromName(column_label);
        int row = rowNumberFromName(row_label);
        const int cell_id_1 = m_dataModel.createId(SpreadKey{row, column});
        // second argument
        column_label = match.captured(3);
        row_label = match.captured(4);
        column = columnNumberFromName(column_label);
        row = rowNumberFromName(row_label);
        const int cell_id_2 = m_dataModel.createId(SpreadKey{row, column});
        // create formula
        return Formula::create(Formula::Operator::Sub, cell_id_1, cell_id_2);
    }

    // is Multiply: e.g. =A1*A2
    pattern_re.setPattern("^\\s*=\\s*([a-zA-Z]+)([1-9][0-9]*)\\s*\\*\\s*([a-zA-Z]+)([1-9][0-9]*)\\s*$");
    match = pattern_re.match(qText);
    if (match.hasMatch()) {
        // first argument
        QString column_label = match.captured(1);
        QString row_label = match.captured(2);
        int column = columnNumberFromName(column_label);
        int row = rowNumberFromName(row_label);
        const int cell_id_1 = m_dataModel.createId(SpreadKey{row, column});
        // second argument
        column_label = match.captured(3);
        row_label = match.captured(4);
        column = columnNumberFromName(column_label);
        row = rowNumberFromName(row_label);
        const int cell_id_2 = m_dataModel.createId(SpreadKey{row, column});
        // create formula
        return Formula::create(Formula::Operator::Mul, cell_id_1, cell_id_2);
    }

    // is Division: e.g. =A1/A2
    pattern_re.setPattern("^\\s*=\\s*([a-zA-Z]+)([1-9][0-9]*)\\s*\\/\\s*([a-zA-Z]+)([1-9][0-9]*)\\s*$");
    match = pattern_re.match(qText);
    if (match.hasMatch()) {
        // first argument
        QString column_label = match.captured(1);
        QString row_label = match.captured(2);
        int column = columnNumberFromName(column_label);
        int row = rowNumberFromName(row_label);
        const int cell_id_1 = m_dataModel.createId(SpreadKey{row, column});
        // second argument
        column_label = match.captured(3);
        row_label = match.captured(4);
        column = columnNumberFromName(column_label);
        row = rowNumberFromName(row_label);
        const int cell_id_2 = m_dataModel.createId(SpreadKey{row, column});
        // create formula
        return Formula::create(Formula::Operator::Div, cell_id_1, cell_id_2);
    }

    // is Summation: e.g. =SUM A1:A2
    pattern_re.setPattern("^\\s*=\\s*[Ss][Uu][Mm]\\s+([a-zA-Z]+)([1-9][0-9]*)\\s*\\:\\s*([a-zA-Z]+)([1-9][0-9]*)\\s*$");
    match = pattern_re.match(qText);
    if (match.hasMatch()) {
        // first argument
        QString column_label = match.captured(1);
        QString row_label = match.captured(2);
        int column = columnNumberFromName(column_label);
        int row = rowNumberFromName(row_label);
        const int cell_id_1 = m_dataModel.createId(SpreadKey{row, column});
        // second argument
        column_label = match.captured(3);
        row_label = match.captured(4);
        column = columnNumberFromName(column_label);
        row = rowNumberFromName(row_label);
        const int cell_id_2 = m_dataModel.createId(SpreadKey{row, column});
        // create formula
        return Formula::create(Formula::Operator::Sum, cell_id_1, cell_id_2);
    }

    return Formula{};
}

QString SpreadModel::formulaValueText(const Formula &formula)
{
    switch (formula.getOperator()) {
    case Formula::Operator::Assign: {
        const QVariant value = m_dataModel.getData(formula.firstOperandId(), spread::Role::Display);
        return value.isNull() ? QString{} : value.toString();
    }
    case Formula::Operator::Add: {
        const QVariant value_1 = m_dataModel.getData(formula.firstOperandId(), spread::Role::Display);
        const QVariant value_2 = m_dataModel.getData(formula.secondOperandId(), spread::Role::Display);
        if (value_1.isNull() && value_2.isNull())
            return "0";
        // check int values
        bool is_int_1 = true;
        bool is_int_2 = true;
        const int int_1 = value_1.isNull() ? 0 : value_1.toInt(&is_int_1);
        const int int_2 = value_2.isNull() ? 0 : value_2.toInt(&is_int_2);
        if (is_int_1 && is_int_2)
            return QString::number(int_1 + int_2);
        // check double values
        bool is_double_1 = true;
        bool is_double_2 = true;
        const double double_1 = value_1.isNull() ? 0 : value_1.toDouble(&is_double_1);
        const double double_2 = value_2.isNull() ? 0 : value_2.toDouble(&is_double_2);
        if (is_double_1 && is_double_2)
            return QString::number(double_1 + double_2);
        return "#ERROR!";
    }
    case Formula::Operator::Sub: {
        const QVariant value_1 = m_dataModel.getData(formula.firstOperandId(), spread::Role::Display);
        const QVariant value_2 = m_dataModel.getData(formula.secondOperandId(), spread::Role::Display);
        if (value_1.isNull() && value_2.isNull())
            return "0";
        // check int values
        bool is_int_1 = true;
        bool is_int_2 = true;
        const int int_1 = value_1.isNull() ? 0 : value_1.toInt(&is_int_1);
        const int int_2 = value_2.isNull() ? 0 : value_2.toInt(&is_int_2);
        if (is_int_1 && is_int_2)
            return QString::number(int_1 - int_2);
        // check double values
        bool is_double_1 = true;
        bool is_double_2 = true;
        const double double_1 = value_1.isNull() ? 0 : value_1.toDouble(&is_double_1);
        const double double_2 = value_2.isNull() ? 0 : value_2.toDouble(&is_double_2);
        if (is_double_1 && is_double_2)
            return QString::number(double_1 - double_2);
        return "#ERROR!";
    }
    case Formula::Operator::Mul: {
        const QVariant value_1 = m_dataModel.getData(formula.firstOperandId(), spread::Role::Display);
        const QVariant value_2 = m_dataModel.getData(formula.secondOperandId(), spread::Role::Display);
        if (value_1.isNull() || value_2.isNull())
            return "0";
        // check int values
        bool is_int_1 = true;
        bool is_int_2 = true;
        const int int_1 = value_1.toInt(&is_int_1);
        const int int_2 = value_2.toInt(&is_int_2);
        if (is_int_1 && is_int_2)
            return QString::number(int_1 * int_2);
        // check double values
        bool is_double_1 = true;
        bool is_double_2 = true;
        const double double_1 = value_1.toDouble(&is_double_1);
        const double double_2 = value_2.toDouble(&is_double_2);
        if (is_double_1 && is_double_2)
            return QString::number(double_1 * double_2);
        return "#ERROR!";
    }
    case Formula::Operator::Div: {
        const QVariant value_1 = m_dataModel.getData(formula.firstOperandId(), spread::Role::Display);
        const QVariant value_2 = m_dataModel.getData(formula.secondOperandId(), spread::Role::Display);
        if (value_1.isNull() && value_2.isNull())
            return "#ERROR!";
        // check int values
        bool is_int_1 = true;
        bool is_int_2 = true;
        const int int_1 = value_1.isNull() ? 0 : value_1.toInt(&is_int_1);
        const int int_2 = value_2.isNull() ? 0 : value_2.toInt(&is_int_2);
        if (is_int_1 && is_int_2) {
            if (int_2 == 0)
                return "#ERROR!";
            return QString::number(int_1 / int_2);
        }
        // check double values
        bool is_double_1 = true;
        bool is_double_2 = true;
        const double double_1 = value_1.isNull() ? 0 : value_1.toDouble(&is_double_1);
        const double double_2 = value_2.isNull() ? 0 : value_2.toDouble(&is_double_2);
        if (is_double_1 && is_double_2) {
            if (double_2 == 0)
                return "#ERROR!";
            return QString::number(double_1 / double_2);
        }
        return "#ERROR!";
    }
    case Formula::Operator::Sum: {
        SpreadKey top_left = m_dataModel.getKey(formula.firstOperandId());
        SpreadKey bottom_right = m_dataModel.getKey(formula.secondOperandId());
        top_left.first = getViewRow(top_left.first);
        top_left.second = getViewColumn(top_left.second);
        bottom_right.first = getViewRow(bottom_right.first);
        bottom_right.second = getViewColumn(bottom_right.second);
        if (bottom_right.first < top_left.first)
            std::swap(top_left.first, bottom_right.first);
        if (bottom_right.second < top_left.second)
            std::swap(top_left.second, bottom_right.second);
        double sum = 0;
        for (int row = top_left.first; row <= bottom_right.first; ++row) {
            for (int column = top_left.second; column <= bottom_right.second; ++column) {
                const int model_row = getModelRow(row);
                const int model_column = getModelColumn(column);
                const SpreadKey key {model_row, model_column};
                const QVariant value = m_dataModel.getData(key, spread::Role::Display);
                if (value.isNull())
                    continue;
                bool is_double = false;
                const double d = value.toDouble(&is_double);
                if (is_double)
                    sum += d;
                else
                    return "#ERROR!";
            }
        }
        return QString::number(sum);
    }
    default:
        break;
    }
    return QString{};
}

int SpreadModel::getViewColumn(int modelColumn) const
{
    auto it = m_viewColumns.find(modelColumn);
    return (it != m_viewColumns.end()) ? it.value() : modelColumn;
}

int SpreadModel::getModelColumn(int viewColumn) const
{
    auto find_view_column = [viewColumn](const auto &item) {
        return item == viewColumn;
    };
    auto it = std::find_if(m_viewColumns.begin(), m_viewColumns.end(), find_view_column);
    return it != m_viewColumns.end() ? it.key() : viewColumn;
}

int SpreadModel::getViewRow(int modelRow) const
{
    auto it = m_viewRows.find(modelRow);
    return (it != m_viewRows.end()) ? it.value() : modelRow;
}

int SpreadModel::getModelRow(int viewRow) const
{
    auto find_view_row = [viewRow](const auto &item){
        return item == viewRow;
    };
    auto it = std::find_if(m_viewRows.begin(), m_viewRows.end(), find_view_row);
    return (it != m_viewRows.end()) ? it.key() : viewRow;
}

void SpreadSelectionModel::toggleColumn(int column)
{
    isColumnSelected(column) ? deselectColumn(column) : selectColumn(column, false);
}

void SpreadSelectionModel::deselectColumn(int column)
{
    const QAbstractItemModel *model = this->model();
    const QModelIndex first = model->index(0, column);
    const QModelIndex last = model->index(model->rowCount() - 1, column);
    QModelIndexList selectedRows = this->selectedRows(column);
    if (selectedRows.empty()) {
        select(QItemSelection{first, last}, SelectionFlag::Deselect);
        return;
    }

    auto topToBottom = [](const QModelIndex &lhs, const QModelIndex &rhs) -> bool
    {
        return lhs.row() < rhs.row();
    };
    std::sort(selectedRows.begin(), selectedRows.end(), topToBottom);

    QModelIndex index = first;
    for (const QModelIndex &selectedRow : selectedRows) {
        if (index.row() < selectedRow.row())
            select(QItemSelection{index, model->index(selectedRow.row() - 1, column)},
                   SelectionFlag::Deselect);
        index = model->index(selectedRow.row() + 1, column);
    }
    if (index.row() <= last.row())
        select(QItemSelection{index, last}, SelectionFlag::Deselect);
}

void SpreadSelectionModel::selectColumn(int column, bool clear)
{
    if (clear)
        this->clear();
    const QAbstractItemModel *model = this->model();
    const QModelIndex first = model->index(0, column);
    const QModelIndex last = model->index(model->rowCount() - 1, column);
    select(QItemSelection{first, last}, SelectionFlag::Select);
}

void SpreadSelectionModel::toggleRow(int row)
{
    isRowSelected(row) ? deselectRow(row) : selectRow(row, false);
}

void SpreadSelectionModel::deselectRow(int row)
{
    const QAbstractItemModel *model = this->model();
    const QModelIndex first = model->index(row, 0);
    const QModelIndex last = model->index(row, model->columnCount() - 1);
    QModelIndexList selectedColumns = this->selectedColumns(row);
    if (selectedColumns.empty()) {
        select(QItemSelection{first, last}, SelectionFlag::Deselect);
        return;
    }

    auto leftToRight = [](const QModelIndex &lhs, const QModelIndex &rhs) -> bool
    {
        return lhs.column() < rhs.column();
    };
    std::sort(selectedColumns.begin(), selectedColumns.end(), leftToRight);

    QModelIndex index = first;
    for (const QModelIndex &selectedColumn : selectedColumns) {
       if (index.column() < selectedColumn.column())
           select(QItemSelection{index, model->index(row, selectedColumn.column() - 1)},
                  SelectionFlag::Deselect);
       index = model->index(row, selectedColumn.column() + 1);
    }
    if (index.column() <= last.column())
       select(QItemSelection{index, last}, SelectionFlag::Deselect);
}

void SpreadSelectionModel::selectRow(int row, bool clear)
{
    if (clear)
        this->clear();
    const QAbstractItemModel *model = this->model();
    const QModelIndex first = model->index(row, 0);
    const QModelIndex last = model->index(row, model->columnCount() - 1);
    select(QItemSelection{first, last}, SelectionFlag::Select);
}

void SpreadSelectionModel::setBehavior(Behavior behavior)
{
    if (behavior == m_behavior)
        return;
    m_behavior = behavior;
    emit behaviorChanged();
}

void HeaderSelectionModel::setCurrent(int current)
{
    switch (m_orientation) {
    case Qt::Horizontal:
        QItemSelectionModel::setCurrentIndex(model()->index(0, current), SelectionFlag::Current);
        break;
    case Qt::Vertical:
        QItemSelectionModel::setCurrentIndex(model()->index(current, 0), SelectionFlag::Current);
        break;
    default:
        break;
    }
}

void HeaderSelectionModel::setSelectionModel(SpreadSelectionModel *selectionModel)
{
    if (selectionModel == m_selectionModel)
        return;
    if (m_selectionModel)
        disconnect(m_selectionModel);
    m_selectionModel = selectionModel;
    if (m_selectionModel)
        connect(m_selectionModel, &SpreadSelectionModel::selectionChanged, this,
                &HeaderSelectionModel::onSelectionChanged);
    emit selectionModelChanged();
}

void HeaderSelectionModel::setOrientation(Qt::Orientation orientation)
{
    if (orientation == m_orientation)
        return;
    m_orientation = orientation;
    emit orientationChanged();
}

void HeaderSelectionModel::onSelectionChanged(const QItemSelection &selected,
                                              const QItemSelection &deselected)
{
    const QAbstractItemModel *model = this->model();
    for (const QModelIndex &index : selected.indexes()) {
        switch (m_orientation) {
        case Qt::Horizontal:
            if (m_selectionModel->isColumnSelected(index.column()))
                select(model->index(0, index.column()), SelectionFlag::Select);
            break;
        case Qt::Vertical:
            if (m_selectionModel->isRowSelected(index.row()))
                select(model->index(index.row(), 0), SelectionFlag::Select);
            break;
        }
    }
    for (const QModelIndex &index : deselected.indexes()) {
        switch (m_orientation) {
        case Qt::Horizontal:
            if (!m_selectionModel->isColumnSelected(index.column()))
                select(model->index(0, index.column()), SelectionFlag::Deselect);
            break;
        case Qt::Vertical:
            if (!m_selectionModel->isRowSelected(index.row()))
                select(model->index(index.row(), 0), SelectionFlag::Deselect);
            break;
        }
    }
}