diff options
-rw-r--r-- | core/CMakeLists.txt | 1 | ||||
-rw-r--r-- | core/subsurface-qt/DiveListNotifier.cpp | 4 | ||||
-rw-r--r-- | core/subsurface-qt/DiveListNotifier.h | 39 | ||||
-rw-r--r-- | desktop-widgets/command_divelist.cpp | 240 | ||||
-rw-r--r-- | desktop-widgets/command_divelist.h | 6 | ||||
-rw-r--r-- | desktop-widgets/divelistview.cpp | 38 | ||||
-rw-r--r-- | desktop-widgets/mainwindow.cpp | 4 | ||||
-rw-r--r-- | desktop-widgets/simplewidgets.cpp | 3 | ||||
-rw-r--r-- | desktop-widgets/tab-widgets/maintab.cpp | 1 | ||||
-rw-r--r-- | qt-models/divetripmodel.cpp | 383 | ||||
-rw-r--r-- | qt-models/divetripmodel.h | 26 |
11 files changed, 645 insertions, 100 deletions
diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index dec719929..46cf43251 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -123,6 +123,7 @@ set(SUBSURFACE_CORE_LIB_SRCS #Subsurface Qt have the Subsurface structs QObjectified for easy access via QML. subsurface-qt/DiveObjectHelper.cpp subsurface-qt/CylinderObjectHelper.cpp + subsurface-qt/DiveListNotifier.cpp ${SERIAL_FTDI} ${PLATFORM_SRC} diff --git a/core/subsurface-qt/DiveListNotifier.cpp b/core/subsurface-qt/DiveListNotifier.cpp new file mode 100644 index 000000000..2009defcd --- /dev/null +++ b/core/subsurface-qt/DiveListNotifier.cpp @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: GPL-2.0 +#include "DiveListNotifier.h" + +DiveListNotifier diveListNotifier; diff --git a/core/subsurface-qt/DiveListNotifier.h b/core/subsurface-qt/DiveListNotifier.h new file mode 100644 index 000000000..94b0063ea --- /dev/null +++ b/core/subsurface-qt/DiveListNotifier.h @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0 + +// The DiveListNotifier emits signals when the dive-list changes (dives/trips created/deleted/moved) +// Note that vectors are passed by reference, so this will only work for signals inside the UI thread! + +#ifndef DIVELISTNOTIFIER_H +#define DIVELISTNOTIFIER_H + +#include "core/dive.h" + +#include <QObject> + +class DiveListNotifier : public QObject { + Q_OBJECT +signals: + + // Note that there are no signals for trips being added / created / time-shifted, + // because these events never happen without a dive being added / created / time-shifted. + + // We send one divesAdded, divesDeleted, divesChanged and divesTimeChanged signal per trip + // (non-associated dives being considered part of the null trip). This is ideal for the + // tree-view, but might be not-so-perfect for the list view, if trips intermingle or + // the deletion spans multiple trips. But most of the time only dives of a single trip + // will be affected and trips don't overlap, so these considerations are moot. + // Notes: + // - The dives are always sorted by start-time. + // - The "trip" arguments are null for top-level-dives. + 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 divesMovedBetweenTrips(dive_trip *from, dive_trip *to, bool deleteFrom, bool createTo, const QVector<dive *> &dives); + void divesTimeChanged(dive_trip *trip, timestamp_t delta, const QVector<dive *> &dives); +}; + +// The DiveListNotifier class has no state and no constructor. +// We can simply define it as a global object. +extern DiveListNotifier diveListNotifier; + +#endif diff --git a/desktop-widgets/command_divelist.cpp b/desktop-widgets/command_divelist.cpp index f0c0a82e2..bca6967e6 100644 --- a/desktop-widgets/command_divelist.cpp +++ b/desktop-widgets/command_divelist.cpp @@ -4,9 +4,41 @@ #include "desktop-widgets/mainwindow.h" #include "desktop-widgets/divelistview.h" #include "core/divelist.h" +#include "core/subsurface-qt/DiveListNotifier.h" namespace Command { +// Generally, signals are sent in batches per trip. To avoid writing the same loop +// again and again, this template takes a vector of trip / dive pairs, sorts it +// by trip and then calls a function-object with trip and a QVector of dives in that trip. +// Input parameters: +// - dives: a vector of trip,dive pairs, which will be sorted and processed in batches by trip. +// - action: a function object, taking a trip-pointer and a QVector of dives, which will be called for each batch. +template<typename Function> +void processByTrip(std::vector<std::pair<dive_trip *, dive *>> &dives, Function action) +{ + // Use std::tie for lexicographical sorting of trip, then start-time + std::sort(dives.begin(), dives.end(), + [](const std::pair<dive_trip *, dive *> &e1, const std::pair<dive_trip *, dive *> &e2) + { return std::tie(e1.first, e1.second->when) < std::tie(e2.first, e2.second->when); }); + + // Then, process the dives in batches by trip + size_t i, j; // Begin and end of batch + for (i = 0; i < dives.size(); i = j) { + dive_trip *trip = dives[i].first; + for (j = i + 1; j < dives.size() && dives[j].first == trip; ++j) + ; // pass + // Copy dives into a QVector. Some sort of "range_view" would be ideal, but Qt doesn't work this way. + QVector<dive *> divesInTrip(j - i); + for (size_t k = i; k < j; ++k) + divesInTrip[k - i] = dives[k].second; + + // Finally, emit the signal + action(trip, divesInTrip); + } +} + + // This helper function removes a dive, takes ownership of the dive and adds it to a DiveToAdd structure. // It is crucial that dives are added in reverse order of deletion, so the the indices are correctly // set and that the trips are added before they are used! @@ -26,6 +58,7 @@ static DiveToAdd removeDive(struct dive *d) } res.dive.reset(unregister_dive(res.idx)); // Remove dive from backend + return res; } @@ -38,8 +71,9 @@ static dive *addDive(DiveToAdd &d) insert_trip_dont_merge(d.tripToAdd.release()); // Return ownership to backend if (d.trip) add_dive_to_trip(d.dive.get(), d.trip); - dive *res = d.dive.release(); // Give up ownership of dive - add_single_dive(d.idx, res); // Return ownership to backend + dive *res = d.dive.release(); // Give up ownership of dive + add_single_dive(d.idx, res); // Return ownership to backend + return res; } @@ -55,6 +89,22 @@ static std::vector<DiveToAdd> removeDives(std::vector<dive *> &divesToDelete) res.push_back(removeDive(d)); divesToDelete.clear(); + // We send one dives-deleted signal per trip (see comments in DiveListNotifier.h). + // Therefore, collect all dives in a array and sort by trip. + std::vector<std::pair<dive_trip *, dive *>> dives; + dives.reserve(res.size()); + for (const DiveToAdd &entry: res) + dives.push_back({ entry.trip, entry.dive.get() }); + + // Send signals. + processByTrip(dives, [&](dive_trip *trip, const QVector<dive *> &divesInTrip) { + // Now, let's check if this trip is supposed to be deleted, by checking if it was marked + // as "add it". We could be smarter here, but let's just check the whole array for brevity. + bool deleteTrip = trip && + std::find_if(res.begin(), res.end(), [trip](const DiveToAdd &entry) + { return entry.tripToAdd.get() == trip; }) != res.end(); + emit diveListNotifier.divesDeleted(trip, deleteTrip, divesInTrip); + }); return res; } @@ -67,10 +117,34 @@ static std::vector<dive *> addDives(std::vector<DiveToAdd> &divesToAdd) std::vector<dive *> res; res.reserve(divesToAdd.size()); + // At the end of the function, to send the proper dives-added signals, + // we the the list of added trips. Create this list now. + std::vector<dive_trip *> addedTrips; + for (const DiveToAdd &entry: divesToAdd) { + if (entry.tripToAdd) + addedTrips.push_back(entry.tripToAdd.get()); + } + + // Now, add the dives for (auto it = divesToAdd.rbegin(); it != divesToAdd.rend(); ++it) res.push_back(addDive(*it)); divesToAdd.clear(); + // We send one dives-deleted signal per trip (see comments in DiveListNotifier.h). + // Therefore, collect all dives in a array and sort by trip. + std::vector<std::pair<dive_trip *, dive *>> dives; + dives.reserve(res.size()); + for (dive *d: res) + dives.push_back({ d->divetrip, d }); + + // Send signals. + processByTrip(dives, [&](dive_trip *trip, const QVector<dive *> &divesInTrip) { + // Now, let's check if this trip is supposed to be created, by checking if it was marked + // as "add it". We could be smarter here, but let's just check the whole array for brevity. + bool createTrip = trip && std::find(addedTrips.begin(), addedTrips.end(), trip) != addedTrips.end(); + // Finally, emit the signal + emit diveListNotifier.divesAdded(trip, createTrip, divesInTrip); + }); return res; } @@ -85,6 +159,20 @@ static void renumberDives(QVector<QPair<int, int>> &divesToRenumber) continue; std::swap(d->number, pair.second); } + + // Emit changed signals per trip. + // First, collect all dives and sort by trip + std::vector<std::pair<dive_trip *, dive *>> dives; + dives.reserve(divesToRenumber.size()); + for (const auto &pair: divesToRenumber) { + dive *d = get_dive_by_uniq_id(pair.first); + dives.push_back({ d->divetrip, d }); + } + + // Send signals. + processByTrip(dives, [&](dive_trip *trip, const QVector<dive *> &divesInTrip) { + emit diveListNotifier.divesChanged(trip, divesInTrip); + }); } // This helper function moves a dive to a trip. The old trip is recorded in the @@ -121,9 +209,17 @@ static OwningTripPtr moveDiveToTrip(DiveToTrip &diveToTrip) // a no-op. static void moveDivesBetweenTrips(DivesToTrip &dives) { - // first bring back the trip(s) - for (OwningTripPtr &trip: dives.tripsToAdd) - insert_trip_dont_merge(trip.release()); // Return ownership to backend + // We collect an array of created trips so that we can instruct + // the model to create a new entry + std::vector<dive_trip *> createdTrips; + createdTrips.reserve(dives.tripsToAdd.size()); + + // First, bring back the trip(s) + for (OwningTripPtr &trip: dives.tripsToAdd) { + dive_trip *t = trip.release(); // Give up ownership + createdTrips.push_back(t); + insert_trip_dont_merge(t); // Return ownership to backend + } dives.tripsToAdd.clear(); for (DiveToTrip &dive: dives.divesToMove) { @@ -133,6 +229,60 @@ static void moveDivesBetweenTrips(DivesToTrip &dives) dives.tripsToAdd.push_back(std::move(tripToAdd)); } + // We send one signal per from-trip/to-trip pair. + // First, collect all dives in a struct and sort by from-trip/to-trip. + struct DiveMoved { + dive_trip *from; + dive_trip *to; + dive *d; + }; + std::vector<DiveMoved> divesMoved; + divesMoved.reserve(dives.divesToMove.size()); + for (const DiveToTrip &entry: dives.divesToMove) + divesMoved.push_back({ entry.trip, entry.dive->divetrip, entry.dive }); + + // Sort lexicographically by from-trip, to-trip and by start-time. + // Use std::tie() for lexicographical sorting. + std::sort(divesMoved.begin(), divesMoved.end(), [] ( const DiveMoved &d1, const DiveMoved &d2) + { return std::tie(d1.from, d1.to, d1.d->when) < std::tie(d2.from, d2.to, d2.d->when); }); + + // Now, process the dives in batches by trip + // TODO: this is a bit different from the cases above, so we don't use the processByTrip template, + // but repeat the loop here. We might think about generalizing the template, if more of such + // "special cases" appear. + size_t i, j; // Begin and end of batch + for (i = 0; i < divesMoved.size(); i = j) { + dive_trip *from = divesMoved[i].from; + dive_trip *to = divesMoved[i].to; + for (j = i + 1; j < divesMoved.size() && divesMoved[j].from == from && divesMoved[j].to == to; ++j) + ; // pass + // Copy dives into a QVector. Some sort of "range_view" would be ideal, but Qt doesn't work this way. + QVector<dive *> divesInTrip(j - i); + for (size_t k = i; k < j; ++k) + divesInTrip[k - i] = divesMoved[k].d; + + // Check if the from-trip was deleted: If yes, it was recorded in the tripsToAdd structure + bool deleteFrom = from && + std::find_if(dives.tripsToAdd.begin(), dives.tripsToAdd.end(), + [from](const OwningTripPtr &trip) { return trip.get() == from; }) != dives.tripsToAdd.end(); + // Check if the to-trip has to be created. For this purpose, we saved an array of trips to be created. + bool createTo = false; + if (to) { + // Check if the element is there... + auto it = std::find(createdTrips.begin(), createdTrips.end(), to); + + // ...if it is - remove it as we don't want the model to create the trip twice! + if (it != createdTrips.end()) { + createTo = true; + // erase/remove would be more performant, but this is irrelevant in the big scheme of things. + createdTrips.erase(it); + } + } + + // Finally, emit the signal + emit diveListNotifier.divesMovedBetweenTrips(from, to, deleteFrom, createTo, divesInTrip); + } + // Reverse the tripsToAdd and the divesToAdd, so that on undo/redo the operations // will be performed in reverse order. std::reverse(dives.tripsToAdd.begin(), dives.tripsToAdd.end()); @@ -144,11 +294,11 @@ AddDive::AddDive(dive *d) setText(tr("add dive")); d->maxdepth.mm = 0; fixup_dive(d); - diveToAdd.trip = d->divetrip; - d->divetrip = nullptr; - diveToAdd.idx = dive_get_insertion_index(d); - d->number = get_dive_nr_at_idx(diveToAdd.idx); - diveToAdd.dive.reset(clone_dive(d)); + d->divetrip = nullptr; // TODO: consider autogroup == true + int idx = dive_get_insertion_index(d); + d->number = get_dive_nr_at_idx(idx); + + divesToAdd.push_back({ OwningDivePtr(clone_dive(d)), nullptr, d->divetrip, idx }); } bool AddDive::workToBeDone() @@ -158,22 +308,27 @@ bool AddDive::workToBeDone() void AddDive::redo() { - diveToRemove = addDive(diveToAdd); + int idx = divesToAdd[0].idx; + divesToRemove = addDives(divesToAdd); mark_divelist_changed(true); // Finally, do the UI stuff: MainWindow::instance()->dive_list()->unselectDives(); - MainWindow::instance()->dive_list()->selectDive(diveToAdd.idx, true); - MainWindow::instance()->refreshDisplay(); + MainWindow::instance()->dive_list()->selectDive(idx, true); + + // Exit from edit mode, but don't recalculate dive list + // TODO: Remove edit mode + MainWindow::instance()->refreshDisplay(false); } void AddDive::undo() { // Simply remove the dive that was previously added - diveToAdd = removeDive(diveToRemove); + divesToAdd = removeDives(divesToRemove); - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); + // Exit from edit mode, but don't recalculate dive list + // TODO: Remove edit mode + MainWindow::instance()->refreshDisplay(false); } DeleteDive::DeleteDive(const QVector<struct dive*> &divesToDeleteIn) : divesToDelete(divesToDeleteIn.toStdVector()) @@ -189,20 +344,13 @@ bool DeleteDive::workToBeDone() void DeleteDive::undo() { divesToDelete = addDives(divesToAdd); - mark_divelist_changed(true); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); } void DeleteDive::redo() { divesToAdd = removeDives(divesToDelete); mark_divelist_changed(true); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); } @@ -212,20 +360,30 @@ ShiftTime::ShiftTime(const QVector<dive *> &changedDives, int amount) setText(tr("shift time of %n dives", "", changedDives.count())); } -void ShiftTime::undo() +void ShiftTime::redo() { for (dive *d: diveList) d->when -= timeChanged; // Changing times may have unsorted the dive table sort_table(&dive_table); - mark_divelist_changed(true); + + // We send one dives-deleted signal per trip (see comments in DiveListNotifier.h). + // Therefore, collect all dives in a array and sort by trip. + std::vector<std::pair<dive_trip *, dive *>> dives; + dives.reserve(diveList.size()); + for (dive *d: diveList) + dives.push_back({ d->divetrip, d }); + + // Send signals. + processByTrip(dives, [&](dive_trip *trip, const QVector<dive *> &divesInTrip) { + emit diveListNotifier.divesTimeChanged(trip, timeChanged, divesInTrip); + }); // Negate the time-shift so that the next call does the reverse timeChanged = -timeChanged; - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); + mark_divelist_changed(true); } bool ShiftTime::workToBeDone() @@ -233,10 +391,10 @@ bool ShiftTime::workToBeDone() return !diveList.isEmpty(); } -void ShiftTime::redo() +void ShiftTime::undo() { - // Same as undo(), since after undo() we reversed the timeOffset - undo(); + // Same as redo(), since after redo() we reversed the timeOffset + redo(); } @@ -249,9 +407,6 @@ void RenumberDives::undo() { renumberDives(divesToRenumber); mark_divelist_changed(true); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); } bool RenumberDives::workToBeDone() @@ -275,9 +430,6 @@ void TripBase::redo() moveDivesBetweenTrips(divesToMove); mark_divelist_changed(true); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); } void TripBase::undo() @@ -393,10 +545,6 @@ void SplitDives::redo() divesToUnsplit[1] = addDive(splitDives[1]); unsplitDive = removeDive(diveToSplit); mark_divelist_changed(true); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); - MainWindow::instance()->refreshProfile(); } void SplitDives::undo() @@ -408,10 +556,6 @@ void SplitDives::undo() splitDives[1] = removeDive(divesToUnsplit[1]); splitDives[0] = removeDive(divesToUnsplit[0]); mark_divelist_changed(true); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); - MainWindow::instance()->refreshProfile(); } MergeDives::MergeDives(const QVector <dive *> &dives) @@ -503,10 +647,6 @@ void MergeDives::redo() renumberDives(divesToRenumber); diveToUnmerge = addDive(mergedDive); unmergedDives = removeDives(divesToMerge); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); - MainWindow::instance()->refreshProfile(); } void MergeDives::undo() @@ -514,10 +654,6 @@ void MergeDives::undo() divesToMerge = addDives(unmergedDives); mergedDive = removeDive(diveToUnmerge); renumberDives(divesToRenumber); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); - MainWindow::instance()->refreshProfile(); } } // namespace Command diff --git a/desktop-widgets/command_divelist.h b/desktop-widgets/command_divelist.h index 8cff4f1ef..e09d3bdc6 100644 --- a/desktop-widgets/command_divelist.h +++ b/desktop-widgets/command_divelist.h @@ -47,10 +47,12 @@ private: bool workToBeDone() override; // For redo - DiveToAdd diveToAdd; + // Note: we use a vector even though we add only a single dive, so + // that we can reuse the multi-dive functions of the other commands. + std::vector<DiveToAdd> divesToAdd; // For undo - dive *diveToRemove; + std::vector<dive *> divesToRemove; }; class DeleteDive : public Base { diff --git a/desktop-widgets/divelistview.cpp b/desktop-widgets/divelistview.cpp index 4d68baca2..e8c6ea0dc 100644 --- a/desktop-widgets/divelistview.cpp +++ b/desktop-widgets/divelistview.cpp @@ -668,11 +668,6 @@ void DiveListView::merge_trip(const QModelIndex &a, int offset) if (trip_a == trip_b || !trip_a || !trip_b) return; Command::mergeTrips(trip_a, trip_b); - rememberSelection(); - reload(currentLayout, false); - restoreSelection(); - mark_divelist_changed(true); - //TODO: emit a signal to signalize that the divelist changed? } void DiveListView::mergeTripAbove() @@ -696,11 +691,6 @@ void DiveListView::removeFromTrip() divesToRemove.append(d); } Command::removeDivesFromTrip(divesToRemove); - - rememberSelection(); - reload(currentLayout, false); - restoreSelection(); - mark_divelist_changed(true); } void DiveListView::newTripAbove() @@ -717,10 +707,6 @@ void DiveListView::newTripAbove() dives.append(d); } Command::createTrip(dives); - - reload(currentLayout, false); - mark_divelist_changed(true); - restoreSelection(); } void DiveListView::addToTripBelow() @@ -765,9 +751,6 @@ void DiveListView::addToTrip(int delta) } } Command::addDivesToTrip(dives, trip); - - reload(currentLayout, false); - restoreSelection(); } void DiveListView::markDiveInvalid() @@ -783,9 +766,6 @@ void DiveListView::markDiveInvalid() // now mark the dive invalid... how do we do THAT? // d->invalid = true; } - if (amount_selected == 0) { - MainWindow::instance()->cleanUpEmpty(); - } mark_divelist_changed(true); MainWindow::instance()->refreshDisplay(); if (prefs.display_invalid_dives == false) { @@ -802,26 +782,12 @@ void DiveListView::deleteDive() return; int i; - int lastDiveNr = -1; QVector<struct dive*> deletedDives; for_each_dive (i, d) { - if (!d->selected) - continue; - deletedDives.append(d); - lastDiveNr = i; + if (d->selected) + deletedDives.append(d); } - // the actual dive deletion is happening in the redo command that is implicitly triggered Command::deleteDive(deletedDives); - if (amount_selected == 0) { - MainWindow::instance()->cleanUpEmpty(); - } - mark_divelist_changed(true); - MainWindow::instance()->refreshDisplay(); - if (lastDiveNr != -1) { - clearSelection(); - selectDive(lastDiveNr); - rememberSelection(); - } } void DiveListView::contextMenuEvent(QContextMenuEvent *event) diff --git a/desktop-widgets/mainwindow.cpp b/desktop-widgets/mainwindow.cpp index d55913e25..05839824a 100644 --- a/desktop-widgets/mainwindow.cpp +++ b/desktop-widgets/mainwindow.cpp @@ -36,6 +36,8 @@ #include "core/settings/qPrefPartialPressureGas.h" #include "core/settings/qPrefTechnicalDetails.h" +#include "core/subsurface-qt/DiveListNotifier.h" + #include "desktop-widgets/about.h" #include "desktop-widgets/command.h" #include "desktop-widgets/divecomputermanagementdialog.h" @@ -492,8 +494,6 @@ void MainWindow::refreshDisplay(bool doRecreateDiveList) dive_list()->setFocus(); WSInfoModel::instance()->updateInfo(); ui.actionAutoGroup->setChecked(autogroup); - if (amount_selected == 0) - cleanUpEmpty(); } void MainWindow::recreateDiveList() diff --git a/desktop-widgets/simplewidgets.cpp b/desktop-widgets/simplewidgets.cpp index 72a81d873..1df69e7bb 100644 --- a/desktop-widgets/simplewidgets.cpp +++ b/desktop-widgets/simplewidgets.cpp @@ -172,9 +172,6 @@ void RenumberDialog::buttonClicked(QAbstractButton *button) } } Command::renumberDives(renumberedDives); - - mark_divelist_changed(true); - MainWindow::instance()->dive_list()->restoreSelection(); } } diff --git a/desktop-widgets/tab-widgets/maintab.cpp b/desktop-widgets/tab-widgets/maintab.cpp index 46217af54..1f4fbc518 100644 --- a/desktop-widgets/tab-widgets/maintab.cpp +++ b/desktop-widgets/tab-widgets/maintab.cpp @@ -809,7 +809,6 @@ void MainTab::acceptChanges() acceptingEdit = false; ui.editDiveSiteButton->setEnabled(!ui.location->text().isEmpty()); emit addDiveFinished(); - MainWindow::instance()->dive_list()->reload(DiveTripModel::CURRENT, true); DivePlannerPointsModel::instance()->setPlanMode(DivePlannerPointsModel::NOTHING); int scrolledBy = MainWindow::instance()->dive_list()->verticalScrollBar()->sliderPosition(); MainWindow::instance()->dive_list()->verticalScrollBar()->setSliderPosition(scrolledBy); diff --git a/qt-models/divetripmodel.cpp b/qt-models/divetripmodel.cpp index 406c5eee6..7a2c6d68d 100644 --- a/qt-models/divetripmodel.cpp +++ b/qt-models/divetripmodel.cpp @@ -5,6 +5,7 @@ #include "core/divelist.h" #include "core/qthelper.h" #include "core/subsurface-string.h" +#include "core/subsurface-qt/DiveListNotifier.h" #include <QIcon> #include <QDebug> @@ -431,6 +432,12 @@ DiveTripModel::DiveTripModel(QObject *parent) : QAbstractItemModel(parent), currentLayout(TREE) { + // Stay informed of changes to the divelist + connect(&diveListNotifier, &DiveListNotifier::divesAdded, this, &DiveTripModel::divesAdded); + connect(&diveListNotifier, &DiveListNotifier::divesDeleted, this, &DiveTripModel::divesDeleted); + connect(&diveListNotifier, &DiveListNotifier::divesChanged, this, &DiveTripModel::divesChanged); + connect(&diveListNotifier, &DiveListNotifier::divesMovedBetweenTrips, this, &DiveTripModel::divesMovedBetweenTrips); + connect(&diveListNotifier, &DiveListNotifier::divesTimeChanged, this, &DiveTripModel::divesTimeChanged); } int DiveTripModel::columnCount(const QModelIndex&) const @@ -627,6 +634,11 @@ QVariant DiveTripModel::headerData(int section, Qt::Orientation orientation, int return ret; } +DiveTripModel::Item::Item(dive_trip *t, const QVector<dive *> &divesIn) : trip(t), + dives(divesIn.toStdVector()) +{ +} + DiveTripModel::Item::Item(dive_trip *t, dive *d) : trip(t), dives({ d }) { @@ -637,6 +649,108 @@ DiveTripModel::Item::Item(dive *d) : trip(nullptr), { } +bool DiveTripModel::Item::isDive(const dive *d) const +{ + return !trip && dives.size() == 1 && dives[0] == d; +} + +dive *DiveTripModel::Item::getDive() const +{ + return !trip && dives.size() == 1 ? dives[0] : nullptr; +} + +timestamp_t DiveTripModel::Item::when() const +{ + return trip ? trip->when : dives[0]->when; +} + +// 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); + }); +} + void DiveTripModel::setupModelData() { int i = dive_table.nr; @@ -727,3 +841,272 @@ bool DiveTripModel::setData(const QModelIndex &index, const QVariant &value, int dive *d = diveOrNull(index); return d ? DiveItem(d).setData(index, value, role) : false; } + +int DiveTripModel::findTripIdx(const dive_trip *trip) const +{ + for (int i = 0; i < (int)items.size(); ++i) + if (items[i].trip == trip) + return i; + return -1; +} + +int DiveTripModel::findDiveIdx(const dive *d) const +{ + for (int i = 0; i < (int)items.size(); ++i) + if (items[i].isDive(d)) + return i; + return -1; +} + +int DiveTripModel::findDiveInTrip(int tripIdx, const dive *d) const +{ + const Item &item = items[tripIdx]; + for (int i = 0; i < (int)item.dives.size(); ++i) + if (item.dives[i] == d) + return i; + return -1; +} + +int DiveTripModel::findInsertionIndex(timestamp_t when) const +{ + for (int i = 0; i < (int)items.size(); ++i) { + if (when > items[i].when()) + return i; + } + return items.size(); +} + +// 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[i], 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; + } +} + +void DiveTripModel::addDivesToTrip(int trip, const QVector<dive *> &dives) +{ + // Construct the parent index, ie. the index of the trip. + QModelIndex parent = createIndex(trip, 0, noParent); + + // Either this is outside of a trip or we're in list mode. + // Thus, add dives at the top-level in batches + addInBatches(items[trip].dives, dives, + [](dive *d, dive *d2) { return d->when >= d2->when; }, // 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); + endInsertRows(); + }); +} + +void DiveTripModel::divesAdded(dive_trip *trip, bool addTrip, const QVector<dive *> &divesIn) +{ + // The dives come from the backend sorted by start-time. But our model is sorted + // reverse-chronologically. Therefore, invert the list. + // TODO: Change sorting of the model to reflect core! + QVector<dive *> dives = divesIn; + std::reverse(dives.begin(), dives.end()); + + if (!trip || currentLayout == LIST) { + // Either this is outside of a trip or we're in list mode. + // Thus, add dives at the top-level in batches + addInBatches(items, dives, + [](dive *d, const Item &entry) { return d->when >= entry.when(); }, // comp + [&](std::vector<Item> &items, const QVector<dive *> &dives, int idx, int from, int to) { // inserter + beginInsertRows(QModelIndex(), idx, idx + to - from - 1); + items.insert(items.begin() + idx, dives.begin() + from, dives.begin() + to); + endInsertRows(); + }); + } else if (addTrip) { + // We're supposed to add the whole trip. Just insert the trip. + int idx = findInsertionIndex(trip->when); // Find the place where we have to insert the thing + beginInsertRows(QModelIndex(), idx, idx); + items.insert(items.begin() + idx, { trip, dives }); + endInsertRows(); + } else { + // Ok, we have to add dives to an existing trip + // Find the trip... + int idx = findTripIdx(trip); + if (idx < 0) { + // We don't know the trip - this shouldn't happen. We seem to have + // missed some signals! + qWarning() << "DiveTripModel::divesAdded(): unknown trip"; + return; + } + + // ...and add dives. + addDivesToTrip(idx, dives); + + // We have to signal that the trip changed, so that the number of dives in th header is updated + QModelIndex tripIndex = createIndex(idx, 0, noParent); + dataChanged(tripIndex, tripIndex); + } +} + +void DiveTripModel::divesDeleted(dive_trip *trip, bool deleteTrip, const QVector<dive *> &divesIn) +{ + // TODO: dives comes sorted by ascending time, but the model is sorted by descending time. + // Instead of being smart, simple reverse the input array. + QVector<dive *> dives = divesIn; + std::reverse(dives.begin(), dives.end()); + + if (!trip || currentLayout == LIST) { + // Either this is outside of a trip or we're in list mode. + // Thus, delete top-level dives. We do this range-wise. + processRangesZip(items, dives, + [](const Item &e, dive *d) { return e.getDive() == d; }, // Condition + [&](std::vector<Item> &items, const QVector<dive *> &, int from, int to, int) -> int { // Action + beginRemoveRows(QModelIndex(), from, to - 1); + items.erase(items.begin() + from, items.begin() + to); + endRemoveRows(); + return from - to; // Delta: negate the number of items deleted + }); + } else { + // Find the trip + int idx = findTripIdx(trip); + if (idx < 0) { + // We don't know the trip - this shouldn't happen. We seem to have + // missed some signals! + qWarning() << "DiveTripModel::divesDeleted(): unknown trip"; + return; + } + + if (deleteTrip) { + // We're supposed to delete the whole trip. Nice, we don't have to + // care about individual dives. Just remove the row. + beginRemoveRows(QModelIndex(), idx, idx); + items.erase(items.begin() + idx); + endRemoveRows(); + } else { + // Construct the parent index, ie. the index of the trip. + QModelIndex parent = createIndex(idx, 0, noParent); + + // Delete a number of dives in a trip. We do this range-wise. + processRangesZip(items[idx].dives, dives, + [](dive *d1, dive *d2) { return d1 == d2; }, // Condition + [&](std::vector<dive *> &diveList, const QVector<dive *> &, int from, int to, int) -> int { // Action + beginRemoveRows(parent, from, to - 1); + diveList.erase(diveList.begin() + from, diveList.begin() + to); + endRemoveRows(); + return from - to; // Delta: negate the number of items deleted + }); + + // We have to signal that the trip changed, so that the number of dives in th header is updated + QModelIndex tripIndex = createIndex(idx, 0, noParent); + dataChanged(tripIndex, tripIndex); + } + } +} + +void DiveTripModel::divesChanged(dive_trip *trip, const QVector<dive *> &divesIn) +{ + // TODO: dives comes sorted by ascending time, but the model is sorted by descending time. + // Instead of being smart, simple reverse the input array. + QVector<dive *> dives = divesIn; + std::reverse(dives.begin(), dives.end()); + + if (!trip || currentLayout == LIST) { + // Either this is outside of a trip or we're in list mode. + // Thus, these are top-level dives. We do this range-wise. + + // Since we know that the dive list is sorted, we will only ever search for the first element + // in dives as this must be the first that we encounter. Once we find a range, increase the + // index accordingly. + processRangesZip(items, dives, + [](const Item &e, dive *d) { return e.getDive() == d; }, // Condition + [&](const std::vector<Item> &, const QVector<dive *> &, int from, int to, int) -> int { // Action + // TODO: We might be smarter about which columns changed! + dataChanged(createIndex(from, 0, noParent), createIndex(to - 1, COLUMNS - 1, noParent)); + return 0; // No items added or deleted + }); + } else { + // Find the trip. + int idx = findTripIdx(trip); + if (idx < 0) { + // We don't know the trip - this shouldn't happen. We seem to have + // missed some signals! + qWarning() << "DiveTripModel::divesChanged(): unknown trip"; + return; + } + + // Change the dives in the trip. We do this range-wise. + processRangesZip(items[idx].dives, dives, + [](dive *d1, dive *d2) { return d1 == d2; }, // Condition + [&](const std::vector<dive *> &, const QVector<dive *> &, int from, int to, int) -> int { // Action + // TODO: We might be smarter about which columns changed! + dataChanged(createIndex(from, 0, idx), createIndex(to - 1, COLUMNS - 1, idx)); + return 0; // No items added or deleted + }); + } +} + +void DiveTripModel::divesMovedBetweenTrips(dive_trip *from, dive_trip *to, bool deleteFrom, bool createTo, const QVector<dive *> &dives) +{ + // Move dives between trips. This is an "interesting" problem, as we might + // move from trip to trip, from trip to top-level or from top-level to trip. + // Moreover, we might have to add a trip first or delete an old trip. + // For simplicity, we will simply used the already existing divesAdded() / divesDeleted() + // functions. This *is* cheating. But let's just try this and see how graceful + // this is handled by Qt and if it gives some ugly UI behavior! + + // But first let's just rule out the trivial cases: same-to-same trip move + // and list view (in which case we don't care). + if (from == to || currentLayout == LIST) + return; + + // Cheating! + divesAdded(to, createTo, dives); + divesDeleted(from, deleteFrom, dives); +} + +void DiveTripModel::divesTimeChanged(dive_trip *trip, timestamp_t delta, const QVector<dive *> &dives) +{ + // As in the case of divesMovedBetweenTrips(), this is a tricky, but solvable, problem. + // We have to consider the direction (delta < 0 or delta >0) and that dives at their destination + // position have different contiguous batches than at their original position. For now, + // cheat and simply do a remove/add pair. Note that for this to work it is crucial the the + // order of the dives don't change. This is indeed the case, as all starting-times where + // moved by the same delta. + + // Unfortunately, deleting of the dives clears current_dive, so we have to remember it. + // TODO: remove this hack! + dive *current = current_dive; + + // Cheating! + divesDeleted(trip, false, dives); + divesAdded(trip, false, dives); + + // Now, restore current_dive + // TODO: remove this hack! + selected_dive = get_divenr(current); +} diff --git a/qt-models/divetripmodel.h b/qt-models/divetripmodel.h index f6125d196..a298b1e72 100644 --- a/qt-models/divetripmodel.h +++ b/qt-models/divetripmodel.h @@ -108,7 +108,12 @@ public: int rowCount(const QModelIndex &parent) const; QModelIndex index(int row, int column, const QModelIndex &parent) const; QModelIndex parent(const QModelIndex &index) const; - +private 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); + void divesMovedBetweenTrips(dive_trip *from, dive_trip *to, bool deleteFrom, bool createTo, const QVector<dive *> &dives); private: // The model has up to 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" @@ -121,11 +126,24 @@ private: // one element, which is the corresponding dive. struct Item { dive_trip *trip; - QVector<dive *> dives; - Item(dive_trip *t, dive *d); // Initialize a trip with one dive - Item(dive *d); // Initialize a top-level dive + std::vector<dive *> dives; // std::vector<> instead of QVector for insert() with three iterators + Item(dive_trip *t, const QVector<dive *> &dives); + Item(dive_trip *t, dive *d); // Initialize a trip with one dive + Item(dive *d); // Initialize a top-level dive + bool isDive(const dive *) const; // Helper function: is this the give dive? + dive *getDive() const; // Helper function: returns top-level-dive or null + timestamp_t when() const; // Helper function: start time of dive *or* trip }; + // Access trips and dives + int findTripIdx(const dive_trip *trip) const; + int findDiveIdx(const dive *d) const; // Find _top_level_ dive + int findDiveInTrip(int tripIdx, const dive *d) const; // Find dive inside trip. Second parameter is index of trip + int findInsertionIndex(timestamp_t when) const; // Where to insert item with timestamp "when" + + // Addition and deletion of dives + void addDivesToTrip(int idx, const QVector<dive *> &dives); + dive *diveOrNull(const QModelIndex &index) const; // Returns a dive if this index represents a dive, null otherwise QPair<dive_trip *, dive *> tripOrDive(const QModelIndex &index) const; // Returns either a pointer to a trip or a dive, or twice null of index is invalid |