aboutsummaryrefslogtreecommitdiffstats
path: root/qt-models/filtermodels.cpp
blob: 4063ba149ef6ceeca5c0798e9ac4c68de2dc510d (plain) (blame)
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
// SPDX-License-Identifier: GPL-2.0
#include "qt-models/filtermodels.h"
#include "qt-models/models.h"
#include "core/display.h"
#include "core/qthelper.h"
#include "core/subsurface-string.h"
#include "core/subsurface-qt/DiveListNotifier.h"
#include "qt-models/divetripmodel.h"

#if !defined(SUBSURFACE_MOBILE)
#include "desktop-widgets/divelistview.h"
#include "desktop-widgets/mainwindow.h"
#endif

#include <QDebug>
#include <algorithm>

#define CREATE_INSTANCE_METHOD(CLASS)             \
	CLASS *CLASS::instance()                  \
	{                                         \
		static CLASS *self = new CLASS(); \
		return self;                      \
	}

CREATE_INSTANCE_METHOD(TagFilterModel)
CREATE_INSTANCE_METHOD(BuddyFilterModel)
CREATE_INSTANCE_METHOD(LocationFilterModel)
CREATE_INSTANCE_METHOD(SuitsFilterModel)
CREATE_INSTANCE_METHOD(MultiFilterSortModel)

FilterModelBase::FilterModelBase(QObject *parent) : QAbstractListModel(parent),
	anyChecked(false),
	negate(false)
{
}

// Get index of item with given name, but ignore last item, as this
// is the "Show Empty Tags" item. Return -1 for not found.
int FilterModelBase::indexOf(const QString &name) const
{
	for (int i = 0; i < rowCount() - 1; i++) {
		if (name == items[i].name)
			return i;
	}
	return -1;
}

int FilterModelBase::findInsertionIndex(const QString &name)
{
	// Find insertion position. Note: we search only up to the last
	// item, because the last item is the "Show Empty Tags" item.
	// N.B: We might do a binary search using std::lower_bound()
	int i;
	for (i = 0; i < rowCount() - 1; i++) {
		if (name < items[i].name)
			return i;
	}
	return i;
}

void FilterModelBase::addItem(const QString &name, bool checked, int count)
{
	int idx = findInsertionIndex(name);
	beginInsertRows(QModelIndex(), idx, idx);
	items.insert(items.begin() + idx, { name, checked, count });
	endInsertRows();
}

void FilterModelBase::changeName(const QString &oldName, const QString &newName)
{
	if (oldName.isEmpty() || newName.isEmpty() || oldName == newName)
		return;
	int oldIndex = indexOf(oldName);
	if (oldIndex < 0)
		return;
	int newIndex = indexOf(newName);

	if (newIndex >= 0) {
		// If there was already an entry with the new name, we are merging entries.
		// Thus, if the old entry was selected, also select the new entry.
		if (items[oldIndex].checked && !items[newIndex].checked) {
			items[newIndex].checked = true;
			dataChanged(createIndex(newIndex, 0), createIndex(newIndex, 0));
		}
		// Now, delete the old item
		beginRemoveRows(QModelIndex(), oldIndex, oldIndex);
		items.erase(items.begin() + oldIndex);
		endRemoveRows();
	} else {
		// There was no entry of the same name. We might have to move the item.
		newIndex = findInsertionIndex(newName);
		if (oldIndex != newIndex && oldIndex + 1 != newIndex) {
			beginMoveRows(QModelIndex(), oldIndex, oldIndex, QModelIndex(), newIndex);
			moveInVector(items, oldIndex, oldIndex + 1, newIndex);
			endMoveRows();
		}

		// The item was moved, but the name still has to be modified
		items[newIndex].name = newName;
		dataChanged(createIndex(newIndex, 0), createIndex(newIndex, 0));
	}
}

// Update the the items array.
// The last item is supposed to be the "Show Empty Tags" entry.
// All other items will be sorted alphabetically. Attention: the passed-in list is modified!
void FilterModelBase::updateList(QStringList &newList)
{
	// Sort list, but leave out last element by using std::prev()
	if (!newList.empty())
		std::sort(newList.begin(), std::prev(newList.end()));

	beginResetModel();

	// Keep copy of the old items array to reimport the checked state later.
	// Note that by using std::move(), this is an essentially free operation:
	// The data is moved from the old array to the new one and the old array
	// is reset to zero size.
	std::vector<Item> oldItems = std::move(items);

	// Resize the cleared array to the new size. This leaves the checked
	// flag in an undefined state (since we didn't define a default constructor).
	items.resize(newList.count());

	// First, reset all checked states to false and set the names
	anyChecked = false;
	for (int i = 0; i < rowCount(); ++i) {
		items[i].name = newList[i];
		items[i].checked = false;
	}

	// Then, restore the checked state.  Ignore the last item, since
	// this is the "Show Empty Tags" entry.
	for (int i = 0; i < (int)oldItems.size() - 1; i++) {
		if (oldItems[i].checked) {
			int ind = newList.indexOf(oldItems[i].name);
			if (ind >= 0 && ind < newList.count() - 1) {
				items[ind].checked = true;
				anyChecked = true;
			}
		}
	}

	// Reset the state of the "Show Empty Tags" entry. But be careful:
	// on program startup, the old list is empty.
	if (!oldItems.empty() && !items.empty() && oldItems.back().checked) {
		items.back().checked = true;
		anyChecked = true;
	}

	// Finally, calculate and cache the counts. Ignore the last item, since
	// this is the "Show Empty Tags" entry.
	for (int i = 0; i < (int)newList.size() - 1; i++)
		items[i].count = countDives(qPrintable(newList[i]));

	// Calculate count of "Empty Tags".
	if (!items.empty())
		items.back().count = countDives("");

	endResetModel();
}

// Decrease count of entry with given name. Remove if count reaches zero.
// Exception: Don't remove the "Show Empty Tags" entry.
void FilterModelBase::decreaseCount(const QString &name)
{
	if (name.isEmpty()) {
		// Decrease the "Show Empty Tags" entry. Keep it even if count reaches 0.
		if (items.empty() || items.back().count <= 0)
			return; // Shouldn't happen!
		--items.back().count;
		int idx = items.size() - 1;
		dataChanged(createIndex(idx, 0), createIndex(idx, 0));
		return;
	}

	int idx = indexOf(name);
	if (idx < 0 || items[idx].count <= 0)
		return; // Shouldn't happen

	if(--items[idx].count == 0) {
		beginRemoveRows(QModelIndex(), idx, idx);
		items.erase(items.begin() + idx);
		endRemoveRows();
	} else {
		dataChanged(createIndex(idx, 0), createIndex(idx, 0));
	}
}

// Increase count of entry with given name. If entry doesn't yet exist, add it.
void FilterModelBase::increaseCount(const QString &name)
{
	if (name.isEmpty()) {
		// Increase the "Show Empty Tags" entry. Keep it even if count reaches 0.
		if (items.empty())
			return; // Shouldn't happen!
		++items.back().count;
		int idx = items.size() - 1;
		dataChanged(createIndex(idx, 0), createIndex(idx, 0));
		return;
	}

	int idx = indexOf(name);
	if (idx < 0) {
		idx = findInsertionIndex(name);
		beginInsertRows(QModelIndex(), idx, idx);
		items.insert(items.begin() + idx, { name, anyChecked, 1 });
		endInsertRows();
	} else {
		++items[idx].count;
		dataChanged(createIndex(idx, 0), createIndex(idx, 0));
	}
}

Qt::ItemFlags FilterModelBase::flags(const QModelIndex &index) const
{
	return QAbstractListModel::flags(index) | Qt::ItemIsUserCheckable;
}

bool FilterModelBase::setData(const QModelIndex &index, const QVariant &value, int role)
{
	if (role == Qt::CheckStateRole) {
		items[index.row()].checked = value.toBool();
		anyChecked = false;
		for (const Item &item: items) {
			if (item.checked) {
				anyChecked = true;
				break;
			}
		}
		dataChanged(index, index, { role });
		return true;
	}
	return false;
}

int FilterModelBase::rowCount(const QModelIndex &) const
{
	return items.size();
}

QVariant FilterModelBase::data(const QModelIndex &index, int role) const
{
	if (role == Qt::CheckStateRole) {
		return items[index.row()].checked ? Qt::Checked : Qt::Unchecked;
	} else if (role == Qt::DisplayRole) {
		const Item &item = items[index.row()];
		return QStringLiteral("%1 (%2)").arg(item.name, QString::number(item.count));
	}
	return QVariant();
}

