forked from subsurface/subsurface
-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathdivetripmodel.cpp
1756 lines (1583 loc) · 58.4 KB
/
divetripmodel.cpp
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: GPL-2.0
#include "qt-models/divetripmodel.h"
#include "core/divefilter.h"
#ifdef SUBSURFACE_MOBILE
#include "qt-models/mobilelistmodel.h"
#endif
#include "core/gettextfromc.h"
#include "core/metrics.h"
#include "core/selection.h"
#include "core/string-format.h"
#include "core/trip.h"
#include "core/qthelper.h"
#include "core/divesite.h"
#include "core/picture.h"
#include "core/subsurface-string.h"
#include "core/tag.h"
#include "qt-models/divelocationmodel.h" // For the dive-site field ids
#include "commands/command.h"
#include <QIcon>
#include <QDebug>
#include <QDateTime>
#include <memory>
#include <algorithm>
// 1) Base functions
static int nitrox_sort_value(const struct dive *dive)
{
int o2, he, o2max;
get_dive_gas(dive, &o2, &he, &o2max);
return he * 1000 + o2;
}
static QVariant dive_table_alignment(int column)
{
switch (column) {
case DiveTripModelBase::DEPTH:
case DiveTripModelBase::DURATION:
case DiveTripModelBase::TEMPERATURE:
case DiveTripModelBase::TOTALWEIGHT:
case DiveTripModelBase::SAC:
case DiveTripModelBase::OTU:
case DiveTripModelBase::MAXCNS:
// Right align numeric columns
return int(Qt::AlignRight | Qt::AlignVCenter);
// NR needs to be left aligned because its the indent marker for trips too
case DiveTripModelBase::NR:
case DiveTripModelBase::DATE:
case DiveTripModelBase::RATING:
case DiveTripModelBase::SUIT:
case DiveTripModelBase::CYLINDER:
case DiveTripModelBase::GAS:
case DiveTripModelBase::TAGS:
case DiveTripModelBase::PHOTOS:
case DiveTripModelBase::COUNTRY:
case DiveTripModelBase::BUDDIES:
case DiveTripModelBase::DIVEGUIDE:
case DiveTripModelBase::LOCATION:
return int(Qt::AlignLeft | Qt::AlignVCenter);
}
return QVariant();
}
QString DiveTripModelBase::tripShortDate(const dive_trip *trip)
{
if (!trip)
return QString();
QDateTime firstTime = timestampToDateTime(trip_date(trip));
QString firstMonth = firstTime.toString("MMM");
return QStringLiteral("%1\n'%2").arg(firstMonth,firstTime.toString("yy"));
}
QString DiveTripModelBase::tripTitle(const dive_trip *trip)
{
if (!trip)
return QString();
QString numDives = tr("(%n dive(s))", "", trip->dives.nr);
int shown = trip_shown_dives(trip);
QString shownDives = shown != trip->dives.nr ? QStringLiteral(" ") + tr("(%L1 shown)").arg(shown) : QString();
QString title(trip->location);
if (title.isEmpty()) {
// so use the date range
QDateTime firstTime = timestampToDateTime(trip_date(trip));
QString firstMonth = firstTime.toString("MMM");
QString firstYear = firstTime.toString("yyyy");
QDateTime lastTime = timestampToDateTime(trip->dives.dives[0]->when);
QString lastMonth = lastTime.toString("MMM");
QString lastYear = lastTime.toString("yyyy");
if (lastMonth == firstMonth && lastYear == firstYear)
title = firstMonth + " " + firstYear;
else if (lastMonth != firstMonth && lastYear == firstYear)
title = firstMonth + "-" + lastMonth + " " + firstYear;
else
title = firstMonth + " " + firstYear + " - " + lastMonth + " " + lastYear;
}
return QStringLiteral("%1 %2%3").arg(title, numDives, shownDives);
}
QVariant DiveTripModelBase::tripData(const dive_trip *trip, int column, int role)
{
#ifdef SUBSURFACE_MOBILE
// Special roles for mobile
switch(role) {
case MobileListModel::TripIdRole: return QString::number(trip->id);
case MobileListModel::TripNrDivesRole: return trip->dives.nr;
case MobileListModel::TripShortDateRole: return tripShortDate(trip);
case MobileListModel::TripTitleRole: return tripTitle(trip);
case MobileListModel::TripLocationRole: return QString(trip->location);
case MobileListModel::TripNotesRole: return QString(trip->notes);
}
#endif
// Set the font for all trips alike
if (role == Qt::FontRole)
return defaultModelFont();
if (role == TRIP_ROLE)
return QVariant::fromValue(const_cast<dive_trip *>(trip)); // Not nice: casting away a const
if (role == Qt::DisplayRole) {
switch (column) {
case DiveTripModelBase::NR:
QString shownText;
int countShown = trip_shown_dives(trip);
if (countShown < trip->dives.nr)
shownText = tr("(%1 shown)").arg(countShown);
return formatTripTitleWithDives(trip) + " " + shownText;
}
}
return QVariant();
}
static const QString icon_names[4] = {
QStringLiteral(":zero"),
QStringLiteral(":photo-in-icon"),
QStringLiteral(":photo-out-icon"),
QStringLiteral(":photo-in-out-icon")
};
static int countPhotos(const struct dive *d)
{ // Determine whether dive has pictures, and whether they were taken during or before/after dive.
const int bufperiod = 120; // A 2-min buffer period. Photos within 2 min of dive are assumed as
int diveTotaltime = dive_endtime(d) - d->when; // taken during the dive, not before/after.
int pic_offset, icon_index = 0;
FOR_EACH_PICTURE (d) { // Step through each of the pictures for this dive:
pic_offset = picture->offset.seconds;
if ((pic_offset < -bufperiod) | (pic_offset > diveTotaltime+bufperiod)) {
icon_index |= 0x02; // If picture is before/after the dive
// then set the appropriate bit ...
} else {
icon_index |= 0x01; // else set the bit for picture during the dive
}
}
return icon_index; // return value: 0=no pictures; 1=pictures during dive;
} // 2=pictures before/after; 3=pictures during as well as before/after
static QString displayDuration(const struct dive *d)
{
if (prefs.units.show_units_table)
return get_dive_duration_string(d->duration.seconds, gettextFromC::tr("h"), gettextFromC::tr("min"), "", ":", d->dc.divemode == FREEDIVE);
else
return get_dive_duration_string(d->duration.seconds, "", "", "", ":", d->dc.divemode == FREEDIVE);
}
static QString displayTemperature(const struct dive *d, bool units)
{
if (!d->watertemp.mkelvin)
return QString();
return get_temperature_string(d->watertemp, units);
}
static QString displaySac(const struct dive *d, bool units)
{
if (!d->sac)
return QString();
QString s = get_volume_string(d->sac, units);
return units ? s + gettextFromC::tr("/min") : s;
}
static QString displayWeight(const struct dive *d, bool units)
{
QString s = weight_string(total_weight(d));
if (!units)
return s;
else if (get_units()->weight == units::KG)
return s + gettextFromC::tr("kg");
else
return s + gettextFromC::tr("lbs");
}
static QPixmap &getGlobeIcon()
{
static std::unique_ptr<QPixmap> icon;
if (!icon) {
const IconMetrics &im = defaultIconMetrics();
icon = std::make_unique<QPixmap>(QIcon(":globe-icon").pixmap(im.sz_small, im.sz_small));
}
return *icon;
}
static QPixmap &getPhotoIcon(int idx)
{
static std::unique_ptr<QPixmap[]> icons;
if (!icons) {
const IconMetrics &im = defaultIconMetrics();
icons = std::make_unique<QPixmap[]>(std::size(icon_names));
for (size_t i = 0; i < std::size(icon_names); ++i)
icons[i] = QIcon(icon_names[i]).pixmap(im.sz_small, im.sz_small);
}
return icons[idx];
}
// textual description of the meaning of a column for use in tooltips
QString DiveTripModelBase::getDescription(int column)
{
switch (column) {
case NR:
return tr("#");
case DATE:
return tr("Date");
case RATING:
return tr("Rating");
case DEPTH:
return tr("Depth(%1)").arg((get_units()->length == units::METERS) ? tr("m") : tr("ft"));
case DURATION:
return tr("Duration");
case TEMPERATURE:
return tr("Temp.(°%1)").arg((get_units()->temperature == units::CELSIUS) ? "C" : "F");
case TOTALWEIGHT:
return tr("Weight(%1)").arg((get_units()->weight == units::KG) ? tr("kg") : tr("lbs"));
case SUIT:
return tr("Suit");
case CYLINDER:
return tr("Cylinder");
case GAS:
return tr("Gas");
case SAC:
const char *unit;
get_volume_units(0, NULL, &unit);
return tr("SAC(%1)").arg(QString(unit).append(tr("/min")));
case OTU:
return tr("OTU");
case MAXCNS:
return tr("Max. CNS");
case TAGS:
return tr("Tags");
case PHOTOS:
return tr("Media before/during/after dive");
case COUNTRY:
return tr("Country");
case BUDDIES:
return tr("Buddy");
case DIVEGUIDE:
return tr("Dive guide");
case LOCATION:
return tr("Location");
default:
return QString();
}
}
QVariant DiveTripModelBase::diveData(const struct dive *d, int column, int role) const
{
#ifdef SUBSURFACE_MOBILE
// Special roles for mobile
switch (role) {
case MobileListModel::DiveDateRole: return (qlonglong)d->when;
// We have to return a QString as trip-id, because that will be used as section
// variable in the QtQuick list view. That has to be a string because it will try
// to do locale-aware sorting. And amazingly this can't be changed.
case MobileListModel::DateTimeRole: return formatDiveDateTime(d);
case MobileListModel::IdRole: return d->id;
case MobileListModel::NumberRole: return d->number;
case MobileListModel::LocationRole: return get_dive_location(d);
case MobileListModel::DepthRole: return get_depth_string(d->dc.maxdepth.mm, true, true);
case MobileListModel::DurationRole: return formatDiveDuration(d);
case MobileListModel::DepthDurationRole: return QStringLiteral("%1 / %2").arg(get_depth_string(d->dc.maxdepth.mm, true, true),
formatDiveDuration(d));
case MobileListModel::RatingRole: return d->rating;
case MobileListModel::VizRole: return d->visibility;
case MobileListModel::SuitRole: return d->suit;
case MobileListModel::AirTempRole: return get_temperature_string(d->airtemp, true);
case MobileListModel::WaterTempRole: return get_temperature_string(d->watertemp, true);
case MobileListModel::SacRole: return formatSac(d);
case MobileListModel::SumWeightRole: return formatSumWeight(d);
case MobileListModel::DiveGuideRole: return d->diveguide;
case MobileListModel::BuddyRole: return d->buddy;
case MobileListModel::TagsRole: return get_taglist_string(d->tag_list);
case MobileListModel::NotesRole: return formatNotes(d);
case MobileListModel::GpsRole: return formatDiveGPS(d);
case MobileListModel::GpsDecimalRole: return format_gps_decimal(d);
case MobileListModel::NoDiveRole: return d->duration.seconds == 0 && d->dc.duration.seconds == 0;
case MobileListModel::DiveSiteRole: return QVariant::fromValue(d->dive_site);
case MobileListModel::CylinderRole: return formatGetCylinder(d).join(", ");
case MobileListModel::GetCylinderRole: return formatGetCylinder(d);
case MobileListModel::CylinderListRole: return formatFullCylinderList();
case MobileListModel::SingleWeightRole: return d->weightsystems.nr <= 1;
case MobileListModel::StartPressureRole: return formatStartPressure(d);
case MobileListModel::EndPressureRole: return formatEndPressure(d);
case MobileListModel::FirstGasRole: return formatFirstGas(d);
case MobileListModel::SelectedRole: return d->selected;
case MobileListModel::DiveInTripRole: return d->divetrip != NULL;
case MobileListModel::IsInvalidRole: return d->invalid;
}
#endif
switch (role) {
case Qt::FontRole:
return d->invalid ? invalidFont : defaultModelFont();
case Qt::ForegroundRole:
return d->invalid ? invalidForeground : QVariant();
case Qt::TextAlignmentRole:
return dive_table_alignment(column);
case Qt::DisplayRole:
switch (column) {
case NR:
return d->number;
case DATE:
return get_dive_date_string(d->when);
case DEPTH:
return get_depth_string(d->maxdepth, prefs.units.show_units_table);
case DURATION:
return displayDuration(d);
case TEMPERATURE:
return displayTemperature(d, prefs.units.show_units_table);
case TOTALWEIGHT:
return displayWeight(d, prefs.units.show_units_table);
case SUIT:
return QString(d->suit);
case CYLINDER:
return d->cylinders.nr > 0 ? QString(get_cylinder(d, 0)->type.description) : QString();
case SAC:
return displaySac(d, prefs.units.show_units_table);
case OTU:
return d->otu;
case MAXCNS:
if (prefs.units.show_units_table)
return QString("%1%").arg(d->maxcns);
else
return d->maxcns;
case TAGS:
return get_taglist_string(d->tag_list);
case PHOTOS:
break;
case COUNTRY:
return QString(get_dive_country(d));
case BUDDIES:
return QString(d->buddy);
case DIVEGUIDE:
return QString(d->diveguide);
case LOCATION:
return QString(get_dive_location(d));
case GAS:
char *gas_string = get_dive_gas_string(d);
QString ret(gas_string);
free(gas_string);
return ret;
}
break;
case Qt::DecorationRole:
switch (column) {
//TODO: ADD A FLAG
case COUNTRY:
return QVariant();
case LOCATION:
if (dive_has_gps_location(d))
return getGlobeIcon();
break;
case PHOTOS:
// If there are photos, show one of the three photo icons: fish= photos during dive;
// sun=photos before/after dive; sun+fish=photos during dive as well as before/after
if (d->pictures.nr > 0)
return getPhotoIcon(countPhotos(d));
break;
}
break;
case Qt::ToolTipRole:
return getDescription(column);
case STAR_ROLE:
return d->rating;
case DIVE_ROLE:
return QVariant::fromValue(const_cast<dive *>(d)); // Not nice: casting away a const
case DIVE_IDX:
return get_divenr(d);
case SELECTED_ROLE:
return d->selected;
case CURRENT_ROLE:
return d == current_dive;
}
return QVariant();
}
QVariant DiveTripModelBase::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Vertical)
return QVariant();
switch (role) {
case Qt::TextAlignmentRole:
return dive_table_alignment(section);
case Qt::FontRole:
return defaultModelFont();
case Qt::InitialSortOrderRole:
// By default, sort NR and DATE descending, everything else ascending.
return section == NR || section == DATE ? Qt::DescendingOrder : Qt::AscendingOrder;
case Qt::DisplayRole:
switch (section) {
case NR:
return tr("#");
case DATE:
return tr("Date");
case RATING:
return tr("Rating");
case DEPTH:
return tr("Depth");
case DURATION:
return tr("Duration");
case TEMPERATURE:
return tr("Temp.");
case TOTALWEIGHT:
return tr("Weight");
case SUIT:
return tr("Suit");
case CYLINDER:
return tr("Cylinder");
case GAS:
return tr("Gas");
case SAC:
return tr("SAC");
case OTU:
return tr("OTU");
case MAXCNS:
return tr("Max CNS");
case TAGS:
return tr("Tags");
case PHOTOS:
return tr("Media");
case COUNTRY:
return tr("Country");
case BUDDIES:
return tr("Buddy");
case DIVEGUIDE:
return tr("Dive guide");
case LOCATION:
return tr("Location");
}
break;
case Qt::ToolTipRole:
return getDescription(section);
}
return QVariant();
}
// After resetting the model, the higher up model or view may call this
// function to get informed on the current selection.
// TODO: Currently, this reads and resets the selection. Make this more
// efficient by maintaining a list of selected dives.
void DiveTripModelBase::initSelection()
{
std::vector<dive *> dives = getDiveSelection();
if (!dives.empty())
setSelection(dives, current_dive);
else
select_newest_visible_dive();
}
// Currently only used by the mobile models
void DiveTripModelBase::reset()
{
beginResetModel();
oldCurrent = nullptr;
clearData();
populate();
uiNotification(tr("finish populating data store"));
endResetModel();
uiNotification(tr("setting up internal data structures"));
emit diveListNotifier.numShownChanged();
uiNotification(tr("done setting up internal data structures"));
}
DiveTripModelBase::DiveTripModelBase(QObject *parent) : QAbstractItemModel(parent),
invalidForeground(Qt::gray)
{
invalidFont.setStrikeOut(true);
}
int DiveTripModelBase::columnCount(const QModelIndex&) const
{
return COLUMNS;
}
Qt::ItemFlags DiveTripModelBase::flags(const QModelIndex &index) const
{
dive *d = diveOrNull(index);
Qt::ItemFlags base = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
// Only dives have editable fields and only the number is editable
return d && index.column() == NR ? base | Qt::ItemIsEditable : base;
}
// Update visibility status of dive and return dives whose visibility changed.
// Attention: the changed dives are removed from the original vector!
static ShownChange updateShown(QVector<dive *> &dives)
{
DiveFilter *filter = DiveFilter::instance();
ShownChange res = filter->update(dives);
if (!res.newShown.empty() || !res.newHidden.empty())
emit diveListNotifier.numShownChanged();
for (dive *d: res.newHidden)
dives.removeAll(d);
for (dive *d: res.newShown)
dives.removeAll(d);
return res;
}
// Update shown status of *all* dives, i.e. reset the filter
static ShownChange updateShownAll()
{
DiveFilter *filter = DiveFilter::instance();
ShownChange res = filter->updateAll();
if (!res.newShown.empty() || !res.newHidden.empty())
emit diveListNotifier.numShownChanged();
return res;
}
void DiveTripModelBase::currentChanged()
{
// On Desktop we use a signal to forward current-dive changed, on mobile we use ROLE_CURRENT.
// TODO: Unify - use the role for both.
#if defined(SUBSURFACE_MOBILE)
static QVector<int> roles = { CURRENT_ROLE };
if (oldCurrent) {
QModelIndex oldIdx = diveToIdx(oldCurrent);
dataChanged(oldIdx, oldIdx, roles);
}
if (current_dive && oldCurrent != current_dive) {
QModelIndex newIdx = diveToIdx(current_dive);
dataChanged(newIdx, newIdx, roles);
}
#else
if (oldCurrent == current_dive)
return;
if (current_dive) {
QModelIndex newIdx = diveToIdx(current_dive);
emit currentDiveChanged(newIdx);
} else {
emit currentDiveChanged(QModelIndex());
}
#endif
oldCurrent = current_dive;
}
// Find a range of matching elements in a vector.
// Input parameters:
// v: vector to be searched
// first: first element to search
// cond: a function that is fed elements and returns an integer:
// - >0: matches
// - 0: doesn't match
// - <0: stop searching, no more elements will be found
// cond is called exactly once per element and from the beginning of the range.
// Returns a pair [first, last) with usual C++ semantics: last-first is the size of the found range.
// If no items were found, first and last are set to the size of the vector.
template <typename Vector, typename Predicate>
std::pair<int, int> findRangeIf(const Vector &v, int first, Predicate cond)
{
int size = (int)v.size();
for (int i = first; i < size; ++i) {
int res = cond(v[i]);
if (res > 0) {
for (int j = i + 1; j < size; ++j) {
if (cond(v[j]) <= 0)
return { i, j };
}
return { i, size };
} else if (res < 0) {
break;
}
}
return { size, size };
}
// Ideally, Qt's model/view functions are processed in batches of contiguous
// items. Therefore, this template is used to process actions on ranges of
// contiguous elements of a vector.
// Input paremeters:
// - items: vector to process, wich must allow random access via [] and the size() function
// - cond: a predicate that is tested for each element. contiguous ranges of elements which
// test for true are collected. cond is fed an element and should return:
// - >0: matches
// - 0: doesn't match
// - <0: stop searching, no more elements will be found
// - action: action that is called with the vector, first and last element of the range.
template<typename Vector, typename Predicate, typename Action>
void processRanges(Vector &items, Predicate cond, Action action)
{
// Note: the "i++" is correct: We know that the last element tested
// negatively -> we can skip it. Thus we avoid checking any element
// twice.
for(int i = 0;; i++) {
std::pair<int,int> range = findRangeIf(items, i, cond);
if (range.first >= (int)items.size())
break;
int delta = action(items, range.first, range.second);
i = range.second + delta;
}
}
// processRangesZip() is a refined version of processRanges(), which operates on two vectors.
// The vectors are supposed to be sorted equivalently. That is, the first matching
// item will of the first vector will match to the first item of the second vector.
// It is supposed that all elements of the second vector will match to an element of
// the first vector.
// Input parameters:
// - items1: vector to process, wich must allow random access via [] and the size() function
// - items2: second vector to process. every item in items2 must match to an item in items1
// in ascending order.
// - cond1: a predicate that is tested for each element of items1 with the next unmatched element
// of items2. returns a boolean
// - action: action that is called with the vectors, first and last element of the first range
// and first element of the last range.
template<typename Vector1, typename Vector2, typename Predicate, typename Action>
void processRangesZip(Vector1 &items1, Vector2 &items2, Predicate cond, Action action)
{
int actItem = 0;
processRanges(items1,
[&](typename Vector1::const_reference &e) mutable -> int { // Condition. Marked mutable so that it can change actItem
if (actItem >= items2.size())
return -1; // No more items -> bail
if (!cond(e, items2[actItem]))
return 0;
++actItem;
return 1;
},
[&](Vector1 &v1, int from, int to) { // Action
return action(v1, items2, from, to, actItem);
});
}
// Add items from vector "v2" to vector "v1" in batches of contiguous objects.
// The items are inserted at places according to a sort order determined by "comp".
// "v1" and "v2" are supposed to be ordered accordingly.
// TODO: We might use binary search with std::lower_bound(), but not sure if it's worth it.
// Input parameters:
// - v1: destination vector
// - v2: source vector
// - comp: compare-function, which is fed elements from v2 and v1. returns true for "insert here".
// - adder: performs the insertion. Perameters: v1, v2, insertion index, from, to range in v2.
template <typename Vector1, typename Vector2, typename Comparator, typename Inserter>
void addInBatches(Vector1 &v1, const Vector2 &v2, Comparator comp, Inserter insert)
{
int idx = 0; // Index where dives will be inserted
int i, j; // Begin and end of range to insert
for (i = 0; i < (int)v2.size(); i = j) {
for (; idx < (int)v1.size() && !comp(v2[i], v1[idx]); ++idx)
; // Pass
// We found the index of the first item to add.
// Now search how many items we should insert there.
if (idx == (int)v1.size()) {
// We were at end -> insert the remaining items
j = v2.size();
} else {
for (j = i + 1; j < (int)v2.size() && comp(v2[j], v1[idx]); ++j)
; // Pass
}
// Now add the batch
insert(v1, v2, idx, i, j);
// Skip over inserted dives for searching the new insertion position plus one.
// If we added at the end, the loop will end anyway.
idx += j - i + 1;
}
}
// 2) TreeModel functions
DiveTripModelTree::DiveTripModelTree(QObject *parent) : DiveTripModelBase(parent)
{
// Stay informed of changes to the divelist
connect(&diveListNotifier, &DiveListNotifier::divesAdded, this, &DiveTripModelTree::divesAdded);
connect(&diveListNotifier, &DiveListNotifier::divesDeleted, this, &DiveTripModelTree::divesDeleted);
connect(&diveListNotifier, &DiveListNotifier::divesChanged, this, &DiveTripModelTree::divesChanged);
connect(&diveListNotifier, &DiveListNotifier::diveSiteChanged, this, &DiveTripModelTree::diveSiteChanged);
connect(&diveListNotifier, &DiveListNotifier::divesMovedBetweenTrips, this, &DiveTripModelTree::divesMovedBetweenTrips);
connect(&diveListNotifier, &DiveListNotifier::divesTimeChanged, this, &DiveTripModelTree::divesTimeChanged);
connect(&diveListNotifier, &DiveListNotifier::divesSelected, this, &DiveTripModelTree::divesSelected);
connect(&diveListNotifier, &DiveListNotifier::tripChanged, this, &DiveTripModelTree::tripChanged);
connect(&diveListNotifier, &DiveListNotifier::filterReset, this, &DiveTripModelTree::filterReset);
connect(&diveListNotifier, &DiveListNotifier::cylinderAdded, this, &DiveTripModelTree::diveChanged);
connect(&diveListNotifier, &DiveListNotifier::cylinderEdited, this, &DiveTripModelTree::diveChanged);
connect(&diveListNotifier, &DiveListNotifier::cylinderRemoved, this, &DiveTripModelTree::diveChanged);
connect(&diveListNotifier, &DiveListNotifier::pictureOffsetChanged, this, &DiveTripModelTree::diveChanged);
connect(&diveListNotifier, &DiveListNotifier::picturesRemoved, this, &DiveTripModelTree::diveChanged);
connect(&diveListNotifier, &DiveListNotifier::picturesAdded, this, &DiveTripModelTree::diveChanged);
connect(&diveListNotifier, &DiveListNotifier::dataReset, this, &DiveTripModelTree::reset);
populate();
}
void DiveTripModelTree::populate()
{
DiveFilter::instance()->reset(); // The data was reset - update filter status. TODO: should this really be done here?
// we want this to be two calls as the second text is overwritten below by the lines starting with "\r"
uiNotification(QObject::tr("populate data model"));
uiNotification(QObject::tr("start processing"));
for (int i = 0; i < dive_table.nr; ++i) {
dive *d = get_dive(i);
if (!d) // should never happen
continue;
update_cylinder_related_info(d);
if (d->hidden_by_filter)
continue;
dive_trip_t *trip = d->divetrip;
// If this dive doesn't have a trip, add as top-level item.
if (!trip) {
items.emplace_back(d);
continue;
}
// Check if that trip is already known to us: search for the first item
// that corresponds to that trip
auto it = std::find_if(items.begin(), items.end(), [trip](const Item &item)
{ return item.d_or_t.trip == trip; });
if (it == items.end()) {
// We didn't find an entry for this trip -> add one
items.emplace_back(trip, d);
} else {
// We found the trip -> simply add the dive
it->dives.push_back(d);
}
}
// Remember the index of the current dive
oldCurrent = current_dive;
uiNotification(QObject::tr("%1 dives processed").arg(dive_table.nr));
}
int DiveTripModelTree::rowCount(const QModelIndex &parent) const
{
// No parent means top level - return the number of top-level items
if (!parent.isValid())
return items.size();
// If the parent has a parent, this is a dive -> no entries
if (parent.parent().isValid())
return 0;
// If this is outside of our top-level list -> no entries
int row = parent.row();
if (row < 0 || row >= (int)items.size())
return 0;
// Only trips have items
const Item &entry = items[parent.row()];
return entry.d_or_t.trip ? entry.dives.size() : 0;
}
void DiveTripModelList::clearData()
{
items.clear();
}
static const quintptr noParent = ~(quintptr)0; // This is the "internalId" marker for top-level item
QModelIndex DiveTripModelTree::index(int row, int column, const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
// In the "internalId", we store either ~0 for top-level items or the
// index of the parent item. A top-level item has an invalid parent.
return createIndex(row, column, parent.isValid() ? parent.row() : noParent);
}
QModelIndex DiveTripModelTree::parent(const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
// In the "internalId", we store either ~0 for top-level items
// or the index of the parent item.
quintptr id = index.internalId();
if (id == noParent)
return QModelIndex();
// Parent must be top-level item
return createIndex(id, 0, noParent);
}
DiveTripModelTree::Item::Item(dive_trip *t, const QVector<dive *> &divesIn) : d_or_t{nullptr, t},
dives(std::vector<dive *>(divesIn.begin(), divesIn.end()))
{
}
DiveTripModelTree::Item::Item(dive_trip *t, dive *d) : d_or_t{nullptr, t}, dives({ d })
{
}
DiveTripModelTree::Item::Item(dive *d) : d_or_t{d, nullptr}
{
}
bool DiveTripModelTree::Item::isDive(const dive *d) const
{
return d_or_t.dive == d;
}
dive *DiveTripModelTree::Item::getDive() const
{
return d_or_t.dive;
}
timestamp_t DiveTripModelTree::Item::when() const
{
return d_or_t.trip ? trip_date(d_or_t.trip) : d_or_t.dive->when;
}
dive_or_trip DiveTripModelTree::tripOrDive(const QModelIndex &index) const
{
if (!index.isValid())
return { nullptr, nullptr };
QModelIndex parent = index.parent();
// An invalid parent means that we're at the top-level
if (!parent.isValid())
return items[index.row()].d_or_t;
// Otherwise, we're at a leaf -> thats a dive
return { items[parent.row()].dives[index.row()], nullptr };
}
dive *DiveTripModelTree::diveOrNull(const QModelIndex &index) const
{
return tripOrDive(index).dive;
}
// The tree-version of the model wants to process the dives per trip.
// This template takes a vector of dives and calls a function batchwise for each trip.
template<typename Function>
void processByTrip(QVector<dive *> dives, Function action)
{
// Sort lexicographically by trip then according to the dive_less_than() function.
std::sort(dives.begin(), dives.end(), [](const dive *d1, const dive *d2)
{ return d1->divetrip == d2->divetrip ? dive_less_than(d1, d2) : d1->divetrip < d2->divetrip; });
// Then, process the dives in batches by trip
int i, j; // Begin and end of batch
for (i = 0; i < dives.size(); i = j) {
dive_trip *trip = dives[i]->divetrip;
for (j = i + 1; j < dives.size() && dives[j]->divetrip == trip; ++j)
; // pass
// Copy dives into a QVector. Some sort of "range_view" would be ideal.
QVector<dive *> divesInTrip(j - i);
for (int k = i; k < j; ++k)
divesInTrip[k - i] = dives[k];
// Finally, emit the signal
action(trip, divesInTrip);
}
}
// This recalculates the filters and add / removes the newly shown / hidden dives
// Attention: Since this uses / modifies the hidden_by_filter flag of the
// core dive structure, only one DiveTripModel[Tree|List] must exist at
// a given time!
void DiveTripModelTree::filterReset()
{
ShownChange change = updateShownAll();
processByTrip(change.newHidden, [this] (dive_trip *trip, const QVector<dive *> &divesInTrip)
{ divesHidden(trip, divesInTrip); });
processByTrip(change.newShown, [this] (dive_trip *trip, const QVector<dive *> &divesInTrip)
{ divesShown(trip, divesInTrip); });
// If the current dive changed, instruct the UI of the changed selection
// TODO: This is way to heavy, as it reloads the whole selection!
if (change.currentChanged)
initSelection();
}
void DiveTripModelTree::divesShown(dive_trip *trip, const QVector<dive *> &dives)
{
if (dives.empty())
return;
if (trip) {
// Find the trip
int idx = findTripIdx(trip);
if (idx < 0) {
addTrip(trip, dives); // Trip had no visible dives.
} else {
addDivesToTrip(idx, dives);
// Update the shown-count of the trip.
dataChanged(createIndex(idx, 0, noParent), createIndex(idx, 0, noParent));
}
} else {
addDivesTopLevel(dives);
}
}
void DiveTripModelTree::divesHidden(dive_trip *trip, const QVector<dive *> &dives)
{
if (dives.empty())
return;
if (trip) {
// Find the trip
int idx = findTripIdx(trip);
if (idx < 0) {
qWarning("DiveTripModelTree::divesHidden(): unknown trip");
return;
}
if (dives.size() == (int)items[idx].dives.size()) {
removeTrip(idx); // If all dives are hidden, remove the whole trip!
} else {
removeDivesFromTrip(idx, dives);
// Note: if dives are shown and hidden from a trip, we send two signals. Shrug.
dataChanged(createIndex(idx, 0, noParent), createIndex(idx, 0, noParent));
}
} else {
removeDivesTopLevel(dives);
}
}
QVariant DiveTripModelTree::data(const QModelIndex &index, int role) const
{
dive_or_trip entry = tripOrDive(index);
if (!entry.trip && !entry.dive)
return QVariant(); // That's an invalid index!
if (role == IS_TRIP_ROLE) {
return !!entry.trip;
} else if (role == TRIP_HAS_CURRENT_ROLE) {
if (!entry.trip)
return false;
const Item &item = items[index.row()];
return std::find(item.dives.begin(), item.dives.end(), current_dive) != item.dives.end();
}
if (entry.trip) {
return tripData(entry.trip, index.column(), role);
} else if (entry.dive) {
#if defined(SUBSURFACE_MOBILE)
if (role == MobileListModel::TripAbove)
return tripInDirection(entry.dive, +1);
if (role == MobileListModel::TripBelow)
return tripInDirection(entry.dive, -1);
#endif
return diveData(entry.dive, index.column(), role);
} else {
return QVariant();
}
}
// After a trip changed, the top level might need to be reordered.
// Move the item and send a "data-changed" signal.
void DiveTripModelTree::topLevelChanged(int idx)
{
if (idx < 0 || idx >= (int)items.size())
return;
// First, try to move backwards
int newIdx = idx;
while (newIdx > 0 && dive_or_trip_less_than(items[idx].d_or_t, items[newIdx - 1].d_or_t))
--newIdx;
// If that didn't change, try to move forward
if (newIdx == idx) {
++newIdx;
while (newIdx < (int)items.size() && !dive_or_trip_less_than(items[idx].d_or_t, items[newIdx].d_or_t))
++newIdx;
}
// If index changed, move items
if (newIdx != idx && newIdx != idx + 1) {
beginMoveRows(QModelIndex(), idx, idx, QModelIndex(), newIdx);
moveInVector(items, idx, idx + 1, newIdx);
endMoveRows();
}
// If we moved the object backwards in the array, we have to
// subtract one from the index to account for the removed object.
if (newIdx > idx)
--newIdx;
// Finally, inform UI of changed trip header
QModelIndex tripIdx = createIndex(newIdx, 0, noParent);
dataChanged(tripIdx, tripIdx);
}
void DiveTripModelTree::addDivesToTrip(int trip, const QVector<dive *> &dives)
{
// Construct the parent index, ie. the index of the trip.
QModelIndex parent = createIndex(trip, 0, noParent);
addInBatches(items[trip].dives, dives,
[](dive *d, dive *d2) { return dive_less_than(d, d2); }, // comp
[&](std::vector<dive *> &items, const QVector<dive *> &dives, int idx, int from, int to) { // inserter
beginInsertRows(parent, idx, idx + to - from - 1);
items.insert(items.begin() + idx, dives.begin() + from, dives.begin() + to);