diff options
author | Berthold Stoeger <bstoeger@mail.tuwien.ac.at> | 2018-07-23 23:41:23 +0200 |
---|---|---|
committer | Dirk Hohndel <dirk@hohndel.org> | 2018-10-11 16:22:27 -0700 |
commit | 43c3885249fb867e7c33c8b3b5846d44e908774f (patch) | |
tree | 3675041ca82295a94c3bc48e9812e26543faacae | |
parent | f427226b3b605523bc8285dbdaaa7f6993af6e6a (diff) | |
download | subsurface-43c3885249fb867e7c33c8b3b5846d44e908774f.tar.gz |
Undo: isolate undo-commands
This refactors the undo-commands (which are now only "commands").
- Move everything in namespace Command. This allows shortening of
names without polluting the global namespace. Moreover, the prefix
Command:: will immediately signal that the undo-machinery is
invoked. This is more terse than UndoCommands::instance()->...
- Remove the Undo in front of the class-names. Creating an "UndoX"
object to do "X" is paradoxical.
- Create a base class for all commands that defines the Qt-translation
functions. Thus all translations end up in the "Command" context.
- Add a workToBeDone() function, which signals whether this should be
added to the UndoStack. Thus the caller doesn't have to check itself
whether this any work will be done. Note: Qt5.9 introduces "setObsolete"
which does the same.
- Split into public and internal header files. In the public header
file only export the function calls, thus hiding all implementation
details from the caller.
- Split in different translation units: One for the stubs, one for
the base classes and one for groups of commands. Currently, there
is only one class of commands: divelist-commands.
- Move the undoStack from the MainWindow class into commands_base.cpp.
If we want to implement MDI, this can easily be moved into an
appropriate Document class.
Signed-off-by: Berthold Stoeger <bstoeger@mail.tuwien.ac.at>
-rw-r--r-- | desktop-widgets/CMakeLists.txt | 4 | ||||
-rw-r--r-- | desktop-widgets/command.cpp | 69 | ||||
-rw-r--r-- | desktop-widgets/command.h | 33 | ||||
-rw-r--r-- | desktop-widgets/command_base.cpp | 35 | ||||
-rw-r--r-- | desktop-widgets/command_base.h (renamed from desktop-widgets/undocommands.h) | 173 | ||||
-rw-r--r-- | desktop-widgets/command_divelist.cpp | 589 | ||||
-rw-r--r-- | desktop-widgets/command_divelist.h | 172 | ||||
-rw-r--r-- | desktop-widgets/divelistview.cpp | 34 | ||||
-rw-r--r-- | desktop-widgets/divelogimportdialog.cpp | 3 | ||||
-rw-r--r-- | desktop-widgets/downloadfromdivecomputer.cpp | 4 | ||||
-rw-r--r-- | desktop-widgets/mainwindow.cpp | 17 | ||||
-rw-r--r-- | desktop-widgets/mainwindow.h | 2 | ||||
-rw-r--r-- | desktop-widgets/simplewidgets.cpp | 7 | ||||
-rw-r--r-- | desktop-widgets/tab-widgets/maintab.cpp | 7 | ||||
-rw-r--r-- | desktop-widgets/undocommands.cpp | 493 | ||||
-rw-r--r-- | profile-widget/profilewidget2.cpp | 5 |
16 files changed, 471 insertions, 1176 deletions
diff --git a/desktop-widgets/CMakeLists.txt b/desktop-widgets/CMakeLists.txt index f5da2ae84..519061ac0 100644 --- a/desktop-widgets/CMakeLists.txt +++ b/desktop-widgets/CMakeLists.txt @@ -85,7 +85,9 @@ set(SUBSURFACE_INTERFACE divepicturewidget.cpp usersurvey.cpp configuredivecomputerdialog.cpp - undocommands.cpp + command.cpp + command_base.cpp + command_divelist.cpp locationinformation.cpp qtwaitingspinner.cpp tab-widgets/TabDiveStatistics.cpp diff --git a/desktop-widgets/command.cpp b/desktop-widgets/command.cpp new file mode 100644 index 000000000..a86b1fe76 --- /dev/null +++ b/desktop-widgets/command.cpp @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include "command.h" +#include "command_divelist.h" + +namespace Command { + +// Dive-list related commands +void addDive(dive *d) +{ + execute(new AddDive(d)); +} + +void deleteDive(const QVector<struct dive*> &divesToDelete) +{ + execute(new DeleteDive(divesToDelete)); +} + +void shiftTime(const QVector<dive *> &changedDives, int amount) +{ + execute(new ShiftTime(changedDives, amount)); +} + +void renumberDives(const QVector<QPair<int, int>> &divesToRenumber) +{ + execute(new RenumberDives(divesToRenumber)); +} + +void removeDivesFromTrip(const QVector<dive *> &divesToRemove) +{ + execute(new RemoveDivesFromTrip(divesToRemove)); +} + +void removeAutogenTrips() +{ + execute(new RemoveAutogenTrips); +} + +void addDivesToTrip(const QVector<dive *> &divesToAddIn, dive_trip *trip) +{ + execute(new AddDivesToTrip(divesToAddIn, trip)); +} + +void createTrip(const QVector<dive *> &divesToAddIn) +{ + execute(new CreateTrip(divesToAddIn)); +} + +void autogroupDives() +{ + execute(new AutogroupDives); +} + +void mergeTrips(dive_trip *trip1, dive_trip *trip2) +{ + execute(new MergeTrips(trip1, trip2)); +} + +void splitDives(dive *d, duration_t time) +{ + execute(new SplitDives(d, time)); +} + +void mergeDives(const QVector <dive *> &dives) +{ + execute(new MergeDives(dives)); +} + +} // namespace Command diff --git a/desktop-widgets/command.h b/desktop-widgets/command.h new file mode 100644 index 000000000..213d8bcda --- /dev/null +++ b/desktop-widgets/command.h @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0 +#ifndef COMMAND_H +#define COMMAND_H + +#include "core/dive.h" +#include <QVector> +#include <QAction> + +// We put everything in a namespace, so that we can shorten names without polluting the global namespace +namespace Command { + +// General commands +void clear(); // Reset the undo stack. Delete all commands. +QAction *undoAction(QObject *parent); // Create an undo action. +QAction *redoAction(QObject *parent); // Create an redo action. + +// Dive-list related commands +void addDive(dive *d); +void deleteDive(const QVector<struct dive*> &divesToDelete); +void shiftTime(const QVector<dive *> &changedDives, int amount); +void renumberDives(const QVector<QPair<int, int>> &divesToRenumber); +void removeDivesFromTrip(const QVector<dive *> &divesToRemove); +void removeAutogenTrips(); +void addDivesToTrip(const QVector<dive *> &divesToAddIn, dive_trip *trip); +void createTrip(const QVector<dive *> &divesToAddIn); +void autogroupDives(); +void mergeTrips(dive_trip *trip1, dive_trip *trip2); +void splitDives(dive *d, duration_t time); +void mergeDives(const QVector <dive *> &dives); + +} // namespace Command + +#endif // COMMAND_H diff --git a/desktop-widgets/command_base.cpp b/desktop-widgets/command_base.cpp new file mode 100644 index 000000000..24ce81225 --- /dev/null +++ b/desktop-widgets/command_base.cpp @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include "command_base.h" + +namespace Command { + +static QUndoStack undoStack; + +// General commands +void clear() +{ + undoStack.clear(); +} + +QAction *undoAction(QObject *parent) +{ + return undoStack.createUndoAction(parent, QCoreApplication::translate("Command", "&Undo")); +} + +QAction *redoAction(QObject *parent) +{ + return undoStack.createRedoAction(parent, QCoreApplication::translate("Command", "&Redo")); +} + +void execute(Base *cmd) +{ + if (cmd->workToBeDone()) + undoStack.push(cmd); + else + delete cmd; +} + +} // namespace Command + + diff --git a/desktop-widgets/undocommands.h b/desktop-widgets/command_base.h index 11c35bb40..f965b8689 100644 --- a/desktop-widgets/undocommands.h +++ b/desktop-widgets/command_base.h @@ -1,15 +1,16 @@ // SPDX-License-Identifier: GPL-2.0 -#ifndef UNDOCOMMANDS_H -#define UNDOCOMMANDS_H +// Note: this header file is used by the undo-machinery and should not be included elsewhere. + +#ifndef COMMAND_BASE_H +#define COMMAND_BASE_H #include "core/dive.h" #include <QUndoCommand> -#include <QCoreApplication> // For Q_DECLARE_TR_FUNCTIONS -#include <QVector> +#include <QCoreApplication> // For Q_DECLARE_TR_FUNCTIONS #include <memory> -// The classes declared in this file represent units-of-work, which can be exectuted / undone +// The classes derived from Command::Base represent units-of-work, which can be exectuted / undone // repeatedly. The command objects are collected in a linear list implemented in the QUndoStack class. // They contain the information that is necessary to either perform or undo the unit-of-work. // The usage is: @@ -136,6 +137,9 @@ // v.clear(v); // Reset the vector to zero length. If the elements weren't release()d, // // the pointed-to dives are freed with free_dive() +// We put everything in a namespace, so that we can shorten names without polluting the global namespace +namespace Command { + // Classes used to automatically call free_dive()/free_trip for owning pointers that go out of scope. struct DiveDeleter { void operator()(dive *d) { free_dive(d); } @@ -148,157 +152,22 @@ struct TripDeleter { typedef std::unique_ptr<dive, DiveDeleter> OwningDivePtr; typedef std::unique_ptr<dive_trip, TripDeleter> OwningTripPtr; -// This helper structure describes a dive that we want to add. -// Potentially it also adds a trip (if deletion of the dive resulted in deletion of the trip) -struct DiveToAdd { - OwningDivePtr dive; // Dive to add - OwningTripPtr tripToAdd; // Not-null if we also have to add a dive - dive_trip *trip; // Trip the dive belongs to, may be null - int idx; // Position in divelist -}; - -// This helper structure describes a dive that should be moved to / removed from -// a trip. If the "trip" member is null, the dive is removed from its trip (if -// it is in a trip, that is) -struct DiveToTrip -{ - struct dive *dive; - dive_trip *trip; -}; - -// This helper structure describes a number of dives to add to /remove from / -// move between trips. -// It has ownership of the trips (if any) that have to be added before hand. -struct DivesToTrip -{ - std::vector<DiveToTrip> divesToMove; // If dive_trip is null, remove from trip - std::vector<OwningTripPtr> tripsToAdd; -}; - -class UndoAddDive : public QUndoCommand { -public: - UndoAddDive(dive *dive); -private: - void undo() override; - void redo() override; - - // For redo - DiveToAdd diveToAdd; - - // For undo - dive *diveToRemove; -}; - -class UndoDeleteDive : public QUndoCommand { +// This is the base class of all commands. +// It defines the Qt-translation functions +class Base : public QUndoCommand { Q_DECLARE_TR_FUNCTIONS(Command) public: - UndoDeleteDive(const QVector<dive *> &divesToDelete); -private: - void undo() override; - void redo() override; - - // For redo - std::vector<struct dive*> divesToDelete; - - std::vector<OwningTripPtr> tripsToAdd; - std::vector<DiveToAdd> divesToAdd; + // Check whether work is to be done. + // TODO: replace by setObsolete (>Qt5.9) + virtual bool workToBeDone() = 0; }; -class UndoShiftTime : public QUndoCommand { - Q_DECLARE_TR_FUNCTIONS(Command) -public: - UndoShiftTime(const QVector<dive *> &changedDives, int amount); -private: - void undo() override; - void redo() override; +// Put a command on the undoStack, but test whether there is something to be done +// beforehand by calling the workToBeDone() function. If nothing is to be done, +// the command will be deleted. +void execute(Base *cmd); - // For redo and undo - QVector<dive *> diveList; - int timeChanged; -}; +} // namespace Command -class UndoRenumberDives : public QUndoCommand { - Q_DECLARE_TR_FUNCTIONS(Command) -public: - UndoRenumberDives(const QVector<QPair<int, int>> &divesToRenumber); -private: - void undo() override; - void redo() override; - - // For redo and undo: pairs of dive-id / new number - QVector<QPair<int, int>> divesToRenumber; -}; - -// The classes UndoRemoveDivesFromTrip, UndoRemoveAutogenTrips, UndoCreateTrip, -// UndoAutogroupDives and UndoMergeTrips all do the same thing, just the intialization -// differs. Therefore, define a base class with the proper data-structures, redo() -// and undo() functions and derive to specialize the initialization. -class UndoTripBase : public QUndoCommand { - Q_DECLARE_TR_FUNCTIONS(Command) -protected: - void undo() override; - void redo() override; - - // For redo and undo - DivesToTrip divesToMove; -}; -struct UndoRemoveDivesFromTrip : public UndoTripBase { - UndoRemoveDivesFromTrip(const QVector<dive *> &divesToRemove); -}; -struct UndoRemoveAutogenTrips : public UndoTripBase { - UndoRemoveAutogenTrips(); -}; -struct UndoAddDivesToTrip : public UndoTripBase { - UndoAddDivesToTrip(const QVector<dive *> &divesToAdd, dive_trip *trip); -}; -struct UndoCreateTrip : public UndoTripBase { - UndoCreateTrip(const QVector<dive *> &divesToAdd); -}; -struct UndoAutogroupDives : public UndoTripBase { - UndoAutogroupDives(); -}; -struct UndoMergeTrips : public UndoTripBase { - UndoMergeTrips(dive_trip *trip1, dive_trip *trip2); -}; - -class UndoSplitDives : public QUndoCommand { -public: - // If time is < 0, split at first surface interval - UndoSplitDives(dive *d, duration_t time); -private: - void undo() override; - void redo() override; - - // For redo - // For each dive to split, we remove one from and put two dives into the backend - dive *diveToSplit; - DiveToAdd splitDives[2]; - - // For undo - // For each dive to unsplit, we remove two dives from and add one into the backend - DiveToAdd unsplitDive; - dive *divesToUnsplit[2]; -}; - -class UndoMergeDives : public QUndoCommand { -public: - UndoMergeDives(const QVector<dive *> &dives); -private: - void undo() override; - void redo() override; - - // For redo - // Add one and remove a batch of dives - DiveToAdd mergedDive; - std::vector<dive *> divesToMerge; - - // For undo - // Remove one and add a batch of dives - dive *diveToUnmerge; - std::vector<DiveToAdd> unmergedDives; - - // For undo and redo - QVector<QPair<int, int>> divesToRenumber; -}; +#endif // COMMAND_BASE_H -#endif // UNDOCOMMANDS_H diff --git a/desktop-widgets/command_divelist.cpp b/desktop-widgets/command_divelist.cpp index 6f638b2a6..d12aebfc2 100644 --- a/desktop-widgets/command_divelist.cpp +++ b/desktop-widgets/command_divelist.cpp @@ -4,60 +4,14 @@ #include "desktop-widgets/mainwindow.h" #include "desktop-widgets/divelistview.h" #include "core/divelist.h" -#include "core/display.h" // for amount_selected -#include "core/subsurface-qt/DiveListNotifier.h" -#include "qt-models/filtermodels.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! -DiveToAdd DiveListBase::removeDive(struct dive *d) -{ - // If the dive to be removed is selected, we will inform the frontend - // later via a signal that the dive changed. - if (d->selected) - selectionChanged = true; - - // If the dive was the current dive, reset the current dive. The calling - // command is responsible of finding a new dive. - if (d == current_dive) { - selectionChanged = true; // Should have been set above, as current dive is always selected. - current_dive = nullptr; - } - +static DiveToAdd removeDive(struct dive *d) +{ DiveToAdd res; res.idx = get_divenr(d); if (res.idx < 0) @@ -72,68 +26,37 @@ DiveToAdd DiveListBase::removeDive(struct dive *d) } res.dive.reset(unregister_dive(res.idx)); // Remove dive from backend - return res; } // This helper function adds a dive and returns ownership to the backend. It may also add a dive trip. // It is crucial that dives are added in reverse order of deletion (see comment above)! // Returns pointer to added dive (which is owned by the backend!) -dive *DiveListBase::addDive(DiveToAdd &d) +static dive *addDive(DiveToAdd &d) { - if (d.tripToAdd) - insert_trip_dont_merge(d.tripToAdd.release()); // Return ownership to backend + if (d.tripToAdd) { + dive_trip *t = d.tripToAdd.release(); // Give up ownership of trip + insert_trip(&t); // 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 - - // Set the filter flag according to current filter settings - bool show = MultiFilterSortModel::instance()->showDive(res); - res->hidden_by_filter = !show; - - add_single_dive(d.idx, res); // Return ownership to backend - - // If the dive to be removed is selected, we will inform the frontend - // later via a signal that the dive changed. - if (res->selected) - selectionChanged = true; - + dive *res = d.dive.release(); // Give up ownership of dive + add_single_dive(d.idx, res); // Return ownership to backend return res; } // This helper function calls removeDive() on a list of dives to be removed and // returns a vector of corresponding DiveToAdd objects, which can later be readded. // The passed in vector is cleared. -std::vector<DiveToAdd> DiveListBase::removeDives(std::vector<dive *> &divesToDelete) +static std::vector<DiveToAdd> removeDives(std::vector<dive *> &divesToDelete) { std::vector<DiveToAdd> res; res.reserve(divesToDelete.size()); - // First, tell the filters that dives are removed. This could - // be done later using the emitted signals, but we do this here - // for symmetry with addDives() - MultiFilterSortModel::instance()->divesDeleted(QVector<dive *>::fromStdVector(divesToDelete)); - for (dive *d: 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 an 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; } @@ -141,79 +64,29 @@ std::vector<DiveToAdd> DiveListBase::removeDives(std::vector<dive *> &divesToDel // of dives to be (re)added and returns a vector of the added dives. It does this in reverse // order, so that trips are created appropriately and indexing is correct. // The passed in vector is cleared. -std::vector<dive *> DiveListBase::addDives(std::vector<DiveToAdd> &divesToAdd) +static std::vector<dive *> addDives(std::vector<DiveToAdd> &divesToAdd) { std::vector<dive *> res; - res.resize(divesToAdd.size()); - - // First, tell the filters that new dives are added. We do this here - // instead of later by signals, so that the filter can set the - // checkboxes of the new rows to its liking. The added dives will - // then appear in the correct shown/hidden state. - QVector<dive *> divesForFilter; - for (const DiveToAdd &entry: divesToAdd) - divesForFilter.push_back(entry.dive.get()); - MultiFilterSortModel::instance()->divesAdded(divesForFilter); - - // 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()); - } + res.reserve(divesToAdd.size()); - // Now, add the dives - // Note: the idiomatic STL-way would be std::transform, but let's use a loop since - // that is closer to classical C-style. - auto it2 = res.rbegin(); - for (auto it = divesToAdd.rbegin(); it != divesToAdd.rend(); ++it, ++it2) - *it2 = addDive(*it); + 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; } // This helper function renumbers dives according to an array of id/number pairs. // The old numbers are stored in the array, thus calling this function twice has no effect. // TODO: switch from uniq-id to indexes once all divelist-actions are controlled by undo-able commands -static void renumberDives(QVector<QPair<dive *, int>> &divesToRenumber) +static void renumberDives(QVector<QPair<int, int>> &divesToRenumber) { for (auto &pair: divesToRenumber) { - dive *d = pair.first; + dive *d = get_dive_by_uniq_id(pair.first); if (!d) 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 = 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 @@ -250,16 +123,10 @@ static OwningTripPtr moveDiveToTrip(DiveToTrip &diveToTrip) // a no-op. static void moveDivesBetweenTrips(DivesToTrip &dives) { - // 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) + // 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 + insert_trip(&t); // Return ownership to backend } dives.tripsToAdd.clear(); @@ -270,247 +137,22 @@ 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()); std::reverse(dives.divesToMove.begin(), dives.divesToMove.end()); } -// When we initialize the command we don't have to roll-back any selection change -DiveListBase::DiveListBase() : firstExecution(true) -{ -} - -// Turn current selection into a vector. -// TODO: This could be made much more efficient if we kept a sorted list of selected dives! -static std::vector<dive *> getDiveSelection() -{ - std::vector<dive *> res; - res.reserve(amount_selected); - - int i; - dive *d; - for_each_dive(i, d) { - if (d->selected) - res.push_back(d); - } - return res; -} - -void DiveListBase::initWork() -{ - selectionChanged = false; -} - -void DiveListBase::finishWork() -{ - if (selectionChanged) // If the selection changed -> tell the frontend - emit diveListNotifier.selectionChanged(); -} - -// Set the current dive either from a list of selected dives, -// or a newly selected dive. In both cases, try to select the -// dive that is newer that is newer than the given date. -// This mimics the old behavior when the current dive changed. -static void setClosestCurrentDive(timestamp_t when, const std::vector<dive *> &selection) -{ - // Start from back until we get the first dive that is before - // the supposed-to-be selected dive. (Note: this mimics the - // old behavior when the current dive changed). - for (auto it = selection.rbegin(); it < selection.rend(); ++it) { - if ((*it)->when > when && !(*it)->hidden_by_filter) { - current_dive = *it; - return; - } - } - - // We didn't find a more recent selected dive -> try to - // find *any* visible selected dive. - for (dive *d: selection) { - if (!d->hidden_by_filter) { - current_dive = d; - return; - } - } - - // No selected dive is visible! Take the closest dive. Note, this might - // return null, but that just means unsetting the current dive (as no - // dive is visible anyway). - current_dive = find_next_visible_dive(when); -} - -// Rese the selection to the dives of the "selection" vector and send the appropriate signals. -// Set the current dive to "currentDive". "currentDive" must be an element of "selection" (or -// null if "seletion" is empty). -void DiveListBase::restoreSelection(const std::vector<dive *> &selection, dive *currentDive) -{ - // To do so, generate vectors of dives to be selected and deselected. - // We send signals batched by trip, so keep track of trip/dive pairs. - std::vector<std::pair<dive_trip *, dive *>> divesToSelect; - std::vector<std::pair<dive_trip *, dive *>> divesToDeselect; - - // TODO: We might want to keep track of selected dives in a more efficient way! - int i; - dive *d; - amount_selected = 0; // We recalculate amount_selected - for_each_dive(i, d) { - // We only modify dives that are currently visible. - if (d->hidden_by_filter) { - d->selected = false; // Note, not necessary, just to be sure - // that we get amount_selected right - continue; - } - - // Search the dive in the list of selected dives. - // TODO: By sorting the list in the same way as the backend, this could be made more efficient. - bool newState = std::find(selection.begin(), selection.end(), d) != selection.end(); - - // TODO: Instead of using select_dive() and deselect_dive(), we set selected directly. - // The reason is that deselect() automatically sets a new current dive, which we - // don't want, as we set it later anyway. - // There is other parts of the C++ code that touches the innards directly, but - // ultimately this should be pushed down to C. - if (newState && !d->selected) { - d->selected = true; - ++amount_selected; - divesToSelect.push_back({ d->divetrip, d }); - } else if (!newState && d->selected) { - d->selected = false; - divesToDeselect.push_back({ d->divetrip, d }); - } - } - - // Send the select and deselect signals - processByTrip(divesToSelect, [&](dive_trip *trip, const QVector<dive *> &divesInTrip) { - emit diveListNotifier.divesSelected(trip, divesInTrip); - }); - processByTrip(divesToDeselect, [&](dive_trip *trip, const QVector<dive *> &divesInTrip) { - emit diveListNotifier.divesDeselected(trip, divesInTrip); - }); - - bool currentDiveChanged = false; - if (current_dive != currentDive) { - currentDiveChanged = true; - - // We cannot simply change the currentd dive to the given dive. - // It might be hidden by a filter and thus not be selected. - if (currentDive->selected) - // Current dive is visible and selected. Excellent. - current_dive = currentDive; - else - // Current not visible -> find a different dive. - setClosestCurrentDive(currentDive->when, selection); - emit diveListNotifier.currentDiveChanged(); - } - - // If anything changed (selection or current dive), send a final signal. - if (!divesToSelect.empty() || !divesToDeselect.empty() || currentDiveChanged) - selectionChanged = true; -} - -void DiveListBase::undo() -{ - auto marker = diveListNotifier.enterCommand(); - initWork(); - undoit(); - finishWork(); -} - -void DiveListBase::redo() -{ - auto marker = diveListNotifier.enterCommand(); - initWork(); - redoit(); - finishWork(); -} - -AddDive::AddDive(dive *d, bool autogroup, bool newNumber) +AddDive::AddDive(dive *d) { setText(tr("add dive")); - // By convention, d is "displayed dive" and can be overwritten. d->maxdepth.mm = 0; - d->dc.maxdepth.mm = 0; fixup_dive(d); - - // Get an owning pointer to a copied or moved dive - // Note: if move is true, this destroys the old dive! - OwningDivePtr divePtr(clone_dive(d)); - divePtr->selected = false; // If we clone a planned dive, it might have been selected. - // We have to clear the flag, as selections will be managed - // on dive-addition. - - // If we alloc a new-trip for autogrouping, get an owning pointer to it. - OwningTripPtr allocTrip; - dive_trip *trip = divePtr->divetrip; - // We have to delete the pointer-to-trip, because this would prevent the core from adding to the trip - // and we would get the count-of-dives in the trip wrong. Yes, that's all horribly subtle! - divePtr->divetrip = nullptr; - if (!trip && autogroup) { - bool alloc; - trip = get_trip_for_new_dive(divePtr.get(), &alloc); - if (alloc) - allocTrip.reset(trip); - } - - int idx = dive_get_insertion_index(divePtr.get()); - if (newNumber) - divePtr->number = get_dive_nr_at_idx(idx); - - divesToAdd.push_back({ std::move(divePtr), std::move(allocTrip), trip, idx }); + 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)); } bool AddDive::workToBeDone() @@ -518,34 +160,24 @@ bool AddDive::workToBeDone() return true; } -void AddDive::redoit() +void AddDive::redo() { - // Remember selection so that we can undo it - selection = getDiveSelection(); - currentDive = current_dive; - - divesToRemove = addDives(divesToAdd); + diveToRemove = addDive(diveToAdd); mark_divelist_changed(true); - // Select the newly added dive - restoreSelection(divesToRemove, divesToRemove[0]); - - // Exit from edit mode, but don't recalculate dive list - // TODO: Remove edit mode - MainWindow::instance()->refreshDisplay(false); + // Finally, do the UI stuff: + MainWindow::instance()->dive_list()->unselectDives(); + MainWindow::instance()->dive_list()->selectDive(diveToAdd.idx, true); + MainWindow::instance()->refreshDisplay(); } -void AddDive::undoit() +void AddDive::undo() { - // Simply remove the dive that was previously added... - divesToAdd = removeDives(divesToRemove); - - // ...and restore the selection - restoreSelection(selection, currentDive); + // Simply remove the dive that was previously added + diveToAdd = removeDive(diveToRemove); - // Exit from edit mode, but don't recalculate dive list - // TODO: Remove edit mode - MainWindow::instance()->refreshDisplay(false); + // Finally, do the UI stuff: + MainWindow::instance()->refreshDisplay(); } DeleteDive::DeleteDive(const QVector<struct dive*> &divesToDeleteIn) : divesToDelete(divesToDeleteIn.toStdVector()) @@ -558,31 +190,23 @@ bool DeleteDive::workToBeDone() return !divesToDelete.empty(); } -void DeleteDive::undoit() +void DeleteDive::undo() { divesToDelete = addDives(divesToAdd); + mark_divelist_changed(true); - // Select all re-added dives and make the first one current - dive *currentDive = !divesToDelete.empty() ? divesToDelete[0] : nullptr; - restoreSelection(divesToDelete, currentDive); + // Finally, do the UI stuff: + MainWindow::instance()->refreshDisplay(); } -void DeleteDive::redoit() +void DeleteDive::redo() { divesToAdd = removeDives(divesToDelete); mark_divelist_changed(true); - // Deselect all dives and select dive that was close to the first deleted dive - dive *newCurrent = nullptr; - if (!divesToAdd.empty()) { - timestamp_t when = divesToAdd[0].dive->when; - newCurrent = find_next_visible_dive(when); - } - if (newCurrent) - restoreSelection(std::vector<dive *>{ newCurrent }, newCurrent); - else - restoreSelection(std::vector<dive *>(), nullptr); + // Finally, do the UI stuff: + MainWindow::instance()->refreshDisplay(); } @@ -592,30 +216,20 @@ ShiftTime::ShiftTime(const QVector<dive *> &changedDives, int amount) setText(tr("shift time of %n dives", "", changedDives.count())); } -void ShiftTime::redoit() +void ShiftTime::undo() { for (dive *d: diveList) d->when -= timeChanged; // Changing times may have unsorted the dive table sort_table(&dive_table); - - // 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); - }); + mark_divelist_changed(true); // Negate the time-shift so that the next call does the reverse timeChanged = -timeChanged; - mark_divelist_changed(true); + // Finally, do the UI stuff: + MainWindow::instance()->refreshDisplay(); } bool ShiftTime::workToBeDone() @@ -623,22 +237,25 @@ bool ShiftTime::workToBeDone() return !diveList.isEmpty(); } -void ShiftTime::undoit() +void ShiftTime::redo() { - // Same as redoit(), since after redoit() we reversed the timeOffset - redoit(); + // Same as undo(), since after undo() we reversed the timeOffset + undo(); } -RenumberDives::RenumberDives(const QVector<QPair<dive *, int>> &divesToRenumberIn) : divesToRenumber(divesToRenumberIn) +RenumberDives::RenumberDives(const QVector<QPair<int, int>> &divesToRenumberIn) : divesToRenumber(divesToRenumberIn) { setText(tr("renumber %n dive(s)", "", divesToRenumber.count())); } -void RenumberDives::undoit() +void RenumberDives::undo() { renumberDives(divesToRenumber); mark_divelist_changed(true); + + // Finally, do the UI stuff: + MainWindow::instance()->refreshDisplay(); } bool RenumberDives::workToBeDone() @@ -646,10 +263,10 @@ bool RenumberDives::workToBeDone() return !divesToRenumber.isEmpty(); } -void RenumberDives::redoit() +void RenumberDives::redo() { // Redo and undo do the same thing! - undoit(); + undo(); } bool TripBase::workToBeDone() @@ -657,17 +274,20 @@ bool TripBase::workToBeDone() return !divesToMove.divesToMove.empty(); } -void TripBase::redoit() +void TripBase::redo() { moveDivesBetweenTrips(divesToMove); mark_divelist_changed(true); + + // Finally, do the UI stuff: + MainWindow::instance()->refreshDisplay(); } -void TripBase::undoit() +void TripBase::undo() { // Redo and undo do the same thing! - redoit(); + redo(); } RemoveDivesFromTrip::RemoveDivesFromTrip(const QVector<dive *> &divesToRemove) @@ -748,18 +368,14 @@ SplitDives::SplitDives(dive *d, duration_t time) split_dive_dont_insert(d, &new1, &new2) : split_dive_at_time_dont_insert(d, time, &new1, &new2); - // If this didn't work, simply return. Empty arrays indicate that nothing is to be done. - if (idx < 0) + // If this didn't work, reset pointers so that redo() and undo() do nothing + if (idx < 0) { + diveToSplit = nullptr; + divesToUnsplit[0] = divesToUnsplit[1]; return; + } - // Currently, the core code selects the dive -> this is not what we want, as - // we manually manage the selection post-command. - // TODO: Reset selection in core. - new1->selected = false; - new2->selected = false; - - diveToSplit.push_back(d); - splitDives.resize(2); + diveToSplit = d; splitDives[0].dive.reset(new1); splitDives[0].trip = d->divetrip; splitDives[0].idx = idx; @@ -770,34 +386,45 @@ SplitDives::SplitDives(dive *d, duration_t time) bool SplitDives::workToBeDone() { - return !diveToSplit.empty(); + return !!diveToSplit; } -void SplitDives::redoit() +void SplitDives::redo() { - divesToUnsplit = addDives(splitDives); - unsplitDive = removeDives(diveToSplit); + if (!diveToSplit) + return; + divesToUnsplit[0] = addDive(splitDives[0]); + divesToUnsplit[1] = addDive(splitDives[1]); + unsplitDive = removeDive(diveToSplit); mark_divelist_changed(true); - // Select split dives and make first dive current - restoreSelection(divesToUnsplit, divesToUnsplit[0]); + // Finally, do the UI stuff: + MainWindow::instance()->refreshDisplay(); + MainWindow::instance()->refreshProfile(); } -void SplitDives::undoit() +void SplitDives::undo() { - // Note: reverse order with respect to redoit() - diveToSplit = addDives(unsplitDive); - splitDives = removeDives(divesToUnsplit); + if (!unsplitDive.dive) + return; + // Note: reverse order with respect to redo() + diveToSplit = addDive(unsplitDive); + splitDives[1] = removeDive(divesToUnsplit[1]); + splitDives[0] = removeDive(divesToUnsplit[0]); mark_divelist_changed(true); - // Select unsplit dive and make it current - restoreSelection(diveToSplit, diveToSplit[0] ); + // Finally, do the UI stuff: + MainWindow::instance()->refreshDisplay(); + MainWindow::instance()->refreshProfile(); } MergeDives::MergeDives(const QVector <dive *> &dives) { setText(tr("merge dive")); + // We start in redo mode + diveToUnmerge = nullptr; + // Just a safety check - if there's not two or more dives - do nothing // The caller should have made sure that this doesn't happen. if (dives.count() < 2) { @@ -808,11 +435,6 @@ MergeDives::MergeDives(const QVector <dive *> &dives) dive_trip *preferred_trip; OwningDivePtr d(merge_dives(dives[0], dives[1], dives[1]->when - dives[0]->when, false, &preferred_trip)); - // Currently, the core code selects the dive -> this is not what we want, as - // we manually manage the selection post-command. - // TODO: Remove selection code from core. - d->selected = false; - // Set the preferred dive trip, so that for subsequent merges the better trip can be selected d->divetrip = preferred_trip; for (int i = 2; i < dives.count(); ++i) { @@ -864,41 +486,42 @@ MergeDives::MergeDives(const QVector <dive *> &dives) // Stop renumbering if stuff isn't in order (see also core/divelist.c) if (newnr <= previousnr) break; - divesToRenumber.append(QPair<dive *,int>(dive_table.dives[i], newnr)); + divesToRenumber.append(QPair<int,int>(dive_table.dives[i]->id, newnr)); previousnr = newnr; } } - mergedDive.resize(1); - mergedDive[0].dive = std::move(d); - mergedDive[0].idx = get_divenr(dives[0]); - mergedDive[0].trip = preferred_trip; + mergedDive.dive = std::move(d); + mergedDive.idx = get_divenr(dives[0]); + mergedDive.trip = preferred_trip; divesToMerge = dives.toStdVector(); } bool MergeDives::workToBeDone() { - return !mergedDive.empty(); + return !!mergedDive.dive; } -void MergeDives::redoit() +void MergeDives::redo() { renumberDives(divesToRenumber); - diveToUnmerge = addDives(mergedDive); + diveToUnmerge = addDive(mergedDive); unmergedDives = removeDives(divesToMerge); - // Select merged dive and make it current - restoreSelection(diveToUnmerge, diveToUnmerge[0]); + // Finally, do the UI stuff: + MainWindow::instance()->refreshDisplay(); + MainWindow::instance()->refreshProfile(); } -void MergeDives::undoit() +void MergeDives::undo() { divesToMerge = addDives(unmergedDives); - mergedDive = removeDives(diveToUnmerge); + mergedDive = removeDive(diveToUnmerge); renumberDives(divesToRenumber); - // Select unmerged dives and make first one current - restoreSelection(divesToMerge, divesToMerge[0]); + // 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 new file mode 100644 index 000000000..8cff4f1ef --- /dev/null +++ b/desktop-widgets/command_divelist.h @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: GPL-2.0 +// Note: this header file is used by the undo-machinery and should not be included elsewhere. + +#ifndef COMMAND_DIVELIST_H +#define COMMAND_DIVELIST_H + +#include "command_base.h" + +#include <QVector> + +// We put everything in a namespace, so that we can shorten names without polluting the global namespace +namespace Command { + +// This helper structure describes a dive that we want to add. +// Potentially it also adds a trip (if deletion of the dive resulted in deletion of the trip) +struct DiveToAdd { + OwningDivePtr dive; // Dive to add + OwningTripPtr tripToAdd; // Not-null if we also have to add a dive + dive_trip *trip; // Trip the dive belongs to, may be null + int idx; // Position in divelist +}; + +// This helper structure describes a dive that should be moved to / removed from +// a trip. If the "trip" member is null, the dive is removed from its trip (if +// it is in a trip, that is) +struct DiveToTrip +{ + struct dive *dive; + dive_trip *trip; +}; + +// This helper structure describes a number of dives to add to /remove from / +// move between trips. +// It has ownership of the trips (if any) that have to be added before hand. +struct DivesToTrip +{ + std::vector<DiveToTrip> divesToMove; // If dive_trip is null, remove from trip + std::vector<OwningTripPtr> tripsToAdd; +}; + +class AddDive : public Base { +public: + AddDive(dive *dive); +private: + void undo() override; + void redo() override; + bool workToBeDone() override; + + // For redo + DiveToAdd diveToAdd; + + // For undo + dive *diveToRemove; +}; + +class DeleteDive : public Base { +public: + DeleteDive(const QVector<dive *> &divesToDelete); +private: + void undo() override; + void redo() override; + bool workToBeDone() override; + + // For redo + std::vector<struct dive*> divesToDelete; + + std::vector<OwningTripPtr> tripsToAdd; + std::vector<DiveToAdd> divesToAdd; +}; + +class ShiftTime : public Base { +public: + ShiftTime(const QVector<dive *> &changedDives, int amount); +private: + void undo() override; + void redo() override; + bool workToBeDone() override; + + // For redo and undo + QVector<dive *> diveList; + int timeChanged; +}; + +class RenumberDives : public Base { +public: + RenumberDives(const QVector<QPair<int, int>> &divesToRenumber); +private: + void undo() override; + void redo() override; + bool workToBeDone() override; + + // For redo and undo: pairs of dive-id / new number + QVector<QPair<int, int>> divesToRenumber; +}; + +// The classes RemoveDivesFromTrip, RemoveAutogenTrips, CreateTrip, AutogroupDives +// and MergeTrips all do the same thing, just the intialization differs. +// Therefore, define a base class with the proper data-structures, redo() +// and undo() functions and derive to specialize the initialization. +class TripBase : public Base { +protected: + void undo() override; + void redo() override; + bool workToBeDone() override; + + // For redo and undo + DivesToTrip divesToMove; +}; +struct RemoveDivesFromTrip : public TripBase { + RemoveDivesFromTrip(const QVector<dive *> &divesToRemove); +}; +struct RemoveAutogenTrips : public TripBase { + RemoveAutogenTrips(); +}; +struct AddDivesToTrip : public TripBase { + AddDivesToTrip(const QVector<dive *> &divesToAdd, dive_trip *trip); +}; +struct CreateTrip : public TripBase { + CreateTrip(const QVector<dive *> &divesToAdd); +}; +struct AutogroupDives : public TripBase { + AutogroupDives(); +}; +struct MergeTrips : public TripBase { + MergeTrips(dive_trip *trip1, dive_trip *trip2); +}; + +class SplitDives : public Base { +public: + // If time is < 0, split at first surface interval + SplitDives(dive *d, duration_t time); +private: + void undo() override; + void redo() override; + bool workToBeDone() override; + + // For redo + // For each dive to split, we remove one from and put two dives into the backend + dive *diveToSplit; + DiveToAdd splitDives[2]; + + // For undo + // For each dive to unsplit, we remove two dives from and add one into the backend + DiveToAdd unsplitDive; + dive *divesToUnsplit[2]; +}; + +class MergeDives : public Base { +public: + MergeDives(const QVector<dive *> &dives); +private: + void undo() override; + void redo() override; + bool workToBeDone() override; + + // For redo + // Add one and remove a batch of dives + DiveToAdd mergedDive; + std::vector<dive *> divesToMerge; + + // For undo + // Remove one and add a batch of dives + dive *diveToUnmerge; + std::vector<DiveToAdd> unmergedDives; + + // For undo and redo + QVector<QPair<int, int>> divesToRenumber; +}; + +} // namespace Command + +#endif // COMMAND_DIVELIST_H diff --git a/desktop-widgets/divelistview.cpp b/desktop-widgets/divelistview.cpp index 27b7e3ed9..4d68baca2 100644 --- a/desktop-widgets/divelistview.cpp +++ b/desktop-widgets/divelistview.cpp @@ -20,7 +20,7 @@ #include <QMessageBox> #include <QHeaderView> #include "core/qthelper.h" -#include "desktop-widgets/undocommands.h" +#include "desktop-widgets/command.h" #include "desktop-widgets/divelistview.h" #include "qt-models/divepicturemodel.h" #include "core/metrics.h" @@ -633,10 +633,8 @@ void DiveListView::mergeDives() if (current_batch.count() > 1) merge_batches.append(current_batch); - for (const QVector<dive *> &batch: merge_batches) { - UndoMergeDives *undoCommand = new UndoMergeDives(batch); - MainWindow::instance()->undoStack->push(undoCommand); - } + for (const QVector<dive *> &batch: merge_batches) + Command::mergeDives(batch); } void DiveListView::splitDives() @@ -650,10 +648,8 @@ void DiveListView::splitDives() if (dive->selected) dives.append(dive); } - for (struct dive *d: dives) { - UndoSplitDives *undoCommand = new UndoSplitDives(d, duration_t{-1}); - MainWindow::instance()->undoStack->push(undoCommand); - } + for (struct dive *d: dives) + Command::splitDives(d, duration_t{-1}); } void DiveListView::renumberDives() @@ -671,8 +667,7 @@ void DiveListView::merge_trip(const QModelIndex &a, int offset) dive_trip_t *trip_b = (dive_trip_t *)b.data(DiveTripModel::TRIP_ROLE).value<void *>(); if (trip_a == trip_b || !trip_a || !trip_b) return; - UndoMergeTrips *undoCommand = new UndoMergeTrips(trip_a, trip_b); - MainWindow::instance()->undoStack->push(undoCommand); + Command::mergeTrips(trip_a, trip_b); rememberSelection(); reload(currentLayout, false); restoreSelection(); @@ -700,11 +695,7 @@ void DiveListView::removeFromTrip() if (d->selected && d->divetrip) divesToRemove.append(d); } - if (divesToRemove.isEmpty()) - return; - - UndoRemoveDivesFromTrip *undoCommand = new UndoRemoveDivesFromTrip(divesToRemove); - MainWindow::instance()->undoStack->push(undoCommand); + Command::removeDivesFromTrip(divesToRemove); rememberSelection(); reload(currentLayout, false); @@ -725,8 +716,7 @@ void DiveListView::newTripAbove() if (d->selected) dives.append(d); } - UndoCreateTrip *undoCommand = new UndoCreateTrip(dives); - MainWindow::instance()->undoStack->push(undoCommand); + Command::createTrip(dives); reload(currentLayout, false); mark_divelist_changed(true); @@ -774,8 +764,7 @@ void DiveListView::addToTrip(int delta) dives.append(d); } } - UndoAddDivesToTrip *undoEntry = new UndoAddDivesToTrip(dives, trip); - MainWindow::instance()->undoStack->push(undoEntry); + Command::addDivesToTrip(dives, trip); reload(currentLayout, false); restoreSelection(); @@ -814,7 +803,7 @@ void DiveListView::deleteDive() int i; int lastDiveNr = -1; - QVector<struct dive*> deletedDives; //a list of all deleted dives to be stored in the undo command + QVector<struct dive*> deletedDives; for_each_dive (i, d) { if (!d->selected) continue; @@ -822,8 +811,7 @@ void DiveListView::deleteDive() lastDiveNr = i; } // the actual dive deletion is happening in the redo command that is implicitly triggered - UndoDeleteDive *undoEntry = new UndoDeleteDive(deletedDives); - MainWindow::instance()->undoStack->push(undoEntry); + Command::deleteDive(deletedDives); if (amount_selected == 0) { MainWindow::instance()->cleanUpEmpty(); } diff --git a/desktop-widgets/divelogimportdialog.cpp b/desktop-widgets/divelogimportdialog.cpp index 151488c0b..668b230a8 100644 --- a/desktop-widgets/divelogimportdialog.cpp +++ b/desktop-widgets/divelogimportdialog.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0 #include "desktop-widgets/divelogimportdialog.h" #include "desktop-widgets/mainwindow.h" +#include "desktop-widgets/command.h" #include "core/color.h" #include "ui_divelogimportdialog.h" #include <QShortcut> @@ -1010,7 +1011,7 @@ void DiveLogImportDialog::on_buttonBox_accepted() process_imported_dives(&table, false, false); autogroup_dives(); - MainWindow::instance()->undoStack->clear(); + Command::clear(); MainWindow::instance()->refreshDisplay(); } diff --git a/desktop-widgets/downloadfromdivecomputer.cpp b/desktop-widgets/downloadfromdivecomputer.cpp index e63de8f56..de0dd0626 100644 --- a/desktop-widgets/downloadfromdivecomputer.cpp +++ b/desktop-widgets/downloadfromdivecomputer.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-2.0 #include "desktop-widgets/downloadfromdivecomputer.h" +#include "desktop-widgets/command.h" #include "core/display.h" #include "core/qthelper.h" #include "core/settings/qPrefDiveComputer.h" @@ -508,7 +509,8 @@ void DownloadFromDCWidget::on_ok_clicked() // first new dive) and select it again after processing all the dives int uniqId = downloadTable.dives[downloadTable.nr - 1]->id; process_imported_dives(&downloadTable, preferDownloaded(), true); - MainWindow::instance()->undoStack->clear(); + autogroup_dives(); + Command::clear(); // after process_imported_dives does any merging or resorting needed, we need // to recreate the model for the dive list so we can select the newest dive MainWindow::instance()->recreateDiveList(); diff --git a/desktop-widgets/mainwindow.cpp b/desktop-widgets/mainwindow.cpp index 06f6b8968..d55913e25 100644 --- a/desktop-widgets/mainwindow.cpp +++ b/desktop-widgets/mainwindow.cpp @@ -37,6 +37,7 @@ #include "core/settings/qPrefTechnicalDetails.h" #include "desktop-widgets/about.h" +#include "desktop-widgets/command.h" #include "desktop-widgets/divecomputermanagementdialog.h" #include "desktop-widgets/divelistview.h" #include "desktop-widgets/divelogexportdialog.h" @@ -48,7 +49,6 @@ #include "desktop-widgets/mapwidget.h" #include "desktop-widgets/subsurfacewebservices.h" #include "desktop-widgets/tab-widgets/maintab.h" -#include "desktop-widgets/undocommands.h" #include "desktop-widgets/updatemanager.h" #include "desktop-widgets/usersurvey.h" @@ -258,9 +258,8 @@ MainWindow::MainWindow() : QMainWindow(), memset(&what, 0, sizeof(what)); updateManager = new UpdateManager(this); - undoStack = new QUndoStack(this); - QAction *undoAction = undoStack->createUndoAction(this, tr("&Undo")); - QAction *redoAction = undoStack->createRedoAction(this, tr("&Redo")); + QAction *undoAction = Command::undoAction(this); + QAction *redoAction = Command::redoAction(this); undoAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Z)); redoAction->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Z)); QList<QAction*>undoRedoActions; @@ -620,7 +619,7 @@ void MainWindow::on_actionCloudstorageopen_triggered() process_loaded_dives(); if (autogroup) autogroup_dives(); - undoStack->clear(); + Command::clear(); hideProgressBar(); refreshDisplay(); } @@ -1075,9 +1074,9 @@ void MainWindow::on_actionAutoGroup_triggered() { set_autogroup(ui.actionAutoGroup->isChecked()); if (autogroup) - undoStack->push(new UndoAutogroupDives); + Command::autogroupDives(); else - undoStack->push(new UndoRemoveAutogenTrips); + Command::removeAutogenTrips(); refreshDisplay(); mark_divelist_changed(true); } @@ -1745,7 +1744,7 @@ void MainWindow::importFiles(const QStringList fileNames) process_imported_dives(&table, false, false); if (autogroup) autogroup_dives(); - undoStack->clear(); + Command::clear(); refreshDisplay(); } @@ -1770,7 +1769,7 @@ void MainWindow::loadFiles(const QStringList fileNames) process_loaded_dives(); if (autogroup) autogroup_dives(); - undoStack->clear(); + Command::clear(); refreshDisplay(); diff --git a/desktop-widgets/mainwindow.h b/desktop-widgets/mainwindow.h index 05f6ade68..113f0699c 100644 --- a/desktop-widgets/mainwindow.h +++ b/desktop-widgets/mainwindow.h @@ -34,7 +34,6 @@ class DivePlannerWidget; class ProfileWidget2; class PlannerDetails; class PlannerSettingsWidget; -class QUndoStack; class LocationInformationWidget; typedef std::pair<QByteArray, QVariant> WidgetProperty; @@ -82,7 +81,6 @@ public: void setApplicationState(const QByteArray& state); void setStateProperties(const QByteArray& state, const PropertyList& tl, const PropertyList& tr, const PropertyList& bl,const PropertyList& br); bool inPlanner(); - QUndoStack *undoStack; NotificationWidget *getNotificationWidget(); void enableDisableCloudActions(); void setCheckedActionFilterTags(bool checked); diff --git a/desktop-widgets/simplewidgets.cpp b/desktop-widgets/simplewidgets.cpp index b7f985bc9..72a81d873 100644 --- a/desktop-widgets/simplewidgets.cpp +++ b/desktop-widgets/simplewidgets.cpp @@ -18,7 +18,7 @@ #include "desktop-widgets/divelistview.h" #include "core/display.h" #include "profile-widget/profilewidget2.h" -#include "desktop-widgets/undocommands.h" +#include "desktop-widgets/command.h" #include "core/metadata.h" class MinMaxAvgWidgetPrivate { @@ -171,8 +171,7 @@ void RenumberDialog::buttonClicked(QAbstractButton *button) renumberedDives.append(QPair<int, int>(dive->id, newNr++)); } } - UndoRenumberDives *undoCommand = new UndoRenumberDives(renumberedDives); - MainWindow::instance()->undoStack->push(undoCommand); + Command::renumberDives(renumberedDives); mark_divelist_changed(true); MainWindow::instance()->dive_list()->restoreSelection(); @@ -246,7 +245,7 @@ void ShiftTimesDialog::buttonClicked(QAbstractButton *button) if (d->selected) affectedDives.append(d); } - MainWindow::instance()->undoStack->push(new UndoShiftTime(affectedDives, amount)); + Command::shiftTime(affectedDives, amount); } } } diff --git a/desktop-widgets/tab-widgets/maintab.cpp b/desktop-widgets/tab-widgets/maintab.cpp index 7f1e6cbc2..46217af54 100644 --- a/desktop-widgets/tab-widgets/maintab.cpp +++ b/desktop-widgets/tab-widgets/maintab.cpp @@ -26,7 +26,7 @@ #include "core/subsurface-string.h" #include "core/gettextfromc.h" #include "desktop-widgets/locationinformation.h" -#include "desktop-widgets/undocommands.h" +#include "desktop-widgets/command.h" #include "TabDiveExtraInfo.h" #include "TabDiveInformation.h" @@ -799,8 +799,7 @@ void MainTab::acceptChanges() updateDiveSite(ui.location->currDiveSiteUuid(), &displayed_dive); copyTagsToDisplayedDive(); - UndoAddDive *undoCommand = new UndoAddDive(&displayed_dive); - MainWindow::instance()->undoStack->push(undoCommand); + Command::addDive(&displayed_dive); editMode = NONE; MainWindow::instance()->exitEditState(); @@ -969,7 +968,7 @@ void MainTab::acceptChanges() if (displayed_dive.when != cd->when) { timestamp_t offset = cd->when - displayed_dive.when; if (offset) - MainWindow::instance()->undoStack->push(new UndoShiftTime(selectedDives, (int)offset)); + Command::shiftTime(selectedDives, (int)offset); } } if (editMode != TRIP && current_dive->divetrip) { diff --git a/desktop-widgets/undocommands.cpp b/desktop-widgets/undocommands.cpp deleted file mode 100644 index 8470e4f2d..000000000 --- a/desktop-widgets/undocommands.cpp +++ /dev/null @@ -1,493 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -#include "desktop-widgets/undocommands.h" -#include "desktop-widgets/mainwindow.h" -#include "desktop-widgets/divelistview.h" -#include "core/divelist.h" -#include "core/subsurface-string.h" -#include "core/gettextfromc.h" - -// 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! -static DiveToAdd removeDive(struct dive *d) -{ - DiveToAdd res; - res.idx = get_divenr(d); - if (res.idx < 0) - qWarning() << "Deletion of unknown dive!"; - - // remove dive from trip - if this is the last dive in the trip - // remove the whole trip. - res.trip = unregister_dive_from_trip(d, false); - if (res.trip && res.trip->nrdives == 0) { - unregister_trip(res.trip); // Remove trip from backend - res.tripToAdd.reset(res.trip); // Take ownership of trip - } - - res.dive.reset(unregister_dive(res.idx)); // Remove dive from backend - return res; -} - -// This helper function adds a dive and returns ownership to the backend. It may also add a dive trip. -// It is crucial that dives are added in reverse order of deletion (see comment above)! -// Returns pointer to added dive (which is owned by the backend!) -static dive *addDive(DiveToAdd &d) -{ - if (d.tripToAdd) { - dive_trip *t = d.tripToAdd.release(); // Give up ownership of trip - insert_trip(&t); // 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 - return res; -} - -// This helper function calls removeDive() on a list of dives to be removed and -// returns a vector of corresponding DiveToAdd objects, which can later be readded. -// The passed in vector is cleared. -static std::vector<DiveToAdd> removeDives(std::vector<dive *> &divesToDelete) -{ - std::vector<DiveToAdd> res; - res.reserve(divesToDelete.size()); - - for (dive *d: divesToDelete) - res.push_back(removeDive(d)); - divesToDelete.clear(); - - return res; -} - -// This helper function is the counterpart fo removeDives(): it calls addDive() on a list -// of dives to be (re)added and returns a vector of the added dives. It does this in reverse -// order, so that trips are created appropriately and indexing is correct. -// The passed in vector is cleared. -static std::vector<dive *> addDives(std::vector<DiveToAdd> &divesToAdd) -{ - std::vector<dive *> res; - res.reserve(divesToAdd.size()); - - for (auto it = divesToAdd.rbegin(); it != divesToAdd.rend(); ++it) - res.push_back(addDive(*it)); - divesToAdd.clear(); - - return res; -} - -// This helper function renumbers dives according to an array of id/number pairs. -// The old numbers are stored in the array, thus calling this function twice has no effect. -// TODO: switch from uniq-id to indexes once all divelist-actions are controlled by "UndoCommands". -static void renumberDives(QVector<QPair<int, int>> &divesToRenumber) -{ - for (auto &pair: divesToRenumber) { - dive *d = get_dive_by_uniq_id(pair.first); - if (!d) - continue; - std::swap(d->number, pair.second); - } -} - -// This helper function moves a dive to a trip. The old trip is recorded in the -// passed-in structure. This means that calling the function twice on the same -// object is a no-op concerning the dive. If the old trip was deleted from the -// core, an owning pointer to the removed trip is returned, otherwise a null pointer. -static OwningTripPtr moveDiveToTrip(DiveToTrip &diveToTrip) -{ - // Firstly, check if we move to the same trip and bail if this is a no-op. - if (diveToTrip.trip == diveToTrip.dive->divetrip) - return {}; - - // Remove from old trip - OwningTripPtr res; - - // Remove dive from trip - if this is the last dive in the trip, remove the whole trip. - dive_trip *trip = unregister_dive_from_trip(diveToTrip.dive, false); - if (trip && trip->nrdives == 0) { - unregister_trip(trip); // Remove trip from backend - res.reset(trip); - } - - // Store old trip and get new trip we should associate this dive with - std::swap(trip, diveToTrip.trip); - add_dive_to_trip(diveToTrip.dive, trip); - return res; -} - -// This helper function moves a set of dives between trips using the -// moveDiveToTrip function. Before doing so, it adds the necessary trips to -// the core. Trips that are removed from the core because they are empty -// are recorded in the passed in struct. The vectors of trips and dives -// are reversed. Thus, calling the function twice on the same object is -// a no-op. -static void moveDivesBetweenTrips(DivesToTrip &dives) -{ - // first bring back the trip(s) - for (OwningTripPtr &trip: dives.tripsToAdd) { - dive_trip *t = trip.release(); // Give up ownership - insert_trip(&t); // Return ownership to backend - } - dives.tripsToAdd.clear(); - - for (DiveToTrip &dive: dives.divesToMove) { - OwningTripPtr tripToAdd = moveDiveToTrip(dive); - // register trips that we'll have to readd - if (tripToAdd) - dives.tripsToAdd.push_back(std::move(tripToAdd)); - } - - // 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()); - std::reverse(dives.divesToMove.begin(), dives.divesToMove.end()); -} - -UndoAddDive::UndoAddDive(dive *d) -{ - setText(gettextFromC::tr("add dive")); - // TODO: handle tags - //saveTags(); - 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)); -} - -void UndoAddDive::redo() -{ - diveToRemove = addDive(diveToAdd); - 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(); -} - -void UndoAddDive::undo() -{ - // Simply remove the dive that was previously added - diveToAdd = removeDive(diveToRemove); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); -} - -UndoDeleteDive::UndoDeleteDive(const QVector<struct dive*> &divesToDeleteIn) : divesToDelete(divesToDeleteIn.toStdVector()) -{ - setText(tr("delete %n dive(s)", "", divesToDelete.size())); -} - -void UndoDeleteDive::undo() -{ - divesToDelete = addDives(divesToAdd); - - mark_divelist_changed(true); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); -} - -void UndoDeleteDive::redo() -{ - divesToAdd = removeDives(divesToDelete); - mark_divelist_changed(true); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); -} - - -UndoShiftTime::UndoShiftTime(const QVector<dive *> &changedDives, int amount) - : diveList(changedDives), timeChanged(amount) -{ - setText(tr("delete %n dive(s)", "", changedDives.size())); -} - -void UndoShiftTime::undo() -{ - for (dive *d: diveList) - d->when -= timeChanged; - - // Changing times may have unsorted the dive table - sort_table(&dive_table); - mark_divelist_changed(true); - - // Negate the time-shift so that the next call does the reverse - timeChanged = -timeChanged; - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); -} - -void UndoShiftTime::redo() -{ - // Same as undo(), since after undo() we reversed the timeOffset - undo(); -} - - -UndoRenumberDives::UndoRenumberDives(const QVector<QPair<int, int>> &divesToRenumberIn) : divesToRenumber(divesToRenumberIn) -{ - setText(tr("renumber %n dive(s)", "", divesToRenumber.count())); -} - -void UndoRenumberDives::undo() -{ - renumberDives(divesToRenumber); - mark_divelist_changed(true); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); -} - -void UndoRenumberDives::redo() -{ - // Redo and undo do the same thing! - undo(); -} - -void UndoTripBase::redo() -{ - moveDivesBetweenTrips(divesToMove); - - mark_divelist_changed(true); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); -} - -void UndoTripBase::undo() -{ - // Redo and undo do the same thing! - redo(); -} - -UndoRemoveDivesFromTrip::UndoRemoveDivesFromTrip(const QVector<dive *> &divesToRemove) -{ - setText(divesToRemove.size() == 1 ? gettextFromC::tr("remove dive from trip") - : gettextFromC::tr("remove %1 dives from trip").arg(divesToRemove.size())); - divesToMove.divesToMove.reserve(divesToRemove.size()); - for (dive *d: divesToRemove) - divesToMove.divesToMove.push_back( {d, nullptr} ); -} - -UndoRemoveAutogenTrips::UndoRemoveAutogenTrips() -{ - setText(gettextFromC::tr("remove autogenerated trips")); - // TODO: don't touch core-innards directly - int i; - struct dive *dive; - for_each_dive(i, dive) { - if (dive->divetrip && dive->divetrip->autogen) - divesToMove.divesToMove.push_back( {dive, nullptr} ); - } -} - -UndoAddDivesToTrip::UndoAddDivesToTrip(const QVector<dive *> &divesToAddIn, dive_trip *trip) -{ - setText(divesToAddIn.size() == 1 ? gettextFromC::tr("add dives to trip") - : gettextFromC::tr("add %1 dives to trip").arg(divesToAddIn.size())); - for (dive *d: divesToAddIn) - divesToMove.divesToMove.push_back( {d, trip} ); -} - -UndoCreateTrip::UndoCreateTrip(const QVector<dive *> &divesToAddIn) -{ - setText(gettextFromC::tr("create trip")); - - if (divesToAddIn.isEmpty()) - return; - - dive_trip *trip = create_trip_from_dive(divesToAddIn[0]); - divesToMove.tripsToAdd.emplace_back(trip); - for (dive *d: divesToAddIn) - divesToMove.divesToMove.push_back( {d, trip} ); -} - -UndoAutogroupDives::UndoAutogroupDives() -{ - setText(gettextFromC::tr("autogroup dives")); - - dive_trip *trip; - bool alloc; - int from, to; - for(int i = 0; (trip = get_dives_to_autogroup(i, &from, &to, &alloc)) != NULL; i = to) { - // If this is an allocated trip, take ownership - if (alloc) - divesToMove.tripsToAdd.emplace_back(trip); - for (int j = from; j < to; ++j) - divesToMove.divesToMove.push_back( { get_dive(j), trip } ); - } -} - -UndoMergeTrips::UndoMergeTrips(dive_trip *trip1, dive_trip *trip2) -{ - if (trip1 == trip2) - return; - dive_trip *newTrip = combine_trips_create(trip1, trip2); - divesToMove.tripsToAdd.emplace_back(newTrip); - for (dive *d = trip1->dives; d; d = d->next) - divesToMove.divesToMove.push_back( { d, newTrip } ); - for (dive *d = trip2->dives; d; d = d->next) - divesToMove.divesToMove.push_back( { d, newTrip } ); -} - -UndoSplitDives::UndoSplitDives(dive *d, duration_t time) -{ - setText(gettextFromC::tr("split dive")); - - // Split the dive - dive *new1, *new2; - int idx = time.seconds < 0 ? - split_dive_dont_insert(d, &new1, &new2) : - split_dive_at_time_dont_insert(d, time, &new1, &new2); - - // If this didn't work, reset pointers so that redo() and undo() do nothing - if (idx < 0) { - diveToSplit = nullptr; - divesToUnsplit[0] = divesToUnsplit[1]; - return; - } - - diveToSplit = d; - splitDives[0].dive.reset(new1); - splitDives[0].trip = d->divetrip; - splitDives[0].idx = idx; - splitDives[1].dive.reset(new2); - splitDives[1].trip = d->divetrip; - splitDives[1].idx = idx + 1; -} - -void UndoSplitDives::redo() -{ - if (!diveToSplit) - return; - divesToUnsplit[0] = addDive(splitDives[0]); - divesToUnsplit[1] = addDive(splitDives[1]); - unsplitDive = removeDive(diveToSplit); - mark_divelist_changed(true); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); - MainWindow::instance()->refreshProfile(); -} - -void UndoSplitDives::undo() -{ - if (!unsplitDive.dive) - return; - // Note: reverse order with respect to redo() - diveToSplit = addDive(unsplitDive); - 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(); -} - -UndoMergeDives::UndoMergeDives(const QVector <dive *> &dives) -{ - setText(gettextFromC::tr("merge dive")); - - // We start in redo mode - diveToUnmerge = nullptr; - - // Just a safety check - if there's not two or more dives - do nothing - // The caller should have made sure that this doesn't happen. - if (dives.count() < 2) { - qWarning() << "Merging less than two dives"; - return; - } - - dive_trip *preferred_trip; - OwningDivePtr d(merge_dives(dives[0], dives[1], dives[1]->when - dives[0]->when, false, &preferred_trip)); - - // Set the preferred dive trip, so that for subsequent merges the better trip can be selected - d->divetrip = preferred_trip; - for (int i = 2; i < dives.count(); ++i) { - d.reset(merge_dives(d.get(), dives[i], dives[i]->when - d->when, false, &preferred_trip)); - // Set the preferred dive trip, so that for subsequent merges the better trip can be selected - d->divetrip = preferred_trip; - } - - // We got our preferred trip, so now the reference can be deleted from the newly generated dive - d->divetrip = nullptr; - - // The merged dive gets the number of the first dive - d->number = dives[0]->number; - - // We will only renumber the remaining dives if the joined dives are consecutive. - // Otherwise all bets are off concerning what the user wanted and doing nothing seems - // like the best option. - int idx = get_divenr(dives[0]); - int num = dives.count(); - if (idx < 0 || idx + num > dive_table.nr) { - // It was the callers responsibility to pass only known dives. - // Something is seriously wrong - give up. - qWarning() << "Merging unknown dives"; - return; - } - // std::equal compares two ranges. The parameters are (begin_range1, end_range1, begin_range2). - // Here, we can compare C-arrays, because QVector guarantees contiguous storage. - if (std::equal(&dives[0], &dives[0] + num, &dive_table.dives[idx]) && - dives[0]->number && dives.last()->number && dives[0]->number < dives.last()->number) { - // We have a consecutive set of dives. Rename all following dives according to the - // number of erased dives. This considers that there might be missing numbers. - // Comment copied from core/divelist.c: - // So if you had a dive list 1 3 6 7 8, and you - // merge 1 and 3, the resulting numbered list will - // be 1 4 5 6, because we assume that there were - // some missing dives (originally dives 4 and 5), - // that now will still be missing (dives 2 and 3 - // in the renumbered world). - // - // Obviously the normal case is that everything is - // consecutive, and the difference will be 1, so the - // above example is not supposed to be normal. - int diff = dives.last()->number - dives[0]->number; - divesToRenumber.reserve(dive_table.nr - idx - num); - int previousnr = dives[0]->number; - for (int i = idx + num; i < dive_table.nr; ++i) { - int newnr = dive_table.dives[i]->number - diff; - - // Stop renumbering if stuff isn't in order (see also core/divelist.c) - if (newnr <= previousnr) - break; - divesToRenumber.append(QPair<int,int>(dive_table.dives[i]->id, newnr)); - previousnr = newnr; - } - } - - mergedDive.dive = std::move(d); - mergedDive.idx = get_divenr(dives[0]); - mergedDive.trip = preferred_trip; - divesToMerge = dives.toStdVector(); -} - -void UndoMergeDives::redo() -{ - renumberDives(divesToRenumber); - diveToUnmerge = addDive(mergedDive); - unmergedDives = removeDives(divesToMerge); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); - MainWindow::instance()->refreshProfile(); -} - -void UndoMergeDives::undo() -{ - divesToMerge = addDives(unmergedDives); - mergedDive = removeDive(diveToUnmerge); - renumberDives(divesToRenumber); - - // Finally, do the UI stuff: - MainWindow::instance()->refreshDisplay(); - MainWindow::instance()->refreshProfile(); -} diff --git a/profile-widget/profilewidget2.cpp b/profile-widget/profilewidget2.cpp index 79b70d719..9221ff293 100644 --- a/profile-widget/profilewidget2.cpp +++ b/profile-widget/profilewidget2.cpp @@ -23,7 +23,7 @@ #include "desktop-widgets/diveplanner.h" #include "desktop-widgets/simplewidgets.h" #include "desktop-widgets/divepicturewidget.h" -#include "desktop-widgets/undocommands.h" +#include "desktop-widgets/command.h" #include "desktop-widgets/mainwindow.h" #include "core/qthelper.h" #include "core/gettextfromc.h" @@ -1685,8 +1685,7 @@ void ProfileWidget2::splitDive() QPointF scenePos = mapToScene(mapFromGlobal(action->data().toPoint())); duration_t time; time.seconds = lrint(timeAxis->valueAt(scenePos)); - UndoSplitDives *undoCommand = new UndoSplitDives(d, time); - MainWindow::instance()->undoStack->push(undoCommand); + Command::splitDives(d, time); emit updateDiveInfo(false); #endif } |