void FilterModelBase::clearFilter()
{
	for (Item &item: items)
		item.checked = false;
	anyChecked = false;
	emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, 0));
}

void FilterModelBase::selectAll()
{
	for (Item &item: items)
		item.checked = true;
	anyChecked = true;
	emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, 0));
}

void FilterModelBase::invertSelection()
{
	for (Item &item: items)
		item.checked = !item.checked;
	anyChecked = std::any_of(items.begin(), items.end(), [](Item &item) { return !!item.checked; });
	emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, 0));
}

void FilterModelBase::setNegate(bool negateParam)
{
	negate = negateParam;
	emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, 0));
}

SuitsFilterModel::SuitsFilterModel(QObject *parent) : FilterModelBase(parent)
{
}

int SuitsFilterModel::countDives(const char *s) const
{
	return count_dives_with_suit(s);
}

bool SuitsFilterModel::doFilter(const dive *d) const
{
	// rowCount() == 0 should never happen, because we have the "no suits" row
	// let's handle it gracefully anyway.
	if (!anyChecked || rowCount() == 0)
		return true;

	// Checked means 'Show', Unchecked means 'Hide'.
	QString suit(d->suit);
	// only show empty suit dives if the user checked that.
	if (suit.isEmpty())
		return items[rowCount() - 1].checked != negate;

	// there is a suit selected
	// Ignore last item, since this is the "Show Empty Tags" entry
	for (int i = 0; i < rowCount() - 1; i++) {
		if (items[i].checked && suit == items[i].name)
			return !negate;
	}
	return negate;
}

void SuitsFilterModel::diveAdded(const dive *d)
{
	increaseCount(QString(d->suit));
}

void SuitsFilterModel::diveDeleted(const dive *d)
{
	decreaseCount(QString(d->suit));
}

void SuitsFilterModel::repopulate()
{
	QStringList list;
	struct dive *dive;
	int i = 0;
	for_each_dive (i, dive) {
		QString suit(dive->suit);
		if (!suit.isEmpty() && !list.contains(suit)) {
			list.append(suit);
		}
	}
	list << tr("No suit set");
	updateList(list);
}

TagFilterModel::TagFilterModel(QObject *parent) : FilterModelBase(parent)
{
}

int TagFilterModel::countDives(const char *s) const
{
	return count_dives_with_tag(s);
}

void TagFilterModel::repopulate()
{
	if (g_tag_list == NULL)
		return;
	QStringList list;
	struct tag_entry *current_tag_entry = g_tag_list;
	while (current_tag_entry != NULL) {
		if (count_dives_with_tag(current_tag_entry->tag->name) > 0)
			list.append(QString(current_tag_entry->tag->name));
		current_tag_entry = current_tag_entry->next;
	}
	list << tr("Empty tags");
	updateList(list);
}

bool TagFilterModel::doFilter(const dive *d) const
{
	// If there's nothing checked, this should show everything
	// rowCount() == 0 should never happen, because we have the "no tags" row
	// let's handle it gracefully anyway.
	if (!anyChecked || rowCount() == 0)
		return true;

	// Checked means 'Show', Unchecked means 'Hide'.
	struct tag_entry *head = d->tag_list;

	if (!head) // last tag means "Show empty tags";
		return items[rowCount() - 1].checked != negate;

	// have at least one tag.
	while (head) {
		QString tagName(head->tag->name);
		int index = indexOf(tagName);
		if (index >= 0 && items[index].checked)
			return !negate;
		head = head->next;
	}
	return negate;
}

void TagFilterModel::diveAdded(const dive *d)
{
	struct tag_entry *head = d->tag_list;
	if (!head) {
		increaseCount(QString());
		return;
	}
	while (head) {
		increaseCount(QString());
		increaseCount(QString(head->tag->name));
		head = head->next;
	}
}

void TagFilterModel::diveDeleted(const dive *d)
{
	struct tag_entry *head = d->tag_list;
	if (!head) {
		decreaseCount(QString());
		return;
	}
	while (head) {
		decreaseCount(QString(head->tag->name));
		head = head->next;
	}
}

BuddyFilterModel::BuddyFilterModel(QObject *parent) : FilterModelBase(parent)
{
}

