Dive list: split DiveTripModel into distinct models (tree and list)

The DiveTripModel was used to represent both, trip and list views.
Thus many functions had conditionals checking for the current mode
and both modes had to be represented by the same data structure.

Instead, split the model in two and derive them from a base class,
which implements common functions and defines an interface.

The model can be switched by a call to resetModel(), which invalidates
any pointer obtained by instance(). This is quite surprising
behavior. To handle it, straighten out the control flow:

DiveListView --> MultiFilterSortModel --> DiveTripModelBase

Before, DiveListView accessed DiveTripModelBase directly.

A goal of this commit is to enable usage of the same model by mobile
and desktop.

Signed-off-by: Berthold Stoeger <bstoeger@mail.tuwien.ac.at>
This commit is contained in:
Berthold Stoeger 2018-12-27 10:06:11 +01:00 committed by Dirk Hohndel
parent b5704ddb57
commit f1fc89b978
8 changed files with 663 additions and 442 deletions

View file

@ -28,20 +28,20 @@
#include "desktop-widgets/simplewidgets.h" #include "desktop-widgets/simplewidgets.h"
DiveListView::DiveListView(QWidget *parent) : QTreeView(parent), mouseClickSelection(false), DiveListView::DiveListView(QWidget *parent) : QTreeView(parent), mouseClickSelection(false),
currentLayout(DiveTripModel::TREE), dontEmitDiveChangedSignal(false), selectionSaved(false), currentLayout(DiveTripModelBase::TREE), dontEmitDiveChangedSignal(false), selectionSaved(false),
initialColumnWidths(DiveTripModel::COLUMNS, 50) // Set up with default length 50 initialColumnWidths(DiveTripModelBase::COLUMNS, 50) // Set up with default length 50
{ {
setItemDelegate(new DiveListDelegate(this)); setItemDelegate(new DiveListDelegate(this));
setUniformRowHeights(true); setUniformRowHeights(true);
setItemDelegateForColumn(DiveTripModel::RATING, new StarWidgetsDelegate(this)); setItemDelegateForColumn(DiveTripModelBase::RATING, new StarWidgetsDelegate(this));
setModel(MultiFilterSortModel::instance()); setModel(MultiFilterSortModel::instance());
setSortingEnabled(true); setSortingEnabled(true);
setContextMenuPolicy(Qt::DefaultContextMenu); setContextMenuPolicy(Qt::DefaultContextMenu);
setSelectionMode(ExtendedSelection); setSelectionMode(ExtendedSelection);
header()->setContextMenuPolicy(Qt::ActionsContextMenu); header()->setContextMenuPolicy(Qt::ActionsContextMenu);
connect(DiveTripModel::instance(), &DiveTripModel::selectionChanged, this, &DiveListView::diveSelectionChanged);
connect(DiveTripModel::instance(), &DiveTripModel::newCurrentDive, this, &DiveListView::currentDiveChanged); resetModel();
// Update selection if all selected dives were hidden by filter // Update selection if all selected dives were hidden by filter
connect(MultiFilterSortModel::instance(), &MultiFilterSortModel::filterFinished, this, &DiveListView::filterFinished); connect(MultiFilterSortModel::instance(), &MultiFilterSortModel::filterFinished, this, &DiveListView::filterFinished);
@ -53,7 +53,7 @@ DiveListView::DiveListView(QWidget *parent) : QTreeView(parent), mouseClickSelec
installEventFilter(this); installEventFilter(this);
for (int i = DiveTripModel::NR; i < DiveTripModel::COLUMNS; i++) for (int i = DiveTripModelBase::NR; i < DiveTripModelBase::COLUMNS; i++)
calculateInitialColumnWidth(i); calculateInitialColumnWidth(i);
setColumnWidths(); setColumnWidths();
} }
@ -63,7 +63,7 @@ DiveListView::~DiveListView()
QSettings settings; QSettings settings;
settings.beginGroup("ListWidget"); settings.beginGroup("ListWidget");
// don't set a width for the last column - location is supposed to be "the rest" // don't set a width for the last column - location is supposed to be "the rest"
for (int i = DiveTripModel::NR; i < DiveTripModel::COLUMNS - 1; i++) { for (int i = DiveTripModelBase::NR; i < DiveTripModelBase::COLUMNS - 1; i++) {
if (isColumnHidden(i)) if (isColumnHidden(i))
continue; continue;
// we used to hardcode them all to 100 - so that might still be in the settings // we used to hardcode them all to 100 - so that might still be in the settings
@ -72,41 +72,50 @@ DiveListView::~DiveListView()
else else
settings.setValue(QString("colwidth%1").arg(i), columnWidth(i)); settings.setValue(QString("colwidth%1").arg(i), columnWidth(i));
} }
settings.remove(QString("colwidth%1").arg(DiveTripModel::COLUMNS - 1)); settings.remove(QString("colwidth%1").arg(DiveTripModelBase::COLUMNS - 1));
settings.endGroup(); settings.endGroup();
} }
void DiveListView::resetModel()
{
MultiFilterSortModel::instance()->resetModel(currentLayout);
// If the model was reset, we have to reconnect the signals and tell
// the filter model to update its source model.
connect(DiveTripModelBase::instance(), &DiveTripModelBase::selectionChanged, this, &DiveListView::diveSelectionChanged);
connect(DiveTripModelBase::instance(), &DiveTripModelBase::newCurrentDive, this, &DiveListView::currentDiveChanged);
}
void DiveListView::calculateInitialColumnWidth(int col) void DiveListView::calculateInitialColumnWidth(int col)
{ {
const QFontMetrics metrics(defaultModelFont()); const QFontMetrics metrics(defaultModelFont());
int em = metrics.width('m'); int em = metrics.width('m');
int zw = metrics.width('0'); int zw = metrics.width('0');
QString header_txt = DiveTripModel::instance()->headerData(col, Qt::Horizontal, Qt::DisplayRole).toString(); QString header_txt = DiveTripModelBase::instance()->headerData(col, Qt::Horizontal, Qt::DisplayRole).toString();
int width = metrics.width(header_txt); int width = metrics.width(header_txt);
int sw = 0; int sw = 0;
switch (col) { switch (col) {
case DiveTripModel::NR: case DiveTripModelBase::NR:
case DiveTripModel::DURATION: case DiveTripModelBase::DURATION:
sw = 8*zw; sw = 8*zw;
break; break;
case DiveTripModel::DATE: case DiveTripModelBase::DATE:
sw = 14*em; sw = 14*em;
break; break;
case DiveTripModel::RATING: case DiveTripModelBase::RATING:
sw = static_cast<StarWidgetsDelegate*>(itemDelegateForColumn(col))->starSize().width(); sw = static_cast<StarWidgetsDelegate*>(itemDelegateForColumn(col))->starSize().width();
break; break;
case DiveTripModel::SUIT: case DiveTripModelBase::SUIT:
case DiveTripModel::SAC: case DiveTripModelBase::SAC:
sw = 7*em; sw = 7*em;
break; break;
case DiveTripModel::PHOTOS: case DiveTripModelBase::PHOTOS:
sw = 5*em; sw = 5*em;
break; break;
case DiveTripModel::BUDDIES: case DiveTripModelBase::BUDDIES:
sw = 50*em; sw = 50*em;
break; break;
case DiveTripModel::LOCATION: case DiveTripModelBase::LOCATION:
sw = 50*em; sw = 50*em;
break; break;
default: default:
@ -126,7 +135,7 @@ void DiveListView::setColumnWidths()
/* if no width are set, use the calculated width for each column; /* if no width are set, use the calculated width for each column;
* for that to work we need to temporarily expand all rows */ * for that to work we need to temporarily expand all rows */
expandAll(); expandAll();
for (int i = DiveTripModel::NR; i < DiveTripModel::COLUMNS; i++) { for (int i = DiveTripModelBase::NR; i < DiveTripModelBase::COLUMNS; i++) {
if (isColumnHidden(i)) if (isColumnHidden(i))
continue; continue;
QVariant width = settings.value(QString("colwidth%1").arg(i)); QVariant width = settings.value(QString("colwidth%1").arg(i));
@ -143,7 +152,7 @@ void DiveListView::setColumnWidths()
int DiveListView::lastVisibleColumn() int DiveListView::lastVisibleColumn()
{ {
int lastColumn = -1; int lastColumn = -1;
for (int i = DiveTripModel::NR; i < DiveTripModel::COLUMNS; i++) { for (int i = DiveTripModelBase::NR; i < DiveTripModelBase::COLUMNS; i++) {
if (isColumnHidden(i)) if (isColumnHidden(i))
continue; continue;
lastColumn = i; lastColumn = i;
@ -249,11 +258,11 @@ void DiveListView::rememberSelection()
Q_FOREACH (const QModelIndex &index, selection.indexes()) { Q_FOREACH (const QModelIndex &index, selection.indexes()) {
if (index.column() != 0) // We only care about the dives, so, let's stick to rows and discard columns. if (index.column() != 0) // We only care about the dives, so, let's stick to rows and discard columns.
continue; continue;
struct dive *d = index.data(DiveTripModel::DIVE_ROLE).value<struct dive *>(); struct dive *d = index.data(DiveTripModelBase::DIVE_ROLE).value<struct dive *>();
if (d) { if (d) {
selectedDives.insert(d->divetrip, get_divenr(d)); selectedDives.insert(d->divetrip, get_divenr(d));
} else { } else {
struct dive_trip *t = index.data(DiveTripModel::TRIP_ROLE).value<dive_trip *>(); struct dive_trip *t = index.data(DiveTripModelBase::TRIP_ROLE).value<dive_trip *>();
if (t) if (t)
selectedDives.insert(t, -1); selectedDives.insert(t, -1);
} }
@ -289,7 +298,7 @@ void DiveListView::selectTrip(dive_trip_t *trip)
return; return;
QAbstractItemModel *m = model(); QAbstractItemModel *m = model();
QModelIndexList match = m->match(m->index(0, 0), DiveTripModel::TRIP_ROLE, QVariant::fromValue(trip), 2, Qt::MatchRecursive); QModelIndexList match = m->match(m->index(0, 0), DiveTripModelBase::TRIP_ROLE, QVariant::fromValue(trip), 2, Qt::MatchRecursive);
QItemSelectionModel::SelectionFlags flags; QItemSelectionModel::SelectionFlags flags;
if (!match.count()) if (!match.count())
return; return;
@ -314,7 +323,7 @@ void DiveListView::clearTripSelection()
// we want to make sure no trips are selected // we want to make sure no trips are selected
Q_FOREACH (const QModelIndex &index, selectionModel()->selectedRows()) { Q_FOREACH (const QModelIndex &index, selectionModel()->selectedRows()) {
dive_trip_t *trip = index.data(DiveTripModel::TRIP_ROLE).value<dive_trip *>(); dive_trip_t *trip = index.data(DiveTripModelBase::TRIP_ROLE).value<dive_trip *>();
if (!trip) if (!trip)
continue; continue;
selectionModel()->select(index, QItemSelectionModel::Deselect); selectionModel()->select(index, QItemSelectionModel::Deselect);
@ -343,7 +352,7 @@ QList<dive_trip_t *> DiveListView::selectedTrips()
{ {
QList<dive_trip_t *> ret; QList<dive_trip_t *> ret;
Q_FOREACH (const QModelIndex &index, selectionModel()->selectedRows()) { Q_FOREACH (const QModelIndex &index, selectionModel()->selectedRows()) {
dive_trip_t *trip = index.data(DiveTripModel::TRIP_ROLE).value<dive_trip *>(); dive_trip_t *trip = index.data(DiveTripModelBase::TRIP_ROLE).value<dive_trip *>();
if (!trip) if (!trip)
continue; continue;
ret.push_back(trip); ret.push_back(trip);
@ -374,7 +383,7 @@ void DiveListView::selectDive(int i, bool scrollto, bool toggle)
if (i == -1) if (i == -1)
return; return;
QAbstractItemModel *m = model(); QAbstractItemModel *m = model();
QModelIndexList match = m->match(m->index(0, 0), DiveTripModel::DIVE_IDX, i, 2, Qt::MatchRecursive); QModelIndexList match = m->match(m->index(0, 0), DiveTripModelBase::DIVE_IDX, i, 2, Qt::MatchRecursive);
if (match.isEmpty()) if (match.isEmpty())
return; return;
QModelIndex idx = match.first(); QModelIndex idx = match.first();
@ -411,7 +420,7 @@ void DiveListView::selectDives(const QList<int> &newDiveSelection)
selectDive(newSelection); selectDive(newSelection);
} }
QAbstractItemModel *m = model(); QAbstractItemModel *m = model();
QModelIndexList idxList = m->match(m->index(0, 0), DiveTripModel::DIVE_IDX, get_divenr(current_dive), 2, Qt::MatchRecursive); QModelIndexList idxList = m->match(m->index(0, 0), DiveTripModelBase::DIVE_IDX, get_divenr(current_dive), 2, Qt::MatchRecursive);
if (!idxList.isEmpty()) { if (!idxList.isEmpty()) {
QModelIndex idx = idxList.first(); QModelIndex idx = idxList.first();
if (idx.parent().isValid()) if (idx.parent().isValid())
@ -462,7 +471,7 @@ bool DiveListView::eventFilter(QObject *, QEvent *event)
void DiveListView::sortIndicatorChanged(int i, Qt::SortOrder order) void DiveListView::sortIndicatorChanged(int i, Qt::SortOrder order)
{ {
DiveTripModel::Layout newLayout = i == (int)DiveTripModel::NR ? DiveTripModel::TREE : DiveTripModel::LIST; DiveTripModelBase::Layout newLayout = i == (int)DiveTripModelBase::NR ? DiveTripModelBase::TREE : DiveTripModelBase::LIST;
/* No layout change? Just re-sort, and scroll to first selection, making sure all selections are expanded */ /* No layout change? Just re-sort, and scroll to first selection, making sure all selections are expanded */
if (currentLayout == newLayout) { if (currentLayout == newLayout) {
sortByColumn(i, order); sortByColumn(i, order);
@ -470,12 +479,12 @@ void DiveListView::sortIndicatorChanged(int i, Qt::SortOrder order)
// clear the model, repopulate with new indexes. // clear the model, repopulate with new indexes.
rememberSelection(); rememberSelection();
unselectDives(); unselectDives();
if (currentLayout == DiveTripModel::TREE) if (currentLayout == DiveTripModelBase::TREE)
backupExpandedRows(); backupExpandedRows();
currentLayout = newLayout; currentLayout = newLayout;
MultiFilterSortModel::instance()->setLayout(newLayout); resetModel();
sortByColumn(i, order); sortByColumn(i, order);
if (newLayout == DiveTripModel::TREE) if (newLayout == DiveTripModelBase::TREE)
restoreExpandedRows(); restoreExpandedRows();
restoreSelection(); restoreSelection();
} }
@ -489,8 +498,7 @@ void DiveListView::setSortOrder(int i, Qt::SortOrder order)
void DiveListView::reload() void DiveListView::reload()
{ {
// A side-effect of setting the layout is reloading the model data resetModel();
MultiFilterSortModel::instance()->setLayout(currentLayout);
if (amount_selected && current_dive != NULL) if (amount_selected && current_dive != NULL)
selectDive(get_divenr(current_dive), true); selectDive(get_divenr(current_dive), true);
@ -519,15 +527,15 @@ void DiveListView::reloadHeaderActions()
QString title = QString("%1").arg(model()->headerData(i, Qt::Horizontal).toString()); QString title = QString("%1").arg(model()->headerData(i, Qt::Horizontal).toString());
QString settingName = QString("showColumn%1").arg(i); QString settingName = QString("showColumn%1").arg(i);
QAction *a = new QAction(title, header()); QAction *a = new QAction(title, header());
bool showHeaderFirstRun = !(i == DiveTripModel::MAXCNS || bool showHeaderFirstRun = !(i == DiveTripModelBase::MAXCNS ||
i == DiveTripModel::GAS || i == DiveTripModelBase::GAS ||
i == DiveTripModel::OTU || i == DiveTripModelBase::OTU ||
i == DiveTripModel::TEMPERATURE || i == DiveTripModelBase::TEMPERATURE ||
i == DiveTripModel::TOTALWEIGHT || i == DiveTripModelBase::TOTALWEIGHT ||
i == DiveTripModel::SUIT || i == DiveTripModelBase::SUIT ||
i == DiveTripModel::CYLINDER || i == DiveTripModelBase::CYLINDER ||
i == DiveTripModel::SAC || i == DiveTripModelBase::SAC ||
i == DiveTripModel::TAGS); i == DiveTripModelBase::TAGS);
bool shown = s.value(settingName, showHeaderFirstRun).toBool(); bool shown = s.value(settingName, showHeaderFirstRun).toBool();
a->setCheckable(true); a->setCheckable(true);
a->setChecked(shown); a->setChecked(shown);
@ -608,9 +616,9 @@ void DiveListView::selectionChanged(const QItemSelection &selected, const QItemS
if (index.column() != 0) if (index.column() != 0)
continue; continue;
const QAbstractItemModel *model = index.model(); const QAbstractItemModel *model = index.model();
struct dive *dive = model->data(index, DiveTripModel::DIVE_ROLE).value<struct dive *>(); struct dive *dive = model->data(index, DiveTripModelBase::DIVE_ROLE).value<struct dive *>();
if (!dive) // it's a trip! if (!dive) // it's a trip!
deselect_dives_in_trip(model->data(index, DiveTripModel::TRIP_ROLE).value<dive_trip *>()); deselect_dives_in_trip(model->data(index, DiveTripModelBase::TRIP_ROLE).value<dive_trip *>());
else else
deselect_dive(dive); deselect_dive(dive);
} }
@ -619,11 +627,11 @@ void DiveListView::selectionChanged(const QItemSelection &selected, const QItemS
continue; continue;
const QAbstractItemModel *model = index.model(); const QAbstractItemModel *model = index.model();
struct dive *dive = model->data(index, DiveTripModel::DIVE_ROLE).value<struct dive *>(); struct dive *dive = model->data(index, DiveTripModelBase::DIVE_ROLE).value<struct dive *>();
if (!dive) { // it's a trip! if (!dive) { // it's a trip!
if (model->rowCount(index)) { if (model->rowCount(index)) {
QItemSelection selection; QItemSelection selection;
select_dives_in_trip(model->data(index, DiveTripModel::TRIP_ROLE).value<dive_trip *>()); select_dives_in_trip(model->data(index, DiveTripModelBase::TRIP_ROLE).value<dive_trip *>());
selection.select(index.child(0, 0), index.child(model->rowCount(index) - 1, 0)); selection.select(index.child(0, 0), index.child(model->rowCount(index) - 1, 0));
selectionModel()->select(selection, QItemSelectionModel::Select | QItemSelectionModel::Rows); selectionModel()->select(selection, QItemSelectionModel::Select | QItemSelectionModel::Rows);
selectionModel()->setCurrentIndex(index, QItemSelectionModel::Select | QItemSelectionModel::NoUpdate); selectionModel()->setCurrentIndex(index, QItemSelectionModel::Select | QItemSelectionModel::NoUpdate);
@ -725,8 +733,8 @@ void DiveListView::merge_trip(const QModelIndex &a, int offset)
int i = a.row() + offset; int i = a.row() + offset;
QModelIndex b = a.sibling(i, 0); QModelIndex b = a.sibling(i, 0);
dive_trip_t *trip_a = a.data(DiveTripModel::TRIP_ROLE).value<dive_trip *>(); dive_trip_t *trip_a = a.data(DiveTripModelBase::TRIP_ROLE).value<dive_trip *>();
dive_trip_t *trip_b = b.data(DiveTripModel::TRIP_ROLE).value<dive_trip *>(); dive_trip_t *trip_b = b.data(DiveTripModelBase::TRIP_ROLE).value<dive_trip *>();
if (trip_a == trip_b || !trip_a || !trip_b) if (trip_a == trip_b || !trip_a || !trip_b)
return; return;
Command::mergeTrips(trip_a, trip_b); Command::mergeTrips(trip_a, trip_b);
@ -757,7 +765,7 @@ void DiveListView::removeFromTrip()
void DiveListView::newTripAbove() void DiveListView::newTripAbove()
{ {
struct dive *d = contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<struct dive *>(); struct dive *d = contextMenuIndex.data(DiveTripModelBase::DIVE_ROLE).value<struct dive *>();
if (!d) // shouldn't happen as we only are setting up this action if this is a dive if (!d) // shouldn't happen as we only are setting up this action if this is a dive
return; return;
//TODO: port to c-code. //TODO: port to c-code.
@ -783,7 +791,7 @@ void DiveListView::addToTripAbove()
void DiveListView::addToTrip(int delta) void DiveListView::addToTrip(int delta)
{ {
// d points to the row that has (mouse-)pointer focus, and there are nr rows selected // d points to the row that has (mouse-)pointer focus, and there are nr rows selected
struct dive *d = contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<struct dive *>(); struct dive *d = contextMenuIndex.data(DiveTripModelBase::DIVE_ROLE).value<struct dive *>();
int nr = selectionModel()->selectedRows().count(); int nr = selectionModel()->selectedRows().count();
QModelIndex t; QModelIndex t;
dive_trip_t *trip = NULL; dive_trip_t *trip = NULL;
@ -792,7 +800,7 @@ void DiveListView::addToTrip(int delta)
// check if its sibling is a trip. // check if its sibling is a trip.
for (int i = 1; i <= nr; i++) { for (int i = 1; i <= nr; i++) {
t = contextMenuIndex.sibling(contextMenuIndex.row() + (delta > 0 ? i: i * -1), 0); t = contextMenuIndex.sibling(contextMenuIndex.row() + (delta > 0 ? i: i * -1), 0);
trip = t.data(DiveTripModel::TRIP_ROLE).value<dive_trip *>(); trip = t.data(DiveTripModelBase::TRIP_ROLE).value<dive_trip *>();
if (trip) if (trip)
break; break;
} }
@ -815,7 +823,7 @@ void DiveListView::addToTrip(int delta)
void DiveListView::markDiveInvalid() void DiveListView::markDiveInvalid()
{ {
int i; int i;
struct dive *d = contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<struct dive *>(); struct dive *d = contextMenuIndex.data(DiveTripModelBase::DIVE_ROLE).value<struct dive *>();
if (!d) if (!d)
return; return;
for_each_dive (i, d) { for_each_dive (i, d) {
@ -834,7 +842,7 @@ void DiveListView::markDiveInvalid()
void DiveListView::deleteDive() void DiveListView::deleteDive()
{ {
struct dive *d = contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<struct dive *>(); struct dive *d = contextMenuIndex.data(DiveTripModelBase::DIVE_ROLE).value<struct dive *>();
if (!d) if (!d)
return; return;
@ -852,17 +860,17 @@ void DiveListView::contextMenuEvent(QContextMenuEvent *event)
QAction *collapseAction = NULL; QAction *collapseAction = NULL;
// let's remember where we are // let's remember where we are
contextMenuIndex = indexAt(event->pos()); contextMenuIndex = indexAt(event->pos());
struct dive *d = contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<struct dive *>(); struct dive *d = contextMenuIndex.data(DiveTripModelBase::DIVE_ROLE).value<struct dive *>();
dive_trip_t *trip = contextMenuIndex.data(DiveTripModel::TRIP_ROLE).value<dive_trip *>(); dive_trip_t *trip = contextMenuIndex.data(DiveTripModelBase::TRIP_ROLE).value<dive_trip *>();
QMenu popup(this); QMenu popup(this);
if (currentLayout == DiveTripModel::TREE) { if (currentLayout == DiveTripModelBase::TREE) {
// verify if there is a node that`s not expanded. // verify if there is a node that`s not expanded.
bool needs_expand = false; bool needs_expand = false;
bool needs_collapse = false; bool needs_collapse = false;
uint expanded_nodes = 0; uint expanded_nodes = 0;
for(int i = 0, end = model()->rowCount(); i < end; i++) { for(int i = 0, end = model()->rowCount(); i < end; i++) {
QModelIndex idx = model()->index(i, 0); QModelIndex idx = model()->index(i, 0);
if (idx.data(DiveTripModel::DIVE_ROLE).value<struct dive *>()) if (idx.data(DiveTripModelBase::DIVE_ROLE).value<struct dive *>())
continue; continue;
if (!isExpanded(idx)) { if (!isExpanded(idx)) {

View file

@ -68,7 +68,7 @@ slots:
private: private:
bool mouseClickSelection; bool mouseClickSelection;
QList<int> expandedRows; QList<int> expandedRows;
DiveTripModel::Layout currentLayout; DiveTripModelBase::Layout currentLayout;
QModelIndex contextMenuIndex; QModelIndex contextMenuIndex;
bool dontEmitDiveChangedSignal; bool dontEmitDiveChangedSignal;
bool selectionSaved; bool selectionSaved;
@ -77,6 +77,7 @@ private:
/* if dive_trip_t is null, there's no problem. */ /* if dive_trip_t is null, there's no problem. */
QMultiHash<dive_trip_t *, int> selectedDives; QMultiHash<dive_trip_t *, int> selectedDives;
void resetModel(); // Call after model changed
void merge_trip(const QModelIndex &a, const int offset); void merge_trip(const QModelIndex &a, const int offset);
void setColumnWidths(); void setColumnWidths();
void calculateInitialColumnWidth(int col); void calculateInitialColumnWidth(int col);

View file

@ -702,7 +702,7 @@ void MainWindow::cleanUpEmpty()
mainTab->updateDiveInfo(true); mainTab->updateDiveInfo(true);
graphics->setEmptyState(); graphics->setEmptyState();
diveList->reload(); diveList->reload();
diveList->setSortOrder(DiveTripModel::NR, Qt::DescendingOrder); diveList->setSortOrder(DiveTripModelBase::NR, Qt::DescendingOrder);
MapWidget::instance()->reload(); MapWidget::instance()->reload();
if (!existing_filename) if (!existing_filename)
setTitle(); setTitle();

View file

@ -52,7 +52,7 @@ void StarWidgetsDelegate::paint(QPainter *painter, const QStyleOptionViewItem &o
if (!index.isValid()) if (!index.isValid())
return; return;
QVariant value = index.model()->data(index, DiveTripModel::STAR_ROLE); QVariant value = index.model()->data(index, DiveTripModelBase::STAR_ROLE);
if (!value.isValid()) if (!value.isValid())
return; return;

File diff suppressed because it is too large Load diff

View file

@ -5,7 +5,23 @@
#include "core/dive.h" #include "core/dive.h"
#include <QAbstractItemModel> #include <QAbstractItemModel>
class DiveTripModel : public QAbstractItemModel { // There are two different representations of the dive list:
// 1) Tree view: two-level model where dives are grouped by trips
// 2) List view: one-level model where dives are sorted by one out
// of many keys (e.g. date, depth, etc.).
//
// These two representations are realized by two classe, viz.
// DiveTripModelTree and DiveTripModelList. Both classes derive
// from DiveTripModelBase, which implements common features (e.g.
// definition of the column types, access of data from the core
// structures) and a common interface.
//
// The currently active model is set via DiveTripModelBase::resetModel().
// This will create a new model. The model can be accessed with
// DiveTripModelBase::instance(). Any pointer obtained by instance()
// is invalid after a call to resetModel()! Yes, this is surprising
// behavior, so care must be taken.
class DiveTripModelBase : public QAbstractItemModel {
Q_OBJECT Q_OBJECT
public: public:
enum Column { enum Column {
@ -40,25 +56,28 @@ public:
enum Layout { enum Layout {
TREE, TREE,
LIST, LIST,
CURRENT
}; };
static DiveTripModel *instance(); // Functions implemented by base class
static DiveTripModelBase *instance();
// Reset the model using the given layout. After this call instance() will return
// a newly allocated object and the old model will have been destroyed! Thus, the
// caller is repsonsible of removing all references to any previous model obtained
// by insance().
static void resetModel(Layout layout);
Qt::ItemFlags flags(const QModelIndex &index) const; Qt::ItemFlags flags(const QModelIndex &index) const;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
DiveTripModel(QObject *parent = 0); DiveTripModelBase(QObject *parent = 0);
void setLayout(Layout layout);
QVariant data(const QModelIndex &index, int role) const;
int columnCount(const QModelIndex&) const; int columnCount(const QModelIndex&) const;
int rowCount(const QModelIndex &parent) const; virtual void filterFinished() = 0;
QModelIndex index(int row, int column, const QModelIndex &parent) const;
QModelIndex parent(const QModelIndex &index) const;
void filterFinished();
// Used for sorting. This is a bit of a layering violation, as sorting should be performed // Used for sorting. This is a bit of a layering violation, as sorting should be performed
// by the higher-up QSortFilterProxyModel, but it makes things so much easier! // by the higher-up QSortFilterProxyModel, but it makes things so much easier!
bool lessThan(const QModelIndex &i1, const QModelIndex &i2) const; virtual bool lessThan(const QModelIndex &i1, const QModelIndex &i2) const = 0;
signals: signals:
// The propagation of selection changes is complex. // The propagation of selection changes is complex.
// The control flow of dive-selection goes: // The control flow of dive-selection goes:
@ -69,17 +88,44 @@ signals:
// perform the appropriate actions. // perform the appropriate actions.
void selectionChanged(const QVector<QModelIndex> &indexes, bool select); void selectionChanged(const QVector<QModelIndex> &indexes, bool select);
void newCurrentDive(QModelIndex index); void newCurrentDive(QModelIndex index);
private slots: protected slots:
void divesSelected(dive_trip *trip, const QVector<dive *> &dives);
void divesDeselected(dive_trip *trip, const QVector<dive *> &dives);
protected:
// Access trip and dive data
static QVariant diveData(const struct dive *d, int column, int role);
static QVariant tripData(const dive_trip *trip, int column, int role);
// Select or deselect dives
virtual void changeDiveSelection(dive_trip *trip, const QVector<dive *> &dives, bool select) = 0;
virtual dive *diveOrNull(const QModelIndex &index) const = 0; // Returns a dive if this index represents a dive, null otherwise
};
class DiveTripModelTree : public DiveTripModelBase
{
Q_OBJECT
public slots:
void divesAdded(dive_trip *trip, bool addTrip, const QVector<dive *> &dives); void divesAdded(dive_trip *trip, bool addTrip, const QVector<dive *> &dives);
void divesDeleted(dive_trip *trip, bool deleteTrip, const QVector<dive *> &dives); void divesDeleted(dive_trip *trip, bool deleteTrip, const QVector<dive *> &dives);
void divesChanged(dive_trip *trip, const QVector<dive *> &dives); void divesChanged(dive_trip *trip, const QVector<dive *> &dives);
void divesTimeChanged(dive_trip *trip, timestamp_t delta, const QVector<dive *> &dives); void divesTimeChanged(dive_trip *trip, timestamp_t delta, const QVector<dive *> &dives);
void divesMovedBetweenTrips(dive_trip *from, dive_trip *to, bool deleteFrom, bool createTo, const QVector<dive *> &dives); void divesMovedBetweenTrips(dive_trip *from, dive_trip *to, bool deleteFrom, bool createTo, const QVector<dive *> &dives);
void divesSelected(dive_trip *trip, const QVector<dive *> &dives);
void divesDeselected(dive_trip *trip, const QVector<dive *> &dives);
void currentDiveChanged(); void currentDiveChanged();
public:
DiveTripModelTree(QObject *parent = nullptr);
private: private:
// The model has up to two levels. At the top level, we have either trips or dives int rowCount(const QModelIndex &parent) const override;
QModelIndex index(int row, int column, const QModelIndex &parent) const override;
QModelIndex parent(const QModelIndex &index) const override;
QVariant data(const QModelIndex &index, int role) const override;
void filterFinished() override;
bool lessThan(const QModelIndex &i1, const QModelIndex &i2) const override;
void changeDiveSelection(dive_trip *trip, const QVector<dive *> &dives, bool select) override;
dive *diveOrNull(const QModelIndex &index) const override;
// The tree model has two levels. At the top level, we have either trips or dives
// that do not belong to trips. Such a top-level item is represented by the "Item" // that do not belong to trips. Such a top-level item is represented by the "Item"
// struct, which is based on the dive_or_trip structure. // struct, which is based on the dive_or_trip structure.
// If it is a trip, additionally, the dives are collected in a vector. // If it is a trip, additionally, the dives are collected in a vector.
@ -97,8 +143,14 @@ private:
dive *getDive() const; // Helper function: returns top-level-dive or null dive *getDive() const; // Helper function: returns top-level-dive or null
timestamp_t when() const; // Helper function: start time of dive *or* trip timestamp_t when() const; // Helper function: start time of dive *or* trip
}; };
// Comparison function between dive and arbitrary entry std::vector<Item> items; // Use std::vector for convenience of emplace_back()
static bool dive_before_entry(const dive *d, const Item &entry);
dive_or_trip tripOrDive(const QModelIndex &index) const;
// Returns either a pointer to a trip or a dive, or twice null of index is invalid
// null, something is really wrong
// Addition and deletion of dives
void addDivesToTrip(int idx, const QVector<dive *> &dives);
void topLevelChanged(int idx);
// Access trips and dives // Access trips and dives
int findTripIdx(const dive_trip *trip) const; int findTripIdx(const dive_trip *trip) const;
@ -106,24 +158,35 @@ private:
int findDiveInTrip(int tripIdx, const dive *d) const; // Find dive inside trip. Second parameter is index of trip int findDiveInTrip(int tripIdx, const dive *d) const; // Find dive inside trip. Second parameter is index of trip
int findInsertionIndex(const dive_trip *trip) const; // Where to insert trip int findInsertionIndex(const dive_trip *trip) const; // Where to insert trip
// Access trip and dive data // Comparison function between dive and arbitrary entry
static QVariant diveData(const struct dive *d, int column, int role); static bool dive_before_entry(const dive *d, const Item &entry);
static QVariant tripData(const dive_trip *trip, int column, int role); };
// Select or deselect dives class DiveTripModelList : public DiveTripModelBase
void changeDiveSelection(dive_trip *trip, const QVector<dive *> &dives, bool select); {
Q_OBJECT
public slots:
void divesAdded(dive_trip *trip, bool addTrip, const QVector<dive *> &dives);
void divesDeleted(dive_trip *trip, bool deleteTrip, const QVector<dive *> &dives);
void divesChanged(dive_trip *trip, const QVector<dive *> &dives);
void divesTimeChanged(dive_trip *trip, timestamp_t delta, const QVector<dive *> &dives);
// Does nothing in list view.
//void divesMovedBetweenTrips(dive_trip *from, dive_trip *to, bool deleteFrom, bool createTo, const QVector<dive *> &dives);
void currentDiveChanged();
// Addition and deletion of dives public:
void addDivesToTrip(int idx, const QVector<dive *> &dives); DiveTripModelList(QObject *parent = nullptr);
void topLevelChanged(int idx); private:
int rowCount(const QModelIndex &parent) const override;
QModelIndex index(int row, int column, const QModelIndex &parent) const override;
QModelIndex parent(const QModelIndex &index) const override;
QVariant data(const QModelIndex &index, int role) const override;
void filterFinished() override;
bool lessThan(const QModelIndex &i1, const QModelIndex &i2) const override;
void changeDiveSelection(dive_trip *trip, const QVector<dive *> &dives, bool select) override;
dive *diveOrNull(const QModelIndex &index) const override;
dive *diveOrNull(const QModelIndex &index) const; // Returns a dive if this index represents a dive, null otherwise std::vector<dive *> items; // TODO: access core data directly
dive_or_trip tripOrDive(const QModelIndex &index) const;
// Returns either a pointer to a trip or a dive, or twice null of index is invalid
// null, something is really wrong
void setupModelData();
std::vector<Item> items; // Use std::vector for convenience of emplace_back()
Layout currentLayout;
}; };
#endif #endif

View file

@ -88,13 +88,14 @@ MultiFilterSortModel::MultiFilterSortModel(QObject *parent) : QSortFilterProxyMo
{ {
setFilterKeyColumn(-1); // filter all columns setFilterKeyColumn(-1); // filter all columns
setFilterCaseSensitivity(Qt::CaseInsensitive); setFilterCaseSensitivity(Qt::CaseInsensitive);
setSourceModel(DiveTripModel::instance());
} }
void MultiFilterSortModel::setLayout(DiveTripModel::Layout layout) void MultiFilterSortModel::resetModel(DiveTripModelBase::Layout layout)
{ {
DiveTripModel *tripModel = DiveTripModel::instance(); DiveTripModelBase::resetModel(layout);
tripModel->setLayout(layout); // Note: setLayout() resets the whole model // DiveTripModelBase::resetModel() generates a new instance.
// Thus, the source model must be reset.
setSourceModel(DiveTripModelBase::instance());
} }
bool MultiFilterSortModel::showDive(const struct dive *d) const bool MultiFilterSortModel::showDive(const struct dive *d) const
@ -143,14 +144,14 @@ bool MultiFilterSortModel::showDive(const struct dive *d) const
bool MultiFilterSortModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const bool MultiFilterSortModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{ {
QModelIndex index0 = sourceModel()->index(source_row, 0, source_parent); QModelIndex index0 = sourceModel()->index(source_row, 0, source_parent);
struct dive *d = sourceModel()->data(index0, DiveTripModel::DIVE_ROLE).value<struct dive *>(); struct dive *d = sourceModel()->data(index0, DiveTripModelBase::DIVE_ROLE).value<struct dive *>();
// For dives, simply check the hidden_by_filter flag // For dives, simply check the hidden_by_filter flag
if (d) if (d)
return !d->hidden_by_filter; return !d->hidden_by_filter;
// Since this is not a dive, it must be a trip // Since this is not a dive, it must be a trip
dive_trip *trip = sourceModel()->data(index0, DiveTripModel::TRIP_ROLE).value<dive_trip *>(); dive_trip *trip = sourceModel()->data(index0, DiveTripModelBase::TRIP_ROLE).value<dive_trip *>();
if (!trip) if (!trip)
return false; // Oops. Neither dive nor trip, something is seriously wrong. return false; // Oops. Neither dive nor trip, something is seriously wrong.
@ -189,7 +190,7 @@ void MultiFilterSortModel::myInvalidate()
invalidateFilter(); invalidateFilter();
// Tell the dive trip model to update the displayed-counts // Tell the dive trip model to update the displayed-counts
DiveTripModel::instance()->filterFinished(); DiveTripModelBase::instance()->filterFinished();
emit filterFinished(); emit filterFinished();
#if !defined(SUBSURFACE_MOBILE) #if !defined(SUBSURFACE_MOBILE)
@ -218,7 +219,7 @@ void MultiFilterSortModel::stopFilterDiveSite()
bool MultiFilterSortModel::lessThan(const QModelIndex &i1, const QModelIndex &i2) const bool MultiFilterSortModel::lessThan(const QModelIndex &i1, const QModelIndex &i2) const
{ {
// Hand sorting down to the source model. // Hand sorting down to the source model.
return DiveTripModel::instance()->lessThan(i1, i2); return DiveTripModelBase::instance()->lessThan(i1, i2);
} }
void MultiFilterSortModel::filterDataChanged(const FilterData& data) void MultiFilterSortModel::filterDataChanged(const FilterData& data)

View file

@ -2,7 +2,7 @@
#ifndef FILTERMODELS_H #ifndef FILTERMODELS_H
#define FILTERMODELS_H #define FILTERMODELS_H
#include "divetripmodel.h" // For DiveTripModel::Layout. TODO: remove in due course #include "divetripmodel.h"
#include <QStringListModel> #include <QStringListModel>
#include <QSortFilterProxyModel> #include <QSortFilterProxyModel>
@ -13,7 +13,6 @@
struct dive; struct dive;
struct dive_trip; struct dive_trip;
class DiveTripModel;
struct FilterData { struct FilterData {
bool validFilter = false; bool validFilter = false;
@ -49,7 +48,7 @@ slots:
void startFilterDiveSite(struct dive_site *ds); void startFilterDiveSite(struct dive_site *ds);
void stopFilterDiveSite(); void stopFilterDiveSite();
void filterChanged(const QModelIndex &from, const QModelIndex &to, const QVector<int> &roles); void filterChanged(const QModelIndex &from, const QModelIndex &to, const QVector<int> &roles);
void setLayout(DiveTripModel::Layout layout); void resetModel(DiveTripModelBase::Layout layout);
void filterDataChanged(const FilterData& data); void filterDataChanged(const FilterData& data);
signals: signals: