diff --git a/src/control/McpServer.cpp b/src/control/McpServer.cpp index 0769068c..095506d2 100644 --- a/src/control/McpServer.cpp +++ b/src/control/McpServer.cpp @@ -365,8 +365,9 @@ QJsonObject McpServer::handleToolsCall(const QJsonObject& params) { const int id = static_cast(args.value("id").toInteger(0)); if (mm.getLayerById(id).isNull()) return textResult(QString("No layer with id %1.").arg(id), true); - const int index = static_cast(args.value("index").toInteger(0)); - _mainWindow->moveLayer(id, index); + const qint64 index = args.value("index").toInteger(-1); + if (index < 0 || index >= mm.nLayers() || !_mainWindow->moveLayer(id, int(index))) + return textResult(QString("Expected a layer index between 0 and %1.").arg(mm.nLayers() - 1), true); return textResult(QString("Moved layer %1 to index %2.").arg(id).arg(index)); } if (name == "set_layer_visible" || name == "set_layer_solo" || name == "set_layer_locked") @@ -694,7 +695,7 @@ QJsonArray McpServer::toolDefinitions() const tools.append(tool("move_layer", "Move a layer to a new stacking index.", QJsonObject{ {"id", prop("integer", "Layer id.")}, - {"index", prop("integer", "Target index (0 = bottom).")} + {"index", prop("integer", "Target index (0 = top).")} }, QJsonArray{"id", "index"})); tools.append(tool("set_layer_visible", "Show or hide a layer. Returns the layer.", diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp index c4268fd2..72c2215f 100644 --- a/src/core/Commands.cpp +++ b/src/core/Commands.cpp @@ -324,49 +324,6 @@ void DeleteLayerCommand::redo() _mainWindow->deleteLayer(_layerId); } -MoveLayerCommand::MoveLayerCommand(MainWindow *mainWindow, uid layerId, MM::MoveElement moveType, QUndoCommand *parent) : - QUndoCommand(parent), - _mainWindow(mainWindow), - _layerId(layerId), - _moveType(moveType) -{ - switch (moveType) { - case MM::Raise: setText(QObject::tr("Raise layer")); break; - case MM::Lower: setText(QObject::tr("Lower layer")); break; - case MM::Top: setText(QObject::tr("Raise layer to top")); break; - case MM::Bottom: setText(QObject::tr("Lower layer to bottom")); break; - default:; // should not happen - } -} - -void MoveLayerCommand::undo() -{ - if (!_layer.isNull()) - { - // Do the inverse move. - _mainWindow->moveLayer(_layerId, _fromIdx); - } -} - -void MoveLayerCommand::redo() -{ - // Store mapping pointer before delete it - _layer = _mainWindow->getMappingManager().getLayerById(_layerId); - _fromIdx = _mainWindow->getMappingManager().getLayerIndex(_layer); - int maxLayerIdx = _mainWindow->getMappingManager().nLayers()-1; - - switch (_moveType) { - case MM::Raise: _toIdx = qMax(_fromIdx - 1, 0); break; - case MM::Lower: _toIdx = qMin(_fromIdx + 1, maxLayerIdx); break; - case MM::Top: _toIdx = 0; break; - case MM::Bottom: _toIdx = maxLayerIdx; break; - default:; // should not happen - } - - // Do the move. - _mainWindow->moveLayer(_layerId, _toIdx); -} - FlipShapeCommand::FlipShapeCommand(MapperGLCanvas *canvas, MShape::FlipDirection direction, QUndoCommand *parent) : TransformShapeCommand (canvas, STEP, parent) { diff --git a/src/core/Commands.h b/src/core/Commands.h index cd791dc6..9b52e2f0 100644 --- a/src/core/Commands.h +++ b/src/core/Commands.h @@ -44,6 +44,7 @@ enum CommandId { }; class MainWindow; +class MappingManager; class MapperGLCanvas; class AddSourceCommand : public QUndoCommand @@ -243,21 +244,23 @@ class DeleteLayerCommand : public QUndoCommand uid _layerId; }; +/// Moves a layer within its project and remembers the row to restore on undo. class MoveLayerCommand : public QUndoCommand { public: - explicit MoveLayerCommand(MainWindow *mainWindow, uid layerId, MM::MoveElement moveType, QUndoCommand *parent = 0); + /// Creates a command for the given layer and direction. + MoveLayerCommand(MappingManager& manager, uid layerId, MM::MoveElement moveType); - void undo() Q_DECL_OVERRIDE; - void redo() Q_DECL_OVERRIDE; + /// Restores the row the layer occupied before the move. + void undo() override; + /// Moves the layer in the requested direction. + void redo() override; private: - MainWindow *_mainWindow; + MappingManager& _manager; Layer::ptr _layer; - uid _layerId; MM::MoveElement _moveType; - int _fromIdx; - int _toIdx; + int _fromIdx = -1; }; /** diff --git a/src/core/MappingManager.cpp b/src/core/MappingManager.cpp index ad5c1841..d501bd39 100644 --- a/src/core/MappingManager.cpp +++ b/src/core/MappingManager.cpp @@ -19,6 +19,8 @@ */ #include "MappingManager.h" + +#include #include namespace mmp { @@ -203,15 +205,18 @@ bool MappingManager::removeLayer(uid mappingId) } } -/// Moves a mapping of given uid by a certain number of steps up or down. +/// Moves a layer to a zero-based row. Returns false for an unknown id or invalid row. bool MappingManager::moveLayer(uid mappingId, int toIndex) { // Make sure the source to which this mapping refers to exists in the manager. int idx = getLayerIndex(mappingId); - if (idx >= 0) + if (idx >= 0 && toIndex >= 0 && toIndex < layerVector.size()) { + if (idx == toIndex) + return true; layerVector.move(idx, toIndex); updateLayerDepths(); + emit layerMoved(mappingId, idx, toIndex); return true; } else @@ -299,26 +304,24 @@ QVector MappingManager::getVisibleSources() const return visibleSources; } -void MappingManager::reorderLayers(QVector mappingIds) +bool MappingManager::reorderLayers(const QVector& layerIds) { - // Both vector needs to have the same size. - Q_ASSERT( mappingIds.size() == layerVector.size() ); - layerVector.clear(); - int depth = 0; - for (QVector::iterator it = mappingIds.begin(); - it != mappingIds.end(); ++it) - { - // Uid should be a key of the layerMap. - Q_ASSERT( layerMap.contains(*it) ); - // Makes sure the uids are not repeated. - Q_ASSERT( ! layerVector.contains(layerMap[*it]) ); - // Adds the mapping at the right place in the vector. - Layer::ptr layer = layerMap[*it]; - layer->setDepth(depth); - layerVector.push_back( layer ); + if (layerIds.size() != layerVector.size()) + return false; - depth++; + QVector ordered; + ordered.reserve(layerIds.size()); + QSet seen; + for (uid id : layerIds) { + const Layer::ptr layer = layerMap.value(id); + if (!layer || seen.contains(id)) + return false; + seen.insert(id); + ordered.append(layer); } + layerVector.swap(ordered); + updateLayerDepths(); + return true; } void MappingManager::updateLayerDepths() diff --git a/src/core/MappingManager.h b/src/core/MappingManager.h index 6997f8a5..24bc01d4 100644 --- a/src/core/MappingManager.h +++ b/src/core/MappingManager.h @@ -39,12 +39,17 @@ namespace mmp { * This is a container class for all the sources and mappings ie. the main model object that allows * CRUD over sources and mappings. */ -class MappingManager +class MappingManager : public QObject { + Q_OBJECT public: - /// Constructor. + /// Constructs an empty project. MappingManager(); +signals: + /// Reports the old and new rows after a layer changes position in the project. + void layerMoved(uid id, int from, int to); + private: // Model elements. /// Container for all sources. @@ -63,7 +68,6 @@ class MappingManager QSize _outputResolution; /// What the triggers of the project (keys of the computer keyboard) do to its settings. - /// Shared by the copies of the manager, which the canvases make to draw. QSharedPointer _links; QSharedPointer _cues; @@ -193,7 +197,7 @@ class MappingManager /// Removes a mapping of given uid. bool removeLayer(uid mappingId); - /// Moves a mapping of given uid by a certain number of steps up or down. + /// Moves a layer to a zero-based row. Returns false for an unknown id or invalid row. bool moveLayer(uid mappingId, int toIndex); /// Returns the number of mappings. @@ -203,7 +207,7 @@ class MappingManager * Returns the i-th mapping in the vector. Good for iterating over all mappings. Vector is * ordered from bottom (deepest) to top (shallowest) layer. */ - Layer::ptr getLayer(int i) { return layerVector[i]; } + Layer::ptr getLayer(int i) const { return layerVector[i]; } /// Returns mapping with given uid. Layer::ptr getLayerById(uid id) const { return layerMap[id]; } @@ -220,8 +224,8 @@ class MappingManager int getLayerDepth(Layer::ptr mapping) const { return -getLayerIndex(mapping); } - /// Reorders the mappings according to given list of uids. QVector needs to - void reorderLayers(QVector mappingIds); + /// Applies a complete permutation of layer ids. An invalid order leaves the project intact. + bool reorderLayers(const QVector& layerIds); /// Update mapping depths after a move. void updateLayerDepths(); diff --git a/src/core/MoveLayerCommand.cpp b/src/core/MoveLayerCommand.cpp new file mode 100644 index 00000000..811558a2 --- /dev/null +++ b/src/core/MoveLayerCommand.cpp @@ -0,0 +1,63 @@ +/* + * MoveLayerCommand.cpp + * + * (c) 2014 Sofian Audry -- info(@)sofianaudry(.)com + * (c) 2014 Alexandre Quessy -- alexandre(@)quessy(.)net + * (c) 2014 Dame Diongue -- baydamd(@)gmail(.)com + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "MappingManager.h" +#include "Commands.h" + +namespace mmp { + +MoveLayerCommand::MoveLayerCommand(MappingManager& manager, uid layerId, MM::MoveElement moveType) + : _manager(manager), _layer(manager.getLayerById(layerId)), _moveType(moveType) +{ + switch (_moveType) { + case MM::Raise: setText(QObject::tr("Raise layer")); break; + case MM::Lower: setText(QObject::tr("Lower layer")); break; + case MM::Top: setText(QObject::tr("Raise layer to top")); break; + case MM::Bottom: setText(QObject::tr("Lower layer to bottom")); break; + } +} + +void MoveLayerCommand::undo() +{ + if (!_manager.moveLayer(_layer->getId(), _fromIdx)) + setObsolete(true); +} + +void MoveLayerCommand::redo() +{ + _fromIdx = _manager.getLayerIndex(_layer); + if (_fromIdx < 0) { + setObsolete(true); + return; + } + const int last = _manager.nLayers() - 1; + int to = _fromIdx; + switch (_moveType) { + case MM::Raise: to = qMax(_fromIdx - 1, 0); break; + case MM::Lower: to = qMin(_fromIdx + 1, last); break; + case MM::Top: to = 0; break; + case MM::Bottom: to = last; break; + } + if (to == _fromIdx || !_manager.moveLayer(_layer->getId(), to)) + setObsolete(true); +} + +} // namespace mmp diff --git a/src/core/Source.cpp b/src/core/Source.cpp index 9c91d289..620f86f7 100644 --- a/src/core/Source.cpp +++ b/src/core/Source.cpp @@ -182,20 +182,18 @@ void Texture::bind() void Texture::uploadBits() { lockMutex(); - _uploadBitsLocked(); + if (bitsHaveChanged()) + _uploadBitsLocked(); unlockMutex(); } void Texture::_uploadBitsLocked() { - if (bitsHaveChanged()) - { - int width = getWidth(); - int height = getHeight(); - const uchar* bits = getBits(); // Resets bitsHaveChanged(). - Util::uploadTextureBits(width, height, getBitsFormat(), getBitsType(), bits, - _uploadedWidth, _uploadedHeight); - } + const int width = getWidth(); + const int height = getHeight(); + const uchar* bits = getBits(); // Resets bitsHaveChanged() and may convert a YUV frame. + Util::uploadTextureBits(width, height, getBitsFormat(), getBitsType(), bits, + _uploadedWidth, _uploadedHeight); } Texture::Texture(uid id) : @@ -719,7 +717,9 @@ void Video::bind() else { glBindTexture(GL_TEXTURE_2D, textureId); - _uploadBitsLocked(); + // Taking the YUV frame cleared its change flag, even if the upload failed. + if (uploading) + _uploadBitsLocked(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); diff --git a/src/core/Source.h b/src/core/Source.h index 98be5995..742e038a 100644 --- a/src/core/Source.h +++ b/src/core/Source.h @@ -258,7 +258,7 @@ class Texture : public Source int effectRenderCount() const; protected: - /// uploadBits() with the mutex already locked. + /// Uploads the current RGB pixels. The caller holds the mutex and detected a new frame. void _uploadBitsLocked(); public: diff --git a/src/core/core.pri b/src/core/core.pri index 5f46cbdb..7078e68d 100644 --- a/src/core/core.pri +++ b/src/core/core.pri @@ -65,6 +65,7 @@ SOURCES += $$PWD/Commands.cpp \ $$PWD/IntermediateImage.cpp \ $$PWD/Layer.cpp \ $$PWD/Link.cpp \ + $$PWD/MoveLayerCommand.cpp \ $$PWD/MappingManager.cpp \ $$PWD/MetaObjectRegistry.cpp \ $$PWD/MidiMessage.cpp \ diff --git a/src/gui/LayerItemDelegate.cpp b/src/gui/LayerItemDelegate.cpp index 8d1fab41..11a2cda0 100644 --- a/src/gui/LayerItemDelegate.cpp +++ b/src/gui/LayerItemDelegate.cpp @@ -267,8 +267,8 @@ void LayerItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opt if (index.column() == MM::GroupButtonColum && isLayerRow(index)) { - bool isSolo = index.model()->data(index, Qt::CheckStateRole + 1).toBool(); - bool isLocked = index.model()->data(index, Qt::CheckStateRole + 2).toBool(); + bool isSolo = index.model()->data(index, LayerTreeModel::SoloRole).toBool(); + bool isLocked = index.model()->data(index, LayerTreeModel::LockedRole).toBool(); // Create all mappings buttons: // solo button QStyleOptionToolButton mappingSoloButton; @@ -456,10 +456,10 @@ bool LayerItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, model->setData(index, !(index.data(Qt::CheckStateRole).toBool()), Qt::CheckStateRole); break; case LayerRowButton::Solo: - model->setData(index, !(index.data(Qt::CheckStateRole + 1).toBool()), Qt::CheckStateRole + 1); + model->setData(index, !(index.data(LayerTreeModel::SoloRole).toBool()), LayerTreeModel::SoloRole); break; case LayerRowButton::Lock: - model->setData(index, !(index.data(Qt::CheckStateRole + 2).toBool()), Qt::CheckStateRole + 2); + model->setData(index, !(index.data(LayerTreeModel::LockedRole).toBool()), LayerTreeModel::LockedRole); break; case LayerRowButton::Duplicate: emit itemDuplicated(index.data(Qt::UserRole).toInt()); diff --git a/src/gui/LayerTreeModel.cpp b/src/gui/LayerTreeModel.cpp index 9732691c..7ddfaefa 100644 --- a/src/gui/LayerTreeModel.cpp +++ b/src/gui/LayerTreeModel.cpp @@ -127,10 +127,10 @@ QVariant LayerTreeModel::data(const QModelIndex &index, int role) const case Qt::SizeHintRole: return rowSizeHint(index.column()); - case Qt::CheckStateRole + 1: + case SoloRole: return layerList.at(index.row()).isSolo ? Qt::Checked : Qt::Unchecked; - case Qt::CheckStateRole + 2: + case LockedRole: return layerList.at(index.row()).isLocked ? Qt::Checked : Qt::Unchecked; case Qt::UserRole: @@ -216,35 +216,29 @@ bool LayerTreeModel::dropMimeData(const QMimeData *data, Qt::DropAction action, if (action == Qt::IgnoreAction) return true; - int endRow; + QByteArray encoded = data->data(MIMETYPE); + QDataStream stream(&encoded, QIODevice::ReadOnly); + int id; + stream >> id; + if (stream.status() != QDataStream::Ok) + return false; + const int from = getItemRowFromId(id); + if (from < 0) + return false; - if (!parent.isValid()) { - if (row < 0) - endRow = layerList.size(); - else - endRow = qMin(row, layerList.size()); - } else { - // Dropped onto a layer, or onto a row under it: the layer takes the row of that layer. - endRow = getItemRowFromId(layerIdOf(parent)); - if (endRow < 0) + // A drop between rows names the insertion gap before removal of the dragged row. + // A drop onto a layer names its final row directly. + int to; + if (parent.isValid()) { + to = getItemRowFromId(layerIdOf(parent)); + if (to < 0) return false; + } else { + const int gap = row < 0 ? int(layerList.size()) : qMin(row, int(layerList.size())); + to = gap > from ? gap - 1 : gap; } - - QByteArray encodeData = data->data(MIMETYPE); - QDataStream stream(&encodeData, QIODevice::ReadOnly); - - while (!stream.atEnd()) { - int id; - stream >> id; - - int row = getItemRowFromId(id); - if (row < 0) - continue; - moveItem(row, endRow); - - ++endRow; - } - + if (to != from) + emit layerMoveRequested(id, to); return true; } @@ -271,7 +265,7 @@ bool LayerTreeModel::setData(const QModelIndex &index, const QVariant &value, in } } - if (role == Qt::CheckStateRole + 1 && value.typeId() == QMetaType::Bool) { + if (role == SoloRole && value.typeId() == QMetaType::Bool) { if (layerList[index.row()].isSolo != value.toBool()) { layerList[index.row()].isSolo = value.toBool(); emit dataChanged(index, index); @@ -279,7 +273,7 @@ bool LayerTreeModel::setData(const QModelIndex &index, const QVariant &value, in } } - if (role == Qt::CheckStateRole + 2 && value.typeId() == QMetaType::Bool) { + if (role == LockedRole && value.typeId() == QMetaType::Bool) { if (layerList[index.row()].isLocked != value.toBool()) { layerList[index.row()].isLocked = value.toBool(); emit dataChanged(index, index); diff --git a/src/gui/LayerTreeModel.h b/src/gui/LayerTreeModel.h index b933d24a..c2c045f8 100644 --- a/src/gui/LayerTreeModel.h +++ b/src/gui/LayerTreeModel.h @@ -61,6 +61,12 @@ class LayerTreeModel : public QAbstractItemModel /// row is under. static const int LayerIdRole = Qt::UserRole + 3; + /// The check state of the solo button on a layer row. + static const int SoloRole = Qt::UserRole + 4; + + /// The check state of the lock button on a layer row. + static const int LockedRole = Qt::UserRole + 5; + /// A row attached under a layer. struct ChildRow { uid id; ///< Id of what the row stands for. @@ -126,6 +132,9 @@ class LayerTreeModel : public QAbstractItemModel bool hasChildRows() const; signals: + /// Requests a new project row for the single layer dragged by the view. + void layerMoveRequested(uid layerId, int to); + /** * Tells that the switch of a child row was clicked: on is the value asked for. The row does * not change by itself; it follows the setting through setChildRows(). diff --git a/src/gui/MainWindow.cpp b/src/gui/MainWindow.cpp index c380996f..0a630440 100644 --- a/src/gui/MainWindow.cpp +++ b/src/gui/MainWindow.cpp @@ -153,6 +153,7 @@ MainWindow::MainWindow() #endif mappingManager = new MappingManager; + connect(mappingManager, &MappingManager::layerMoved, this, &MainWindow::showLayerMove); // A cue reached or placed, by a key, a pad, OSC or the inspector, is said in the status bar: // during a show, one sees which cue went. @@ -424,8 +425,8 @@ void MainWindow::handleLayerItemChanged(const QModelIndex &index) // Change properties. layer->setName(index.data(Qt::EditRole).toString()); layer->setVisible(index.data(Qt::CheckStateRole).toBool()); - layer->setSolo(index.data(Qt::CheckStateRole + 1).toBool()); - layer->setLocked(index.data(Qt::CheckStateRole + 2).toBool()); + layer->setSolo(index.data(LayerTreeModel::SoloRole).toBool()); + layer->setLocked(index.data(LayerTreeModel::LockedRole).toBool()); // Update model (important to make sure icons get updated in the interface). layerListModel->updateModel(); @@ -691,18 +692,6 @@ void MainWindow::setEffectEnabled(LinkTarget::ElementKind element, uid elementId } } -void MainWindow::handleLayerIndexesMoved() -{ - // Resync mapping manager. - syncLayerManager(); - - // Update canvases according to new order. - updateCanvases(); - - // Update playing state. - updatePlayingState(); -} - void MainWindow::handleSourceItemSelected(QTreeWidgetItem* item) { Q_UNUSED(item); @@ -805,11 +794,11 @@ void MainWindow::layerPropertyChanged(uid id, QString propertyName, QVariant val } else if (propertyName == "solo") { - layerListModel->setData(index, layer->isSolo(), Qt::CheckStateRole + 1); + layerListModel->setData(index, layer->isSolo(), LayerTreeModel::SoloRole); } else if (propertyName == "locked") { - layerListModel->setData(index, layer->isLocked(), Qt::CheckStateRole + 2); + layerListModel->setData(index, layer->isLocked(), LayerTreeModel::LockedRole); } } @@ -1904,16 +1893,16 @@ void MainWindow::reorderLayerItem() QAction *actionSender = qobject_cast(sender()); if (actionSender == layerRaiseAction) { - undoStack->push(new MoveLayerCommand(this, getCurrentLayerId(), MM::Raise)); + undoStack->push(new MoveLayerCommand(*mappingManager, getCurrentLayerId(), MM::Raise)); } else if (actionSender == layerLowerAction) { - undoStack->push(new MoveLayerCommand(this, getCurrentLayerId(), MM::Lower)); + undoStack->push(new MoveLayerCommand(*mappingManager, getCurrentLayerId(), MM::Lower)); } else if (actionSender == layerRaiseToTopAction) { - undoStack->push(new MoveLayerCommand(this, getCurrentLayerId(), MM::Top)); + undoStack->push(new MoveLayerCommand(*mappingManager, getCurrentLayerId(), MM::Top)); } else if (actionSender == layerLowerToBottomAction) { - undoStack->push(new MoveLayerCommand(this, getCurrentLayerId(), MM::Bottom)); + undoStack->push(new MoveLayerCommand(*mappingManager, getCurrentLayerId(), MM::Bottom)); } } @@ -2238,7 +2227,7 @@ void MainWindow::setLayerSolo(uid layerId, bool solo) layer->setSolo(solo); // Change list item check state QModelIndex index = layerListModel->getIndexFromId(layerId); - layerListModel->setData(index, solo, Qt::CheckStateRole + 1); + layerListModel->setData(index, solo, LayerTreeModel::SoloRole); // Update canvases updateCanvases(); } @@ -2255,7 +2244,7 @@ void MainWindow::setLayerLocked(uid layerId, bool locked) layer->getShape()->setLocked(locked); // Change list item check state QModelIndex index = layerListModel->getIndexFromId(layerId); - layerListModel->setData(index, locked, Qt::CheckStateRole + 2); + layerListModel->setData(index, locked, LayerTreeModel::LockedRole); // Update canvases updateCanvases(); } @@ -2270,15 +2259,6 @@ void MainWindow::deleteLayer(uid layerId) } } -void MainWindow::moveLayer(uid layerId, int idx) -{ - // Cannot delete unexisting mapping. - if (Layer::getUidAllocator().exists(layerId)) - { - moveLayerItem(layerId, idx); - } -} - void MainWindow::duplicateLayer(uid layerId) { // Clone current Mapping. @@ -4425,22 +4405,15 @@ void MainWindow::removeLayerItem(uid layerId) refreshLinksWindow(); } -void MainWindow::moveLayerItem(uid layerId, int idx) +bool MainWindow::moveLayer(uid layerId, int idx) { - Layer::ptr layer = mappingManager->getLayerById(layerId); - Q_CHECK_PTR(layer); - - // Remove mapping from model. - mappingManager->moveLayer(layerId, idx); - - // Remove widget from layerList. - int row = layerListModel->getItemRowFromId(layerId); - Q_ASSERT( row >= 0 ); - layerListModel->moveItem(row, idx); - - // Update list. - layerListModel->updateModel(); + return mappingManager->moveLayer(layerId, idx); +} +void MainWindow::showLayerMove(uid layerId, int from, int idx) +{ + Q_ASSERT(layerListModel->getItemRowFromId(layerId) == from); + layerListModel->moveItem(from, idx); QModelIndex index = layerListModel->getIndexFromRow(idx); layerList->selectionModel()->select(index, QItemSelectionModel::Select); layerList->setCurrentIndex(index); @@ -4940,19 +4913,6 @@ void MainWindow::clearWindow() clearProject(); } -void MainWindow::syncLayerManager() -{ - // Reorder mappings. - QVector newOrder; - for (int row=0; rowrowCount(); row++) -// for (int row=layerListModel->rowCount()-1; row>=0; row--) - { - uid layerId = layerListModel->getIndexFromRow(row).data(Qt::UserRole).toInt(); - newOrder.push_back(layerId); - } - mappingManager->reorderLayers(newOrder); -} - bool MainWindow::fileExists(const QString &file) { QFileInfo checkFile(file); @@ -5339,7 +5299,7 @@ void MainWindow::connectProjectWidgets() connect(layerListModel, &LayerTreeModel::dataChanged, this, &MainWindow::handleLayerItemChanged); - connect(layerListModel, &LayerTreeModel::rowsMoved, this, &MainWindow::handleLayerIndexesMoved); + connect(layerListModel, &LayerTreeModel::layerMoveRequested, mappingManager, &MappingManager::moveLayer); connect(layerListModel, &LayerTreeModel::modelReset, this, &MainWindow::updateLayerTreeDecoration); connect(layerListModel, &LayerTreeModel::rowsInserted, this, &MainWindow::updateLayerTreeDecoration); @@ -5364,7 +5324,7 @@ void MainWindow::disconnectProjectWidgets() disconnect(layerListModel, &LayerTreeModel::dataChanged, this, &MainWindow::handleLayerItemChanged); - disconnect(layerListModel, &LayerTreeModel::rowsMoved, this, &MainWindow::handleLayerIndexesMoved); + disconnect(layerListModel, &LayerTreeModel::layerMoveRequested, mappingManager, &MappingManager::moveLayer); disconnect(layerListModel, &LayerTreeModel::modelReset, this, &MainWindow::updateLayerTreeDecoration); disconnect(layerListModel, &LayerTreeModel::rowsInserted, this, &MainWindow::updateLayerTreeDecoration); diff --git a/src/gui/MainWindow.h b/src/gui/MainWindow.h index 1288fb45..38ee8df1 100644 --- a/src/gui/MainWindow.h +++ b/src/gui/MainWindow.h @@ -145,7 +145,8 @@ private slots: // void handleItemDoubleClicked(QListWidgetItem* item); void handleLayerItemSelectionChanged(const QModelIndex &index); void handleLayerItemChanged(const QModelIndex &index); - void handleLayerIndexesMoved(); + /// Mirrors a project move in the tree, selection and canvases. + void showLayerMove(uid layerId, int from, int to); /// Shows the triangle and the indentation of the list of layers only when a row is under a layer. void updateLayerTreeDecoration(); /// Shows the triangle and the indentation of the list of sources only when a source has an effect. @@ -314,8 +315,8 @@ public slots: /// Deletes/removes a mapping. void deleteLayer(uid mappingId); - /// Moves a mapping to given index. - void moveLayer(uid mappingId, int idx); + /// Moves an existing layer to a valid row and reports success. + bool moveLayer(uid mappingId, int idx); /// Clone/duplicate a mapping void duplicateLayer(uid mappingId); @@ -480,15 +481,12 @@ public slots: uid addNewSource(Source* source); void addLayerItem(uid mappingId); void removeLayerItem(uid mappingId); - void moveLayerItem(uid mappingId, int steps); void addSourceItem(uid sourceId, const QIcon& icon, const QString& name); void updateSourceItem(uid sourceId, const QIcon& icon, const QString& name); void removeSourceItem(uid sourceId); void renameLayer(uid mappingId, const QString& name); void renameSource(uid sourceId, const QString& name); void clearWindow(); - // Resync mapping manager order the same as the GUI. - void syncLayerManager(); // Check if the file exists bool fileExists(const QString& file); // Check if the file is supported diff --git a/src/gui/MapperGLCanvas.cpp b/src/gui/MapperGLCanvas.cpp index 9ed45025..db3a92e5 100644 --- a/src/gui/MapperGLCanvas.cpp +++ b/src/gui/MapperGLCanvas.cpp @@ -578,7 +578,7 @@ void MapperGLCanvas::mousePressEvent(QMouseEvent* event) } // Possibility of changing shape in output by clicking on it. - MappingManager manager = getMainWindow()->getMappingManager(); + const MappingManager& manager = getMainWindow()->getMappingManager(); QVector mappings = manager.getVisibleLayers(); for (QVector::const_iterator it = mappings.begin(); it != mappings.end(); ++it) @@ -1198,7 +1198,7 @@ void MapperGLCanvas::_snapVertex(QPointF* p) { QSettings settings; int vertexStickRadius = settings.value("vertexStickRadius", MM::VERTEX_STICK_RADIUS).toInt(); - MappingManager manager = MainWindow::window()->getMappingManager(); + const MappingManager& manager = MainWindow::window()->getMappingManager(); MShape::ptr currentShape = getCurrentShape(); for (int i = 0; i < manager.nLayers(); i++) { diff --git a/tests/TestLayerTree.cpp b/tests/TestLayerTree.cpp index 5fdd43f7..71de30be 100644 --- a/tests/TestLayerTree.cpp +++ b/tests/TestLayerTree.cpp @@ -20,6 +20,7 @@ #include "Generators.h" #include "LayerItemDelegate.h" #include "LayerTreeModel.h" +#include "MappingManager.h" #include "LearnMode.h" #include "Shapes.h" #include "SourceItemDelegate.h" @@ -53,8 +54,14 @@ struct ThreeLayers { ThreeLayers() : tester(&model, QAbstractItemModelTester::FailureReportingMode::QtTest) { + QObject::connect(&model, &LayerTreeModel::layerMoveRequested, &manager, &MappingManager::moveLayer); + QObject::connect(&manager, &MappingManager::layerMoved, &model, [this](uid, int from, int to) { + model.moveItem(from, to); + }); for (const QString& name : { QString("Layer 1"), QString("Layer 2"), QString("Layer 3") }) { Layer::ptr layer = makeLayer(name); + manager.addSource(layer->getSource()); + manager.addLayer(layer); layers << layer; model.addItem(layer, QIcon(), name); model.updateModel(); @@ -62,6 +69,7 @@ struct ThreeLayers { } uid id(int i) const { return layers.at(i)->getId(); } + MappingManager manager; LayerTreeModel model; QAbstractItemModelTester tester; QList layers; @@ -88,14 +96,39 @@ void TestLayerTree::rowsFollowStackOrder() QVERIFY(!t.model.hasChildRows()); } +void TestLayerTree::layerSwitchRolesAreIndependent() +{ + ThreeLayers t; + const QModelIndex layer = t.model.index(0, MM::HideColumn); + QVERIFY(t.model.setData(layer, true, LayerTreeModel::SoloRole)); + QVERIFY(layer.data(LayerTreeModel::SoloRole).toBool()); + QVERIFY(!layer.data(LayerTreeModel::LockedRole).toBool()); + QVERIFY(t.model.setData(layer, true, LayerTreeModel::LockedRole)); + QVERIFY(t.model.setData(layer, false, LayerTreeModel::SoloRole)); + QVERIFY(layer.data(LayerTreeModel::LockedRole).toBool()); + QVERIFY(layer.data(Qt::CheckStateRole).toBool()); + QVERIFY(!layer.data(Qt::AccessibleTextRole).isValid()); + QVERIFY(!layer.data(Qt::AccessibleDescriptionRole).isValid()); +} + void TestLayerTree::dragChangesOrder() { ThreeLayers t; QSignalSpy moved(&t.model, &QAbstractItemModel::rowsMoved); + QSignalSpy reset(&t.model, &QAbstractItemModel::modelReset); + QItemSelectionModel selection(&t.model); + selection.setCurrentIndex(t.model.index(2, 0), QItemSelectionModel::ClearAndSelect); // Drag the bottom layer to the top of the list. QVERIFY(dragLayer(t.model, 2, 0)); QCOMPARE(layerNames(t.model), QStringList({ "Layer 1", "Layer 3", "Layer 2" })); QCOMPARE(moved.count(), 1); + QCOMPARE(reset.count(), 0); + QCOMPARE(selection.currentIndex().row(), 0); + QCOMPARE(t.model.layerIdOf(selection.currentIndex()), t.id(0)); + QCOMPARE(t.manager.getLayerIndex(t.id(0)), 0); + QVERIFY(dragLayer(t.model, 0, t.model.rowCount())); + QCOMPARE(t.manager.getLayerIndex(t.id(0)), 2); + QCOMPARE(layerNames(t.model), QStringList({ "Layer 3", "Layer 2", "Layer 1" })); } void TestLayerTree::dropOnLayerMovesToItsRow() @@ -194,7 +227,7 @@ void TestLayerTree::layerIdOfChildIsItsLayer() QCOMPARE(t.model.getItemId(layer), t.id(1)); // A child row is not a layer: it has no eye, no solo and no lock. QVERIFY(!child.data(Qt::CheckStateRole).isValid()); - QVERIFY(!child.data(Qt::CheckStateRole + 1).isValid()); + QVERIFY(!child.data(LayerTreeModel::SoloRole).isValid()); } void TestLayerTree::childRowsAreNotEditable() diff --git a/tests/TestLayerTree.h b/tests/TestLayerTree.h index 79099319..a4a4f442 100644 --- a/tests/TestLayerTree.h +++ b/tests/TestLayerTree.h @@ -20,6 +20,7 @@ class TestLayerTree: public QObject private slots: void rowsFollowStackOrder(); + void layerSwitchRolesAreIndependent(); void dragChangesOrder(); void dropOnLayerMovesToItsRow(); void childRowIsUnderItsLayer(); diff --git a/tests/TestMappingManager.cpp b/tests/TestMappingManager.cpp index 29bbbf61..83e9e55a 100644 --- a/tests/TestMappingManager.cpp +++ b/tests/TestMappingManager.cpp @@ -11,6 +11,8 @@ #include "Generators.h" #include "MappingManager.h" +#include "Commands.h" +#include #include "Shapes.h" using namespace mmp; @@ -81,6 +83,60 @@ void TestMappingManager::newLayersGoOnTop() QCOMPARE(manager.getLayer(1), first); } +void TestMappingManager::moveWithinStack() +{ + MappingManager manager; + const Source::ptr source = makeColor("red"); + manager.addSource(source); + const uid first = manager.addLayer(makeColorLayer(source, "first")); + const uid second = manager.addLayer(makeColorLayer(source, "second")); + QVERIFY(manager.moveLayer(first, 0)); + QVERIFY(!manager.moveLayer(first, -1)); + QVERIFY(!manager.moveLayer(first, manager.nLayers())); + QCOMPARE(manager.getLayerIndex(first), 0); + QCOMPARE(manager.getLayerIndex(second), 1); + QVERIFY(manager.moveLayer(first, 1)); + QCOMPARE(manager.getLayerIndex(first), 1); +} + +void TestMappingManager::undoMoveWithoutWindow() +{ + MappingManager manager; + const Source::ptr source = makeColor("red"); + manager.addSource(source); + const uid first = manager.addLayer(makeColorLayer(source, "first")); + const uid middle = manager.addLayer(makeColorLayer(source, "middle")); + const uid last = manager.addLayer(makeColorLayer(source, "last")); + QUndoStack stack; + stack.push(new MoveLayerCommand(manager, middle, MM::Top)); + QCOMPARE(manager.getLayer(0)->getId(), middle); + stack.undo(); + QCOMPARE(manager.getLayer(0)->getId(), last); + QCOMPARE(manager.getLayer(1)->getId(), middle); + QCOMPARE(manager.getLayer(2)->getId(), first); + stack.redo(); + QCOMPARE(manager.getLayer(0)->getId(), middle); + QCOMPARE(manager.getLayer(1)->getId(), last); +} + +void TestMappingManager::reorderIsAtomic() +{ + MappingManager manager; + const Source::ptr source = makeColor("red"); + manager.addSource(source); + const uid first = manager.addLayer(makeColorLayer(source, "first")); + const uid second = manager.addLayer(makeColorLayer(source, "second")); + QVERIFY(manager.reorderLayers({ first, second })); + const QList> invalidOrders = { { second }, { second, second }, { second, NULL_UID } }; + for (const QVector& order : invalidOrders) { + QVERIFY(!manager.reorderLayers(order)); + QCOMPARE(manager.getLayer(0)->getId(), first); + QCOMPARE(manager.getLayer(1)->getId(), second); + QCOMPARE(manager.getLayer(0)->getDepth(), 0); + QCOMPARE(manager.getLayer(1)->getDepth(), 1); + } +} + void TestMappingManager::findByNamePattern() { MappingManager manager; diff --git a/tests/TestMappingManager.h b/tests/TestMappingManager.h index b9353e7b..0b91d01b 100644 --- a/tests/TestMappingManager.h +++ b/tests/TestMappingManager.h @@ -23,6 +23,9 @@ private slots: void addAndFindSources(); void addAndFindLayers(); void newLayersGoOnTop(); + void moveWithinStack(); + void undoMoveWithoutWindow(); + void reorderIsAtomic(); void findByNamePattern(); void removeLayer(); void removeSourceRemovesItsLayers(); diff --git a/tests/TestVideo.cpp b/tests/TestVideo.cpp index b9ff74ac..3a89c3c1 100644 --- a/tests/TestVideo.cpp +++ b/tests/TestVideo.cpp @@ -195,6 +195,27 @@ class FrameFeeder : public VideoImpl bool _doSeek(qint64) override { return false; } }; +// Keep the real decoded frame for RGB conversion, but make the attempted YUV upload fail. +class FailedYuvFrame : public FrameFeeder +{ +public: + QVideoFrame takeVideoFrame() override + { + FrameFeeder::takeVideoFrame(); + return {}; + } +}; + +class TestFrameVideo : public Video +{ +public: + explicit TestFrameVideo(VideoImpl* frames) + { + delete _impl; + _impl = frames; + } +}; + /// Turns FrameStats on for the life of the object. struct FrameStatsOn { @@ -470,6 +491,35 @@ void TestVideo::yuvShaderDraw() context.doneCurrent(); } +void TestVideo::failedYuvUploadUsesCurrentFrame() +{ + QOffscreenSurface surface; + surface.create(); + QOpenGLContext context; + if (!context.create() || !context.makeCurrent(&surface) || context.isOpenGLES() || !YuvTexture::isAvailable()) + QSKIP("Needs the desktop OpenGL YUV path"); + + auto* frames = new FailedYuvFrame; + TestFrameVideo video(frames); + QVideoFrame black(QVideoFrameFormat(QSize(CLIP_SIZE, CLIP_SIZE), QVideoFrameFormat::Format_RGBX8888)); + QVERIFY(black.map(QVideoFrame::WriteOnly)); + memset(black.bits(0), 0, black.mappedBytes(0)); + black.unmap(); + frames->feed(black); + video.update(); + video.bind(); + + frames->feed(_makeYuvFrame(QVideoFrameFormat::Format_NV12, QVideoFrameFormat::ColorRange_Video)); + QVERIFY(frames->hasVideoFrame()); + video.bind(); + QVERIFY(!frames->bitsHaveChanged()); + QVERIFY(!video.boundYuv()); + QImage pixels(CLIP_SIZE, CLIP_SIZE, QImage::Format_RGBA8888); + glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.bits()); + QCOMPARE(glGetError(), GLenum(GL_NO_ERROR)); + _checkQuadrants([&](int x, int y) { return pixels.pixelColor(x, y); }, "RGB fallback"); +} + void TestVideo::decodedYuvShaderDraw() { if (!_clips.contains("yuv420p")) diff --git a/tests/TestVideo.h b/tests/TestVideo.h index 19f468b6..c6b5d70c 100644 --- a/tests/TestVideo.h +++ b/tests/TestVideo.h @@ -34,6 +34,7 @@ private slots: void glUpload_data(); void glUpload(); + void failedYuvUploadUsesCurrentFrame(); void yuvShaderDraw_data(); void yuvShaderDraw(); diff --git a/tests/tests.pro b/tests/tests.pro index 5b3db761..e8cf50d9 100644 --- a/tests/tests.pro +++ b/tests/tests.pro @@ -192,6 +192,7 @@ SOURCES += \ $$CORE/CameraImpl.cpp \ $$CORE/Layer.cpp \ $$CORE/Link.cpp \ + $$CORE/MoveLayerCommand.cpp \ $$CORE/MappingManager.cpp \ $$CORE/ProjectReader.cpp \ $$CORE/ProjectWriter.cpp \