From 7ef7562b065ee3602836f92060d35190ee443fec Mon Sep 17 00:00:00 2001 From: Lioncash Date: Mon, 26 Aug 2019 02:15:25 -0400 Subject: [PATCH] Editor/LayersEditor: Simplify moveRows implementation We can leverage std::rotate to make shuffling around the mappings less complex by defining a begin, end, and a pivot point and using them with it. --- Editor/LayersEditor.cpp | 49 ++++++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/Editor/LayersEditor.cpp b/Editor/LayersEditor.cpp index 4931acf..59efc19 100644 --- a/Editor/LayersEditor.cpp +++ b/Editor/LayersEditor.cpp @@ -1,8 +1,13 @@ #include "LayersEditor.hpp" -#include "MainWindow.hpp" -#include -#include + +#include + #include +#include +#include + +#include "MainWindow.hpp" + class LayerDataChangeUndoCommand : public EditorUndoCommand { QModelIndex m_index; @@ -446,29 +451,27 @@ bool LayersModel::insertRows(int row, int count, const QModelIndex& parent) { bool LayersModel::moveRows(const QModelIndex& sourceParent, int sourceRow, int count, const QModelIndex& destinationParent, int destinationChild) { - if (!m_node) + if (!m_node) { return false; - bool moving = beginMoveRows(sourceParent, sourceRow, sourceRow + count - 1, destinationParent, destinationChild); - std::vector& layers = *m_node->m_obj; - if (destinationChild < sourceRow) { - for (int i = 0; i < count; ++i) { - amuse::LayerMapping tmp = std::move(layers[sourceRow]); - for (int j = sourceRow; j != destinationChild; --j) - layers[j] = std::move(layers[j - 1]); - layers[destinationChild] = std::move(tmp); - ++sourceRow; - ++destinationChild; - } - } else if (destinationChild > sourceRow) { - for (int i = 0; i < count; ++i) { - amuse::LayerMapping tmp = std::move(layers[sourceRow]); - for (int j = sourceRow; j != destinationChild - 1; ++j) - layers[j] = std::move(layers[j + 1]); - layers[destinationChild - 1] = std::move(tmp); - } } - if (moving) + + const bool moving = + beginMoveRows(sourceParent, sourceRow, sourceRow + count - 1, destinationParent, destinationChild); + std::vector& layers = *m_node->m_obj; + + const auto pivot = std::make_move_iterator(layers.begin() + sourceRow); + const auto begin = std::make_move_iterator(layers.begin() + destinationChild); + const auto end = pivot + count; + + if (destinationChild < sourceRow) { + std::rotate(begin, pivot, end); + } else if (destinationChild > sourceRow) { + std::rotate(pivot, end, begin); + } + + if (moving) { endMoveRows(); + } return true; }