int BuddyFilterModel::countDives(const char *s) const
{
	return count_dives_with_person(s);
}

static QStringList getDiveBuddies(const dive *d)
{
	QString persons = QString(d->buddy) + "," + QString(d->divemaster);
	QStringList personsList = persons.split(',', QString::SkipEmptyParts);
	for (QString &s: personsList)
		s = s.trimmed();
	return personsList;
}

bool BuddyFilterModel::doFilter(const dive *d) const
{
	// If there's nothing checked, this should show everything
	// rowCount() == 0 should never happen, because we have the "no tags" row
	// let's handle it gracefully anyway.
	if (!anyChecked || rowCount() == 0)
		return true;

	QStringList personsList = getDiveBuddies(d);
	// only show empty buddie dives if the user checked that.
	if (personsList.isEmpty())
		return items[rowCount() - 1].checked != negate;

	// have at least one buddy
	// Ignore last item, since this is the "Show Empty Tags" entry
	for (int i = 0; i < rowCount() - 1; i++) {
		if (items[i].checked && personsList.contains(items[i].name, Qt::CaseInsensitive))
			return !negate;
	}
	return negate;
}

void BuddyFilterModel::diveAdded(const dive *d)
{
	QStringList buddies = getDiveBuddies(d);
	if (buddies.empty()) {
		increaseCount(QString());
		return;
	}
	for(const QString &buddy: buddies)
		increaseCount(buddy);
}

void BuddyFilterModel::diveDeleted(const dive *d)
{
	QStringList buddies = getDiveBuddies(d);
	if (buddies.empty()) {
		decreaseCount(QString());
		return;
	}
	for(const QString &buddy: buddies)
		decreaseCount(buddy);
}

void BuddyFilterModel::repopulate()
{
	QStringList list;
	struct dive *dive;
	int i = 0;
	for_each_dive (i, dive) {
		QString persons = QString(dive->buddy) + "," + QString(dive->divemaster);
		Q_FOREACH (const QString &person, persons.split(',', QString::SkipEmptyParts)) {
			// Remove any leading spaces
			if (!list.contains(person.trimmed())) {
				list.append(person.trimmed());
			}
		}
	}
	list << tr("No buddies");
	updateList(list);
}

LocationFilterModel::LocationFilterModel(QObject *parent) : FilterModelBase(parent)
{
}

int LocationFilterModel::countDives(const char *s) const
{
	return count_dives_with_location(s);
}

bool LocationFilterModel::doFilter(const dive *d) const
{
	// rowCount() == 0 should never happen, because we have the "no location" row
	// let's handle it gracefully anyway.
	if (!anyChecked || rowCount() == 0)
		return true;

	// Checked means 'Show', Unchecked means 'Hide'.
	QString location(get_dive_location(d));
	// only show empty location dives if the user checked that.
	if (location.isEmpty())
		return items[rowCount() - 1].checked != negate;

	// There is a location selected
	// Ignore last item, since this is the "Show Empty Tags" entry
	for (int i = 0; i < rowCount() - 1; i++) {
		if (items[i].checked && location == items[i].name)
			return !negate;
	}
	return negate;
}

void LocationFilterModel::diveAdded(const dive *d)
{
	increaseCount(get_dive_location(d));
}

void LocationFilterModel::diveDeleted(const dive *d)
{
	decreaseCount(get_dive_location(d));
}

void LocationFilterModel::repopulate()
{
	QStringList list;
	struct dive *dive;
	int i = 0;
	for_each_dive (i, dive) {
		QString location(get_dive_location(dive));
		if (!location.isEmpty() && !list.contains(location)) {
			list.append(location);
		}
	}
	list << tr("No location set");
	updateList(list);
}

void LocationFilterModel::addName(const QString &newName)
{
	if (newName.isEmpty() || indexOf(newName) >= 0)
		return;
	int count = countDives(qPrintable(newName));
	// If any old item was checked, also check the new one so that
	// dives with the added dive site are shown.
	addItem(newName, anyChecked, count);
}

MultiFilterSortModel::MultiFilterSortModel(QObject *parent) : QSortFilterProxyModel(parent),
	divesDisplayed(0),
	curr_dive_site(NULL),
	model(DiveTripModel::instance())
{
	setFilterKeyColumn(-1); // filter all columns
	setFilterCaseSensitivity(Qt::CaseInsensitive);
	setSourceModel(model);
}

void MultiFilterSortModel::setLayout(DiveTripModel::Layout layout)
{
	DiveTripModel *tripModel = DiveTripModel::instance();
	tripModel->setLayout(layout);	// Note: setLayout() resets the whole model
}

void MultiFilterSortModel::divesAdded(const QVector<dive *> &dives)
{
	// TODO: We call diveAdded for every dive and model.
	// If multiple dives are added (e.g. import dive) this will lead to a large
	// number of model changes and might be a pessimization compared to a full
	// model reload. Instead, the models should take the vector, calculate the
	// new fields and add them at once.
	for (FilterModelBase *model: models) {
		for (const dive *d: dives)
			model->diveAdded(d);
	}
}

void MultiFilterSortModel::divesDeleted(const QVector<dive *> &dives)
{
	// TODO: See comment for divesDeleted
	for (FilterModelBase *model: models) {
		for (const dive *d: dives)
			model->diveDeleted(d);
	}
}

bool MultiFilterSortModel::showDive(const struct dive *d) const
{
	if (curr_dive_site) {
		dive_site *ds = d->dive_site;
		if (!ds)
			return false;
		return ds == curr_dive_site || same_string(ds->name, curr_dive_site->name);
	}

	if (models.isEmpty())
		return true;

	for (const FilterModelBase *model: models) {
		if (!model->doFilter(d))
			return false;
	}

	return true;
}

bool MultiFilterSortModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
	QModelIndex index0 = sourceModel()->index(source_row, 0, source_parent);
	struct dive *d = sourceModel()->data(index0, DiveTripModel::DIVE_ROLE).value<struct dive *>();

	// For dives, simply check the hidden_by_filter flag
	if (d)
		return !d->hidden_by_filter;

	// Since this is not a dive, it must be a trip
	dive_trip *trip = sourceModel()->data(index0, DiveTripModel::TRIP_ROLE).value<dive_trip *>();

	if (!trip)
		return false; // Oops. Neither dive nor trip, something is seriously wrong.

	// Show the trip if any dive is visible
	for (int i = 0; i < trip->dives.nr; ++i) {
		if (!trip->dives.dives[i]->hidden_by_filter)
			return true;
	}
	return false;
}

void MultiFilterSortModel::filterChanged(const QModelIndex &from, const QModelIndex &to, const QVector<int> &roles)
{
	// Only redo the filter if a checkbox changed. If the count of an entry changed,
	// we do *not* want to recalculate the filters.
	if (roles.contains(Qt::CheckStateRole))
		myInvalidate();
}

void MultiFilterSortModel::myInvalidate()
{
	int i;
	struct dive *d;

	divesDisplayed = 0;

	// Apply filter for each dive
	for_each_dive (i, d) {
		bool show = showDive(d);
		filter_dive(d, show);
		if (show)
			divesDisplayed++;
	}

	invalidateFilter();

	// Tell the dive trip model to update the displayed-counts
	DiveTripModel::instance()->filterFinished();
	emit filterFinished();

#if !defined(SUBSURFACE_MOBILE)
	if (curr_dive_site)
		MainWindow::instance()->diveList->expandAll();
#endif
}

void MultiFilterSortModel::addFilterModel(FilterModelBase *model)
{
	models.append(model);
	connect(model, &FilterModelBase::dataChanged, this, &MultiFilterSortModel::filterChanged);
}

void MultiFilterSortModel::removeFilterModel(FilterModelBase *model)
{
	models.removeAll(model);
	disconnect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(myInvalidate()));
}

void MultiFilterSortModel::clearFilter()
{
	Q_FOREACH (FilterModelBase *iface, models) {
		iface->clearFilter();
	}
	myInvalidate();
}

void MultiFilterSortModel::startFilterDiveSite(struct dive_site *ds)
{
	curr_dive_site = ds;
	myInvalidate();
}

void MultiFilterSortModel::stopFilterDiveSite()
{
	curr_dive_site = NULL;
	myInvalidate();
}

bool MultiFilterSortModel::lessThan(const QModelIndex &i1, const QModelIndex &i2) const
{
	// Hand sorting down to the source model.
	return model->lessThan(i1, i2);
}