Skip to content

OpenToonz - An open-source full-featured 2D animation creation software

C

Fix memory leaks, dead stores and improve resource management

andeonec6d5892126b
diff --git a/toonz/sources/toonz/cellkeyframeselection.cpp b/toonz/sources/toonz/cellkeyframeselection.cpp
index 5c021ec6a..92d10c051 100644
--- a/toonz/sources/toonz/cellkeyframeselection.cpp
+++ b/toonz/sources/toonz/cellkeyframeselection.cpp
@@ -18,6 +18,9 @@
#include <QApplication>
#include <QClipboard>
+// C++ includes
+#include <memory>
+
//=============================================================================
// TCellKeyframeSelection
//-----------------------------------------------------------------------------
@@ -26,14 +29,7 @@ TCellKeyframeSelection::TCellKeyframeSelection(
TCellSelection *cellSelection, TKeyframeSelection *keyframeSelection)
: m_cellSelection(cellSelection)
, m_keyframeSelection(keyframeSelection)
- , m_xsheetHandle(0) {}
-
-//-----------------------------------------------------------------------------
-
-TCellKeyframeSelection::~TCellKeyframeSelection() {
- delete m_cellSelection;
- delete m_keyframeSelection;
-}
+ , m_xsheetHandle(nullptr) {}
//-----------------------------------------------------------------------------
@@ -53,32 +49,37 @@ bool TCellKeyframeSelection::isEmpty() const {
//-----------------------------------------------------------------------------
void TCellKeyframeSelection::copyCellsKeyframes() {
- TCellKeyframeData *data = new TCellKeyframeData();
- // Copy cells
+ auto data = std::make_unique<TCellKeyframeData>();
+ bool hasData = false;
+
int r0, c0, r1, c1;
m_cellSelection->getSelectedCells(r0, c0, r1, c1);
- if (!isEmpty()) {
+ if (!m_cellSelection->isEmpty()) {
int colCount = c1 - c0 + 1;
int rowCount = r1 - r0 + 1;
- if (colCount <= 0 || rowCount <= 0) return;
- TXsheet *xsh = m_xsheetHandle->getXsheet();
- TCellData *cellData = new TCellData();
- cellData->setCells(xsh, r0, c0, r1, c1);
- data->setCellData(cellData);
+ if (colCount > 0 && rowCount > 0) {
+ TXsheet *xsh = m_xsheetHandle->getXsheet();
+ auto *cellData = new TCellData();
+ cellData->setCells(xsh, r0, c0, r1, c1);
+ data->setCellData(cellData);
+ hasData = true;
+ }
}
- // Copy keyframes
- if (!isEmpty()) {
- QClipboard *clipboard = QApplication::clipboard();
- TXsheet *xsh = m_xsheetHandle->getXsheet();
- TKeyframeData *keyframeData = new TKeyframeData();
+
+ if (!m_keyframeSelection->isEmpty()) {
+ TXsheet *xsh = m_xsheetHandle->getXsheet();
+ auto *keyframeData = new TKeyframeData();
TKeyframeData::Position startPos(r0, c0);
keyframeData->setKeyframes(m_keyframeSelection->getSelection(), xsh,
startPos);
data->setKeyframeData(keyframeData);
+ hasData = true;
+ }
+
+ if (hasData) {
+ QApplication::clipboard()->setMimeData(data.release(),
+ QClipboard::Clipboard);
}
- // Set the clipboard
- QClipboard *clipboard = QApplication::clipboard();
- clipboard->setMimeData(data, QClipboard::Clipboard);
}
//-----------------------------------------------------------------------------
@@ -94,7 +95,7 @@ void TCellKeyframeSelection::deleteCellsKeyframes() {
// clear cells without shifting
// TODO: behavior of deleting cell+keyframe should also follow the preference
// option.
- m_cellSelection->deleteCells(false);
+ m_cellSelection->deleteCells(false); // clear without shifting
m_keyframeSelection->deleteKeyframes();
TUndoManager::manager()->endBlock();
}
@@ -103,8 +104,9 @@ void TCellKeyframeSelection::deleteCellsKeyframes() {
void TCellKeyframeSelection::cutCellsKeyframes() {
copyCellsKeyframes();
+
TUndoManager::manager()->beginBlock();
- int r0, r1, c0, c1;
+ int r0, c0, r1, c1;
m_cellSelection->getSelectedCells(r0, c0, r1, c1);
m_cellSelection->cutCells(true);
m_keyframeSelection->deleteKeyframesWithShift(r0, r1, c0, c1);
@@ -117,19 +119,18 @@ void TCellKeyframeSelection::selectCellsKeyframes(int r0, int c0, int r1,
int c1) {
m_cellSelection->selectCells(r0, c0, r1, c1);
TXsheet *xsh = m_xsheetHandle->getXsheet();
- m_xsheetHandle->getXsheet();
if (r1 < r0) std::swap(r0, r1);
if (c1 < c0) std::swap(c0, c1);
m_keyframeSelection->clear();
- int r, c;
- for (c = c0; c <= c1; c++)
- for (r = r0; r <= r1; r++) {
- TStageObjectId id =
- c < 0 ? TStageObjectId::CameraId(xsh->getCameraColumnIndex())
+ for (int c = c0; c <= c1; ++c) {
+ TStageObjectId id =
+ (c < 0) ? TStageObjectId::CameraId(xsh->getCameraColumnIndex())
: TStageObjectId::ColumnId(c);
- TStageObject *stObj = xsh->getStageObject(id);
+ TStageObject *stObj = xsh->getStageObject(id);
+ for (int r = r0; r <= r1; ++r) {
if (stObj->isKeyframe(r)) m_keyframeSelection->select(r, c);
}
+ }
}
//-----------------------------------------------------------------------------
@@ -138,8 +139,8 @@ void TCellKeyframeSelection::selectCellKeyframe(int row, int col) {
m_cellSelection->selectCell(row, col);
TXsheet *xsh = m_xsheetHandle->getXsheet();
TStageObjectId id =
- col < 0 ? TStageObjectId::CameraId(xsh->getCameraColumnIndex())
- : TStageObjectId::ColumnId(col);
+ (col < 0) ? TStageObjectId::CameraId(xsh->getCameraColumnIndex())
+ : TStageObjectId::ColumnId(col);
TStageObject *stObj = xsh->getStageObject(id);
m_keyframeSelection->clear();
if (stObj->isKeyframe(row)) m_keyframeSelection->select(row, col);
diff --git a/toonz/sources/toonz/cellkeyframeselection.h b/toonz/sources/toonz/cellkeyframeselection.h
index 20768ba4a..77a036e7a 100644
--- a/toonz/sources/toonz/cellkeyframeselection.h
+++ b/toonz/sources/toonz/cellkeyframeselection.h
@@ -7,7 +7,7 @@
#include "cellselection.h"
#include "keyframeselection.h"
#include "tgeometry.h"
-#include <set>
+#include <memory>
class TXsheetHandle;
@@ -16,18 +16,25 @@ class TXsheetHandle;
//-----------------------------------------------------------------------------
class TCellKeyframeSelection final : public TSelection {
- TCellSelection *m_cellSelection;
- TKeyframeSelection *m_keyframeSelection;
-
- TXsheetHandle *m_xsheetHandle;
+ std::unique_ptr<TCellSelection> m_cellSelection;
+ std::unique_ptr<TKeyframeSelection> m_keyframeSelection;
+ TXsheetHandle *m_xsheetHandle = nullptr;
public:
TCellKeyframeSelection(TCellSelection *cellSelection,
TKeyframeSelection *keyframeSelection);
- ~TCellKeyframeSelection();
+ ~TCellKeyframeSelection() = default; // unique_ptr handles deletion
+
+ // Prohibit copying and moving
+ TCellKeyframeSelection(const TCellKeyframeSelection &) = delete;
+ TCellKeyframeSelection &operator=(const TCellKeyframeSelection &) = delete;
+ TCellKeyframeSelection(TCellKeyframeSelection &&) = delete;
+ TCellKeyframeSelection &operator=(TCellKeyframeSelection &&) = delete;
- TCellSelection *getCellSelection() { return m_cellSelection; }
- TKeyframeSelection *getKeyframeSelection() { return m_keyframeSelection; }
+ TCellSelection *getCellSelection() const { return m_cellSelection.get(); }
+ TKeyframeSelection *getKeyframeSelection() const {
+ return m_keyframeSelection.get();
+ }
void setXsheetHandle(TXsheetHandle *xsheetHandle) {
m_xsheetHandle = xsheetHandle;
@@ -42,43 +49,10 @@ public:
void deleteCellsKeyframes();
void cutCellsKeyframes();
- //! \note: puo' anche essere r0>r1 o c0>c1
+ //! \note: r0, c0, r1, c1 can be in any order (r0>r1 or c0>c1)
void selectCellsKeyframes(int r0, int c0, int r1, int c1);
void selectCellKeyframe(int row, int col);
void selectNone() override;
-
- /*
- void getSelectedCells(int &r0, int &c0, int &r1, int &c1) const;
- Range getSelectedCells() const;
-
-bool isCellSelected(int r , int c) const;
-bool isRowSelected(int row) const;
-bool isColSelected(int col) const;
-
-bool areAllColSelectedLocked() const;
-
- //commands
-void reverseCells();
- void swingCells();
- void incrementCells();
-void duplicateCells();
- void randomCells();
- void stepCells(int count);
- void eachCells(int count);
-void step2Cells() {stepCells(2);}
-void step3Cells() {stepCells(3);}
-void step4Cells() {stepCells(4);}
-void each2Cells() {eachCells(2);}
-void each3Cells() {eachCells(3);}
-void each4Cells() {eachCells(4);}
- void rollupCells();
- void rolldownCells();
-
- void setKeyframes();
- void cloneLevel();
-void insertCells();
-
-void openTimeStretchPopup();*/
};
#endif // TCELLKEYFRAMESELECTION_H
diff --git a/toonz/sources/toonz/cellselection.cpp b/toonz/sources/toonz/cellselection.cpp
index a58d06c84..651ff8f39 100644
--- a/toonz/sources/toonz/cellselection.cpp
+++ b/toonz/sources/toonz/cellselection.cpp
@@ -72,6 +72,9 @@
#include <QApplication>
#include <QClipboard>
+// C++ includes
+#include <memory>
+
//=============================================================================
namespace {
//-----------------------------------------------------------------------------
@@ -100,8 +103,7 @@ void copyCellsWithoutUndo(int r0, int c0, int r1, int c1) {
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
TCellData *data = new TCellData();
data->setCells(xsh, r0, c0, r1, c1);
- QClipboard *clipboard = QApplication::clipboard();
- clipboard->setMimeData(data, QClipboard::Clipboard);
+ QApplication::clipboard()->setMimeData(data, QClipboard::Clipboard);
}
//-----------------------------------------------------------------------------
@@ -262,18 +264,11 @@ public:
->setName(item.second);
}
- int c0BeforeCut = c0;
- int c1BeforeCut = c1;
// Cut cells that are in newSelection
cutCellsWithoutUndo(r0, c0, r1, c1);
// If the columns were empty, reset them (this is necessary for special
// columns, sound columns or palette)
- assert(c1BeforeCut - c0BeforeCut + 1 == (int)m_areOldColumnsEmpty.size());
- int c;
- for (c = c0BeforeCut; c <= c1BeforeCut; c++) {
- if (!m_areOldColumnsEmpty[c - c0BeforeCut] || !xsh->getColumn(c))
- continue;
- }
+ assert(c1 - c0 + 1 == (int)m_areOldColumnsEmpty.size());
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
if (m_containsSoundColumn)
@@ -907,16 +902,18 @@ public:
//=============================================================================
-// Paste drawings in cell without undo
-void pasteDrawingsInCellWithoutUndo(TXsheet *xsh, TXshSimpleLevel *level,
+// Paste drawings in cell without undo use smart pointer for free
+void pasteDrawingsInCellWithoutUndo(TXsheet *xsh, TXshSimpleLevelP level,
const std::set<TFrameId> &frameIds, int r0,
int c0) {
int frameToInsert = frameIds.size();
xsh->insertCells(r0, c0, frameToInsert);
std::set<TFrameId>::const_iterator it;
int r = r0;
+ // Use smart pointer to ensure the level stays alive during the operation
+ TXshSimpleLevelP levelRef = level;
for (it = frameIds.begin(); it != frameIds.end(); it++, r++) {
- TXshCell cell(level, *it);
+ TXshCell cell(levelRef.getPointer(), *it);
xsh->setCell(r, c0, cell);
}
}
@@ -1007,8 +1004,6 @@ public:
TCellData *beforeData, bool containsSoundColumn)
: m_areOldColumnsEmpty(areColumnsEmpty)
, m_containsSoundColumn(containsSoundColumn) {
- QClipboard *clipboard = QApplication::clipboard();
- /*-- Keep the pasted cells in data --*/
TCellData *data = new TCellData();
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
data->setCells(xsh, r0, c0, r1, c1);
@@ -1037,16 +1032,13 @@ public:
m_oldSelection->getSelectedCells(oldR0, oldC0, oldR1, oldC1);
QClipboard *clipboard = QApplication::clipboard();
- int c0BeforeCut = c0;
- int c1BeforeCut = c1;
cutCellsWithoutUndo(r0, c0, r1, c1);
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
- assert(c1BeforeCut - c0BeforeCut + 1 == (int)m_areOldColumnsEmpty.size());
+ assert(c1 - c0 + 1 == (int)m_areOldColumnsEmpty.size());
int c;
- for (c = c0BeforeCut; c <= c1BeforeCut; c++) {
- if (!m_areOldColumnsEmpty[c - c0BeforeCut] || !xsh->getColumn(c))
- continue;
+ for (c = c0; c <= c1; c++) {
+ if (!m_areOldColumnsEmpty[c - c0] || !xsh->getColumn(c)) continue;
xsh->removeColumn(c);
xsh->insertColumn(c);
}
@@ -1130,7 +1122,6 @@ public:
OverwritePasteNumbersUndo(int r0, int c0, int r1, int c1, int oldR0,
int oldC0, int oldR1, int oldC1,
TCellData *beforeData) {
- QClipboard *clipboard = QApplication::clipboard();
// keep the pasted data
TCellData *data = new TCellData();
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
@@ -1159,8 +1150,6 @@ public:
m_oldSelection->getSelectedCells(oldR0, oldC0, oldR1, oldC1);
QClipboard *clipboard = QApplication::clipboard();
- int c0BeforeCut = c0;
- int c1BeforeCut = c1;
cutCellsWithoutUndo(r0, c0, r1, c1);
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
@@ -2621,12 +2610,14 @@ void TCellSelection::deleteCells(bool withShift) {
}
}
- DeleteCellsUndo *undo =
- new DeleteCellsUndo(new TCellSelection(m_range), data, withShift);
+ // Use unique_ptr to prevent memory leak in case of early return
+ std::unique_ptr<DeleteCellsUndo> undo(
+ new DeleteCellsUndo(new TCellSelection(m_range), data, withShift));
deleteCellsWithoutUndo(r0, c0, r1, c1, withShift);
- TUndoManager::manager()->add(undo);
+ // Transfer ownership to TUndoManager
+ TUndoManager::manager()->add(undo.release());
if (!removedColIds.empty()) {
TUndoManager::manager()->endBlock();
@@ -2641,8 +2632,7 @@ void TCellSelection::deleteCells(bool withShift) {
TApp::instance()->getCurrentScene()->setDirtyFlag(true);
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
- if (undo->containsSoundColumn())
- TApp::instance()->getCurrentXsheet()->notifyXsheetSoundChanged();
+ TApp::instance()->getCurrentXsheet()->notifyXsheetSoundChanged();
}
//-----------------------------------------------------------------------------
@@ -2654,7 +2644,8 @@ void TCellSelection::cutCells() { cutCells(false); }
void TCellSelection::cutCells(bool withoutCopy) {
if (isEmpty()) return;
- CutCellsUndo *undo = new CutCellsUndo(new TCellSelection(m_range));
+ std::unique_ptr<CutCellsUndo> undo(
+ new CutCellsUndo(new TCellSelection(m_range)));
int r0, c0, r1, c1;
getSelectedCells(r0, c0, r1, c1);
@@ -2664,8 +2655,7 @@ void TCellSelection::cutCells(bool withoutCopy) {
// check if the operation may remove expression reference as column becomes
// empty and deleted after the operation.
if (!checkColumnRemoval(r0, c0, r1, c1, removedColIds)) {
- delete undo;
- return;
+ return; // unique_ptr will be automatically deleted
}
undo->setCurrentData(r0, c0, r1, c1);
@@ -2683,7 +2673,8 @@ void TCellSelection::cutCells(bool withoutCopy) {
cutCellsWithoutUndo(r0, c0, r1, c1);
- TUndoManager::manager()->add(undo);
+ // Transfer ownership to TUndoManager
+ TUndoManager::manager()->add(undo.release());
if (!removedColIds.empty()) {
TUndoManager::manager()->endBlock();
@@ -2698,8 +2689,7 @@ void TCellSelection::cutCells(bool withoutCopy) {
TApp::instance()->getCurrentScene()->setDirtyFlag(true);
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
- if (undo->containsSoundColumn())
- TApp::instance()->getCurrentXsheet()->notifyXsheetSoundChanged();
+ TApp::instance()->getCurrentXsheet()->notifyXsheetSoundChanged();
}
//-----------------------------------------------------------------------------
@@ -3068,22 +3058,21 @@ static void dRenumberCells(int col, int r0, int r1) {
TXshCell cell = xsh->getCell(r, col);
if (!cell.isEmpty() && cell.getSimpleLevel() &&
(r <= 0 || xsh->getCell(r - 1, col) != cell)) {
- // In case the cell was already mapped, skip
TXshCell &toCell = cellsMap[cell];
if (!toCell.isEmpty()) continue;
- // Build cell mapping
- TXshSimpleLevel *sl = cell.getSimpleLevel();
+ TXshSimpleLevel *sl = cell.getSimpleLevel(); // Get raw pointer
TFrameId oldFid = cell.getFrameId();
TFrameId newFid =
TFrameId(r + 1, 0, oldFid.getZeroPadding(), oldFid.getStartSeqInd());
- toCell.m_level = sl;
+ // Convert TXshSimpleLevel* to TXshLevelP (base class smart pointer)
+ toCell.m_level = TXshLevelP(sl); // This constructor should exist
toCell.m_frameId = newFid;
- // Build the level frames mapping
- if (sl->isFid(oldFid))
+ // Check if sl is not null before using it
+ if (sl && sl->isFid(oldFid))
levelsTable[sl].push_back(std::make_pair(oldFid, newFid));
}
}
@@ -3101,6 +3090,7 @@ static void dRenumberCells(int col, int r0, int r1) {
CellsMap::iterator it, end = cellsMap.end();
for (it = cellsMap.begin(); it != end; ++it) {
if (cellsMap.find(it->second) == cellsMap.end() &&
+ it->first.getSimpleLevel() &&
it->first.getSimpleLevel()->isFid(it->second.getFrameId())) {
TFrameId &fid = it->second.m_frameId;
fid = TFrameId(fid.getNumber(), getNextLetter(fid.getLetter()),
diff --git a/toonz/sources/toonz/cellselection.h b/toonz/sources/toonz/cellselection.h
index 14f2d80f0..adf83cc8c 100644
--- a/toonz/sources/toonz/cellselection.h
+++ b/toonz/sources/toonz/cellselection.h
@@ -6,6 +6,7 @@
#include "toonzqt/selection.h"
#include "tgeometry.h"
#include <set>
+#include <QList>
class TimeStretchPopup;
class ReframePopup;
@@ -55,12 +56,12 @@ public:
void cutCells();
void cutCells(bool withoutCopy);
- /*- セルの上書きペースト -*/
+ /*- Overwrite paste cells -*/
void overWritePasteCells();
// paste cell numbers only
void overwritePasteNumbers();
- //! \note: puo' anche essere r0>r1 o c0>c1
+ //! \note: r0, c0, r1, c1 can be in any order (r0>r1 or c0>c1)
void selectCells(int r0, int c0, int r1, int c1);
void selectCell(int row, int col);
void selectNone() override;
@@ -127,7 +128,7 @@ public:
static bool isEnabledCommand(std::string commandId);
- void createBlankDrawing(int row, int col, bool inRange);
+ void createBlankDrawing(int row, int col, bool multiple);
void createBlankDrawings();
void fillEmptyCell();
int getResizePivotRow() const { return m_resizePivotRow; }
diff --git a/toonz/sources/toonz/filebrowser.cpp b/toonz/sources/toonz/filebrowser.cpp
index 4f55b817d..9e60c0a17 100644
--- a/toonz/sources/toonz/filebrowser.cpp
+++ b/toonz/sources/toonz/filebrowser.cpp
@@ -1,3 +1,5 @@
+
+
#include "filebrowser.h"
// Tnz6 includes
@@ -81,6 +83,9 @@
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/adaptor/transformed.hpp>
+// C++ includes
+#include <memory> // std::unique_ptr, std::make_unique
+
namespace ba = boost::adaptors;
using namespace DVGui;
@@ -101,15 +106,12 @@ class FrameCountTask final : public TThread::Runnable {
public:
FrameCountTask(const TFilePath &path, const QDateTime &modifiedDate);
-
~FrameCountTask();
void run() override;
-
QThread::Priority runningPriority() override;
public slots:
-
void onStarted(TThread::RunnableP thisTask) override;
void onCanceled(TThread::RunnableP thisTask) override;
};
@@ -124,8 +126,8 @@ struct FCData {
bool m_underProgress;
int m_retryCount;
- FCData() {}
- FCData(const QDateTime &date);
+ FCData() = default;
+ explicit FCData(const QDateTime &date);
};
//=============================================================================
@@ -137,7 +139,6 @@ std::set<FileBrowser *> activeBrowsers;
std::map<TFilePath, FCData> frameCountMap;
QMutex frameCountMapMutex;
QMutex levelFileMutex;
-
} // namespace
//=============================================================================
@@ -146,7 +147,7 @@ QMutex levelFileMutex;
FileBrowser::FileBrowser(QWidget *parent, Qt::WindowFlags flags,
bool noContextMenu, bool multiSelectionEnabled)
- : QFrame(parent), m_folderName(0), m_itemViewer(0) {
+ : QFrame(parent), m_folderName(nullptr), m_itemViewer(nullptr) {
// style sheet
setObjectName("FileBrowser");
setFrameStyle(QFrame::StyledPanel);
@@ -155,7 +156,7 @@ FileBrowser::FileBrowser(QWidget *parent, Qt::WindowFlags flags,
m_folderTreeView = new DvDirTreeView(this);
QFrame *box = new QFrame(this);
QLabel *folderLabel = new QLabel(tr("Folder: "), this);
- m_folderName = new QLineEdit();
+ m_folderName = new QLineEdit(this);
m_itemViewer = new DvItemViewer(box, noContextMenu, multiSelectionEnabled,
DvItemViewer::Browser);
DvItemViewerTitleBar *titleBar = new DvItemViewerTitleBar(m_itemViewer, box);
@@ -214,12 +215,8 @@ FileBrowser::FileBrowser(QWidget *parent, Qt::WindowFlags flags,
m_mainSplitter->setSizes(QList<int>() << 270 << 500);
- // Modernized signal-slot connections using member function pointers
connect(m_folderTreeView, &DvDirTreeView::currentNodeChanged,
itemViewPlayDelegate, &DVItemViewPlayDelegate::resetPlayWidget);
-
- // if the current folder is changed in the folder tree, then update in the
- // item view
connect(m_folderTreeView, &DvDirTreeView::currentNodeChanged, this,
&FileBrowser::onTreeFolderChanged);
@@ -235,17 +232,17 @@ FileBrowser::FileBrowser(QWidget *parent, Qt::WindowFlags flags,
&FileBrowser::newFolder);
connect(&m_frameCountReader, &FrameCountReader::calculatedFrameCount,
- m_itemViewer->getPanel(),
- [panel = m_itemViewer->getPanel()]() { panel->update(); });
+ m_itemViewer->getPanel(), qOverload<>(&DvItemViewerPanel::update));
QAction *refresh = CommandManager::instance()->getAction(MI_RefreshTree);
connect(refresh, &QAction::triggered, this, &FileBrowser::refresh);
addAction(refresh);
// Version Control instance connection
- if (Preferences::instance()->isSVNEnabled())
+ if (Preferences::instance()->isSVNEnabled()) {
connect(VersionControl::instance(), &VersionControl::commandDone, this,
&FileBrowser::onVersionControlCommandDone);
+ }
// if the folderName is edited, move the current folder accordingly
connect(m_folderName, &QLineEdit::editingFinished, this,
@@ -258,7 +255,6 @@ FileBrowser::FileBrowser(QWidget *parent, Qt::WindowFlags flags,
&FileBrowser::onBackButtonPushed);
connect(buttonBar, &DvItemViewerButtonBar::folderFwd, this,
&FileBrowser::onFwdButtonPushed);
-
// when the history changes, enable/disable the history buttons accordingly
connect(this, &FileBrowser::historyChanged, buttonBar,
&DvItemViewerButtonBar::onHistoryChanged);
@@ -279,11 +275,10 @@ FileBrowser::FileBrowser(QWidget *parent, Qt::WindowFlags flags,
//-----------------------------------------------------------------------------
-FileBrowser::~FileBrowser() {}
+FileBrowser::~FileBrowser() = default; // all child widgets are auto-deleted
//-----------------------------------------------------------------------------
-/*! when the m_folderName is edited, move the current folder accordingly
- */
+
void FileBrowser::onFolderEdited() {
TFilePath inputPath(m_folderName->text().toStdWString());
QModelIndex index = DvDirModel::instance()->getIndexByPath(inputPath);
@@ -315,27 +310,26 @@ void FileBrowser::storeFolderHistory() {
QModelIndex currentModelIndex = m_folderTreeView->currentIndex();
if (!currentModelIndex.isValid()) return;
-
if (m_indexHistoryList[m_currentPosition] == currentModelIndex) return;
// If there is no next history item, then create it
if (m_currentPosition == m_indexHistoryList.size() - 1) {
m_indexHistoryList << currentModelIndex;
- m_currentPosition++;
+ ++m_currentPosition;
}
// If the next history item is the same as the current one, just move to it
else if (m_indexHistoryList[m_currentPosition + 1] == currentModelIndex) {
- m_currentPosition++;
+ ++m_currentPosition;
}
// If the next history item is different from the current one, then replace
// with the new one
else {
int size = m_indexHistoryList.size();
// remove the old history items
- for (int i = m_currentPosition + 1; i < size; i++)
+ for (int i = m_currentPosition + 1; i < size; ++i)
m_indexHistoryList.removeLast();
m_indexHistoryList << currentModelIndex;
- m_currentPosition++;
+ ++m_currentPosition;
}
refreshHistoryButtons();
}
@@ -343,15 +337,15 @@ void FileBrowser::storeFolderHistory() {
//-----------------------------------------------------------------------------
void FileBrowser::refreshHistoryButtons() {
- emit historyChanged((m_currentPosition != 0),
- (m_currentPosition != m_indexHistoryList.size() - 1));
+ emit historyChanged(m_currentPosition != 0,
+ m_currentPosition != m_indexHistoryList.size() - 1);
}
//-----------------------------------------------------------------------------
void FileBrowser::onBackButtonPushed() {
if (m_currentPosition == 0) return;
- m_currentPosition--;
+ --m_currentPosition;
QModelIndex currentIndex = m_indexHistoryList[m_currentPosition];
m_folderTreeView->setCurrentIndex(currentIndex);
m_folderTreeView->collapseAll();
@@ -360,7 +354,6 @@ void FileBrowser::onBackButtonPushed() {
m_folderTreeView->expand(currentIndex);
}
m_folderTreeView->update();
-
refreshHistoryButtons();
}
@@ -368,7 +361,7 @@ void FileBrowser::onBackButtonPushed() {
void FileBrowser::onFwdButtonPushed() {
if (m_currentPosition >= m_indexHistoryList.size() - 1) return;
- m_currentPosition++;
+ ++m_currentPosition;
QModelIndex currentIndex = m_indexHistoryList[m_currentPosition];
m_folderTreeView->setCurrentIndex(currentIndex);
m_folderTreeView->collapseAll();
@@ -377,7 +370,6 @@ void FileBrowser::onFwdButtonPushed() {
m_folderTreeView->expand(currentIndex);
}
m_folderTreeView->update();
-
refreshHistoryButtons();
}
@@ -387,7 +379,7 @@ void FileBrowser::onFwdButtonPushed() {
void FileBrowser::clearHistory() {
int size = m_indexHistoryList.size();
// leave the last item
- for (int i = 1; i < size; i++) m_indexHistoryList.removeLast();
+ for (int i = 1; i < size; ++i) m_indexHistoryList.removeLast();
m_currentPosition = 0;
refreshHistoryButtons();
}
@@ -410,18 +402,18 @@ void FileBrowser::sortByDataModel(DataType dataType, bool isDiscendent) {
struct locals {
static inline bool itemLess(int aIdx, int bIdx, FileBrowser &fb,
DataType dataType) {
- return (fb.compareData(dataType, aIdx, bIdx) > 0);
+ return fb.compareData(dataType, aIdx, bIdx) > 0;
}
static inline bool indexLess(int aIdx, int bIdx,
const std::vector<int> &vec) {
- return (vec[aIdx] < vec[bIdx]);
+ return vec[aIdx] < vec[bIdx];
}
static inline int complement(int val, int max) {
return (assert(0 <= val && val <= max), max - val);
}
- }; // locals
+ };
if (dataType != getCurrentOrderType()) {
// Build the permutation table
@@ -478,7 +470,9 @@ void FileBrowser::sortByDataModel(DataType dataType, bool isDiscendent) {
FileSelection *fs =
dynamic_cast<FileSelection *>(m_itemViewer->getPanel()->getSelection());
- if (!fs->isEmpty()) {
+ if (!fs || fs->isEmpty()) {
+ // nothing to do
+ } else {
int iCount = int(m_items.size()), lastIdx = iCount - 1;
std::vector<int> newSelectedIndices;
@@ -523,13 +517,13 @@ void FileBrowser::refreshCurrentFolderItems() {
// put the parent directory item
TFilePath parentFp = m_folder.getParentDir();
if (parentFp != TFilePath("") && parentFp != m_folder)
- m_items.push_back(Item(parentFp, true, false));
+ m_items.emplace_back(parentFp, true, false);
// register all folder items by using the folder tree model
DvDirModel *model = DvDirModel::instance();
QModelIndex currentIndex = model->getIndexByPath(m_folder);
if (currentIndex.isValid()) {
- for (int i = 0; i < model->rowCount(currentIndex); i++) {
+ for (int i = 0; i < model->rowCount(currentIndex); ++i) {
QModelIndex tmpIndex = model->index(i, 0, currentIndex);
if (tmpIndex.isValid()) {
DvDirModelFileFolderNode *node =
@@ -537,11 +531,11 @@ void FileBrowser::refreshCurrentFolderItems() {
if (node) {
TFilePath childFolderPath = node->getPath();
if (TFileStatus(childFolderPath).isLink())
- m_items.push_back(Item(childFolderPath, true, true,
- QString::fromStdWString(node->getName())));
+ m_items.emplace_back(childFolderPath, true, true,
+ QString::fromStdWString(node->getName()));
else
- m_items.push_back(Item(childFolderPath, true, false,
- QString::fromStdWString(node->getName())));
+ m_items.emplace_back(childFolderPath, true, false,
+ QString::fromStdWString(node->getName()));
}
}
}
@@ -567,42 +561,41 @@ void FileBrowser::refreshCurrentFolderItems() {
} catch (...) {
}
}
- TFilePathSet::iterator it;
- for (it = files.begin(); it != files.end(); ++it) {
+
+ for (const TFilePath &it : files) {
#ifdef _WIN32
// include folder shortcut items
- if (it->getType() == "lnk") {
- TFileStatus info(*it);
+ if (it.getType() == "lnk") {
+ TFileStatus info(it);
if (info.isLink() && info.isDirectory()) {
- m_items.push_back(
- Item(*it, true, true, QString::fromStdString((*it).getName())));
+ m_items.emplace_back(it, true, true,
+ QString::fromStdString(it.getName()));
}
continue;
}
#endif
// skip the plt file (Palette file for TOONZ 4.6 and earlier)
- if (it->getType() == "plt") continue;
+ if (it.getType() == "plt") continue;
// filter the file
else if (m_filter.isEmpty()) {
- if (it->getType() != "tnz" && it->getType() != "scr" &&
- it->getType() != "tnzbat" && it->getType() != "mpath" &&
- it->getType() != "curve" && it->getType() != "tpl" &&
- TFileType::getInfo(*it) == TFileType::UNKNOW_FILE)
+ if (it.getType() != "tnz" && it.getType() != "scr" &&
+ it.getType() != "tnzbat" && it.getType() != "mpath" &&
+ it.getType() != "curve" && it.getType() != "tpl" &&
+ TFileType::getInfo(it) == TFileType::UNKNOW_FILE)
continue;
- } else if (!m_filter.contains(QString::fromStdString(it->getType())))
+ } else if (!m_filter.contains(QString::fromStdString(it.getType())))
continue;
// store the filtered file paths
- m_items.push_back(Item(*it));
+ m_items.emplace_back(it);
}
// update the m_multiFileItemMap
m_multiFileItemMap.clear();
- for (it = all_files.begin(); it != all_files.end(); it++) {
- TFrameId tFrameId;
- tFrameId = it->getFrame();
- TFilePath levelName(it->getLevelName());
+ for (const TFilePath &it : all_files) {
+ TFrameId tFrameId = it.getFrame();
+ TFilePath levelName(it.getLevelName());
if (levelName.isLevelName()) {
Item &levelItem = m_multiFileItemMap[levelName];
@@ -610,12 +603,11 @@ void FileBrowser::refreshCurrentFolderItems() {
// TODO:
// For now, leave it as is, but if obtaining FileInfo takes too much
// time, consider making it optional 2015/12/28 shun_iwasawa
- QFileInfo fileInfo(QString::fromStdWString(it->getWideString()));
+ QFileInfo fileInfo(QString::fromStdWString(it.getWideString()));
// Get creation time safely across platforms
QDateTime creationTime = fileInfo.birthTime();
if (!creationTime.isValid())
- creationTime =
- fileInfo.metadataChangeTime(); // or fileInfo.lastModified()
+ creationTime = fileInfo.metadataChangeTime();
// Update level infos
if (levelItem.m_creationDate.isNull() ||
@@ -642,8 +634,7 @@ void FileBrowser::refreshCurrentFolderItems() {
if (node) {
QList<TFilePath> list = node->getMissingFiles();
missingItemCount = list.size();
- for (int i = 0; i < missingItemCount; i++)
- m_items.push_back(Item(list.at(i)));
+ for (int i = 0; i < missingItemCount; ++i) m_items.emplace_back(list.at(i));
}
// Refresh Data (fill Item field)
@@ -652,12 +643,11 @@ void FileBrowser::refreshCurrentFolderItems() {
// If I added some missing items I need to sort items.
if (missingItemCount > 0) {
DataType currentDataType = getCurrentOrderType();
- int i;
- for (i = 1; i < m_items.size(); i++) {
+ for (int i = 1; i < (int)m_items.size(); ++i) {
int index = i;
while (index > 0 && compareData(currentDataType, index - 1, index) > 0) {
std::swap(m_items[index - 1], m_items[index]);
- index = index - 1;
+ --index;
}
}
}
@@ -720,51 +710,49 @@ void FileBrowser::setUnregisteredFolder(const TFilePath &fp) {
}
}
- TFilePathSet::iterator it;
-
// register all folder items
- for (it = folders.begin(); it != folders.end(); ++it) {
- if (TFileStatus(*it).isLink())
- m_items.push_back(Item(*it, true, true));
+ for (const TFilePath &it : folders) {
+ if (TFileStatus(it).isLink())
+ m_items.emplace_back(it, true, true);
else
- m_items.push_back(Item(*it, true, false));
+ m_items.emplace_back(it, true, false);
}
- for (it = files.begin(); it != files.end(); ++it) {
+ for (const TFilePath &it : files) {
#ifdef _WIN32
// include folder shortcut items
- if (it->getType() == "lnk") {
- TFileStatus info(*it);
+ if (it.getType() == "lnk") {
+ TFileStatus info(it);
if (info.isLink() && info.isDirectory()) {
- m_items.push_back(
- Item(*it, true, true, QString::fromStdString((*it).getName())));
+ m_items.emplace_back(it, true, true,
+ QString::fromStdString(it.getName()));
}
continue;
}
#endif
// skip the plt file (Palette file for TOONZ 4.6 and earlier)
- if (it->getType() == "plt") continue;
+ if (it.getType() == "plt") continue;
// filtering
else if (m_filter.isEmpty()) {
- if (it->getType() != "tnz" && it->getType() != "scr" &&
- it->getType() != "tnzbat" && it->getType() != "mpath" &&
- it->getType() != "curve" && it->getType() != "tpl" &&
- TFileType::getInfo(*it) == TFileType::UNKNOW_FILE)
+ if (it.getType() != "tnz" && it.getType() != "scr" &&
+ it.getType() != "tnzbat" && it.getType() != "mpath" &&
+ it.getType() != "curve" && it.getType() != "tpl" &&
+ TFileType::getInfo(it) == TFileType::UNKNOW_FILE)
continue;
- } else if (!m_filter.contains(QString::fromStdString(it->getType())))
+ } else if (!m_filter.contains(QString::fromStdString(it.getType())))
continue;
- m_items.push_back(Item(*it));
+ m_items.emplace_back(it);
}
// update the m_multiFileItemMap
m_multiFileItemMap.clear();
- for (it = all_files.begin(); it != all_files.end(); it++) {
- TFilePath levelName(it->getLevelName());
+ for (const TFilePath &it : all_files) {
+ TFilePath levelName(it.getLevelName());
if (levelName.isLevelName()) {
Item &levelItem = m_multiFileItemMap[levelName];
- levelItem.m_frameIds.push_back(it->getFrame());
+ levelItem.m_frameIds.push_back(it.getFrame());
levelItem.m_frameCount++;
}
}
@@ -790,15 +778,13 @@ void FileBrowser::setHistoryDay(std::string dayDateString) {
m_dayDateString = dayDateString;
const History::Day *day = History::instance()->getDay(dayDateString);
m_items.clear();
- if (day == 0) {
+ if (day == nullptr) {
m_folderName->setText("");
} else {
m_folderName->setText(QString::fromStdString(dayDateString));
std::vector<TFilePath> files;
day->getFiles(files);
- std::vector<TFilePath>::iterator it;
- for (it = files.begin(); it != files.end(); ++it)
- m_items.push_back(Item(*it));
+ for (const TFilePath &it : files) m_items.emplace_back(it);
}
refreshData();
}
@@ -808,16 +794,15 @@ void FileBrowser::setHistoryDay(std::string dayDateString) {
* paths(m_path)
*/
void FileBrowser::refreshData() {
- std::vector<Item>::iterator it;
- for (it = m_items.begin(); it != m_items.end(); ++it) {
- if (it->m_name == QString(""))
- it->m_name = toQString(it->m_path.withoutParentDir());
+ for (Item &it : m_items) {
+ if (it.m_name.isEmpty())
+ it.m_name = toQString(it.m_path.withoutParentDir());
}
}
//-----------------------------------------------------------------------------
-int FileBrowser::getItemCount() const { return m_items.size(); }
+int FileBrowser::getItemCount() const { return int(m_items.size()); }
//-----------------------------------------------------------------------------
@@ -827,9 +812,8 @@ void FileBrowser::readInfo(Item &item) {
if (info.exists()) {
// Use birthTime(), fall back to metadataChangeTime() if unavailable
item.m_creationDate = info.birthTime();
- if (!item.m_creationDate.isValid()) {
+ if (!item.m_creationDate.isValid())
item.m_creationDate = info.metadataChangeTime();
- }
item.m_modifiedDate = info.lastModified();
item.m_fileType = info.suffix();
item.m_fileSize = info.size();
@@ -843,12 +827,10 @@ void FileBrowser::readInfo(Item &item) {
readFrameCount(item);
item.m_validInfo = true;
- } else if (fp.isLevelName()) // for levels johndoe..tif etc.
- {
+ } else if (fp.isLevelName()) {
try {
// Find this level's item
- std::map<TFilePath, Item>::iterator it =
- m_multiFileItemMap.find(TFilePath(item.m_path.getLevelName()));
+ auto it = m_multiFileItemMap.find(TFilePath(item.m_path.getLevelName()));
if (it == m_multiFileItemMap.end()) throw "";
item.m_creationDate = it->second.m_creationDate;
@@ -860,14 +842,6 @@ void FileBrowser::readInfo(Item &item) {
// keep the list of frameIds at the first time and try to reuse it.
item.m_frameIds = it->second.m_frameIds;
-
- // The old way
- /*TLevelReaderP lr(fp);
-item.m_frameCount = lr->loadInfo()->getFrameCount();
-item.m_creationDate = QDateTime();
-item.m_modifiedDate = QDateTime();
-item.m_fileSize = -1;
-item.m_validInfo = true;*/
} catch (...) {
item.m_frameCount = 0;
}
@@ -896,7 +870,7 @@ void FileBrowser::readFrameCount(Item &item) {
QVariant FileBrowser::getItemData(int index, DataType dataType,
bool isSelected) {
- if (index < 0 || index >= (int)m_items.size()) return QVariant();
+ if (index < 0 || index >= getItemCount()) return QVariant();
Item &item = m_items[index];
if (dataType == Name) {
// show two dots( ".." ) for the parent directory item
@@ -933,9 +907,8 @@ QVariant FileBrowser::getItemData(int index, DataType dataType,
else if (dataType == ToolTip || dataType == FullPath)
return QString::fromStdWString(item.m_path.getWideString());
- else if (dataType == IsFolder) {
+ else if (dataType == IsFolder)
return item.m_isFolder;
- }
if (!item.m_validInfo) {
readInfo(item);
@@ -969,7 +942,7 @@ QVariant FileBrowser::getItemData(int index, DataType dataType,
//-----------------------------------------------------------------------------
bool FileBrowser::isSceneItem(int index) const {
- return 0 <= index && index < (int)m_items.size() &&
+ return 0 <= index && index < getItemCount() &&
m_items[index].m_path.getType() == "tnz";
}
@@ -978,7 +951,7 @@ bool FileBrowser::isSceneItem(int index) const {
bool FileBrowser::canRenameItem(int index) const {
// if viewing history, cannot rename anything
if (getFolder() == TFilePath()) return false;
- if (index < 0 || index >= (int)m_items.size()) return false;
+ if (index < 0 || index >= getItemCount()) return false;
// for now, disable rename for folders
if (m_items[index].m_isFolder) return false;
TFilePath fp = m_items[index].m_path;
@@ -988,8 +961,7 @@ bool FileBrowser::canRenameItem(int index) const {
//-----------------------------------------------------------------------------
int FileBrowser::findIndexWithPath(TFilePath path) {
- int i;
- for (i = 0; i < m_items.size(); i++)
+ for (int i = 0; i < (int)m_items.size(); ++i)
if (m_items[i].m_path == path) return i;
return -1;
}
@@ -1026,7 +998,6 @@ void FileBrowser::renameItem(int index, const QString &newName) {
QModelIndex index = m_folderTreeView->currentIndex();
if (index.isValid()) {
DvDirModel::instance()->refresh(index);
- // m_folderTreeView->getDvDirModel()->refresh(index);
m_folderTreeView->update();
}
}
@@ -1039,11 +1010,11 @@ bool FileBrowser::renameFile(TFilePath &fp, QString newName) {
if (isSpaceString(newName)) return true;
TFilePath newFp(newName.toStdWString());
- if (newFp.getType() != "" && newFp.getType() != fp.getType()) {
+ if (!newFp.getType().empty() && newFp.getType() != fp.getType()) {
DVGui::error(tr("Can't change file extension"));
return false;
}
- if (newFp.getType() == "") newFp = newFp.withType(fp.getType());
+ if (newFp.getType().empty()) newFp = newFp.withType(fp.getType());
if (newFp.getFrame() != TFrameId::EMPTY_FRAME &&
newFp.getFrame() != TFrameId::NO_FRAME) {
DVGui::error(tr("Can't set a drawing number"));
@@ -1069,10 +1040,6 @@ bool FileBrowser::renameFile(TFilePath &fp, QString newName) {
TSystem::renameFileOrLevel_throw(newFp, fp, true);
IconGenerator::instance()->remove(fp);
if (fp.getType() == "tnz") {
- /* TFilePath folder = fp.getParentDir() + (fp.getName() + "_files");
-TFilePath newFolder = newFp.getParentDir() + (newFp.getName() + "_files");
-TSystem::renameFile(newFolder, folder);
-*/
TFilePath sceneIconFp = ToonzScene::getIconPath(fp);
TFilePath sceneIconNewFp = ToonzScene::getIconPath(newFp);
if (TFileStatus(sceneIconFp).doesExist()) {
@@ -1095,35 +1062,36 @@ TSystem::renameFile(newFolder, folder);
//-----------------------------------------------------------------------------
QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {
- auto isOldLevelType = [](TFilePath &path) -> bool {
+ auto isOldLevelType = [](const TFilePath &path) -> bool {
return path.getType() == "tzp" || path.getType() == "tzu";
};
- // TODO: move the definition of actions to this class too?
FileSelection *fs =
dynamic_cast<FileSelection *>(m_itemViewer->getPanel()->getSelection());
- if (!fs) return 0;
+ if (!fs) return nullptr;
std::vector<TFilePath> files;
fs->getSelectedFiles(files);
- QMenu *menu = new QMenu(parent);
+ // Use unique_ptr for automatic memory management
+ auto menu = std::make_unique<QMenu>(parent);
CommandManager *cm = CommandManager::instance();
// when folder item is right-clicked
if (0 <= index && index < (int)m_items.size() && m_items[index].m_isFolder) {
DvDirModel *model = DvDirModel::instance();
DvDirModelNode *node = model->getNode(model->getIndexByPath(files[0]));
+
if (!node || !node->isRenameEnabled()) return nullptr;
+
DvDirModelFileFolderNode *fnode =
dynamic_cast<DvDirModelFileFolderNode *>(node);
if (!fnode || fnode->isProjectFolder()) return nullptr;
menu->addAction(cm->getAction(MI_Clear));
QAction *action =
- new QAction(QIcon(createQIcon("rename")), tr("Rename"), menu);
+ menu->addAction(QIcon(createQIcon("rename")), tr("Rename"));
connect(action, &QAction::triggered, this, &FileBrowser::renameFolder);
- menu->addAction(action);
- return menu;
+ return menu.release();
}
if (files.empty()) {
@@ -1132,7 +1100,7 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {
if (!Preferences::instance()->isWatchFileSystemEnabled()) {
menu->addAction(cm->getAction(MI_RefreshTree));
}
- return menu;
+ return menu.release();
}
if (files.size() == 1 && files[0].getType() == "tnz") {
@@ -1141,16 +1109,15 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {
bool areResources = true;
bool areScenes = false;
- int i, j;
- for (i = 0; i < (int)files.size(); i++) {
- TFileType::Type type = TFileType::getInfo(files[i]);
+ for (const TFilePath &f : files) {
+ TFileType::Type type = TFileType::getInfo(f);
if (areResources && !TFileType::isResource(type)) areResources = false;
if (!areScenes && TFileType::isScene(type)) areScenes = true;
}
bool areFullcolor = true;
- for (i = 0; i < (int)files.size(); i++) {
- TFileType::Type type = TFileType::getInfo(files[i]);
+ for (const TFilePath &f : files) {
+ TFileType::Type type = TFileType::getInfo(f);
if (!TFileType::isFullColor(type)) {
areFullcolor = false;
break;
@@ -1167,9 +1134,8 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {
title = tr("Load As Sub-xsheet");
else
title = tr("Load");
- QAction *action = new QAction(QIcon(createQIcon("import")), title, menu);
+ QAction *action = menu->addAction(QIcon(createQIcon("import")), title);
connect(action, &QAction::triggered, this, &FileBrowser::loadResources);
- menu->addAction(action);
menu->addSeparator();
}
@@ -1189,17 +1155,19 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {
menu->addAction(cm->getAction(MI_AddToBatchCleanupList));
}
- for (i = 0; i < files.size(); i++)
+ int i;
+ for (i = 0; i < (int)files.size(); ++i)
if (!TFileType::isViewable(TFileType::getInfo(files[i])) &&
files[i].getType() != "tpl")
break;
- if (i == files.size()) {
+ if (i == (int)files.size()) {
std::string type = files[0].getType();
- for (j = 0; j < files.size(); j++)
+ int j;
+ for (j = 0; j < (int)files.size(); ++j)
if (isOldLevelType(files[j])) break;
- if (j == files.size()) menu->addAction(cm->getAction(MI_ViewFile));
+ if (j == (int)files.size()) menu->addAction(cm->getAction(MI_ViewFile));
- for (j = 0; j < files.size(); j++) {
+ for (j = 0; j < (int)files.size(); ++j) {
if ((files[0].getType() == "pli" && files[j].getType() != "pli") ||
(files[0].getType() != "pli" && files[j].getType() == "pli"))
break;
@@ -1207,7 +1175,7 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {
(!isOldLevelType(files[0]) && isOldLevelType(files[j])))
break;
}
- if (j == files.size()) {
+ if (j == (int)files.size()) {
menu->addAction(cm->getAction(MI_ConvertFiles));
// iwsw commented out temporarily
// menu->addAction(cm->getAction(MI_ToonShadedImageToTLV));
@@ -1218,7 +1186,7 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {
}
if (files.size() == 1 && files[0].getType() != "tnz") {
QAction *action =
- new QAction(QIcon(createQIcon("rename")), tr("Rename"), menu);
+ menu->addAction(QIcon(createQIcon("rename")), tr("Rename"));
connect(action, &QAction::triggered, this,
&FileBrowser::renameAsToonzLevel);
menu->addAction(action);
@@ -1257,16 +1225,16 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {
m_folderTreeView->getCurrentNode());
if (node) {
// Check Version Control Status
- DvItemListModel::Status status =
- (DvItemListModel::Status)m_itemViewer->getModel()
+ DvItemListModel::Status status = DvItemListModel::Status(
+ m_itemViewer->getModel()
->getItemData(index, DvItemListModel::VersionControlStatus)
- .toInt();
+ .toInt());
// Remove the added actions
if (status == DvItemListModel::VC_Missing) menu->clear();
- QMenu *vcMenu = new QMenu(tr("Version Control"), parent);
- QAction *action;
+ auto vcMenu = std::make_unique<QMenu>(tr("Version Control"), parent);
+ QAction *action = nullptr;
if (status == DvItemListModel::VC_ReadOnly ||
(status == DvItemListModel::VC_ToUpdate && files.size() == 1)) {
@@ -1382,7 +1350,6 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {
connect(action, &QAction::triggered, this,
&FileBrowser::showFrameRangeLockInfo);
}
-
} else if (status == DvItemListModel::VC_PartialEdited) {
action = vcMenu->addAction(tr("Get"));
connect(action, &QAction::triggered, this,
@@ -1415,7 +1382,7 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {
if (!vcMenu->isEmpty()) {
menu->addSeparator();
- menu->addMenu(vcMenu);
+ menu->addMenu(vcMenu.release()); // transfer ownership to menu
}
}
@@ -1424,7 +1391,7 @@ QMenu *FileBrowser::getContextMenu(QWidget *parent, int index) {
menu->addAction(cm->getAction(MI_RefreshTree));
}
- return menu;
+ return menu.release();
}
//-----------------------------------------------------------------------------
@@ -1441,10 +1408,10 @@ void FileBrowser::startDragDrop() {
if (files.empty()) return;
QList<QUrl> urls;
- for (int i = 0; i < (int)files.size(); i++) {
- if (TSystem::doesExistFileOrLevel(files[i]))
- urls.append(QUrl::fromLocalFile(
- QString::fromStdWString(files[i].getWideString())));
+ for (const TFilePath &f : files) {
+ if (TSystem::doesExistFileOrLevel(f))
+ urls.append(
+ QUrl::fromLocalFile(QString::fromStdWString(f.getWideString())));
}
if (urls.isEmpty()) return;
@@ -1457,13 +1424,14 @@ void FileBrowser::startDragDrop() {
scalePixmapKeepingAspectRatio(icon, iconSize, Qt::transparent);
if (!dropThumbnail.isNull()) drag->setPixmap(dropThumbnail);
drag->setMimeData(mimeData);
- Qt::DropAction dropAction = drag->exec(Qt::CopyAction);
+
+ drag->exec(Qt::CopyAction);
}
//-----------------------------------------------------------------------------
-bool FileBrowser::dropMimeData(QTreeWidgetItem *parent, int index,
- const QMimeData *data, Qt::DropAction action) {
+bool FileBrowser::dropMimeData(QTreeWidgetItem *, int, const QMimeData *,
+ Qt::DropAction) {
return false;
}
@@ -1488,12 +1456,11 @@ void FileBrowser::onTreeFolderChanged() {
//-----------------------------------------------------------------------------
-void FileBrowser::changeFolder(const QModelIndex &index) {}
+void FileBrowser::changeFolder(const QModelIndex &) {}
//-----------------------------------------------------------------------------
-void FileBrowser::onDataChanged(const QModelIndex &topLeft,
- const QModelIndex &bottomRight) {
+void FileBrowser::onDataChanged(const QModelIndex &, const QModelIndex &) {
onTreeFolderChanged();
}
@@ -1523,8 +1490,7 @@ bool FileBrowser::drop(const QMimeData *mimeData) {
const CastItems *items = dynamic_cast<const CastItems *>(mimeData);
if (!items) return false;
- int i;
- for (i = 0; i < items->getItemCount(); i++) {
+ for (int i = 0; i < items->getItemCount(); ++i) {
CastItem *item = items->getItem(i);
if (TXshSimpleLevel *sl = item->getSimpleLevel()) {
TFilePath levelPath = sl->getPath().withParentDir(getFolder());
@@ -1544,7 +1510,7 @@ bool FileBrowser::drop(const QMimeData *mimeData) {
QString sceneName =
QInputDialog::getText(this, tr("Save Scene"), tr("Scene name:"),
QLineEdit::Normal, QString(), &ok);
- if (!ok || sceneName == "") return false;
+ if (!ok || sceneName.isEmpty()) return false;
scenePath = folderPath + sceneName.toStdWString();
} else
scenePath = folderPath + scene->getSceneName();
@@ -1560,10 +1526,11 @@ bool FileBrowser::drop(const QMimeData *mimeData) {
folderPath +=
TFilePath(levelName + ::to_wstring(sl->getPath().getDottedType()));
if (TSystem::doesExistFileOrLevel(folderPath)) {
- QString question = "Level " + toQString(folderPath) +
- " already exists\nDo you want to duplicate it?";
- int ret = DVGui::MsgBox(question, QObject::tr("Duplicate"),
- QObject::tr("Don't Duplicate"), 0);
+ QString question =
+ tr("Level %1 already exists\nDo you want to duplicate it?")
+ .arg(toQString(folderPath));
+ int ret =
+ DVGui::MsgBox(question, tr("Duplicate"), tr("Don't Duplicate"), 0);
if (ret == 2 || ret == 0) return false;
TFilePath path = folderPath;
NameBuilder *nameBuilder =
@@ -1581,7 +1548,7 @@ bool FileBrowser::drop(const QMimeData *mimeData) {
newSl->setPalette(sl->getPalette());
newSl->setScene(sl->getScene());
std::set<TFrameId> frames = s->getSelectedFids();
- for (auto const &fid : frames) {
+ for (const TFrameId &fid : frames) {
newSl->setFrame(fid, sl->getFrame(fid, false));
}
@@ -1589,7 +1556,6 @@ bool FileBrowser::drop(const QMimeData *mimeData) {
refreshFolder(folderPath.getParentDir());
return true;
} else if (mimeData->hasUrls()) {
- int count = 0;
for (const QUrl &url : mimeData->urls()) {
TFilePath srcFp(url.toLocalFile().toStdWString());
TFilePath dstFp = srcFp.withParentDir(folderPath);
@@ -1615,56 +1581,41 @@ void FileBrowser::loadResources() {
std::vector<TFilePath> filePaths;
fs->getSelectedFiles(filePaths);
-
if (filePaths.empty()) return;
IoCmd::LoadResourceArguments args;
args.resourceDatas.assign(filePaths.begin(), filePaths.end());
-
IoCmd::loadResources(args);
}
//-----------------------------------------------------------------------------
-void RenameAsToonzPopup::onOk() {
- if (!isValidFileName(m_name->text())) {
- DVGui::error(
- tr("The file name cannot be empty or contain any of the following "
- "characters:(new line) \\ / : * ? \" |"));
- return;
- }
- if (isReservedFileName_message(m_name->text())) return;
- accept();
-}
-
-RenameAsToonzPopup::RenameAsToonzPopup(const QString name, int frames,
+RenameAsToonzPopup::RenameAsToonzPopup(const QString &name, int frames,
bool isFolder)
: Dialog(TApp::instance()->getMainWindow(), true, true, "RenameAsToonz") {
- setWindowTitle(QString(tr("Rename")));
+ setWindowTitle(tr("Rename"));
beginHLayout();
QLabel *lbl;
if (frames == -1) {
if (isFolder)
- lbl = new QLabel(QString(tr("Renaming Folder ")) + name);
+ lbl = new QLabel(tr("Renaming Folder ") + name, this);
else
- lbl = new QLabel(QString(tr("Renaming File ")) + name);
+ lbl = new QLabel(tr("Renaming File ") + name, this);
} else
- lbl = new QLabel(
- QString(tr("Creating an animation level of %1 frames").arg(frames)));
+ lbl = new QLabel(tr("Creating an animation level of %1 frames").arg(frames),
+ this);
lbl->setFixedHeight(20);
lbl->setObjectName("TitleTxtLabel");
- m_name = new LineEdit(frames == -1 ? "" : name);
+ m_name = new LineEdit(frames == -1 ? QString() : name, this);
m_name->setFixedHeight(20);
- // Modernized: Removed commented connection as it's not used
- m_overwrite = new QCheckBox(tr("Delete Original Files"));
+ m_overwrite = new QCheckBox(tr("Delete Original Files"), this);
m_overwrite->setFixedHeight(20);
- QFormLayout *formLayout = new QFormLayout;
-
+ QFormLayout *formLayout = new QFormLayout(this);
QHBoxLayout *labelLayout = new QHBoxLayout;
labelLayout->addStretch();
labelLayout->addWidget(lbl);
@@ -1673,21 +1624,35 @@ RenameAsToonzPopup::RenameAsToonzPopup(const QString name, int frames,
formLayout->addRow(labelLayout);
formLayout->addRow((isFolder) ? tr("Folder Name:") : tr("Level Name:"),
m_name);
-
if (!isFolder) formLayout->addRow(m_overwrite);
addLayout(formLayout);
-
endHLayout();
m_okBtn = new QPushButton(tr("Rename"), this);
m_okBtn->setDefault(true);
m_cancelBtn = new QPushButton(tr("Cancel"), this);
+
connect(m_okBtn, &QPushButton::clicked, this, &RenameAsToonzPopup::onOk);
connect(m_cancelBtn, &QPushButton::clicked, this, &QDialog::reject);
addButtonBarWidget(m_okBtn, m_cancelBtn);
}
+//-----------------------------------------------------------------------------
+
+void RenameAsToonzPopup::onOk() {
+ if (!isValidFileName(m_name->text())) {
+ DVGui::error(
+ tr("The file name cannot be empty or contain any of the following "
+ "characters:(new line) \\ / : * ? \" |"));
+ return;
+ }
+ if (isReservedFileName_message(m_name->text())) return;
+ accept();
+}
+
+//-----------------------------------------------------------------------------
+
namespace {
bool parsePathName(const QString &fullpath, QString &parentPath, QString &name,
@@ -1710,12 +1675,12 @@ bool parsePathName(const QString &fullpath, QString &parentPath, QString &name,
if (index <= 0) return false;
format = filename.right(filename.size() - index - 1);
- if (format == "") return false;
+ if (format.isEmpty()) return false;
- index--;
+ --index;
if (!filename.at(index).isDigit()) return false;
- while (index >= 0 && filename.at(index).isDigit()) index--;
+ while (index >= 0 && filename.at(index).isDigit()) --index;
if (index < 0) return false;
@@ -1728,16 +1693,14 @@ bool parsePathName(const QString &fullpath, QString &parentPath, QString &name,
void getLevelFiles(const QString &parentPath, const QString &name,
const QString &format, QStringList &pathIn) {
- QString dummy, dummy1, filter = "*." + format;
+ QString filter = "*." + format;
QDir dir(parentPath, filter);
QStringList list = dir.entryList();
- for (int i = 0; i < list.size(); i++) {
- QString item = list.at(i);
- QString itemName;
+ for (const QString &item : list) {
+ QString dummy, dummy1, itemName;
if (!parsePathName(item, dummy, itemName, dummy1) || name != itemName)
continue;
-
pathIn.push_back(item);
}
}
@@ -1747,30 +1710,25 @@ void getLevelFiles(const QString &parentPath, const QString &name,
QString getFrame(const QString &filename) {
int index = filename.lastIndexOf('.');
- if (index <= 0) return "";
-
- index--;
- if (!filename.at(index).isDigit()) return "";
+ if (index <= 0) return QString();
- int to, from;
- to = from = index;
- while (from >= 0 && filename.at(from).isDigit()) from--;
+ --index;
+ if (!filename.at(index).isDigit()) return QString();
- if (from < 0) return "";
+ int to = index, from = index;
+ while (from >= 0 && filename.at(from).isDigit()) --from;
- char padStr[5];
- padStr[4] = '\0';
-
- int i, frame = 0;
+ if (from < 0) return QString();
+ char padStr[5] = {0};
QString number = filename.mid(from + 1, to - from);
- for (i = 0; i < 4 - number.size(); i++) padStr[i] = '0';
- for (i = 0; i < number.size(); i++)
+ for (int i = 0; i < 4 - number.size(); ++i) padStr[i] = '0';
+ for (int i = 0; i < number.size(); ++i)
padStr[4 - number.size() + i] = number.at(i).toLatin1();
return QString(padStr);
}
-//------------------------------------------------------------------
+//-----------------------------------------------------------
void renameSingleFileOrToonzLevel(const QString &fullpath) {
TFilePath fpin(fullpath.toStdString());
@@ -1782,9 +1740,9 @@ void renameSingleFileOrToonzLevel(const QString &fullpath) {
std::string name = popup.getName().toStdString();
if (name == fpin.getName()) {
- DVGui::error(QString(
+ DVGui::error(
QObject::tr("The specified name is already assigned to the %1 file.")
- .arg(fullpath)));
+ .arg(fullpath));
return;
}
@@ -1792,9 +1750,9 @@ void renameSingleFileOrToonzLevel(const QString &fullpath) {
TSystem::renameFileOrLevel(fpin.withName(name), fpin, true);
else {
if (TSystem::doesExistFileOrLevel(fpin.withName(name))) {
- DVGui::error(QString(
+ DVGui::error(
QObject::tr("The specified name is already assigned to the %1 file.")
- .arg(fpin.withName(name).getQString())));
+ .arg(fpin.withName(name).getQString()));
return;
} else
TSystem::copyFileOrLevel(fpin.withName(name), fpin);
@@ -1812,7 +1770,6 @@ void doRenameAsToonzLevel(const QString &fullpath) {
}
QStringList pathIn;
-
getLevelFiles(parentPath, name, format, pathIn);
if (pathIn.empty()) return;
@@ -1826,7 +1783,6 @@ void doRenameAsToonzLevel(const QString &fullpath) {
name = popup.getName();
QString levelOutStr = parentPath + "/" + name + ".." + format;
-
TFilePath levelOut(levelOutStr.toStdWString());
if (TSystem::doesExistFileOrLevel(levelOut)) {
QApplication::restoreOverrideCursor();
@@ -1839,24 +1795,22 @@ void doRenameAsToonzLevel(const QString &fullpath) {
TSystem::removeFileOrLevel(levelOut);
}
- int i;
- for (i = 0; i < pathIn.size(); i++) {
- QString padStr = getFrame(pathIn[i]);
- if (padStr == "") continue;
+ for (const QString &fname : pathIn) {
+ QString padStr = getFrame(fname);
+ if (padStr.isEmpty()) continue;
QString pathOut = parentPath + "/" + name + "." + padStr + "." + format;
if (popup.doOverwrite()) {
- if (!QFile::rename(parentPath + "/" + pathIn[i], pathOut)) {
- QString tmp(parentPath + "/" + pathIn[i]);
- DVGui::error(QString(
- QObject::tr("It is not possible to rename the %1 file.").arg(tmp)));
+ if (!QFile::rename(parentPath + "/" + fname, pathOut)) {
+ QString tmp(parentPath + "/" + fname);
+ DVGui::error(
+ QObject::tr("It is not possible to rename the %1 file.").arg(tmp));
return;
}
- } else if (!QFile::copy(parentPath + "/" + pathIn[i], pathOut)) {
- QString tmp(parentPath + "/" + pathIn[i]);
- DVGui::error(QString(
- QObject::tr("It is not possible to copy the %1 file.").arg(tmp)));
-
+ } else if (!QFile::copy(parentPath + "/" + fname, pathOut)) {
+ QString tmp(parentPath + "/" + fname);
+ DVGui::error(
+ QObject::tr("It is not possible to copy the %1 file.").arg(tmp));
return;
}
}
@@ -1897,8 +1851,8 @@ void FileBrowser::renameFolder() {
if (popup.exec() != QDialog::Accepted) return;
std::string name = popup.getName().toStdString();
if (name == srcPath.getName()) {
- DVGui::error(QString(
- QObject::tr("The specified name is already assigned to the folder.")));
+ DVGui::error(
+ QObject::tr("The specified name is already assigned to the folder."));
return;
}
@@ -1911,7 +1865,6 @@ void FileBrowser::renameFolder() {
}
QApplication::restoreOverrideCursor();
-
refreshFolder(srcPath.getParentDir());
}
@@ -2091,35 +2044,24 @@ void FileBrowser::convertToPaintedTlv() {
#endif
//-----------------------------------------------------------------------------
+
void FileBrowser::onSelectedItems(const std::set<int> &indexes) {
std::set<TFilePath> filePaths;
- std::set<int>::const_iterator it;
-
- // Pass the frameId lists for reuse (one vector per selected item)
std::list<std::vector<TFrameId>> frameIDs;
- if (indexes.empty()) { // Inform selection is released
+ if (indexes.empty()) {
emit filePathsSelected(filePaths, frameIDs);
return;
}
- size_t itemsSize = m_items.size(); // Cache size to avoid mid-loop changes
- for (it = indexes.begin(); it != indexes.end(); ++it) {
- int idx = *it;
- if (idx < 0 || static_cast<size_t>(idx) >= itemsSize) {
- // Skip invalid indices
- continue;
- }
+ size_t itemsSize = m_items.size();
+ for (int idx : indexes) {
+ if (idx < 0 || static_cast<size_t>(idx) >= itemsSize) continue;
- // Collect file paths
filePaths.insert(m_items[idx].m_path);
-
- // Append the frame IDs vector to the list (preserves per-item structure)
frameIDs.push_back(m_items[idx].m_frameIds);
}
- // Reuse the lists of TFrameId to skip loadInfo() when loading sequential
- // levels
emit filePathsSelected(filePaths, frameIDs);
}
@@ -2127,12 +2069,11 @@ void FileBrowser::onSelectedItems(const std::set<int> &indexes) {
void FileBrowser::onClickedItem(int index) {
if (0 <= index && index < (int)m_items.size()) {
- // if the folder is clicked, then move the current folder
TFilePath fp = m_items[index].m_path;
if (m_items[index].m_isFolder) {
setFolder(fp, true);
- QModelIndex index = m_folderTreeView->currentIndex();
- if (index.isValid()) m_folderTreeView->scrollTo(index);
+ QModelIndex idx = m_folderTreeView->currentIndex();
+ if (idx.isValid()) m_folderTreeView->scrollTo(idx);
} else
emit filePathClicked(fp);
}
@@ -2143,12 +2084,11 @@ void FileBrowser::onClickedItem(int index) {
void FileBrowser::onDoubleClickedItem(int index) {
// TODO: Avoid duplicate code with onClickedItem().
if (0 <= index && index < (int)m_items.size()) {
- // if the folder is doubleClicked, then move the current folder
TFilePath fp = m_items[index].m_path;
if (m_items[index].m_isFolder) {
setFolder(fp, true);
- QModelIndex index = m_folderTreeView->currentIndex();
- if (index.isValid()) m_folderTreeView->scrollTo(index);
+ QModelIndex idx = m_folderTreeView->currentIndex();
+ if (idx.isValid()) m_folderTreeView->scrollTo(idx);
} else
emit filePathDoubleClicked(fp);
}
@@ -2157,9 +2097,7 @@ void FileBrowser::onDoubleClickedItem(int index) {
//-----------------------------------------------------------------------------
void FileBrowser::refreshFolder(const TFilePath &folderPath) {
- std::set<FileBrowser *>::iterator it;
- for (it = activeBrowsers.begin(); it != activeBrowsers.end(); ++it) {
- FileBrowser *browser = *it;
+ for (FileBrowser *browser : activeBrowsers) {
DvDirModel::instance()->refreshFolder(folderPath);
if (browser->getFolder() == folderPath) {
browser->setFolder(folderPath, false, true);
@@ -2170,9 +2108,7 @@ void FileBrowser::refreshFolder(const TFilePath &folderPath) {
//-----------------------------------------------------------------------------
void FileBrowser::updateItemViewerPanel() {
- std::set<FileBrowser *>::iterator it;
- for (it = activeBrowsers.begin(); it != activeBrowsers.end(); ++it) {
- FileBrowser *browser = *it;
+ for (FileBrowser *browser : activeBrowsers) {
browser->m_itemViewer->getPanel()->update();
}
}
@@ -2186,16 +2122,14 @@ void FileBrowser::getExpandedFolders(DvDirModelNode *node,
if (!m_folderTreeView->isExpanded(newIndex)) return;
expandedNodes.push_back(node);
- int i = 0;
- for (i = 0; i < node->getChildCount(); i++)
+ for (int i = 0; i < node->getChildCount(); ++i)
getExpandedFolders(node->getChild(i), expandedNodes);
}
//-----------------------------------------------------------------------------
void FileBrowser::refresh() {
- TFilePath originalFolder(
- m_folder); // setFolder is invoked by Qt throughout the following...
+ TFilePath originalFolder(m_folder);
int dx = m_folderTreeView->verticalScrollBar()->value();
DvDirModelNode *rootNode = DvDirModel::instance()->getNode(QModelIndex());
@@ -2209,12 +2143,10 @@ void FileBrowser::refresh() {
m_folderTreeView->setRefreshVersionControlEnabled(vcEnabled);
QList<DvDirModelNode *> expandedNodes;
- int i;
- for (i = 0; i < rootNode->getChildCount(); i++)
+ for (int i = 0; i < rootNode->getChildCount(); ++i)
getExpandedFolders(rootNode->getChild(i), expandedNodes);
- for (i = 0; i < expandedNodes.size(); i++) {
- DvDirModelNode *node = expandedNodes[i];
+ for (DvDirModelNode *node : expandedNodes) {
if (!node || !node->hasChildren()) continue;
QModelIndex ind = DvDirModel::instance()->getIndexByNode(node);
if (!ind.isValid()) continue;
@@ -2256,7 +2188,6 @@ void FileBrowser::newFolder() {
try {
TSystem::mkDir(folderPath);
-
} catch (...) {
DVGui::error(tr("It is not possible to create the %1 folder.")
.arg(toQString(folderPath)));
@@ -2275,7 +2206,7 @@ void FileBrowser::newFolder() {
if (newFolderIndex.isValid()) {
m_folderTreeView->setCurrentIndex(newFolderIndex);
m_folderTreeView->scrollTo(newFolderIndex);
- m_folderTreeView->QAbstractItemView::edit(newFolderIndex);
+ m_folderTreeView->QTreeView::edit(newFolderIndex);
}
}
@@ -2286,7 +2217,7 @@ void FileBrowser::showEvent(QShowEvent *) {
// refresh
if (getFolder() != TFilePath())
setFolder(getFolder(), false, true);
- else if (getDayDateString() != "")
+ else if (!getDayDateString().empty())
setHistoryDay(getDayDateString());
m_folderTreeView->scrollTo(m_folderTreeView->currentIndex());
@@ -2321,7 +2252,6 @@ void FileBrowser::selectNone() { m_itemViewer->selectNone(); }
//-----------------------------------------------------------------------------
void FileBrowser::enableDoubleClickToOpenScenes() {
- // perhaps this should disconnect existing signal handlers first
connect(this, &FileBrowser::filePathDoubleClicked, this,
&FileBrowser::tryToOpenScene);
}
@@ -2351,49 +2281,40 @@ FrameCountReader::FrameCountReader() : m_executor() {
//-----------------------------------------------------------------------------
-FrameCountReader::~FrameCountReader() {}
+FrameCountReader::~FrameCountReader() = default;
//-----------------------------------------------------------------------------
int FrameCountReader::getFrameCount(const TFilePath &fp) {
QDateTime modifiedDate =
QFileInfo(QString::fromStdWString(fp.getWideString())).lastModified();
- std::map<TFilePath, FCData>::iterator it;
{
- // Access the static map to find an occurrence of the path.
QMutexLocker locker(&frameCountMapMutex);
- it = frameCountMap.find(fp);
+ auto it = frameCountMap.find(fp);
if (it != frameCountMap.end()) {
if (it->second.m_frameCount > 0 && it->second.m_date == modifiedDate) {
- // Found an unmodified occurrence with correctly calculated frame count
return it->second.m_frameCount;
}
+ if ((modifiedDate == it->second.m_date) &&
+ (it->second.m_underProgress || it->second.m_retryCount < 0)) {
+ return -1;
+ }
} else {
- // First time this frame count is calculated - initialize FC data
frameCountMap[fp] = FCData(modifiedDate);
- goto calculateTask;
}
-
- if ((modifiedDate == it->second.m_date) &&
- (it->second.m_underProgress || it->second.m_retryCount < 0))
- return -1;
}
-calculateTask:
-
- // Now, we have to calculate the frame count; first, create a frame count
- // calculation task and submit it.
- FrameCountTask *task = new FrameCountTask(fp, modifiedDate);
+ // We have to calculate the frame count; create a task and submit it.
+ auto *task = new FrameCountTask(fp, modifiedDate);
connect(task, &FrameCountTask::finished, this,
&FrameCountReader::calculatedFrameCount);
connect(task, &FrameCountTask::exception, this,
&FrameCountReader::calculatedFrameCount);
m_executor.addTask(task);
-
- return -1; // FrameCount has not yet been calculated
+ return -1;
}
//-----------------------------------------------------------------------------
@@ -2413,7 +2334,7 @@ FrameCountTask::FrameCountTask(const TFilePath &path,
//-----------------------------------------------------------------------------
-FrameCountTask::~FrameCountTask() {}
+FrameCountTask::~FrameCountTask() = default;
//-----------------------------------------------------------------------------
@@ -2423,8 +2344,7 @@ void FrameCountTask::run() {
QMutexLocker fCMapMutex(&frameCountMapMutex);
- std::map<TFilePath, FCData>::iterator it = frameCountMap.find(m_path);
-
+ auto it = frameCountMap.find(m_path);
if (it == frameCountMap.end()) return;
// Memorize the found frameCount into the frameCountMap
@@ -2433,8 +2353,7 @@ void FrameCountTask::run() {
it->second.m_date = m_modifiedDate;
} else {
// Seems that tlv reads sometimes may fail, returning invalid frame counts
- // (typically 0).
- // However, if no exception was thrown, we try to recover it
+ // (typically 0). However, if no exception was thrown, we try to recover it
it->second.m_underProgress = false;
it->second.m_retryCount--;
}
@@ -2448,18 +2367,13 @@ QThread::Priority FrameCountTask::runningPriority() {
//-----------------------------------------------------------------------------
-// NOTE: onStarted and onCanceled are invoked on the same thread - so m_started
-// operations are serialized, it can be non-thread-guarded.
-void FrameCountTask::onStarted(TThread::RunnableP thisTask) {
- m_started = true;
-}
+void FrameCountTask::onStarted(TThread::RunnableP) { m_started = true; }
//-----------------------------------------------------------------------------
-void FrameCountTask::onCanceled(TThread::RunnableP thisTask) {
+void FrameCountTask::onCanceled(TThread::RunnableP) {
if (!m_started) {
QMutexLocker fCMapMutex(&frameCountMapMutex);
-
frameCountMap.erase(m_path);
}
}
diff --git a/toonz/sources/toonz/filebrowser.h b/toonz/sources/toonz/filebrowser.h
index 3e68d3a40..32a300e9b 100644
--- a/toonz/sources/toonz/filebrowser.h
+++ b/toonz/sources/toonz/filebrowser.h
@@ -10,11 +10,11 @@
#include <QCheckBox>
#include <QList>
#include <QModelIndex>
+
#include "dvitemview.h"
#include "tfilepath.h"
#include "toonzqt/dvdialog.h"
#include "versioncontrol.h"
-
#include "tthread.h"
class QLineEdit;
@@ -27,12 +27,13 @@ class QFileSystemWatcher;
//-----------------------------------------------------------------------------
//! FrameCountReader is the class responsible for calculation of levels' frame
-//! counts in the file browser. Since on many file formats this requires to
-//! open the level file and scan each frame (MOV-like), and on some machine
+//! counts in the file browser. Since on many file formats this requires to open
+//! the level file and scan each frame (MOV-like), and on some machine
//! configurations such a task can be time consuming, we dedicate a separate
//! thread for it - just like the icon generator does. Calculated frame counts
//! are also stored for quick lookup once they have been calculated the first
//! time.
+
class FrameCountReader final : public QObject {
Q_OBJECT
@@ -47,6 +48,9 @@ public:
signals:
void calculatedFrameCount();
+
+private:
+ Q_DISABLE_COPY_MOVE(FrameCountReader);
};
//-----------------------------------------------------------------------------
@@ -55,8 +59,10 @@ class FileBrowser final : public QFrame, public DvItemListModel {
Q_OBJECT
public:
- FileBrowser(QWidget *parent, Qt::WindowFlags flags = Qt::WindowFlags(),
- bool noContextMenu = false, bool multiSelectionEnabled = false);
+ explicit FileBrowser(QWidget *parent,
+ Qt::WindowFlags flags = Qt::WindowFlags(),
+ bool noContextMenu = false,
+ bool multiSelectionEnabled = false);
~FileBrowser();
void sortByDataModel(DataType dataType, bool isDiscendent) override;
@@ -74,16 +80,16 @@ public:
QMenu *getContextMenu(QWidget *parent, int index) override;
/*!
- This function adds to the types to be filtered a new type;
- if this function is never called, the default filter is all image
- files and scene files and palette files
- */
+This functions adds to the types to be filtered a new type;
+if this function is never called, the default filter is all image
+files and scene files and palette files
+*/
void addFilterType(const QString &type);
/*!
- The setFilterTypes function directly specifies the list of file
- types to be displayed in the file browser.
- */
+The setFilterTypes function directly specifies the list of file
+types to be displayed in the file browser.
+*/
void setFilterTypes(const QStringList &types);
const QStringList &getFilterTypes() const { return m_filter; }
void removeFilterType(const QString &type);
@@ -100,11 +106,10 @@ public:
std::string getDayDateString() const { return m_dayDateString; }
static void refreshFolder(const TFilePath &folder);
-
static void updateItemViewerPanel();
- // returns true if the file has been renamed. After the call, fp contains
- // the new path
+ // Returns true if the file was renamed. After the call, fp contains the new
+ // path.
static bool renameFile(TFilePath &fp, QString newName);
void makeCurrentProjectVisible();
@@ -147,7 +152,6 @@ public slots:
protected slots:
void refresh();
-
void changeFolder(const QModelIndex &index);
void onDataChanged(const QModelIndex &topLeft,
const QModelIndex &bottomRight);
@@ -187,7 +191,6 @@ protected slots:
void getRevisionHistory();
void onVersionControlCommandDone(const QStringList &files);
-
void onFileSystemChanged(const QString &folderPath);
// If filePath is a valid scene file, open it. Otherwise do nothing.
@@ -202,8 +205,8 @@ signals:
const std::list<std::vector<TFrameId>> &);
void treeFolderChanged(const TFilePath &);
- // for activating/deactivating the folder history buttons (back button &
- // forward button)
+ // for activating/deactivating the folder history buttons( back button &
+ // forward button )
void historyChanged(bool, bool);
private:
@@ -244,7 +247,7 @@ private:
// folder history
QList<QModelIndex> m_indexHistoryList;
- int m_currentPosition;
+ int m_currentPosition = 0;
std::vector<Item> m_items;
TFilePath m_folder;
@@ -255,37 +258,33 @@ private:
private:
void readFrameCount(Item &item);
void readInfo(Item &item);
-
void refreshCurrentFolderItems();
- DvItemListModel::Status getItemVersionControlStatus(
- const FileBrowser::Item &item);
+ DvItemListModel::Status getItemVersionControlStatus(const Item &item);
+
+ Q_DISABLE_COPY_MOVE(FileBrowser);
};
//--------------------------------------------------------------------
class RenameAsToonzPopup final : public DVGui::Dialog {
Q_OBJECT
+
QPushButton *m_okBtn, *m_cancelBtn;
DVGui::LineEdit *m_name;
QCheckBox *m_overwrite;
public:
- RenameAsToonzPopup(const QString name = "", int frames = -1,
- bool isFolder = false);
+ explicit RenameAsToonzPopup(const QString &name = QString(), int frames = -1,
+ bool isFolder = false);
- bool doOverwrite() { return m_overwrite->isChecked(); }
- QString getName() { return m_name->text(); }
-
-private:
- // TPropertyGroup* getFormatProperties(const std::string &ext);
+ bool doOverwrite() const { return m_overwrite->isChecked(); }
+ QString getName() const { return m_name->text(); }
-public slots:
- //! Starts the conversion.
- // void onConvert();
- // void onOptionsClicked();
+private slots:
void onOk();
-};
-//-----------------------------------------------------------
+private:
+ Q_DISABLE_COPY_MOVE(RenameAsToonzPopup);
+};
-#endif
+#endif // FILEBROWSER_INCLUDED
diff --git a/toonz/sources/toonz/fileselection.cpp b/toonz/sources/toonz/fileselection.cpp
index 834e1b758..5d91b27e7 100644
--- a/toonz/sources/toonz/fileselection.cpp
+++ b/toonz/sources/toonz/fileselection.cpp
@@ -47,12 +47,13 @@
#include <QVariant>
#include <QMainWindow>
-using namespace DVGui;
+// C++ includes
+#include <memory>
-// TODO: spostare i comandi in FileBrowser?
+using namespace DVGui;
+// TODO Refactor Move commands to FileBrowser class
//------------------------------------------------------------------------
-
namespace {
//=============================================================================
@@ -60,26 +61,29 @@ namespace {
//-----------------------------------------------------------------------------
class CopyFilesUndo final : public TUndo {
- QMimeData *m_oldData;
- QMimeData *m_newData;
+ std::unique_ptr<QMimeData> m_oldData;
+ std::unique_ptr<QMimeData> m_newData;
public:
CopyFilesUndo(QMimeData *oldData, QMimeData *newData)
- : m_oldData(oldData), m_newData(newData) {}
+ : m_oldData(cloneData(oldData)), m_newData(cloneData(newData)) {}
void undo() const override {
QClipboard *clipboard = QApplication::clipboard();
- clipboard->setMimeData(cloneData(m_oldData), QClipboard::Clipboard);
+ clipboard->setMimeData(cloneData(m_oldData.get()), QClipboard::Clipboard);
}
void redo() const override {
QClipboard *clipboard = QApplication::clipboard();
- clipboard->setMimeData(cloneData(m_newData), QClipboard::Clipboard);
+ clipboard->setMimeData(cloneData(m_newData.get()), QClipboard::Clipboard);
}
int getSize() const override { return sizeof(*this); }
QString getHistoryString() override { return QObject::tr("Copy File"); }
+
+private:
+ Q_DISABLE_COPY_MOVE(CopyFilesUndo);
};
//=============================================================================
@@ -92,14 +96,10 @@ class PasteFilesUndo final : public TUndo {
public:
PasteFilesUndo(std::vector<TFilePath> files, TFilePath folder)
- : m_newFiles(files), m_folder(folder) {}
-
- ~PasteFilesUndo() {}
+ : m_newFiles(std::move(files)), m_folder(std::move(folder)) {}
void undo() const override {
- int i;
- for (i = 0; i < (int)m_newFiles.size(); i++) {
- TFilePath path = m_newFiles[i];
+ for (const TFilePath &path : m_newFiles) {
if (!TSystem::doesExistFileOrLevel(path)) continue;
try {
TSystem::removeFileOrLevel(path);
@@ -111,10 +111,9 @@ public:
void redo() const override {
if (!TSystem::touchParentDir(m_folder)) TSystem::mkDir(m_folder);
- const FileData *data =
+ const auto *data =
dynamic_cast<const FileData *>(QApplication::clipboard()->mimeData());
if (!data) return;
- TApp *app = TApp::instance();
std::vector<TFilePath> files;
data->getFiles(m_folder, files);
FileBrowser::refreshFolder(m_folder);
@@ -124,12 +123,17 @@ public:
QString getHistoryString() override {
QString str = QObject::tr("Paste File : ");
- for (int i = 0; i < (int)m_newFiles.size(); i++) {
- if (i != 0) str += QString(", ");
- str += QString::fromStdString(m_newFiles[i].getLevelName());
+ bool first = true;
+ for (const TFilePath &path : m_newFiles) {
+ if (!first) str += QString(", ");
+ first = false;
+ str += QString::fromStdString(path.getLevelName());
}
return str;
}
+
+private:
+ Q_DISABLE_COPY_MOVE(PasteFilesUndo);
};
//=============================================================================
@@ -137,19 +141,15 @@ public:
//-----------------------------------------------------------------------------
class DuplicateUndo final : public TUndo {
- std::vector<TFilePath> m_newFiles;
std::vector<TFilePath> m_files;
+ std::vector<TFilePath> m_newFiles;
public:
DuplicateUndo(std::vector<TFilePath> files, std::vector<TFilePath> newFiles)
- : m_files(files), m_newFiles(newFiles) {}
-
- ~DuplicateUndo() {}
+ : m_files(std::move(files)), m_newFiles(std::move(newFiles)) {}
void undo() const override {
- int i;
- for (i = 0; i < (int)m_newFiles.size(); i++) {
- TFilePath path = m_newFiles[i];
+ for (const TFilePath &path : m_newFiles) {
if (!TSystem::doesExistFileOrLevel(path)) continue;
if (path.getType() == "tnz")
TSystem::rmDirTree(path.getParentDir() + (path.getName() + "_files"));
@@ -162,9 +162,7 @@ public:
}
void redo() const override {
- int i;
- for (i = 0; i < (int)m_files.size(); i++) {
- TFilePath fp = m_files[i];
+ for (const TFilePath &fp : m_files) {
ImageUtils::duplicate(fp);
FileBrowser::refreshFolder(fp.getParentDir());
}
@@ -175,42 +173,49 @@ public:
QString getHistoryString() override {
QString str = QObject::tr("Duplicate File : ");
- int i;
- for (i = 0; i < (int)m_files.size(); i++) {
- if (i != 0) str += QString(", ");
-
- TFilePath fp = m_files[i];
- TFilePath newFp = m_newFiles[i];
-
+ bool first = true;
+ for (size_t i = 0; i < m_files.size(); ++i) {
+ if (!first) str += QString(", ");
+ first = false;
str += QString("%1 > %2")
- .arg(QString::fromStdString(fp.getLevelName()))
- .arg(QString::fromStdString(newFp.getLevelName()));
+ .arg(QString::fromStdString(m_files[i].getLevelName()))
+ .arg(QString::fromStdString(m_newFiles[i].getLevelName()));
}
return str;
}
+
+private:
+ Q_DISABLE_COPY_MOVE(DuplicateUndo);
};
TPaletteP viewedPalette;
-//-----------------------------------------------------------------------------
+
} // namespace
//------------------------------------------------------------------------
-FileSelection::FileSelection() : m_exportScenePopup(0) {}
+FileSelection::FileSelection() : m_exportScenePopup(nullptr) {}
-FileSelection::~FileSelection() { m_infoViewers.clear(); }
+FileSelection::~FileSelection() {
+ // QPointer automatically nullifies, but we still own the InfoViewer objects.
+ // They are stored in m_infoViewers as QPointer; we need to delete them.
+ // However, QPointer does not own the objects; we must delete the raw
+ // pointers.
+ for (auto &viewer : m_infoViewers) {
+ delete viewer; // delete if not null
+ }
+ // m_exportScenePopup is a unique_ptr, no manual delete needed
+}
//------------------------------------------------------------------------
void FileSelection::getSelectedFiles(std::vector<TFilePath> &files) {
if (!getModel()) return;
const std::set<int> &indices = getSelectedIndices();
- std::set<int>::const_iterator it;
- for (it = indices.begin(); it != indices.end(); ++it) {
+ for (int idx : indices) {
QString name =
- getModel()->getItemData(*it, DvItemListModel::FullPath).toString();
- TFilePath fp(name.toStdWString());
- files.push_back(fp);
+ getModel()->getItemData(idx, DvItemListModel::FullPath).toString();
+ files.emplace_back(name.toStdWString());
}
}
@@ -245,9 +250,8 @@ void FileSelection::addToBatchRenderList() {
}
std::vector<TFilePath> files;
getSelectedFiles(files);
- int i;
- for (i = 0; i < files.size(); i++)
- BatchesController::instance()->addComposerTask(files[i]);
+ for (const TFilePath &fp : files)
+ BatchesController::instance()->addComposerTask(fp);
DVGui::info(QObject::tr(" Task added to the Batch Render List."));
}
@@ -262,9 +266,8 @@ void FileSelection::addToBatchCleanupList() {
std::vector<TFilePath> files;
getSelectedFiles(files);
- int i;
- for (i = 0; i < files.size(); i++)
- BatchesController::instance()->addCleanupTask(files[i]);
+ for (const TFilePath &fp : files)
+ BatchesController::instance()->addCleanupTask(fp);
DVGui::info(QObject::tr(" Task added to the Batch Cleanup List."));
}
@@ -288,24 +291,19 @@ void FileSelection::deleteFiles() {
question = QObject::tr("Deleting %1. Are you sure?").arg(fn);
}
} else {
- question =
- QObject::tr("Deleting %n files. Are you sure?", "", (int)files.size());
+ question = QObject::tr("Deleting %n files. Are you sure?", "",
+ static_cast<int>(files.size()));
}
int ret =
DVGui::MsgBox(question, QObject::tr("Delete"), QObject::tr("Cancel"), 1);
if (ret == 2 || ret == 0) return;
- int i;
- for (i = 0; i < (int)files.size(); i++) {
- // folder case
- if (TFileStatus(files[i]).isDirectory()) {
- QFile(files[i].getQString()).moveToTrash();
- }
- // file
- else {
- TSystem::moveFileOrLevelToRecycleBin(files[i]);
- IconGenerator::instance()->remove(files[i]);
- // TODO: cancellare anche xxxx_files se files[i] == xxxx.tnz
+ for (const TFilePath &fp : files) {
+ if (TFileStatus(fp).isDirectory()) {
+ QFile(fp.getQString()).moveToTrash();
+ } else {
+ TSystem::moveFileOrLevelToRecycleBin(fp);
+ IconGenerator::instance()->remove(fp);
}
}
selectNone();
@@ -320,29 +318,30 @@ void FileSelection::copyFiles() {
if (files.empty()) return;
QClipboard *clipboard = QApplication::clipboard();
- QMimeData *oldData = cloneData(clipboard->mimeData());
- FileData *data = new FileData();
+ std::unique_ptr<QMimeData> oldData(cloneData(clipboard->mimeData()));
+ auto *data = new FileData();
data->setFiles(files);
- QApplication::clipboard()->setMimeData(data);
- QMimeData *newData = cloneData(clipboard->mimeData());
+ clipboard->setMimeData(data);
+ std::unique_ptr<QMimeData> newData(cloneData(clipboard->mimeData()));
- TUndoManager::manager()->add(new CopyFilesUndo(oldData, newData));
+ TUndoManager::manager()->add(
+ new CopyFilesUndo(oldData.release(), newData.release()));
}
//------------------------------------------------------------------------
void FileSelection::pasteFiles() {
- const FileData *data =
+ const auto *data =
dynamic_cast<const FileData *>(QApplication::clipboard()->mimeData());
if (!data) return;
- TApp *app = TApp::instance();
- FileBrowser *model = dynamic_cast<FileBrowser *>(getModel());
+ auto *model = dynamic_cast<FileBrowser *>(getModel());
if (!model) return;
TFilePath folder = model->getFolder();
std::vector<TFilePath> newFiles;
data->getFiles(folder, newFiles);
FileBrowser::refreshFolder(folder);
- TUndoManager::manager()->add(new PasteFilesUndo(newFiles, folder));
+ TUndoManager::manager()->add(
+ new PasteFilesUndo(std::move(newFiles), std::move(folder)));
}
//------------------------------------------------------------------------
@@ -353,7 +352,7 @@ void FileSelection::showFolderContents() {
TFilePath folderPath;
if (!files.empty()) folderPath = files[0].getParentDir();
if (folderPath.isEmpty()) {
- FileBrowser *model = dynamic_cast<FileBrowser *>(getModel());
+ auto *model = dynamic_cast<FileBrowser *>(getModel());
if (!model) return;
folderPath = model->getFolder();
}
@@ -375,22 +374,25 @@ void FileSelection::viewFileInfo() {
std::vector<TFilePath> files;
getSelectedFiles(files);
if (files.empty()) return;
- int j = 0;
- for (j = 0; j < files.size(); j++) {
- InfoViewer *infoViewer = 0;
- int i;
- for (i = 0; i < m_infoViewers.size(); i++) {
- InfoViewer *v = m_infoViewers.at(i);
- if (!v->isHidden()) continue;
- infoViewer = v;
- break;
+
+ for (const TFilePath &fp : files) {
+ QPointer<InfoViewer> infoViewer = nullptr;
+
+ // Look for a hidden InfoViewer that can be reused
+ for (auto &v : m_infoViewers) {
+ if (v && v->isHidden()) {
+ infoViewer = v;
+ break;
+ }
}
+
if (!infoViewer) {
infoViewer = new InfoViewer();
m_infoViewers.append(infoViewer);
}
+
FileBrowserPopup::setModalBrowserToParent(infoViewer);
- infoViewer->setItem(0, 0, files[j]);
+ infoViewer->setItem(0, 0, fp);
}
}
@@ -399,25 +401,23 @@ void FileSelection::viewFileInfo() {
void FileSelection::viewFile() {
std::vector<TFilePath> files;
getSelectedFiles(files);
- int i = 0;
- for (i = 0; i < files.size(); i++) {
- if (!TFileType::isViewable(TFileType::getInfo(files[i])) &&
- files[i].getType() != "tpl")
+ for (const TFilePath &fp : files) {
+ if (!TFileType::isViewable(TFileType::getInfo(fp)) && fp.getType() != "tpl")
continue;
if (Preferences::instance()->isDefaultViewerEnabled() &&
- (files[i].getType() == "mov" || files[i].getType() == "avi" ||
- files[i].getType() == "3gp"))
- QDesktopServices::openUrl(QUrl("file:///" + toQString(files[i])));
- else if (files[i].getType() == "tpl") {
- viewedPalette = StudioPalette::instance()->getPalette(files[i], false);
+ (fp.getType() == "mov" || fp.getType() == "avi" ||
+ fp.getType() == "3gp"))
+ QDesktopServices::openUrl(QUrl("file:///" + toQString(fp)));
+ else if (fp.getType() == "tpl") {
+ viewedPalette = StudioPalette::instance()->getPalette(fp, false);
TApp::instance()
->getPaletteController()
->getCurrentLevelPalette()
->setPalette(viewedPalette.getPointer());
CommandManager::instance()->execute("MI_OpenPalette");
} else {
- FlipBook *fb = ::viewFile(files[i]);
+ FlipBook *fb = ::viewFile(fp);
if (fb) {
FileBrowserPopup::setModalBrowserToParent(fb->parentWidget());
}
@@ -432,7 +432,8 @@ void FileSelection::convertFiles() {
getSelectedFiles(files);
if (files.empty()) return;
- static ConvertPopup *popup = new ConvertPopup(false);
+ static std::unique_ptr<ConvertPopup> popup =
+ std::make_unique<ConvertPopup>(false);
if (popup->isConverting()) {
DVGui::info(QObject::tr(
"A conversion task is in progress! wait until it stops or cancel it"));
@@ -454,11 +455,7 @@ void FileSelection::premultiplyFiles() {
std::vector<TFilePath> files;
getSelectedFiles(files);
- int i;
- for (i = 0; i < (int)files.size(); i++) {
- TFilePath fp = files[i];
- ImageUtils::premultiply(fp);
- }
+ for (const TFilePath &fp : files) ImageUtils::premultiply(fp);
}
//------------------------------------------------------------------------
@@ -467,20 +464,18 @@ void FileSelection::duplicateFiles() {
std::vector<TFilePath> files;
std::vector<TFilePath> newFiles;
getSelectedFiles(files);
- int i;
- for (i = 0; i < (int)files.size(); i++) {
- TFilePath fp = files[i];
+ for (const TFilePath &fp : files) {
TFilePath newPath = ImageUtils::duplicate(fp);
newFiles.push_back(newPath);
FileBrowser::refreshFolder(fp.getParentDir());
}
- TUndoManager::manager()->add(new DuplicateUndo(files, newFiles));
+ TUndoManager::manager()->add(
+ new DuplicateUndo(std::move(files), std::move(newFiles)));
}
//------------------------------------------------------------------------
-static int collectAssets(TFilePath scenePath) {
- // bool dirtyFlag = TNotifier::instance()->getDirtyFlag();
+static int collectAssets(const TFilePath &scenePath) {
ToonzScene scene;
scene.load(scenePath);
ResourceCollector collector(&scene);
@@ -490,7 +485,6 @@ static int collectAssets(TFilePath scenePath) {
if (count > 0) {
scene.save(scenePath);
}
- // TNotifier::instance()->setDirtyFlag(dirtyFlag);
return count;
}
@@ -502,7 +496,7 @@ void FileSelection::collectAssets() {
if (files.empty()) return;
int collectedAssets = 0;
- int count = files.size();
+ int count = static_cast<int>(files.size());
if (count > 1) {
QMainWindow *mw = TApp::instance()->getMainWindow();
@@ -510,10 +504,10 @@ void FileSelection::collectAssets() {
QObject::tr("Abort"), 0, count, mw);
progress.setWindowModality(Qt::WindowModal);
- int i;
- for (i = 1; i <= count; i++) {
- collectedAssets += ::collectAssets(files[i - 1]);
- progress.setValue(i);
+ int i = 1;
+ for (const TFilePath &fp : files) {
+ collectedAssets += ::collectAssets(fp);
+ progress.setValue(i++);
if (progress.wasCanceled()) break;
}
progress.setValue(count);
@@ -537,7 +531,8 @@ void FileSelection::separateFilesByColors() {
getSelectedFiles(files);
if (files.empty()) return;
- static SeparateColorsPopup *popup = new SeparateColorsPopup();
+ static std::unique_ptr<SeparateColorsPopup> popup =
+ std::make_unique<SeparateColorsPopup>();
if (popup->isConverting()) {
DVGui::MsgBox(INFORMATION, QObject::tr("A separation task is in progress! "
"wait until it stops or cancel it"));
@@ -546,13 +541,11 @@ void FileSelection::separateFilesByColors() {
popup->setFiles(files);
popup->show();
popup->raise();
- // popup->exec();
}
//------------------------------------------------------------------------
-static int importScene(TFilePath scenePath) {
- // bool dirtyFlag = TNotifier::instance()->getDirtyFlag();
+static int importScene(const TFilePath &scenePath) {
ToonzScene scene;
try {
IoCmd::loadScene(scene, scenePath, true);
@@ -562,7 +555,6 @@ static int importScene(TFilePath scenePath) {
.arg(QString::fromStdWString(e.getMessage())));
return 0;
} catch (...) {
- // TNotifier::instance()->notify(TGlobalChange(true));
DVGui::error(
QObject::tr("Error loading scene %1").arg(toQString(scenePath)));
return 0;
@@ -579,7 +571,6 @@ static int importScene(TFilePath scenePath) {
DvDirModel::instance()->refreshFolder(
TProjectManager::instance()->getCurrentProjectPath().getParentDir());
- // TNotifier::instance()->setDirtyFlag(dirtyFlag);
return 1;
}
@@ -591,7 +582,7 @@ void FileSelection::importScenes() {
if (files.empty()) return;
int importedSceneCount = 0;
- int count = files.size();
+ int count = static_cast<int>(files.size());
if (count > 1) {
QMainWindow *mw = TApp::instance()->getMainWindow();
@@ -599,11 +590,11 @@ void FileSelection::importScenes() {
QObject::tr("Abort"), 0, count, mw);
progress.setWindowModality(Qt::WindowModal);
- int i;
- for (i = 1; i <= count; i++) {
- int ret = ::importScene(files[i - 1]);
+ int i = 1;
+ for (const TFilePath &fp : files) {
+ int ret = ::importScene(fp);
importedSceneCount += ret;
- progress.setValue(i);
+ progress.setValue(i++);
if (progress.wasCanceled()) break;
}
progress.setValue(count);
@@ -617,15 +608,16 @@ void FileSelection::importScenes() {
DVGui::info(QObject::tr("One scene imported"));
else
DVGui::info(QString::number(importedSceneCount) +
- QObject::tr("%1 scenes imported").arg(importedSceneCount));
+ QObject::tr(" scenes imported"));
}
+
//------------------------------------------------------------------------
void FileSelection::exportScenes() {
std::vector<TFilePath> files;
getSelectedFiles(files);
if (!m_exportScenePopup)
- m_exportScenePopup = new ExportScenePopup(files);
+ m_exportScenePopup = std::make_unique<ExportScenePopup>(files);
else
m_exportScenePopup->setScenes(files);
m_exportScenePopup->show();
@@ -637,9 +629,9 @@ void FileSelection::exportScene(TFilePath scenePath) {
if (scenePath.isEmpty()) return;
std::vector<TFilePath> files;
- files.push_back(scenePath);
+ files.push_back(std::move(scenePath));
if (!m_exportScenePopup)
- m_exportScenePopup = new ExportScenePopup(files);
+ m_exportScenePopup = std::make_unique<ExportScenePopup>(files);
else
m_exportScenePopup->setScenes(files);
m_exportScenePopup->show();
@@ -650,12 +642,10 @@ void FileSelection::exportScene(TFilePath scenePath) {
void FileSelection::selectAll() {
DvItemSelection::selectAll();
const std::set<int> &indices = getSelectedIndices();
- if (indices.size()) {
- std::set<int>::const_iterator it;
- it = indices.begin();
+ if (!indices.empty()) {
+ int firstIdx = *indices.begin();
QString name =
- getModel()->getItemData(*it, DvItemListModel::FullPath).toString();
- TFilePath fp(name.toStdWString());
+ getModel()->getItemData(firstIdx, DvItemListModel::FullPath).toString();
FileBrowser::updateItemViewerPanel();
}
}
@@ -679,7 +669,7 @@ public:
return;
}
- FileSelection *fs = new FileSelection();
+ auto fs = std::make_unique<FileSelection>();
fs->exportScene(fp);
}
} ExportCurrentSceneCommandHandler;
diff --git a/toonz/sources/toonz/fileselection.h b/toonz/sources/toonz/fileselection.h
index 29fd8d567..dfe92c174 100644
--- a/toonz/sources/toonz/fileselection.h
+++ b/toonz/sources/toonz/fileselection.h
@@ -6,6 +6,11 @@
#include "dvitemview.h"
#include "tfilepath.h"
+// Qt includes
+#include <QList>
+#include <QPointer>
+#include <memory>
+
class InfoViewer;
class ExportScenePopup;
@@ -14,16 +19,22 @@ class ExportScenePopup;
//-----------------------------------------------------------------------------
class FileSelection final : public DvItemSelection {
- QList<InfoViewer *> m_infoViewers;
- ExportScenePopup *m_exportScenePopup;
+ QList<QPointer<InfoViewer>> m_infoViewers; // QPointer handles nullification
+ std::unique_ptr<ExportScenePopup> m_exportScenePopup;
public:
FileSelection();
- ~FileSelection();
+ virtual ~FileSelection();
+
+ // Prohibit copying and moving
+ FileSelection(const FileSelection&) = delete;
+ FileSelection& operator=(const FileSelection&) = delete;
+ FileSelection(FileSelection&&) = delete;
+ FileSelection& operator=(FileSelection&&) = delete;
- void getSelectedFiles(std::vector<TFilePath> &files);
+ void getSelectedFiles(std::vector<TFilePath>& files);
- // commands
+ // Commands
void enableCommands() override;
void duplicateFiles();
diff --git a/toonz/sources/toonz/fillholespopup.cpp b/toonz/sources/toonz/fillholespopup.cpp
index 02e053b5f..feb102576 100644
--- a/toonz/sources/toonz/fillholespopup.cpp
+++ b/toonz/sources/toonz/fillholespopup.cpp
@@ -1,34 +1,48 @@
+
+
#include "fillholespopup.h"
-#include "toonz/fill.h"
+// Tnz6 includes
+#include "menubarcommandids.h"
+#include "selectionutils.h"
+#include "tools/toolutils.h"
+#include "tundo.h"
+#include "ttoonzimage.h"
+
+// TnzQt includes
#include "toonzqt/dvdialog.h"
#include "toonzqt/intfield.h"
#include "toonzqt/menubarcommand.h"
-#include "menubarcommandids.h"
-#include "selectionutils.h"
+
+// TnzLib includes
+#include "toonz/fill.h"
#include "toonz/txshlevel.h"
#include "toonz/txshsimplelevel.h"
#include "toonz/txshleveltypes.h"
-#include "ttoonzimage.h"
-#include "tools/toolutils.h"
-#include "tundo.h"
#include "toonz/ttileset.h"
#include "toonz/ttilesaver.h"
#include "toonz/txsheethandle.h"
+// Qt includes
#include <QPushButton>
#include <QProgressBar>
+#include <memory>
+#include <utility> // for std::pair (kept for compatibility)
+#include <cassert>
+
using namespace DVGui;
using namespace ToolUtils;
+//-----------------------------------------------------------------------------
+
class TFillHolesUndo final : public TRasterUndo {
int m_size;
public:
TFillHolesUndo(TTileSetCM32* tileSet, int size, TXshSimpleLevel* sl,
const TFrameId& fid)
- : TRasterUndo(tileSet, sl, fid, false, false, 0), m_size(size) {};
+ : TRasterUndo(tileSet, sl, fid, false, false, 0), m_size(size) {}
void redo() const override {
TToonzImageP image = getImage();
@@ -38,20 +52,26 @@ public:
fillHoles(image->getRaster(), m_size);
app->getCurrentXsheet()->notifyXsheetChanged();
notifyImageChanged();
- };
+ }
+
int getSize() const override {
return sizeof(*this) + TRasterUndo::getSize();
- };
- QString getToolName() override { return QString("Fill Holes"); };
+ }
+
+ QString getToolName() override { return QStringLiteral("Fill Holes"); }
};
-FillHolesDialog::FillHolesDialog() : Dialog(0, true, true, "Fill Small Holes") {
+//-----------------------------------------------------------------------------
+
+FillHolesDialog::FillHolesDialog()
+ : Dialog(nullptr, true, true, "Fill Small Holes")
+ , m_progressDialog(nullptr) {
setWindowTitle(tr("Fill Small Holes"));
setModal(false);
setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
beginVLayout();
- m_size = new IntField(this,false);
+ m_size = new IntField(this, false);
m_size->setRange(1, 25);
m_size->setValue(5);
addWidget(tr("Size"), m_size);
@@ -60,57 +80,80 @@ FillHolesDialog::FillHolesDialog() : Dialog(0, true, true, "Fill Small Holes") {
QPushButton* okBtn = new QPushButton(tr("Apply"), this);
okBtn->setDefault(true);
QPushButton* cancelBtn = new QPushButton(tr("Cancel"), this);
- bool ret = connect(okBtn, SIGNAL(clicked()), this, SLOT(apply()));
- ret = ret && connect(cancelBtn, SIGNAL(clicked()), this, SLOT(reject()));
- assert(ret);
+
+ connect(okBtn, &QPushButton::clicked, this, &FillHolesDialog::apply);
+ connect(cancelBtn, &QPushButton::clicked, this, &QDialog::reject);
addButtonBarWidget(okBtn, cancelBtn);
-};
+}
+
+//-----------------------------------------------------------------------------
void FillHolesDialog::apply() {
std::set<TXshLevel*> levels;
SelectionUtils::getSelectedLevels(levels);
- std::vector<std::pair<TXshSimpleLevel*, TFrameId>> Frames;
- for (const auto& level : levels) {
+
+ // Collect all frames from Toonz raster levels
+ std::vector<std::pair<TXshSimpleLevel*, TFrameId>> frames;
+ for (TXshLevel* level : levels) {
if (level->getType() != TXshLevelType::TZP_XSHLEVEL) continue;
TXshSimpleLevel* sl = level->getSimpleLevel();
if (!sl) continue;
for (const TFrameId& fid : sl->getFids()) {
- Frames.push_back(std::make_pair(sl, fid));
+ frames.emplace_back(sl, fid);
}
}
- int size = Frames.size();
- if (size == 0) {
+
+ const int totalFrames = static_cast<int>(frames.size());
+ if (totalFrames == 0) {
DVGui::warning(tr("No Toonz Raster Level Selected"));
return;
- } else {
- m_progressDialog =
- new ProgressDialog("Filling Holes...", QObject::tr("Cancel"), 0, size, this);
- m_progressDialog->show();
}
+ // Create progress dialog – use std::make_unique for automatic cleanup
+ m_progressDialog = std::make_unique<ProgressDialog>(
+ tr("Filling Holes..."), tr("Cancel"), 0, totalFrames, this);
+ m_progressDialog->show();
+
int count = 0;
TUndoManager::manager()->beginBlock();
- for (const auto& frame : Frames) {
- TXshSimpleLevel* sl = frame.first;
- TFrameId fid = frame.second;
-
- TImageP img = sl->getFrame(fid, true);
- TToonzImageP ti = TToonzImageP(img);
- TRasterCM32P ras = ti->getRaster();
- TTileSetCM32* tileSet = new TTileSetCM32(ras->getSize());
- TTileSaverCM32* saver = new TTileSaverCM32(ras, tileSet);
- if (m_progressDialog->wasCanceled()) break;
- fillHoles(ras, m_size->getValue(), saver);
- if (tileSet->getTileCount() != 0)
+
+ for (const auto& frame : frames) {
+ const auto& [sl, fid] = frame;
+
+ TImageP img = sl->getFrame(fid, true);
+ TToonzImageP ti = img;
+ if (!ti) continue; // safety check
+ TRasterCM32P ras = ti->getRaster();
+
+ auto tileSet = std::make_unique<TTileSetCM32>(ras->getSize());
+ auto saver = std::make_unique<TTileSaverCM32>(ras, tileSet.get());
+
+ if (m_progressDialog->wasCanceled()) {
+ break;
+ }
+
+ fillHoles(ras, m_size->getValue(), saver.get());
+
+ if (tileSet->getTileCount() != 0) {
+ // Transfer ownership of tileSet to the undo object
TUndoManager::manager()->add(
- new TFillHolesUndo(tileSet, m_size->getValue(), sl, fid));
- count++;
+ new TFillHolesUndo(tileSet.release(), m_size->getValue(), sl, fid));
+ // saver is destroyed automatically when we leave the scope
+ }
+ // else: tileSet and saver are automatically destroyed by unique_ptr
+
+ ++count;
m_progressDialog->setValue(count);
}
+
+ // Progress dialog is automatically destroyed when m_progressDialog is reset
+ m_progressDialog.reset();
+
TUndoManager::manager()->endBlock();
- m_progressDialog->close();
Dialog::accept();
}
-OpenPopupCommandHandler<FillHolesDialog> fillholesPopup(MI_FillHoles);
\ No newline at end of file
+//-----------------------------------------------------------------------------
+
+OpenPopupCommandHandler<FillHolesDialog> fillholesPopup(MI_FillHoles);
diff --git a/toonz/sources/toonz/fillholespopup.h b/toonz/sources/toonz/fillholespopup.h
index a76e9c594..280e976a6 100644
--- a/toonz/sources/toonz/fillholespopup.h
+++ b/toonz/sources/toonz/fillholespopup.h
@@ -1,16 +1,37 @@
+#pragma once
+
+#ifndef FILLHOLESDIALOG_H
+#define FILLHOLESDIALOG_H
+
#include "toonzqt/dvdialog.h"
#include "toonzqt/intfield.h"
#include <QProgressBar>
+#include <memory> // for std::unique_ptr
+
+// Forward declaration
+namespace DVGui {
+class ProgressDialog;
+}
+
class FillHolesDialog final : public DVGui::Dialog {
Q_OBJECT
DVGui::IntField* m_size;
- DVGui::ProgressDialog* m_progressDialog;
+ std::unique_ptr<DVGui::ProgressDialog> m_progressDialog; // automatic cleanup
public:
- FillHolesDialog();
+ explicit FillHolesDialog();
+ ~FillHolesDialog() = default; // unique_ptr handles destruction
+
+ // Prohibit copying and moving
+ FillHolesDialog(const FillHolesDialog&) = delete;
+ FillHolesDialog& operator=(const FillHolesDialog&) = delete;
+ FillHolesDialog(FillHolesDialog&&) = delete;
+ FillHolesDialog& operator=(FillHolesDialog&&) = delete;
protected slots:
void apply();
-};
\ No newline at end of file
+};
+
+#endif // FILLHOLESDIALOG_H
diff --git a/toonz/sources/toonz/filmstripcommand.cpp b/toonz/sources/toonz/filmstripcommand.cpp
index f310685cc..e521b0571 100644
--- a/toonz/sources/toonz/filmstripcommand.cpp
+++ b/toonz/sources/toonz/filmstripcommand.cpp
@@ -1,52 +1,65 @@
#include "filmstripcommand.h"
+
+// Tnz6 includes
#include "tapp.h"
-#include "toonz/palettecontroller.h"
-#include "toonz/txshlevelhandle.h"
-#include "toonz/txsheethandle.h"
-#include "toonz/tscenehandle.h"
-#include "toonz/tpalettehandle.h"
-#include "toonz/tframehandle.h"
-#include "tinbetween.h"
-#include "tvectorimage.h"
-#include "ttoonzimage.h"
-#include "toonzqt/selection.h"
-#include "toonzqt/dvdialog.h"
+#include "tundo.h"
+#include "historytypes.h"
#include "drawingdata.h"
-#include "toonzqt/strokesdata.h"
-#include "toonzqt/rasterimagedata.h"
+#include "tinbetween.h"
#include "timagecache.h"
+
#include "tools/toolhandle.h"
#include "tools/toolutils.h"
#include "tools/rasterselection.h"
+
+// TnzQt includes
+#include "toonzqt/selection.h"
+#include "toonzqt/dvdialog.h"
+#include "toonzqt/strokesdata.h"
+#include "toonzqt/rasterimagedata.h"
#include "toonzqt/icongenerator.h"
+#include "toonzqt/gutil.h"
+
+// TnzLib includes
+#include "toonz/palettecontroller.h"
+
+#include "toonz/txshlevelhandle.h"
+#include "toonz/txsheethandle.h"
+#include "toonz/tscenehandle.h"
+#include "toonz/tpalettehandle.h"
+#include "toonz/tframehandle.h"
-#include "tundo.h"
#include "toonz/txshsimplelevel.h"
#include "toonz/txshchildlevel.h"
#include "toonz/txshsoundlevel.h"
#include "toonz/txshpalettelevel.h"
#include "toonz/txshpalettecolumn.h"
#include "toonz/txshsoundcolumn.h"
+
#include "toonz/txsheet.h"
#include "toonz/txshcell.h"
#include "toonz/toonzscene.h"
#include "toonz/levelset.h"
#include "toonz/txshleveltypes.h"
+
#include "toonz/toonzimageutils.h"
#include "toonz/trasterimageutils.h"
#include "toonz/tcamera.h"
#include "toonz/preferences.h"
-#include "trop.h"
-
-#include "toonzqt/gutil.h"
-#include "historytypes.h"
+// TnzCore includes
+#include "trop.h"
+// Qt includes
#include <QApplication>
#include <QClipboard>
+// C++ includes
+#include <memory>
+#include <algorithm>
+
//=============================================================================
TFrameId operator+(const TFrameId &fid, int d) {
@@ -115,33 +128,26 @@ static void updateXSheet(TXshSimpleLevel *sl, std::vector<TFrameId> oldFids,
//=============================================================================
// makeSpaceForFid
-// se necessario renumera gli altri fid del livello in modo che
-// framesToInsert siano liberi
-// n.b. modifica
+// TODO: If necessary, renumber other frame IDs in the level
+// before inserting framesToInsert, so that the IDs are free.
//-----------------------------------------------------------------------------
void makeSpaceForFids(TXshSimpleLevel *sl,
const std::set<TFrameId> &framesToInsert) {
- std::vector<TFrameId> fids;
- std::vector<TFrameId> oldFids;
+ std::vector<TFrameId> fids, oldFids;
sl->getFids(fids);
- sl->getFids(oldFids);
- std::set<TFrameId>::const_iterator it;
+ oldFids = fids;
std::set<TFrameId> touchedFids;
- for (it = framesToInsert.begin(); it != framesToInsert.end(); ++it) {
- // devo inserire fid
- TFrameId fid(*it);
- std::vector<TFrameId>::iterator j;
- // controllo che non ci sia gia'
- j = fids.begin();
- while (j = std::find(j, fids.end(), fid), j != fids.end()) {
- // c'e' gia' un fid. faccio fid -> fid + 1
+ for (const TFrameId &fidBase : framesToInsert) {
+ TFrameId fid = fidBase;
+ auto j = fids.begin();
+ while ((j = std::find(j, fids.end(), fid)) != fids.end()) {
touchedFids.insert(fid);
fid = fid + 1;
touchedFids.insert(fid);
*j = fid;
- // adesso devo controllare che il nuovo fid non ci sia gia' nella
- // parte restante dell'array fids
+ // Now I need to check that the new fid is not already
+// in the remaining part of the fids array
++j;
}
}
@@ -155,12 +161,10 @@ void makeSpaceForFids(TXshSimpleLevel *sl,
//=============================================================================
namespace {
-//-----------------------------------------------------------------------------
void copyFramesWithoutUndo(TXshSimpleLevel *sl, std::set<TFrameId> &frames) {
QClipboard *clipboard = QApplication::clipboard();
- TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
- DrawingData *data = new DrawingData();
+ auto *data = new DrawingData();
data->setLevelFrames(sl, frames);
clipboard->setMimeData(data, QClipboard::Clipboard);
}
@@ -168,20 +172,19 @@ void copyFramesWithoutUndo(TXshSimpleLevel *sl, std::set<TFrameId> &frames) {
//-----------------------------------------------------------------------------
// frames is a selected frames in the film strip
bool pasteAreasWithoutUndo(const QMimeData *data, TXshSimpleLevel *sl,
- std::set<TFrameId> &frames, TTileSet **tileSet,
+ std::set<TFrameId> &frames,
+ std::unique_ptr<TTileSet> &tileSet,
std::map<TFrameId, std::set<int>> &indices) {
// paste between the same level must keep the palette unchanged
// Not emitting PaletteChanged signal can avoid the update of color model
bool paletteHasChanged = true;
- if (const StrokesData *strokesData =
- dynamic_cast<const StrokesData *>(data)) {
- std::set<TFrameId>::iterator it;
- for (it = frames.begin(); it != frames.end(); ++it) {
- TImageP img = sl->getFrame(*it, true);
+ if (const auto *strokesData = dynamic_cast<const StrokesData *>(data)) {
+ for (const TFrameId &fid : frames) {
+ TImageP img = sl->getFrame(fid, true);
if (!img) {
img = sl->createEmptyFrame();
- sl->setFrame(*it, img);
+ sl->setFrame(fid, img);
}
TVectorImageP vi = img;
TToonzImageP ti = img;
@@ -189,10 +192,11 @@ bool pasteAreasWithoutUndo(const QMimeData *data, TXshSimpleLevel *sl,
if (vi) {
std::set<int> imageIndices;
strokesData->getImage(vi, imageIndices, true);
- indices[*it] = imageIndices;
+ indices[fid] = imageIndices;
} else if (ti) {
- ToonzImageData *toonzImageData = strokesData->toToonzImageData(ti);
- return pasteAreasWithoutUndo(toonzImageData, sl, frames, tileSet,
+ std::unique_ptr<ToonzImageData> toonzImageData(
+ strokesData->toToonzImageData(ti));
+ return pasteAreasWithoutUndo(toonzImageData.get(), sl, frames, tileSet,
indices);
} else if (ri) {
double dpix, dpiy;
@@ -203,43 +207,35 @@ bool pasteAreasWithoutUndo(const QMimeData *data, TXshSimpleLevel *sl,
dpiy = dpi.y;
ri->setDpi(dpix, dpiy);
}
- FullColorImageData *fullColorImageData =
- strokesData->toFullColorImageData(ri);
- return pasteAreasWithoutUndo(fullColorImageData, sl, frames, tileSet,
- indices);
+ std::unique_ptr<FullColorImageData> fullColorImageData(
+ strokesData->toFullColorImageData(ri));
+ return pasteAreasWithoutUndo(fullColorImageData.get(), sl, frames,
+ tileSet, indices);
}
}
- }
- // when pasting the copied area selected with the selection tool
- else if (const RasterImageData *rasterImageData =
- dynamic_cast<const RasterImageData *>(data)) {
- std::set<TFrameId>::iterator it;
- for (it = frames.begin(); it != frames.end(); ++it) {
+ } else if (const auto *rasterImageData =
+ dynamic_cast<const RasterImageData *>(data)) {
+ for (const TFrameId &fid : frames) {
if ((sl->getType() == PLI_XSHLEVEL || sl->getType() == TZP_XSHLEVEL) &&
dynamic_cast<const FullColorImageData *>(rasterImageData)) {
DVGui::error(QObject::tr(
"The copied selection cannot be pasted in the current drawing."));
return false;
}
- // obtain the image data to be pasted
- TImageP img = sl->getFrame(*it, true);
+ TImageP img = sl->getFrame(fid, true);
if (!img) {
img = sl->createEmptyFrame();
- sl->setFrame(*it, img);
+ sl->setFrame(fid, img);
}
TToonzImageP ti = img;
TRasterImageP ri = img;
TVectorImageP vi = img;
- // pasting TLV
if (ti) {
TRasterP ras;
double dpiX, dpiY;
std::vector<TRectD> rects;
- std::vector<TStroke> strokes;
- std::vector<TStroke> originalStrokes;
+ std::vector<TStroke> strokes, originalStrokes;
TAffine affine;
-
- // style will be merged in getData() if the palettes are different
int styleCountBeforePasteImage = ti->getPalette()->getStyleCount();
rasterImageData->getData(ras, dpiX, dpiY, rects, strokes,
@@ -252,12 +248,12 @@ bool pasteAreasWithoutUndo(const QMimeData *data, TXshSimpleLevel *sl,
ti->getDpi(imgDpiX, imgDpiY);
TScale sc(imgDpiX / dpiX, imgDpiY / dpiY);
affine *= sc;
- int i;
+
TRectD boxD;
- if (rects.size() > 0) boxD = rects[0];
- if (strokes.size() > 0) boxD = strokes[0].getBBox();
- for (i = 0; i < rects.size(); i++) boxD += rects[i];
- for (i = 0; i < strokes.size(); i++) boxD += strokes[i].getBBox();
+ if (!rects.empty()) boxD = rects[0];
+ if (!strokes.empty()) boxD = strokes[0].getBBox();
+ for (const auto &r : rects) boxD += r;
+ for (const auto &s : strokes) boxD += s.getBBox();
boxD = affine * boxD;
TRect box = ToonzImageUtils::convertWorldToRaster(boxD, ti);
TPoint pos = box.getP00();
@@ -265,37 +261,29 @@ bool pasteAreasWithoutUndo(const QMimeData *data, TXshSimpleLevel *sl,
if (pos.x < 0) pos.x = 0;
if (pos.y < 0) pos.y = 0;
- if (*tileSet == 0)
- *tileSet = new TTileSetCM32(ti->getRaster()->getSize());
+ if (!tileSet)
+ tileSet = std::make_unique<TTileSetCM32>(ti->getRaster()->getSize());
if (box.overlaps(ti->getRaster()->getBounds()))
- (*tileSet)->add(ti->getRaster(), box);
+ tileSet->add(ti->getRaster(), box);
else
- (*tileSet)->add(0);
+ tileSet->add(nullptr);
TRasterCM32P app = ras;
if (app) {
TRop::over(ti->getRaster(), app, pos, affine);
- ToolUtils::updateSaveBox(sl, *it);
+ ToolUtils::updateSaveBox(sl, fid);
}
} else if (ri) {
TRasterP ras;
- double dpiX = 0, dpiY = 0;
- double imgDpiX = 0, imgDpiY = 0;
+ double dpiX = 0, dpiY = 0, imgDpiX = 0, imgDpiY = 0;
std::vector<TRectD> rects;
- std::vector<TStroke> strokes;
- std::vector<TStroke> originalStrokes;
+ std::vector<TStroke> strokes, originalStrokes;
TAffine affine;
- TPointD cameraDpi;
-
ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();
- if (scene) {
- TCamera *camera = scene->getCurrentCamera();
- cameraDpi = camera->getDpi();
- if (cameraDpi.x == 0.0 ||
- cameraDpi.y == 0.0) // it should never happen. just in case...
- return false;
- } else
- return false;
+ if (!scene) return false;
+ TCamera *camera = scene->getCurrentCamera();
+ TPointD cameraDpi = camera->getDpi();
+ if (cameraDpi.x == 0.0 || cameraDpi.y == 0.0) return false;
rasterImageData->getData(ras, dpiX, dpiY, rects, strokes,
originalStrokes, affine, ri->getPalette());
@@ -303,7 +291,6 @@ bool pasteAreasWithoutUndo(const QMimeData *data, TXshSimpleLevel *sl,
dpiX = cameraDpi.x;
dpiY = cameraDpi.y;
}
-
ri->getDpi(imgDpiX, imgDpiY);
if (imgDpiX == 0 || imgDpiY == 0) {
imgDpiX = cameraDpi.x;
@@ -311,30 +298,34 @@ bool pasteAreasWithoutUndo(const QMimeData *data, TXshSimpleLevel *sl,
}
TScale sc(imgDpiX / dpiX, imgDpiY / dpiY);
affine *= sc;
- int i;
+
TRectD boxD;
- if (rects.size() > 0) boxD = rects[0];
- if (strokes.size() > 0) boxD = strokes[0].getBBox();
- for (i = 0; i < rects.size(); i++) boxD += rects[i];
- for (i = 0; i < strokes.size(); i++) boxD += strokes[i].getBBox();
+ if (!rects.empty()) boxD = rects[0];
+ if (!strokes.empty()) boxD = strokes[0].getBBox();
+ for (const auto &r : rects) boxD += r;
+ for (const auto &s : strokes) boxD += s.getBBox();
boxD = affine * boxD;
TRect box = TRasterImageUtils::convertWorldToRaster(boxD, ri);
TPoint pos = box.getP00();
- if (*tileSet == 0)
- *tileSet = new TTileSetFullColor(ri->getRaster()->getSize());
+
+ if (!tileSet)
+ tileSet =
+ std::make_unique<TTileSetFullColor>(ri->getRaster()->getSize());
if (box.overlaps(ri->getRaster()->getBounds()))
- (*tileSet)->add(ri->getRaster(), box);
+ tileSet->add(ri->getRaster(), box);
else
- (*tileSet)->add(0);
+ tileSet->add(nullptr);
+
TRasterCM32P app = ras;
if (app)
TRop::over(ri->getRaster(), app, ri->getPalette(), pos, affine);
else
TRop::over(ri->getRaster(), ras, pos, affine);
} else if (vi) {
- StrokesData *strokesData =
- rasterImageData->toStrokesData(sl->getScene());
- return pasteAreasWithoutUndo(strokesData, sl, frames, tileSet, indices);
+ std::unique_ptr<StrokesData> strokesData(
+ rasterImageData->toStrokesData(sl->getScene()));
+ return pasteAreasWithoutUndo(strokesData.get(), sl, frames, tileSet,
+ indices);
}
}
} else
@@ -354,11 +345,11 @@ bool pasteAreasWithoutUndo(const QMimeData *data, TXshSimpleLevel *sl,
}
//-----------------------------------------------------------------------------
-// Se insert == true incolla i frames nel livello inserendoli, se necessario
-// spostando
-// verso il basso i preesistenti. Altrimenti incolla i frames sostituendoli.
-// il parametro clone images si mette a false quando questa funzione viene usata
-// per un undo/redo.
+// If insert == true, paste the frames into the level by inserting them,
+// moving the existing frames downward if necessary.
+// Otherwise, paste the frames by replacing existing ones.
+// The parameter cloneImages is set to false when this function
+// is used for undo/redo operations.
bool pasteFramesWithoutUndo(const DrawingData *data, TXshSimpleLevel *sl,
std::set<TFrameId> &frames,
@@ -390,28 +381,24 @@ bool pasteFramesWithoutUndo(const DrawingData *data, TXshSimpleLevel *sl,
//-----------------------------------------------------------------------------
-// "Svuota" i frames: i frames vengono buttati e al loro posto
-// vengono inseriti frames vuoti.
+// "Clear" the frames: the existing frames are discarded
+// and replaced with empty frames.
std::map<TFrameId, QString> clearFramesWithoutUndo(
const TXshSimpleLevelP &sl, const std::set<TFrameId> &frames) {
std::map<TFrameId, QString> clearedFrames;
if (!sl || frames.empty()) return clearedFrames;
- std::set<TFrameId>::const_iterator it;
- for (it = frames.begin(); it != frames.end(); ++it) {
- TFrameId frameId = *it;
- /* UINT にキャストしたらだめだろ */
- // QString id =
- // "clearFrames"+QString::number((UINT)sl.getPointer())+"-"+QString::number(it->getNumber());
+ for (const TFrameId &frameId : frames) {
+/* You shouldn’t cast to UINT */
+// QString id =
+// "clearFrames"+QString::number((UINT)sl.getPointer())+"-"+QString::number(it->getNumber());
QString id = "clearFrames" + QString::number((uintptr_t)sl.getPointer()) +
- "-" + QString::number(it->getNumber());
+ "-" + QString::number(frameId.getNumber());
TImageCache::instance()->add(id, sl->getFrame(frameId, false));
clearedFrames[frameId] = id;
- // empty frame must be created BEFORE erasing frame or it may initialize
- // palette.
- TImageP emptyFrame = sl->createEmptyFrame();
+ TImageP emptyFrame = sl->createEmptyFrame();
sl->eraseFrame(frameId);
- sl->setFrame(*it, emptyFrame);
+ sl->setFrame(frameId, emptyFrame);
}
invalidateIcons(sl.getPointer(), frames);
TApp::instance()->getCurrentLevel()->notifyLevelChange();
@@ -421,12 +408,10 @@ std::map<TFrameId, QString> clearFramesWithoutUndo(
//-----------------------------------------------------------------------------
-// Rimuove i frames dal livello
void removeFramesWithoutUndo(const TXshSimpleLevelP &sl,
const std::set<TFrameId> &frames) {
if (!sl || frames.empty()) return;
- std::set<TFrameId>::const_iterator it;
- for (it = frames.begin(); it != frames.end(); ++it) sl->eraseFrame(*it);
+ for (const TFrameId &fid : frames) sl->eraseFrame(fid);
removeIcons(sl.getPointer(), frames);
sl->setDirtyFlag(true);
TApp::instance()->getCurrentLevel()->notifyLevelChange();
@@ -439,34 +424,25 @@ void cutFramesWithoutUndo(TXshSimpleLevel *sl, std::set<TFrameId> &frames) {
HookSet *levelHooks = sl->getHookSet();
int currentFrameIndex = TApp::instance()->getCurrentFrame()->getFrameIndex();
- std::set<TFrameId>::const_iterator it;
- int i = 0;
- for (it = frames.begin(); it != frames.end(); ++it, i++) {
- TFrameId frameId = *it;
- // QString id =
- // "cutFrames"+QString::number((UINT)sl)+"-"+QString::number(it->getNumber());
+ int i = 0;
+ for (const TFrameId &frameId : frames) {
QString id = "cutFrames" + QString::number((uintptr_t)sl) + "-" +
- QString::number(it->getNumber());
+ QString::number(frameId.getNumber());
TImageCache::instance()->add(id, sl->getFrame(frameId, false));
imageSet[frameId] = id;
}
removeIcons(sl, frames);
-
sl->setDirtyFlag(true);
QClipboard *clipboard = QApplication::clipboard();
- DrawingData *data = new DrawingData();
+ auto *data = new DrawingData();
data->setFrames(imageSet, sl, *levelHooks);
clipboard->setMimeData(data, QClipboard::Clipboard);
- for (it = frames.begin(); it != frames.end(); ++it, i++) {
- sl->eraseFrame(*it);
- }
+ for (const TFrameId &fid : frames) sl->eraseFrame(fid);
std::vector<TFrameId> newFids;
sl->getFids(newFids);
- // Devo settare i nuovi fids al frame handle prima di mandare la notifica di
- // cambiamento del livello
TApp::instance()->getCurrentFrame()->setFrameIds(newFids);
TApp::instance()->getCurrentFrame()->setFrameIndex(currentFrameIndex);
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
@@ -482,16 +458,15 @@ void insertNotEmptyframes(const TXshSimpleLevelP &sl,
std::vector<TFrameId> fids;
sl->getFids(fids);
std::set<TFrameId> frames;
- for (auto const &frame : framesToInsert) {
- frames.insert(frame.first);
- }
+ for (const auto &[fid, _] : framesToInsert) frames.insert(fid);
+
makeSpaceForFids(sl.getPointer(), frames);
- for (auto const &frame : framesToInsert) {
- TImageP img = TImageCache::instance()->get(frame.second, false);
- TImageCache::instance()->remove(frame.second);
+ for (const auto &[fid, cacheId] : framesToInsert) {
+ TImageP img = TImageCache::instance()->get(cacheId, false);
+ TImageCache::instance()->remove(cacheId);
assert(img);
- sl->setFrame(frame.first, img);
+ sl->setFrame(fid, img);
}
invalidateIcons(sl.getPointer(), frames);
sl->setDirtyFlag(true);
@@ -505,8 +480,8 @@ void insertNotEmptyframes(const TXshSimpleLevelP &sl,
class PasteRasterAreasUndo final : public TUndo {
TXshSimpleLevelP m_level;
std::set<TFrameId> m_frames;
- TTileSet *m_tiles;
- RasterImageData *m_data;
+ std::unique_ptr<TTileSet> m_tiles;
+ std::unique_ptr<RasterImageData> m_data;
TPaletteP m_oldPalette;
TPaletteP m_newPalette;
bool m_isFrameInserted;
@@ -515,21 +490,15 @@ public:
PasteRasterAreasUndo(TXshSimpleLevel *sl, const std::set<TFrameId> &frames,
TTileSet *tiles, RasterImageData *data, TPalette *plt,
bool isFrameInserted)
- : TUndo()
- , m_level(sl)
+ : m_level(sl)
, m_frames(frames)
, m_tiles(tiles)
+ , m_data(data->clone())
, m_oldPalette(plt->clone())
, m_isFrameInserted(isFrameInserted) {
- m_data = data->clone();
assert(m_tiles->getTileCount() == m_frames.size());
}
- ~PasteRasterAreasUndo() {
- if (m_tiles) delete m_tiles;
- if (m_data) delete m_data;
- }
-
void onAdd() override { m_newPalette = m_level->getPalette()->clone(); }
void undo() const override {
@@ -537,38 +506,45 @@ public:
std::set<TFrameId> frames = m_frames;
if (m_isFrameInserted) {
- // Faccio remove dei frame incollati
removeFramesWithoutUndo(m_level, frames);
} else {
- std::set<TFrameId>::const_iterator it;
- int i = 0;
- TTileSetCM32 *tileSetCM = dynamic_cast<TTileSetCM32 *>(m_tiles);
- TTileSetFullColor *tileSetFC = dynamic_cast<TTileSetFullColor *>(m_tiles);
- for (it = m_frames.begin(); it != m_frames.end(); it++, i++) {
- TImageP image = m_level->getFrame(*it, true);
+ int i = 0;
+ const TTileSetCM32 *tileSetCM =
+ dynamic_cast<const TTileSetCM32 *>(m_tiles.get());
+ const TTileSetFullColor *tileSetFC =
+ dynamic_cast<const TTileSetFullColor *>(m_tiles.get());
+ for (const TFrameId &fid : m_frames) {
+ TImageP image = m_level->getFrame(fid, true);
if (!image) continue;
TRasterImageP ri(image);
TToonzImageP ti(image);
if (tileSetCM) {
const TTileSetCM32::Tile *tile = tileSetCM->getTile(i);
- if (!tile) continue;
+ if (!tile) {
+ ++i;
+ continue;
+ }
TRasterCM32P tileRas;
tile->getRaster(tileRas);
assert(ti);
ti->getRaster()->copy(tileRas, tile->m_rasterBounds.getP00());
- ToolUtils::updateSaveBox(m_level, *it);
+ ToolUtils::updateSaveBox(m_level, fid);
} else if (tileSetFC) {
const TTileSetFullColor::Tile *tile = tileSetFC->getTile(i);
- if (!tile) continue;
+ if (!tile) {
+ ++i;
+ continue;
+ }
TRasterP tileRas;
tile->getRaster(tileRas);
assert(ri);
ri->getRaster()->copy(tileRas, tile->m_rasterBounds.getP00());
}
+ ++i;
}
}
- // Setto la vecchia paletta al livello
- if (m_oldPalette.getPointer()) {
+
+ if (m_oldPalette) {
m_level->getPalette()->assign(m_oldPalette->clone());
TApp::instance()
->getPaletteController()
@@ -588,19 +564,15 @@ public:
m_level->setFrame(*m_frames.begin(), img);
}
- std::set<TFrameId> frames = m_frames;
-
- std::set<TFrameId>::const_iterator it;
- for (it = m_frames.begin(); it != m_frames.end(); it++) {
- TImageP image = m_level->getFrame(*it, true);
+ for (const TFrameId &fid : m_frames) {
+ TImageP image = m_level->getFrame(fid, true);
TRasterImageP ri = image;
TToonzImageP ti = image;
if (ti) {
TRasterP ras;
double dpiX, dpiY;
std::vector<TRectD> rects;
- std::vector<TStroke> strokes;
- std::vector<TStroke> originalStrokes;
+ std::vector<TStroke> strokes, originalStrokes;
TAffine affine;
m_data->getData(ras, dpiX, dpiY, rects, strokes, originalStrokes,
affine, ti->getPalette());
@@ -609,24 +581,23 @@ public:
TScale sc(imgDpiX / dpiX, imgDpiY / dpiY);
affine *= sc;
- int i;
TRectD boxD;
- if (rects.size() > 0) boxD = rects[0];
- if (strokes.size() > 0) boxD = strokes[0].getBBox();
- for (i = 0; i < rects.size(); i++) boxD += rects[i];
- for (i = 0; i < strokes.size(); i++) boxD += strokes[i].getBBox();
- boxD = affine * boxD;
- TRect box = ToonzImageUtils::convertWorldToRaster(boxD, ti);
- TPoint pos = box.getP00();
+ if (!rects.empty()) boxD = rects[0];
+ if (!strokes.empty()) boxD = strokes[0].getBBox();
+ for (const auto &r : rects) boxD += r;
+ for (const auto &s : strokes) boxD += s.getBBox();
+ boxD = affine * boxD;
+ TRect box = ToonzImageUtils::convertWorldToRaster(boxD, ti);
+ TPoint pos = box.getP00();
+
TRasterCM32P app = ras;
TRop::over(ti->getRaster(), app, pos, affine);
- ToolUtils::updateSaveBox(m_level, *it);
+ ToolUtils::updateSaveBox(m_level, fid);
} else if (ri) {
TRasterP ras;
double dpiX, dpiY;
std::vector<TRectD> rects;
- std::vector<TStroke> strokes;
- std::vector<TStroke> originalStrokes;
+ std::vector<TStroke> strokes, originalStrokes;
TAffine affine;
m_data->getData(ras, dpiX, dpiY, rects, strokes, originalStrokes,
affine, ri->getPalette());
@@ -644,15 +615,16 @@ public:
ri->getDpi(imgDpiX, imgDpiY);
TScale sc(imgDpiX / dpiX, imgDpiY / dpiY);
affine *= sc;
- int i;
+
TRectD boxD;
- if (rects.size() > 0) boxD = rects[0];
- if (strokes.size() > 0) boxD = strokes[0].getBBox();
- for (i = 0; i < rects.size(); i++) boxD += rects[i];
- for (i = 0; i < strokes.size(); i++) boxD += strokes[i].getBBox();
- boxD = affine * boxD;
- TRect box = TRasterImageUtils::convertWorldToRaster(boxD, ri);
- TPoint pos = box.getP00();
+ if (!rects.empty()) boxD = rects[0];
+ if (!strokes.empty()) boxD = strokes[0].getBBox();
+ for (const auto &r : rects) boxD += r;
+ for (const auto &s : strokes) boxD += s.getBBox();
+ boxD = affine * boxD;
+ TRect box = TRasterImageUtils::convertWorldToRaster(boxD, ri);
+ TPoint pos = box.getP00();
+
TRasterCM32P app = ras;
if (app)
TRop::over(ri->getRaster(), app, ri->getPalette(), pos, affine);
@@ -661,7 +633,7 @@ public:
}
}
- if (m_newPalette.getPointer()) {
+ if (m_newPalette) {
m_level->getPalette()->assign(m_newPalette->clone());
TApp::instance()
->getPaletteController()
@@ -680,16 +652,18 @@ public:
QString getHistoryString() override {
QString str = QObject::tr("Paste : Level %1 : Frame ")
.arg(QString::fromStdWString(m_level->getName()));
-
- std::set<TFrameId>::const_iterator it;
- for (it = m_frames.begin(); it != m_frames.end(); it++) {
- if (it != m_frames.begin()) str += QString(", ");
- str += QString::number((*it).getNumber());
+ bool first = true;
+ for (const TFrameId &fid : m_frames) {
+ if (!first) str += QString(", ");
+ first = false;
+ str += QString::number(fid.getNumber());
}
-
return str;
}
int getHistoryType() override { return HistoryType::FilmStrip; }
+
+private:
+ Q_DISABLE_COPY_MOVE(PasteRasterAreasUndo);
};
//=============================================================================
@@ -700,7 +674,7 @@ class PasteVectorAreasUndo final : public TUndo {
TXshSimpleLevelP m_level;
std::set<TFrameId> m_frames;
std::map<TFrameId, std::set<int>> m_indices;
- StrokesData *m_data;
+ std::unique_ptr<StrokesData> m_data;
TPaletteP m_oldPalette;
TPaletteP m_newPalette;
bool m_isFrameInserted;
@@ -709,50 +683,35 @@ public:
PasteVectorAreasUndo(TXshSimpleLevel *sl, const std::set<TFrameId> &frames,
std::map<TFrameId, std::set<int>> &indices,
StrokesData *data, TPalette *plt, bool isFrameInserted)
- : TUndo()
- , m_level(sl)
+ : m_level(sl)
, m_frames(frames)
, m_indices(indices)
+ , m_data(data->clone())
, m_oldPalette(plt->clone())
- , m_isFrameInserted(isFrameInserted) {
- m_data = data->clone();
- }
-
- ~PasteVectorAreasUndo() {
- if (m_data) delete m_data;
- }
+ , m_isFrameInserted(isFrameInserted) {}
void onAdd() override { m_newPalette = m_level->getPalette()->clone(); }
void undo() const override {
if (!m_level || m_frames.empty()) return;
- std::set<TFrameId> frames = m_frames;
-
if (m_isFrameInserted) {
- // Faccio remove dei frame incollati
- removeFramesWithoutUndo(m_level, frames);
+ removeFramesWithoutUndo(m_level, m_frames);
} else {
- std::set<TFrameId>::const_iterator it;
- for (it = m_frames.begin(); it != m_frames.end(); it++) {
- TVectorImageP img = m_level->getFrame(*it, true);
- assert(img);
+ for (const TFrameId &fid : m_frames) {
+ TVectorImageP img = m_level->getFrame(fid, true);
if (!img) continue;
- std::map<TFrameId, std::set<int>>::const_iterator mapIt =
- m_indices.find(*it);
- if (mapIt == m_indices.end()) continue;
- std::set<int> imageIndices = mapIt->second;
- ;
- std::set<int>::const_iterator it2 = imageIndices.end();
- while (it2 != imageIndices.begin()) {
- it2--;
+ auto it = m_indices.find(fid);
+ if (it == m_indices.end()) continue;
+ const std::set<int> &imageIndices = it->second;
+ // remove strokes in reverse order
+ for (auto it2 = imageIndices.rbegin(); it2 != imageIndices.rend();
+ ++it2)
img->removeStroke(*it2);
- }
}
}
- // Setto la vecchia paletta al livello
- if (m_oldPalette.getPointer()) {
+ if (m_oldPalette) {
m_level->getPalette()->assign(m_oldPalette->clone());
TApp::instance()
->getPaletteController()
@@ -773,17 +732,15 @@ public:
m_level->setFrame(*m_frames.begin(), img);
}
- std::set<TFrameId> frames = m_frames;
- std::set<TFrameId>::const_iterator it;
- for (it = m_frames.begin(); it != m_frames.end(); it++) {
- TVectorImageP img = m_level->getFrame(*it, true);
+ for (const TFrameId &fid : m_frames) {
+ TVectorImageP img = m_level->getFrame(fid, true);
assert(img);
if (!img) continue;
std::set<int> app;
m_data->getImage(img, app, true);
}
- if (m_newPalette.getPointer()) {
+ if (m_newPalette) {
m_level->getPalette()->assign(m_newPalette->clone());
TApp::instance()
->getPaletteController()
@@ -800,136 +757,19 @@ public:
QString getHistoryString() override {
QString str = QObject::tr("Paste : Level %1 : Frame ")
.arg(QString::fromStdWString(m_level->getName()));
-
- std::set<TFrameId>::const_iterator it;
- for (it = m_frames.begin(); it != m_frames.end(); it++) {
- if (it != m_frames.begin()) str += QString(", ");
- str += QString::number((*it).getNumber());
+ bool first = true;
+ for (const TFrameId &fid : m_frames) {
+ if (!first) str += QString(", ");
+ first = false;
+ str += QString::number(fid.getNumber());
}
-
return str;
}
int getHistoryType() override { return HistoryType::FilmStrip; }
-};
-
-/*//=============================================================================
-// PasteAreasUndo
-//-----------------------------------------------------------------------------
-
-class PasteAreasUndo final : public TUndo
-{
- TXshSimpleLevelP m_level;
- std::set<TFrameId> m_frames;
- TPaletteP m_oldPalette;
- TPaletteP m_newPalette;
- bool m_isFrameInserted;
-
-public:
- PasteAreasUndo(TXshSimpleLevel *sl, const std::set<TFrameId> &frames, bool
-isFrameInserted)
- : TUndo()
- , m_level(sl)
- , m_frames(frames)
- , m_isFrameInserted(isFrameInserted)
- {
- m_oldPalette = m_level->getPalette()->clone();
- if(!m_isFrameInserted)
- {
- std::set<TFrameId>::iterator it;
- for(it=m_frames.begin(); it!=m_frames.end(); it++)
- {
- TImageP img = m_level->getFrame(*it,true);
- TImageCache::instance()->add("PasteAreasUndoOld"+QString::number((UINT)this)+QString::number((*it).getNumber()),
-img->cloneImage());
- }
- }
- }
-
- void onAdd()
- {
- m_newPalette = m_level->getPalette()->clone();
- std::set<TFrameId>::iterator it;
- for(it=m_frames.begin(); it!=m_frames.end(); it++)
- {
- TImageP img = m_level->getFrame(*it,true);
- TImageCache::instance()->add("PasteAreasUndoNew"+QString::number((UINT)this)+QString::number((*it).getNumber()),
-img->cloneImage());
- }
- }
- ~PasteAreasUndo() {
- std::set<TFrameId>::const_iterator it;
-
- if(!m_isFrameInserted)
- {
- for(it=m_frames.begin(); it!=m_frames.end(); it++)
- TImageCache::instance()->remove("PasteAreasUndoOld"+QString::number((UINT)this)+QString::number((*it).getNumber()));
- }
- for(it=m_frames.begin(); it!=m_frames.end(); it++)
- TImageCache::instance()->remove("PasteAreasUndoNew"+QString::number((UINT)this)+QString::number((*it).getNumber()));
- }
-
- void undo() const
- {
- std::set<TFrameId> frames = m_frames;
-
- if(m_isFrameInserted)
- {
- // Faccio remove dei frame incollati
- removeFramesWithoutUndo(m_level, frames);
- }
- else
- {
- std::set<TFrameId>::const_iterator it;
- for(it=m_frames.begin(); it!=m_frames.end(); it++)
- {
- TImageP img =
-TImageCache::instance()->get("PasteAreasUndoOld"+QString::number((UINT)this)+QString::number((*it).getNumber()),true);
- assert(img);
- m_level->setFrame(*it,img);
- }
- }
-
- //Setto la vecchia paletta al livello
- if(m_oldPalette.getPointer())
- {
- m_level->getPalette()->assign(m_oldPalette->clone());
- TApp::instance()->getPaletteController()->getCurrentLevelPalette()->notifyPaletteChanged();
- }
-
- invalidateIcons(m_level.getPointer(), m_frames);
- TApp::instance()->getCurrentLevel()->notifyLevelChange();
- }
-
- void redo() const
- {
- if(!m_level || m_frames.empty()) return;
-
- std::set<TFrameId> frames = m_frames;
-
- std::set<TFrameId>::const_iterator it;
- for(it=m_frames.begin(); it!=m_frames.end(); it++)
- {
- TImageP img =
-TImageCache::instance()->get("PasteAreasUndoNew"+QString::number((UINT)this)+QString::number((*it).getNumber()),true);
- if(!img) continue;
- m_level->setFrame(*it, img, true);
- }
-
- if(m_newPalette.getPointer())
- {
- m_level->getPalette()->assign(m_newPalette->clone());
- TApp::instance()->getPaletteController()->getCurrentLevelPalette()->notifyPaletteChanged();
- }
-
- invalidateIcons(m_level.getPointer(), m_frames);
- TApp::instance()->getCurrentLevel()->notifyLevelChange();
- }
-
- int getSize() const{
- return sizeof(*this);
- }
-};*/
+private:
+ Q_DISABLE_COPY_MOVE(PasteVectorAreasUndo);
+};
//=============================================================================
// PasteFramesUndo
@@ -940,10 +780,10 @@ class PasteFramesUndo final : public TUndo {
std::set<TFrameId> m_frames;
std::vector<TFrameId> m_oldLevelFrameId;
TPaletteP m_oldPalette;
- DrawingData *m_oldData;
- DrawingData *m_newData;
+ std::unique_ptr<DrawingData> m_oldData;
+ std::unique_ptr<DrawingData> m_newData;
DrawingData::ImageSetType m_setType;
- HookSet *m_oldLevelHooks;
+ std::unique_ptr<HookSet> m_oldLevelHooks;
bool m_updateXSheet;
bool m_keepOriginalPalette;
@@ -952,18 +792,18 @@ public:
const std::vector<TFrameId> &oldLevelFrameId,
TPaletteP oldPalette, DrawingData::ImageSetType setType,
HookSet *oldLevelHooks, bool keepOriginalPalette,
- DrawingData *oldData = 0)
+ DrawingData *oldData = nullptr)
: m_sl(sl)
, m_frames(frames)
, m_oldLevelFrameId(oldLevelFrameId)
, m_oldPalette(oldPalette)
- , m_setType(setType)
- , m_keepOriginalPalette(keepOriginalPalette)
, m_oldData(oldData)
- , m_oldLevelHooks(oldLevelHooks) {
+ , m_setType(setType)
+ , m_oldLevelHooks(oldLevelHooks)
+ , m_keepOriginalPalette(keepOriginalPalette) {
QClipboard *clipboard = QApplication::clipboard();
QMimeData *data = cloneData(clipboard->mimeData());
- m_newData = dynamic_cast<DrawingData *>(data);
+ m_newData.reset(dynamic_cast<DrawingData *>(data));
assert(m_newData);
m_updateXSheet =
Preferences::instance()->isSyncLevelRenumberWithXsheetEnabled();
@@ -971,7 +811,7 @@ public:
~PasteFramesUndo() {
if (m_oldData) m_oldData->releaseData();
- if (m_newData) m_newData->releaseData();
+ // m_newData automatically deleted by unique_ptr
}
void undo() const override {
@@ -979,11 +819,9 @@ public:
if (selection) selection->selectNone();
std::set<TFrameId> frames = m_frames;
- // Faccio remove dei frame incollati
if (m_setType != DrawingData::OVER_SELECTION)
removeFramesWithoutUndo(m_sl, frames);
- // Renumero i frame con i vecchi fids
if (m_setType == DrawingData::INSERT) {
assert(m_sl->getFrameCount() == m_oldLevelFrameId.size());
if (m_updateXSheet) {
@@ -1000,19 +838,15 @@ public:
TApp::instance()->getCurrentLevel()->notifyLevelChange();
}
- // Reinserisco i vecchi frame che ho sovrascritto
- if (m_setType != DrawingData::INSERT) {
+ if (m_setType != DrawingData::INSERT && m_oldData) {
std::set<TFrameId> framesToModify;
m_oldData->getFrames(framesToModify);
-
bool dummy = true;
- // Incollo i frames sovrascrivendoli
- pasteFramesWithoutUndo(m_oldData, m_sl.getPointer(), framesToModify,
+ pasteFramesWithoutUndo(m_oldData.get(), m_sl.getPointer(), framesToModify,
DrawingData::OVER_SELECTION, true, dummy);
}
- // Setto la vecchia paletta al livello
- if (m_oldPalette.getPointer()) {
+ if (m_oldPalette) {
TPalette *levelPalette = m_sl->getPalette();
if (levelPalette) levelPalette->assign(m_oldPalette.getPointer());
@@ -1038,8 +872,8 @@ public:
std::set<TFrameId> frames = m_frames;
bool keepOriginalPalette = m_keepOriginalPalette;
- pasteFramesWithoutUndo(m_newData, m_sl.getPointer(), frames, m_setType,
- true, keepOriginalPalette, true);
+ pasteFramesWithoutUndo(m_newData.get(), m_sl.getPointer(), frames,
+ m_setType, true, keepOriginalPalette, true);
}
int getSize() const override { return sizeof(*this); }
@@ -1047,16 +881,18 @@ public:
QString getHistoryString() override {
QString str = QObject::tr("Paste : Level %1 : Frame ")
.arg(QString::fromStdWString(m_sl->getName()));
-
- std::set<TFrameId>::const_iterator it;
- for (it = m_frames.begin(); it != m_frames.end(); it++) {
- if (it != m_frames.begin()) str += QString(", ");
- str += QString::number((*it).getNumber());
+ bool first = true;
+ for (const TFrameId &fid : m_frames) {
+ if (!first) str += QString(", ");
+ first = false;
+ str += QString::number(fid.getNumber());
}
-
return str;
}
int getHistoryType() override { return HistoryType::FilmStrip; }
+
+private:
+ Q_DISABLE_COPY_MOVE(PasteFramesUndo);
};
//=============================================================================
@@ -1066,53 +902,46 @@ public:
class DeleteFramesUndo final : public TUndo {
TXshSimpleLevel *m_sl;
std::set<TFrameId> m_frames;
- DrawingData *m_oldData;
- DrawingData *m_newData;
+ std::unique_ptr<DrawingData> m_oldData;
+ std::unique_ptr<DrawingData> m_newData;
public:
DeleteFramesUndo(TXshSimpleLevel *sl, std::set<TFrameId> &frames,
DrawingData *oldData, DrawingData *newData)
: m_sl(sl), m_frames(frames), m_oldData(oldData), m_newData(newData) {}
- ~DeleteFramesUndo() {
- if (m_oldData) m_oldData->releaseData();
- if (m_newData) m_newData->releaseData();
- }
-
void pasteFramesFromData(const DrawingData *data) const {
std::set<TFrameId> frames = m_frames;
-
- bool dummy = true;
- // Incollo i frames sovrascrivendoli
+ bool dummy = true;
pasteFramesWithoutUndo(data, m_sl, frames, DrawingData::OVER_SELECTION,
true, dummy);
}
- void undo() const override { pasteFramesFromData(m_oldData); }
+ void undo() const override { pasteFramesFromData(m_oldData.get()); }
+ // NOTE: I cannot use the method "clearFramesWithoutUndo(...)" because
+// it creates a NEW empty frame, discarding the previous one
+// and any modifications that may have been made to it afterwards.
- // OSS.: Non posso usare il metodo "clearFramesWithoutUndo(...)" perche'
- // genera un NUOVO frame vuoto, perdendo quello precedente e le eventuali
- // modifiche che ad esso possono essere state fatte successivamente.
- void redo() const override { pasteFramesFromData(m_newData); }
+ void redo() const override { pasteFramesFromData(m_newData.get()); }
int getSize() const override { return sizeof(*this); }
QString getHistoryString() override {
QString str = QObject::tr("Delete Frames : Level %1 : Frame ")
.arg(QString::fromStdWString(m_sl->getName()));
-
- std::set<TFrameId>::const_iterator it;
- for (it = m_frames.begin(); it != m_frames.end(); it++) {
- if (it != m_frames.begin()) str += QString(", ");
- str += QString::number((*it).getNumber());
+ bool first = true;
+ for (const TFrameId &fid : m_frames) {
+ if (!first) str += QString(", ");
+ first = false;
+ str += QString::number(fid.getNumber());
}
-
return str;
}
int getHistoryType() override { return HistoryType::FilmStrip; }
-};
-//=============================================================================
+private:
+ Q_DISABLE_COPY_MOVE(DeleteFramesUndo);
+};
//-----------------------------------------------------------------------------
@@ -1120,7 +949,7 @@ class CutFramesUndo final : public TUndo {
TXshSimpleLevel *m_sl;
std::set<TFrameId> m_framesCutted;
std::vector<TFrameId> m_oldFrames;
- DrawingData *m_newData;
+ std::unique_ptr<DrawingData> m_newData;
public:
CutFramesUndo(TXshSimpleLevel *sl, std::set<TFrameId> &framesCutted,
@@ -1128,32 +957,26 @@ public:
: m_sl(sl), m_framesCutted(framesCutted), m_oldFrames(oldFrames) {
QClipboard *clipboard = QApplication::clipboard();
QMimeData *data = cloneData(clipboard->mimeData());
- m_newData = dynamic_cast<DrawingData *>(data);
+ m_newData.reset(dynamic_cast<DrawingData *>(data));
assert(m_newData);
}
- ~CutFramesUndo() {
- if (m_newData) m_newData->releaseData();
- }
-
void undo() const override {
std::set<TFrameId> frames = m_framesCutted;
bool dummy = true;
- pasteFramesWithoutUndo(m_newData, m_sl, frames, DrawingData::OVER_SELECTION,
- true, dummy);
+ pasteFramesWithoutUndo(m_newData.get(), m_sl, frames,
+ DrawingData::OVER_SELECTION, true, dummy);
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
}
void redo() const override {
- // Prendo il clipboard corrente.
- QClipboard *clipboard = QApplication::clipboard();
- QMimeData *currentData = cloneData(clipboard->mimeData());
+ QClipboard *clipboard = QApplication::clipboard();
+ std::unique_ptr<QMimeData> currentData(cloneData(clipboard->mimeData()));
std::set<TFrameId> frames = m_framesCutted;
cutFramesWithoutUndo(m_sl, frames);
- // Setto il clipboard corrente
- clipboard->setMimeData(currentData, QClipboard::Clipboard);
+ clipboard->setMimeData(currentData.release(), QClipboard::Clipboard);
}
int getSize() const override { return sizeof(*this); }
@@ -1161,16 +984,18 @@ public:
QString getHistoryString() override {
QString str = QObject::tr("Cut Frames : Level %1 : Frame ")
.arg(QString::fromStdWString(m_sl->getName()));
-
- std::set<TFrameId>::const_iterator it;
- for (it = m_framesCutted.begin(); it != m_framesCutted.end(); it++) {
- if (it != m_framesCutted.begin()) str += QString(", ");
- str += QString::number((*it).getNumber());
+ bool first = true;
+ for (const TFrameId &fid : m_framesCutted) {
+ if (!first) str += QString(", ");
+ first = false;
+ str += QString::number(fid.getNumber());
}
-
return str;
}
int getHistoryType() override { return HistoryType::FilmStrip; }
+
+private:
+ Q_DISABLE_COPY_MOVE(CutFramesUndo);
};
//-----------------------------------------------------------------------------
@@ -1178,22 +1003,18 @@ public:
class RemoveFramesUndo final : public TUndo {
TXshSimpleLevel *m_sl;
std::set<TFrameId> m_framesRemoved;
- DrawingData *m_oldData;
+ std::unique_ptr<DrawingData> m_oldData;
public:
RemoveFramesUndo(TXshSimpleLevel *sl, std::set<TFrameId> &framesRemoved,
DrawingData *oldData)
: m_sl(sl), m_framesRemoved(framesRemoved), m_oldData(oldData) {}
- ~RemoveFramesUndo() {
- if (m_oldData) m_oldData->releaseData();
- }
-
void undo() const override {
std::set<TFrameId> frames = m_framesRemoved;
bool dummy = true;
- pasteFramesWithoutUndo(m_oldData, m_sl, frames, DrawingData::OVER_SELECTION,
- true, dummy);
+ pasteFramesWithoutUndo(m_oldData.get(), m_sl, frames,
+ DrawingData::OVER_SELECTION, true, dummy);
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
}
@@ -1207,26 +1028,27 @@ public:
QString getHistoryString() override {
QString str = QObject::tr("Remove Frames : Level %1 : Frame ")
.arg(QString::fromStdWString(m_sl->getName()));
-
- std::set<TFrameId>::const_iterator it;
- for (it = m_framesRemoved.begin(); it != m_framesRemoved.end(); it++) {
- if (it != m_framesRemoved.begin()) str += QString(", ");
- str += QString::number((*it).getNumber());
+ bool first = true;
+ for (const TFrameId &fid : m_framesRemoved) {
+ if (!first) str += QString(", ");
+ first = false;
+ str += QString::number(fid.getNumber());
}
-
return str;
}
int getHistoryType() override { return HistoryType::FilmStrip; }
+
+private:
+ Q_DISABLE_COPY_MOVE(RemoveFramesUndo);
};
} // namespace
//=============================================================================
-
+// AddFramesUndo
//-----------------------------------------------------------------------------
namespace {
-//-----------------------------------------------------------------------------
class AddFramesUndo final : public TUndo {
TXshSimpleLevelP m_level;
@@ -1236,9 +1058,11 @@ class AddFramesUndo final : public TUndo {
public:
AddFramesUndo(const TXshSimpleLevelP &level,
- const std::set<TFrameId> insertedFids,
+ const std::set<TFrameId> &insertedFids,
std::vector<TFrameId> oldFids)
- : m_level(level), m_insertedFids(insertedFids), m_oldFids(oldFids) {
+ : m_level(level)
+ , m_insertedFids(insertedFids)
+ , m_oldFids(std::move(oldFids)) {
m_updateXSheet =
Preferences::instance()->isSyncLevelRenumberWithXsheetEnabled();
}
@@ -1261,7 +1085,7 @@ public:
void redo() const override {
makeSpaceForFids(m_level.getPointer(), m_insertedFids);
- for (auto const &fid : m_insertedFids) {
+ for (const TFrameId &fid : m_insertedFids) {
m_level->setFrame(fid, m_level->createEmptyFrame());
IconGenerator::instance()->invalidate(m_level.getPointer(), fid);
}
@@ -1277,16 +1101,18 @@ public:
QString getHistoryString() override {
QString str = QObject::tr("Add Frames : Level %1 : Frame ")
.arg(QString::fromStdWString(m_level->getName()));
-
- std::set<TFrameId>::const_iterator it;
- for (it = m_insertedFids.begin(); it != m_insertedFids.end(); it++) {
- if (it != m_insertedFids.begin()) str += QString(", ");
- str += QString::number((*it).getNumber());
+ bool first = true;
+ for (const TFrameId &fid : m_insertedFids) {
+ if (!first) str += QString(", ");
+ first = false;
+ str += QString::number(fid.getNumber());
}
-
return str;
}
int getHistoryType() override { return HistoryType::FilmStrip; }
+
+private:
+ Q_DISABLE_COPY_MOVE(AddFramesUndo);
};
} // namespace
@@ -1308,20 +1134,20 @@ void FilmstripCmd::addFrames(TXshSimpleLevel *sl, int start, int end,
if (!oldFids.empty()) tmplFid = oldFids.front();
std::set<TFrameId> fidsToInsert;
- int frame = 0;
- for (frame = start; frame <= end; frame += step)
+ for (int frame = start; frame <= end; frame += step) {
fidsToInsert.insert(TFrameId(frame, "", tmplFid.getZeroPadding(),
tmplFid.getStartSeqInd()));
+ }
makeSpaceForFids(sl, fidsToInsert);
- for (auto const &fid : fidsToInsert) {
+ for (const TFrameId &fid : fidsToInsert) {
sl->setFrame(fid, sl->createEmptyFrame());
IconGenerator::instance()->invalidate(sl, fid);
}
sl->setDirtyFlag(true);
- AddFramesUndo *undo = new AddFramesUndo(sl, fidsToInsert, oldFids);
+ auto *undo = new AddFramesUndo(sl, fidsToInsert, std::move(oldFids));
TUndoManager::manager()->add(undo);
TApp *app = TApp::instance();
@@ -1339,7 +1165,7 @@ class RenumberUndo final : public TUndo {
TXshSimpleLevelP m_level;
std::vector<TFrameId> m_fids;
std::map<TFrameId, TFrameId> m_mapOldFrameId;
- bool m_updateXSheet = false;
+ bool m_updateXSheet;
public:
RenumberUndo(const TXshSimpleLevelP &level, const std::vector<TFrameId> &fids,
@@ -1349,14 +1175,14 @@ public:
std::vector<TFrameId> oldFids;
m_level->getFids(oldFids);
assert(oldFids.size() == m_fids.size());
- int i;
- for (i = 0; i < m_fids.size(); i++) {
+ for (size_t i = 0; i < m_fids.size(); ++i) {
if (m_fids[i] != oldFids[i]) m_mapOldFrameId[m_fids[i]] = oldFids[i];
}
m_updateXSheet =
Preferences::instance()->isSyncLevelRenumberWithXsheetEnabled() ||
forceCallUpdateXSheet;
}
+
void renumber(std::vector<TFrameId> fids) const {
if (m_updateXSheet) {
std::vector<TFrameId> oldFrames;
@@ -1369,24 +1195,22 @@ public:
m_level->setDirtyFlag(true);
TApp::instance()->getCurrentLevel()->notifyLevelChange();
}
+
void undo() const override {
std::vector<TFrameId> fids;
m_level->getFids(fids);
assert(fids.size() == m_fids.size());
- int i;
- for (i = 0; i < fids.size(); i++) {
- if (m_mapOldFrameId.count(fids[i]) > 0) {
- std::map<TFrameId, TFrameId>::const_iterator it;
- it = m_mapOldFrameId.find(fids[i]);
- assert(it != m_mapOldFrameId.end());
- if (it != m_mapOldFrameId.end()) fids[i] = TFrameId(it->second);
- }
+ for (size_t i = 0; i < fids.size(); ++i) {
+ auto it = m_mapOldFrameId.find(fids[i]);
+ if (it != m_mapOldFrameId.end()) fids[i] = TFrameId(it->second);
}
renumber(fids);
}
+
void redo() const override { renumber(m_fids); }
+
int getSize() const override {
- return sizeof(*this) + sizeof(TFrameId) * m_fids.size();
+ return sizeof(*this) + int(sizeof(TFrameId) * m_fids.size());
}
QString getHistoryString() override {
@@ -1394,18 +1218,18 @@ public:
.arg(QString::fromStdWString(m_level->getName()));
}
int getHistoryType() override { return HistoryType::FilmStrip; }
+
+private:
+ Q_DISABLE_COPY_MOVE(RenumberUndo);
};
QString getNextLetter(const QString &letter) {
- // 空なら a を返す
if (letter.isEmpty()) return QString('a');
- // 1文字かつ z または Z ならEmptyを返す
if (letter == 'z' || letter == 'Z') return QString();
QByteArray byteArray = letter.toUtf8();
- // それ以外の場合、最後の文字をとにかく1進めて返す
- byteArray.data()[byteArray.size() - 1]++;
+ ++byteArray.data()[byteArray.size() - 1];
return QString::fromUtf8(byteArray);
-};
+}
} // namespace
@@ -1420,52 +1244,40 @@ void FilmstripCmd::renumber(
if (!sl || sl->isSubsequence() || sl->isReadOnly()) return;
if (table.empty()) return;
- // table:src->dst; check that src is a fid of the level
- std::vector<std::pair<TFrameId, TFrameId>>::const_iterator it;
- for (it = table.begin(); it != table.end(); ++it) {
- TFrameId srcFid = it->first;
- if (!sl->isFid(srcFid)) {
- // todo: error messages
- return;
- }
+ for (const auto &[srcFid, dstFid] : table) {
+ if (!sl->isFid(srcFid)) return;
}
- // tmp contains all the level fids that are not affected by the renumbering
- std::vector<TFrameId> fids, rfids, oldFrames;
- sl->getFids(fids);
+ std::vector<TFrameId> fids, oldFrames;
sl->getFids(oldFrames);
- std::set<TFrameId> tmp;
- for (int i = 0; i < (int)fids.size(); i++) tmp.insert(fids[i]);
- for (it = table.begin(); it != table.end(); ++it) tmp.erase(it->first);
+ fids = oldFrames;
+ std::set<TFrameId> tmp(fids.begin(), fids.end());
+ for (const auto &[srcFid, _] : table) tmp.erase(srcFid);
- // fids contain the new numbering of all the level drawings
- // (note: fids can be not ordered)
- for (int i = 0; i < (int)fids.size(); i++) {
+ for (size_t i = 0; i < fids.size(); ++i) {
TFrameId srcFid = fids[i];
- for (it = table.begin(); it != table.end() && it->first != srcFid; ++it) {
- }
+ auto it =
+ std::find_if(table.begin(), table.end(),
+ [&srcFid](const auto &p) { return p.first == srcFid; });
if (it != table.end()) {
- // srcFid is affected by the renumbering
TFrameId tarFid = it->second;
- // make sure that srcFid has not been used. add a letter if this is needed
if (tmp.count(tarFid) > 0) {
do {
tarFid =
TFrameId(tarFid.getNumber(), getNextLetter(tarFid.getLetter()),
tarFid.getZeroPadding(), tarFid.getStartSeqInd());
} while (!tarFid.getLetter().isEmpty() && tmp.count(tarFid) > 0);
- if (tarFid.getLetter().isEmpty()) {
- // todo: error message
- return;
- }
+ if (tarFid.getLetter().isEmpty()) return;
}
tmp.insert(tarFid);
fids[i] = tarFid;
}
}
+ TXshSimpleLevelP slP(sl);
TUndoManager::manager()->add(
- new RenumberUndo(sl, fids, forceCallUpdateXSheet));
+ new RenumberUndo(slP, fids, forceCallUpdateXSheet));
+
if (Preferences::instance()->isSyncLevelRenumberWithXsheetEnabled() ||
forceCallUpdateXSheet) {
updateXSheet(sl, oldFrames, fids);
@@ -1473,17 +1285,6 @@ void FilmstripCmd::renumber(
sl->renumber(fids);
TApp::instance()->getCurrentScene()->setDirtyFlag(true);
TApp::instance()->getCurrentLevel()->notifyLevelChange();
-
- /*
-int i;
-std::set<TFrameId>::iterator it2;
-it2=frames.begin();
-std::set<TFrameId> newFrames;
-for (i=0; i<frames.size(); i++, it2++)
-newFrames.insert(TFrameId(startFrame+(i*stepFrame),it2->getLetter()));
-assert(frames.size()==newFrames.size());
-frames.swap(newFrames);
-*/
}
//-----------------------------------------------------------------------------
@@ -1494,37 +1295,30 @@ void FilmstripCmd::renumber(TXshSimpleLevel *sl, std::set<TFrameId> &frames,
assert(startFrame > 0 && stepFrame > 0);
if (startFrame <= 0 || stepFrame <= 0 || frames.empty()) return;
- std::vector<TFrameId> fids;
- std::vector<TFrameId> oldFrames;
+ std::vector<TFrameId> fids, oldFrames;
sl->getFids(oldFrames);
- sl->getFids(fids);
+ fids = oldFrames;
std::set<TFrameId> modifiedFids;
-
- // tmp contiene i frames del livello, meno quelli da renumerare
std::set<TFrameId> tmp(fids.begin(), fids.end());
- std::set<TFrameId>::const_iterator it;
- for (it = frames.begin(); it != frames.end(); ++it) tmp.erase(*it);
+ for (const TFrameId &fid : frames) tmp.erase(fid);
- int frame = startFrame;
- std::vector<TFrameId>::iterator j = fids.begin();
- for (it = frames.begin(); it != frames.end(); ++it) {
- TFrameId srcFid(*it);
+ int frame = startFrame;
+ auto j = fids.begin();
+ for (const TFrameId &srcFid : frames) {
TFrameId dstFid(frame, "", srcFid.getZeroPadding(),
srcFid.getStartSeqInd());
frame += stepFrame;
- // faccio il controllo su tmp e non su fids. considera:
- // fids = [1,2,3,4], renumber = [2->3,3->5]
+ // I perform the check on tmp instead of fids. Consider:
+// fids = [1,2,3,4], renumber = [2->3, 3->5]
if (tmp.count(dstFid) > 0) {
DVGui::error(("can't renumber: frame conflict"));
return;
}
j = std::find(j, fids.end(), srcFid);
- // i frames selezionati fanno parte del livello sl. Quindi:
assert(j != fids.end());
- assert(srcFid == *j);
- if (j == fids.end()) continue; // per sicurezza
- int k = std::distance(fids.begin(), j);
+ if (j == fids.end()) continue;
+ int k = int(std::distance(fids.begin(), j));
if (srcFid != dstFid) {
modifiedFids.insert(srcFid);
modifiedFids.insert(dstFid);
@@ -1532,20 +1326,24 @@ void FilmstripCmd::renumber(TXshSimpleLevel *sl, std::set<TFrameId> &frames,
++j;
}
}
- TUndoManager::manager()->add(new RenumberUndo(sl, fids));
+
+ TXshSimpleLevelP slP(sl);
+ TUndoManager::manager()->add(new RenumberUndo(slP, fids));
+
if (Preferences::instance()->isSyncLevelRenumberWithXsheetEnabled()) {
updateXSheet(sl, oldFrames, fids);
}
sl->renumber(fids);
sl->setDirtyFlag(true);
TApp::instance()->getCurrentScene()->setDirtyFlag(true);
- int i;
- std::set<TFrameId>::iterator it2;
- it2 = frames.begin();
+
std::set<TFrameId> newFrames;
- for (i = 0; i < frames.size(); i++, it2++)
- newFrames.insert(TFrameId(startFrame + (i * stepFrame), it2->getLetter(),
- it2->getZeroPadding(), it2->getStartSeqInd()));
+ int i = 0;
+ for (const TFrameId &fid : frames) {
+ newFrames.insert(TFrameId(startFrame + (i * stepFrame), fid.getLetter(),
+ fid.getZeroPadding(), fid.getStartSeqInd()));
+ ++i;
+ }
assert(frames.size() == newFrames.size());
frames.swap(newFrames);
@@ -1575,109 +1373,103 @@ void FilmstripCmd::paste(TXshSimpleLevel *sl, std::set<TFrameId> &frames) {
if (TPalette *pal = sl->getPalette()) oldPalette = pal->clone();
QClipboard *clipboard = QApplication::clipboard();
- QMimeData *data = cloneData(clipboard->mimeData());
- // when pasting the filmstrip frames
- DrawingData *drawingData = dynamic_cast<DrawingData *>(data);
- if (drawingData) {
+ std::unique_ptr<QMimeData> data(cloneData(clipboard->mimeData()));
+
+ if (auto *drawingData = dynamic_cast<DrawingData *>(data.get())) {
if (sl->isSubsequence()) return;
- // keep the chosen option of "Keep Original Palette" and reproduce it in
- // undo
bool keepOriginalPalette;
-
- HookSet *oldLevelHooks = new HookSet();
- *oldLevelHooks = *sl->getHookSet();
+ auto *oldLevelHooks = new HookSet();
+ *oldLevelHooks = *sl->getHookSet();
bool isPaste =
pasteFramesWithoutUndo(drawingData, sl, frames, DrawingData::INSERT,
true, keepOriginalPalette);
- if (!isPaste) return;
+ if (!isPaste) {
+ delete oldLevelHooks;
+ return;
+ }
TUndoManager::manager()->add(new PasteFramesUndo(
sl, frames, oldLevelFrameId, oldPalette, DrawingData::INSERT,
oldLevelHooks, keepOriginalPalette));
+ return;
}
- // when pasting the copied part of the image which is selected with the
- // selection tool
- else {
- bool isFrameToInsert =
- (frames.size() == 1) ? !sl->isFid((*frames.begin())) : false;
- TTileSet *tileSet = 0;
- std::map<TFrameId, std::set<int>> indices;
- TUndo *undo = 0;
- TPaletteP plt = sl->getPalette()->clone();
- QImage clipImage = clipboard->image();
-
- FullColorImageData *fullColorData =
- dynamic_cast<FullColorImageData *>(data);
-
- if ((!clipImage.isNull() || fullColorData) &&
- sl->getType() != OVL_XSHLEVEL) {
- DVGui::error(QObject::tr(
- "Can't paste full raster data on a non full raster level."));
- return;
- }
- if (sl->getType() == OVL_XSHLEVEL && !clipImage.isNull()) {
- // This stuff is only if we have a pasted image from outside OpenToonz
+ bool isFrameToInsert =
+ (frames.size() == 1) ? !sl->isFid(*frames.begin()) : false;
+ std::unique_ptr<TTileSet> tileSet;
+ std::map<TFrameId, std::set<int>> indices;
+ std::unique_ptr<TUndo> undo;
+ TPaletteP plt = sl->getPalette()->clone();
+ QImage clipImage = clipboard->image();
- if (sl->getResolution().lx < clipImage.width() ||
- sl->getResolution().ly < clipImage.height()) {
- clipImage =
- clipImage.scaled(sl->getResolution().lx, sl->getResolution().ly,
- Qt::KeepAspectRatio);
- }
+ auto *fullColorData = dynamic_cast<FullColorImageData *>(data.get());
+
+ if ((!clipImage.isNull() || fullColorData) && sl->getType() != OVL_XSHLEVEL) {
+ DVGui::error(QObject::tr(
+ "Can't paste full raster data on a non full raster level."));
+ return;
+ }
- // create variables to go into the Full Color Image data
- std::vector<TRectD> rects;
- const std::vector<TStroke> strokes;
- const std::vector<TStroke> originalStrokes;
- TAffine aff;
- TRasterP ras = rasterFromQImage(clipImage);
- rects.push_back(TRectD(0.0 - clipImage.width() / 2,
- 0.0 - clipImage.height() / 2,
- clipImage.width() / 2, clipImage.height() / 2));
- FullColorImageData *qimageData = new FullColorImageData();
-
- TDimension dim = sl->getResolution();
-
- qimageData->setData(ras, plt, 120.0, 120.0, dim, rects, strokes,
- originalStrokes, aff);
- data = qimageData;
- // end of pasted from outside OpenToonz stuff
- // data holds all the info either way now.
+ if (sl->getType() == OVL_XSHLEVEL && !clipImage.isNull()) {
+ if (sl->getResolution().lx < clipImage.width() ||
+ sl->getResolution().ly < clipImage.height()) {
+ clipImage = clipImage.scaled(sl->getResolution().lx,
+ sl->getResolution().ly, Qt::KeepAspectRatio);
}
- if (sl && sl->getType() == OVL_XSHLEVEL) {
- // make selection always work on new raster cells
- ToolHandle *toolHandle = TApp::instance()->getCurrentTool();
- if (toolHandle->getTool()->getName() == "T_Selection") {
- TSelection *ts = toolHandle->getTool()->getSelection();
- RasterSelection *rs = dynamic_cast<RasterSelection *>(ts);
- if (rs) {
- toolHandle->getTool()->onDeactivate();
- toolHandle->getTool()->onActivate();
- rs->pasteSelection();
- return;
- }
+ std::vector<TRectD> rects;
+ const std::vector<TStroke> strokes, originalStrokes;
+ TAffine aff;
+ TRasterP ras = rasterFromQImage(clipImage);
+ rects.emplace_back(0.0 - clipImage.width() / 2,
+ 0.0 - clipImage.height() / 2, clipImage.width() / 2,
+ clipImage.height() / 2);
+ auto *qimageData = new FullColorImageData();
+ TDimension dim = sl->getResolution();
+ qimageData->setData(ras, plt, 120.0, 120.0, dim, rects, strokes,
+ originalStrokes, aff);
+ data.reset(qimageData);
+ }
+
+ if (sl && sl->getType() == OVL_XSHLEVEL) {
+ ToolHandle *toolHandle = TApp::instance()->getCurrentTool();
+ if (toolHandle->getTool()->getName() == "T_Selection") {
+ TSelection *ts = toolHandle->getTool()->getSelection();
+ if (auto *rs = dynamic_cast<RasterSelection *>(ts)) {
+ toolHandle->getTool()->onDeactivate();
+ toolHandle->getTool()->onActivate();
+ rs->pasteSelection();
+ return;
}
}
+ }
+
+ bool isPaste =
+ pasteAreasWithoutUndo(data.get(), sl, frames, tileSet, indices);
+ if (!isPaste) return;
- bool isPaste = pasteAreasWithoutUndo(data, sl, frames, &tileSet, indices);
- RasterImageData *rasterImageData = dynamic_cast<RasterImageData *>(data);
- StrokesData *strokesData = dynamic_cast<StrokesData *>(data);
- if (rasterImageData && tileSet)
- undo = new PasteRasterAreasUndo(sl, frames, tileSet, rasterImageData,
- plt.getPointer(), isFrameToInsert);
- if (strokesData && tileSet) {
+ if (auto *rasterImageData = dynamic_cast<RasterImageData *>(data.get())) {
+ if (tileSet) {
+ undo = std::make_unique<PasteRasterAreasUndo>(
+ sl, frames, tileSet.release(), rasterImageData, plt.getPointer(),
+ isFrameToInsert);
+ }
+ if (!indices.empty()) {
+ undo = std::make_unique<PasteVectorAreasUndo>(
+ sl, frames, indices, rasterImageData->toStrokesData(sl->getScene()),
+ plt.getPointer(), isFrameToInsert);
+ }
+ } else if (auto *strokesData = dynamic_cast<StrokesData *>(data.get())) {
+ if (tileSet) {
TImageP img = sl->getFrame(*frames.begin(), false);
TRasterImageP ri = img;
TToonzImageP ti = img;
- assert(img);
- if (ti)
- undo = new PasteRasterAreasUndo(sl, frames, tileSet,
- strokesData->toToonzImageData(ti),
- plt.getPointer(), isFrameToInsert);
- else if (ri) {
+ if (ti) {
+ undo = std::make_unique<PasteRasterAreasUndo>(
+ sl, frames, tileSet.release(), strokesData->toToonzImageData(ti),
+ plt.getPointer(), isFrameToInsert);
+ } else if (ri) {
double dpix, dpiy;
ri->getDpi(dpix, dpiy);
if (dpix == 0 || dpiy == 0) {
@@ -1686,20 +1478,19 @@ void FilmstripCmd::paste(TXshSimpleLevel *sl, std::set<TFrameId> &frames) {
dpiy = dpi.y;
ri->setDpi(dpix, dpiy);
}
- undo = new PasteRasterAreasUndo(sl, frames, tileSet,
- strokesData->toFullColorImageData(ri),
- plt.getPointer(), isFrameToInsert);
+ undo = std::make_unique<PasteRasterAreasUndo>(
+ sl, frames, tileSet.release(),
+ strokesData->toFullColorImageData(ri), plt.getPointer(),
+ isFrameToInsert);
}
+ } else if (!indices.empty()) {
+ undo = std::make_unique<PasteVectorAreasUndo>(
+ sl, frames, indices, strokesData, plt.getPointer(), isFrameToInsert);
}
- if (strokesData && !indices.empty())
- undo = new PasteVectorAreasUndo(sl, frames, indices, strokesData,
- plt.getPointer(), isFrameToInsert);
- if (rasterImageData && !indices.empty())
- undo = new PasteVectorAreasUndo(
- sl, frames, indices, rasterImageData->toStrokesData(sl->getScene()),
- plt.getPointer(), isFrameToInsert);
- if (!isPaste) return;
- if (undo) TUndoManager::manager()->add(undo);
+ }
+
+ if (undo) {
+ TUndoManager::manager()->add(undo.release());
}
}
@@ -1716,20 +1507,24 @@ void FilmstripCmd::merge(TXshSimpleLevel *sl, std::set<TFrameId> &frames) {
std::set<TFrameId> frameIdToChange;
QClipboard *clipboard = QApplication::clipboard();
- if (const DrawingData *drawingData =
+ if (const auto *drawingData =
dynamic_cast<const DrawingData *>(clipboard->mimeData())) {
drawingData->getFrames(frameIdToChange);
- DrawingData *data = new DrawingData();
+ auto *data = new DrawingData();
data->setLevelFrames(sl, frameIdToChange);
- HookSet *oldLevelHooks = new HookSet();
- *oldLevelHooks = *sl->getHookSet();
+ auto *oldLevelHooks = new HookSet();
+ *oldLevelHooks = *sl->getHookSet();
bool keepOriginalPalette = true;
bool isPaste = pasteFramesWithoutUndo(drawingData, sl, frames,
DrawingData::OVER_FRAMEID, true,
keepOriginalPalette);
- if (!isPaste) return;
+ if (!isPaste) {
+ delete data;
+ delete oldLevelHooks;
+ return;
+ }
TUndoManager::manager()->add(new PasteFramesUndo(
sl, frames, oldLevelFrameId, oldPalette, DrawingData::OVER_FRAMEID,
oldLevelHooks, keepOriginalPalette, data));
@@ -1750,19 +1545,23 @@ void FilmstripCmd::pasteInto(TXshSimpleLevel *sl, std::set<TFrameId> &frames) {
if (TPalette *pal = sl->getPalette()) oldPalette = pal->clone();
QClipboard *clipboard = QApplication::clipboard();
- if (const DrawingData *drawingData =
+ if (const auto *drawingData =
dynamic_cast<const DrawingData *>(clipboard->mimeData())) {
- DrawingData *data = new DrawingData();
+ auto *data = new DrawingData();
data->setLevelFrames(sl, frames);
- HookSet *oldLevelHooks = new HookSet();
- *oldLevelHooks = *sl->getHookSet();
+ auto *oldLevelHooks = new HookSet();
+ *oldLevelHooks = *sl->getHookSet();
bool keepOriginalPalette = true;
bool isPaste = pasteFramesWithoutUndo(drawingData, sl, frames,
DrawingData::OVER_SELECTION, true,
keepOriginalPalette);
- if (!isPaste) return;
+ if (!isPaste) {
+ delete data;
+ delete oldLevelHooks;
+ return;
+ }
TUndoManager::manager()->add(new PasteFramesUndo(
sl, frames, oldLevelFrameId, oldPalette, DrawingData::OVER_SELECTION,
@@ -1794,11 +1593,7 @@ void FilmstripCmd::clear(TXshSimpleLevel *sl, std::set<TFrameId> &frames) {
if (sl->isReadOnly()) {
std::set<TFrameId> editableFrames = sl->getEditableRange();
if (editableFrames.empty()) return;
-
- // Browser all the frames and return if some frames are not editable
- std::set<TFrameId>::const_iterator it;
- for (it = frames.begin(); it != frames.end(); ++it) {
- TFrameId frameId = *it;
+ for (const TFrameId &frameId : frames) {
if (editableFrames.count(frameId) == 0) return;
}
}
@@ -1807,9 +1602,9 @@ void FilmstripCmd::clear(TXshSimpleLevel *sl, std::set<TFrameId> &frames) {
std::set<TFrameId> oldFrames = frames;
std::map<TFrameId, QString> clearedFrames =
clearFramesWithoutUndo(sl, frames);
- DrawingData *oldData = new DrawingData();
+ auto *oldData = new DrawingData();
oldData->setFrames(clearedFrames, sl, *levelHooks);
- DrawingData *newData = new DrawingData();
+ auto *newData = new DrawingData();
newData->setLevelFrames(sl, frames);
frames.clear();
TUndoManager::manager()->add(
@@ -1817,24 +1612,22 @@ void FilmstripCmd::clear(TXshSimpleLevel *sl, std::set<TFrameId> &frames) {
}
//=============================================================================
-// clear
+// remove
//-----------------------------------------------------------------------------
void FilmstripCmd::remove(TXshSimpleLevel *sl, std::set<TFrameId> &frames) {
if (!sl || frames.empty() || sl->isSubsequence() || sl->isReadOnly()) return;
std::map<TFrameId, QString> imageSet;
- std::set<TFrameId>::const_iterator it;
int i = 0;
- for (it = frames.begin(); it != frames.end(); ++it, i++) {
- TFrameId frameId = *it;
- QString id = "removeFrames" + QString::number((uintptr_t)sl) + "-" +
- QString::number(it->getNumber());
+ for (const TFrameId &frameId : frames) {
+ QString id = "removeFrames" + QString::number((uintptr_t)sl) + "-" +
+ QString::number(frameId.getNumber());
TImageCache::instance()->add(id, sl->getFrame(frameId, false));
imageSet[frameId] = id;
}
- HookSet *levelHooks = sl->getHookSet();
- DrawingData *oldData = new DrawingData();
+ HookSet *levelHooks = sl->getHookSet();
+ auto *oldData = new DrawingData();
oldData->setFrames(imageSet, sl, *levelHooks);
removeFramesWithoutUndo(sl, frames);
@@ -1843,18 +1636,14 @@ void FilmstripCmd::remove(TXshSimpleLevel *sl, std::set<TFrameId> &frames) {
//-----------------------------------------------------------------------------
namespace {
-//-----------------------------------------------------------------------------
void insertEmptyFilmstripFrames(const TXshSimpleLevelP &sl,
const std::set<TFrameId> &frames) {
if (!sl || frames.empty()) return;
makeSpaceForFids(sl.getPointer(), frames);
- std::set<TFrameId>::const_iterator it;
- for (it = frames.begin(); it != frames.end(); ++it)
- sl->setFrame(*it, sl->createEmptyFrame());
+ for (const TFrameId &fid : frames) sl->setFrame(fid, sl->createEmptyFrame());
invalidateIcons(sl.getPointer(), frames);
sl->setDirtyFlag(true);
- // TApp::instance()->getCurrentScene()->setDirtyFlag(true);
TApp::instance()->getCurrentLevel()->notifyLevelChange();
}
@@ -1870,13 +1659,12 @@ public:
UndoInsertEmptyFrames(const TXshSimpleLevelP &level,
std::set<TFrameId> frames,
std::vector<TFrameId> oldFrames)
- : m_level(level), m_frames(frames), m_oldFrames(oldFrames) {
+ : m_level(level)
+ , m_frames(std::move(frames))
+ , m_oldFrames(std::move(oldFrames)) {
if (m_level->getType() == TZP_XSHLEVEL) {
- std::set<TFrameId>::iterator it;
- for (it = m_frames.begin(); it != m_frames.end(); it++) {
- TToonzImageP img = m_level->getFrame(*it, true);
- // TImageCache::instance()->add("UndoInsertEmptyFrames"+QString::number((UINT)this),
- // img);
+ for (const TFrameId &fid : m_frames) {
+ TToonzImageP img = m_level->getFrame(fid, true);
TImageCache::instance()->add(
"UndoInsertEmptyFrames" + QString::number((uintptr_t)this), img);
}
@@ -1886,7 +1674,6 @@ public:
}
~UndoInsertEmptyFrames() {
- // TImageCache::instance()->remove("UndoInsertEmptyFrames"+QString::number((UINT)this));
TImageCache::instance()->remove("UndoInsertEmptyFrames" +
QString::number((uintptr_t)this));
}
@@ -1906,19 +1693,14 @@ public:
void redo() const override {
if (!m_level || m_frames.empty()) return;
- if (m_level->getType() == PLI_XSHLEVEL)
+ if (m_level->getType() == PLI_XSHLEVEL) {
FilmstripCmd::insert(m_level.getPointer(), m_frames, false);
- else if (m_level->getType() == TZP_XSHLEVEL) {
+ } else if (m_level->getType() == TZP_XSHLEVEL) {
makeSpaceForFids(m_level.getPointer(), m_frames);
- std::set<TFrameId>::const_iterator it;
- // TToonzImageP image =
- // (TToonzImageP)TImageCache::instance()->get("UndoInsertEmptyFrames"+QString::number((UINT)this),
- // true);
TToonzImageP image = (TToonzImageP)TImageCache::instance()->get(
"UndoInsertEmptyFrames" + QString::number((uintptr_t)this), true);
if (!image) return;
- for (it = m_frames.begin(); it != m_frames.end(); ++it)
- m_level->setFrame(*it, image);
+ for (const TFrameId &fid : m_frames) m_level->setFrame(fid, image);
invalidateIcons(m_level.getPointer(), m_frames);
m_level->setDirtyFlag(true);
TApp::instance()->getCurrentLevel()->notifyLevelChange();
@@ -1932,6 +1714,9 @@ public:
.arg(QString::fromStdWString(m_level->getName()));
}
int getHistoryType() override { return HistoryType::FilmStrip; }
+
+private:
+ Q_DISABLE_COPY_MOVE(UndoInsertEmptyFrames);
};
} // namespace
@@ -1949,7 +1734,7 @@ void FilmstripCmd::insert(TXshSimpleLevel *sl, const std::set<TFrameId> &frames,
insertEmptyFilmstripFrames(sl, frames);
if (withUndo)
TUndoManager::manager()->add(
- new UndoInsertEmptyFrames(sl, frames, oldFrames));
+ new UndoInsertEmptyFrames(sl, frames, std::move(oldFrames)));
TApp::instance()->getCurrentScene()->setDirtyFlag(true);
}
@@ -1957,31 +1742,28 @@ void FilmstripCmd::insert(TXshSimpleLevel *sl, const std::set<TFrameId> &frames,
//-----------------------------------------------------------------------------
namespace {
-//-----------------------------------------------------------------------------
void performReverse(const TXshSimpleLevelP &sl,
const std::set<TFrameId> &frames) {
if (!sl || frames.empty()) return;
- std::vector<TFrameId> fids;
- std::vector<TFrameId> oldFrames;
+ std::vector<TFrameId> fids, oldFrames;
sl->getFids(oldFrames);
- sl->getFids(fids);
- int i = 0, j = (int)fids.size() - 1;
+ fids = oldFrames;
+ int i = 0, j = int(fids.size()) - 1;
for (;;) {
- while (i < j && frames.count(fids[i]) == 0) i++;
- while (i < j && frames.count(fids[j]) == 0) j--;
+ while (i < j && frames.count(fids[i]) == 0) ++i;
+ while (i < j && frames.count(fids[j]) == 0) --j;
if (i >= j) break;
std::swap(fids[i], fids[j]);
- i++;
- j--;
+ ++i;
+ --j;
}
if (Preferences::instance()->isSyncLevelRenumberWithXsheetEnabled()) {
updateXSheet(sl.getPointer(), oldFrames, fids);
}
sl->renumber(fids);
sl->setDirtyFlag(true);
- // TApp::instance()->getCurrentScene()->setDirtyFlag(true);
TApp::instance()->getCurrentLevel()->notifyLevelChange();
}
@@ -1993,17 +1775,20 @@ class FilmstripReverseUndo final : public TUndo {
public:
FilmstripReverseUndo(TXshSimpleLevelP level, std::set<TFrameId> frames)
- : m_level(level), m_frames(frames) {}
+ : m_level(std::move(level)), m_frames(std::move(frames)) {}
void undo() const override { performReverse(m_level, m_frames); }
void redo() const override { performReverse(m_level, m_frames); }
- int getSize() const override { return sizeof *this; }
+ int getSize() const override { return sizeof(*this); }
QString getHistoryString() override {
return QObject::tr("Reverse : Level %1")
.arg(QString::fromStdWString(m_level->getName()));
}
int getHistoryType() override { return HistoryType::FilmStrip; }
+
+private:
+ Q_DISABLE_COPY_MOVE(FilmstripReverseUndo);
};
} // namespace
@@ -2023,36 +1808,31 @@ void FilmstripCmd::reverse(TXshSimpleLevel *sl, std::set<TFrameId> &frames) {
//-----------------------------------------------------------------------------
namespace {
-//-----------------------------------------------------------------------------
void performSwing(const TXshSimpleLevelP &sl,
const std::set<TFrameId> &frames) {
if (!sl) return;
- int count = frames.size() - 1;
- if (count <= 0) return; // niente swing con un solo frame
+ int count = int(frames.size()) - 1;
+ if (count <= 0) return;
TFrameId lastFid = *frames.rbegin();
TFrameId insertPoint = lastFid + 1;
std::set<TFrameId> framesToInsert;
- int i;
- for (i = 0; i < count; i++) framesToInsert.insert(insertPoint + i);
+ for (int i = 0; i < count; ++i) framesToInsert.insert(insertPoint + i);
- std::vector<TImage *> clonedImages;
- std::set<TFrameId>::const_reverse_iterator k;
- k = frames.rbegin();
- for (++k; k != frames.rend(); ++k) {
+ std::vector<TImageP> clonedImages;
+ for (auto k = frames.rbegin(); k != frames.rend(); ++k) {
TImageP img = sl->getFrame(*k, false);
- clonedImages.push_back(img ? img->cloneImage() : 0);
+ clonedImages.push_back(img ? img->cloneImage() : nullptr);
}
makeSpaceForFids(sl.getPointer(), framesToInsert);
assert(count == (int)clonedImages.size());
- for (i = 0; i < count && (int)i < (int)clonedImages.size(); i++) {
- TImage *img = clonedImages[i];
+ for (int i = 0; i < count; ++i) {
+ TImage *img = clonedImages[i].getPointer();
if (img) sl->setFrame(insertPoint + i, img);
}
invalidateIcons(sl.getPointer(), framesToInsert);
sl->setDirtyFlag(true);
- // TApp::instance()->getCurrentScene()->setDirtyFlag(true);
TApp::instance()->getCurrentLevel()->notifyLevelChange();
}
@@ -2067,13 +1847,11 @@ public:
FilmstripSwingUndo(const TXshSimpleLevelP &level,
const std::set<TFrameId> &frames)
: m_level(level), m_frames(frames) {
- int count = frames.size() - 1;
- if (count <= 0) return; // niente swing con un solo frame
+ int count = int(frames.size()) - 1;
+ if (count <= 0) return;
TFrameId lastFid = *frames.rbegin();
TFrameId insertPoint = lastFid + 1;
- std::set<TFrameId> framesToInsert;
- int i;
- for (i = 0; i < count; i++) m_newFrames.insert(insertPoint + i);
+ for (int i = 0; i < count; ++i) m_newFrames.insert(insertPoint + i);
}
void undo() const override {
@@ -2086,13 +1864,16 @@ public:
if (selection) selection->selectNone();
performSwing(m_level, m_frames);
}
- int getSize() const override { return sizeof *this; }
+ int getSize() const override { return sizeof(*this); }
QString getHistoryString() override {
return QObject::tr("Swing : Level %1")
.arg(QString::fromStdWString(m_level->getName()));
}
int getHistoryType() override { return HistoryType::FilmStrip; }
+
+private:
+ Q_DISABLE_COPY_MOVE(FilmstripSwingUndo);
};
} // namespace
@@ -2112,19 +1893,17 @@ void FilmstripCmd::swing(TXshSimpleLevel *sl, std::set<TFrameId> &frames) {
//-----------------------------------------------------------------------------
namespace {
-//-----------------------------------------------------------------------------
void stepFilmstripFrames(const TXshSimpleLevelP &sl,
const std::set<TFrameId> &frames, int step = 2) {
if (!sl || frames.empty() || step < 2) return;
- std::vector<TFrameId> fids;
+ std::vector<TFrameId> fids, oldFrames;
+ sl->getFids(oldFrames);
+ fids = oldFrames;
std::set<TFrameId> changedFids;
std::vector<int> insertIndices;
- std::vector<TFrameId> oldFrames;
- sl->getFids(oldFrames);
- sl->getFids(fids);
- int i, offset = 0;
- for (i = 0; i < (int)fids.size(); i++) {
+ int offset = 0;
+ for (size_t i = 0; i < fids.size(); ++i) {
bool frameToStep = (frames.count(fids[i]) > 0);
if (offset > 0) {
changedFids.insert(fids[i]);
@@ -2132,7 +1911,7 @@ void stepFilmstripFrames(const TXshSimpleLevelP &sl,
changedFids.insert(fids[i]);
}
if (frameToStep) {
- insertIndices.push_back(i);
+ insertIndices.push_back(int(i));
offset += step - 1;
}
}
@@ -2140,13 +1919,11 @@ void stepFilmstripFrames(const TXshSimpleLevelP &sl,
updateXSheet(sl.getPointer(), oldFrames, fids);
}
sl->renumber(fids);
- for (i = 0; i < (int)insertIndices.size(); i++) {
- int j = insertIndices[i];
- TFrameId fid = fids[j];
+ for (int idx : insertIndices) {
+ TFrameId fid = fids[idx];
TImageP img = sl->getFrame(fid, false);
if (img) {
- int h;
- for (h = 1; h < step; h++) {
+ for (int h = 1; h < step; ++h) {
sl->setFrame(fid + h, img->cloneImage());
changedFids.insert(fid + h);
}
@@ -2174,16 +1951,15 @@ public:
assert(m_level);
m_level->getFids(m_oldFrames);
int d = 0;
- std::set<TFrameId>::const_iterator it;
- for (it = frames.begin(); it != frames.end(); ++it)
- for (int j = 1; j < step; j++) m_insertedFrames.insert(*it + (++d));
+ for (const TFrameId &fid : frames) {
+ for (int j = 1; j < step; ++j) m_insertedFrames.insert(fid + (++d));
+ }
m_updateXSheet =
Preferences::instance()->isSyncLevelRenumberWithXsheetEnabled();
}
void undo() const override {
removeFramesWithoutUndo(m_level, m_insertedFrames);
- std::set<TFrameId>::const_iterator it = m_frames.begin();
if (m_updateXSheet) {
std::vector<TFrameId> newFrames;
m_level->getFids(newFrames);
@@ -2200,7 +1976,7 @@ public:
if (selection) selection->selectNone();
stepFilmstripFrames(m_level, m_frames, m_step);
}
- int getSize() const override { return sizeof *this; }
+ int getSize() const override { return sizeof(*this); }
QString getHistoryString() override {
return QObject::tr("Step %1 : Level %2")
@@ -2208,6 +1984,9 @@ public:
.arg(QString::fromStdWString(m_level->getName()));
}
int getHistoryType() override { return HistoryType::FilmStrip; }
+
+private:
+ Q_DISABLE_COPY_MOVE(StepFilmstripUndo);
};
} // namespace
@@ -2220,7 +1999,7 @@ void FilmstripCmd::step(TXshSimpleLevel *sl, std::set<TFrameId> &frames,
int step) {
if (!sl || sl->isSubsequence() || sl->isReadOnly()) return;
QApplication::setOverrideCursor(Qt::WaitCursor);
- StepFilmstripUndo *undo = new StepFilmstripUndo(sl, frames, step);
+ auto *undo = new StepFilmstripUndo(sl, frames, step);
stepFilmstripFrames(sl, frames, step);
TUndoManager::manager()->add(undo);
frames.clear();
@@ -2232,35 +2011,29 @@ void FilmstripCmd::step(TXshSimpleLevel *sl, std::set<TFrameId> &frames,
//-----------------------------------------------------------------------------
namespace {
-//-----------------------------------------------------------------------------
std::map<TFrameId, QString> eachFilmstripFrames(
const TXshSimpleLevelP &sl, const std::set<TFrameId> &frames, int each) {
- if (frames.empty() || !sl || each < 2) return std::map<TFrameId, QString>();
+ if (frames.empty() || !sl || each < 2) return {};
std::vector<TFrameId> framesToDelete;
- std::set<TFrameId>::const_iterator it;
int k = 0;
- for (it = frames.begin(); it != frames.end(); ++it, ++k)
- if ((k % each) > 0) framesToDelete.push_back(*it);
- int i = 0;
- std::vector<TFrameId>::reverse_iterator fit;
+ for (const TFrameId &fid : frames) {
+ if ((k % each) > 0) framesToDelete.push_back(fid);
+ ++k;
+ }
std::map<TFrameId, QString> cutFrames;
-
- for (fit = framesToDelete.rbegin(); fit != framesToDelete.rend(); ++fit) {
+ for (auto fit = framesToDelete.rbegin(); fit != framesToDelete.rend();
+ ++fit) {
TImageP img = sl->getFrame(*fit, false);
if (img) {
- // QString id =
- // "eachFrames"+QString::number((UINT)sl.getPointer())+"-"+QString::number(fit->getNumber());
QString id = "eachFrames" + QString::number((uintptr_t)sl.getPointer()) +
"-" + QString::number(fit->getNumber());
TImageCache::instance()->add(id, img);
-
cutFrames[*fit] = id;
}
- sl->eraseFrame(*fit); // toglie da cache?
+ sl->eraseFrame(*fit);
IconGenerator::instance()->remove(sl.getPointer(), *fit);
}
-
TApp::instance()->getCurrentLevel()->notifyLevelChange();
return cutFrames;
}
@@ -2278,13 +2051,11 @@ public:
const std::set<TFrameId> &frames,
std::map<TFrameId, QString> deletedFrames)
: m_level(level)
- , m_cutFrames(deletedFrames)
+ , m_cutFrames(std::move(deletedFrames))
, m_each(each)
, m_frames(frames) {}
~EachFilmstripUndo() {
- std::map<TFrameId, QString>::iterator it = m_cutFrames.begin();
- for (; it != m_cutFrames.end(); ++it)
- TImageCache::instance()->remove(it->second);
+ for (const auto &[_, id] : m_cutFrames) TImageCache::instance()->remove(id);
}
void undo() const override {
TSelection *selection = TSelection::getCurrent();
@@ -2296,7 +2067,7 @@ public:
if (selection) selection->selectNone();
eachFilmstripFrames(m_level, m_frames, m_each);
}
- int getSize() const override { return sizeof *this; }
+ int getSize() const override { return sizeof(*this); }
QString getHistoryString() override {
return QObject::tr("Each %1 : Level %2")
@@ -2304,6 +2075,9 @@ public:
.arg(QString::fromStdWString(m_level->getName()));
}
int getHistoryType() override { return HistoryType::FilmStrip; }
+
+private:
+ Q_DISABLE_COPY_MOVE(EachFilmstripUndo);
};
} // namespace
@@ -2318,7 +2092,7 @@ void FilmstripCmd::each(TXshSimpleLevel *sl, std::set<TFrameId> &frames,
std::map<TFrameId, QString> deletedFrames =
eachFilmstripFrames(sl, frames, each);
TUndoManager::manager()->add(
- new EachFilmstripUndo(sl, each, frames, deletedFrames));
+ new EachFilmstripUndo(sl, each, frames, std::move(deletedFrames)));
frames.clear();
TApp::instance()->getCurrentScene()->setDirtyFlag(true);
}
@@ -2327,7 +2101,6 @@ void FilmstripCmd::each(TXshSimpleLevel *sl, std::set<TFrameId> &frames,
//-----------------------------------------------------------------------------
namespace {
-//-----------------------------------------------------------------------------
class UndoDuplicateDrawing final : public TUndo {
TXshSimpleLevelP m_level;
@@ -2338,13 +2111,13 @@ class UndoDuplicateDrawing final : public TUndo {
public:
UndoDuplicateDrawing(const TXshSimpleLevelP &level,
- const std::vector<TFrameId> oldFrames,
+ const std::vector<TFrameId> &oldFrames,
std::set<TFrameId> frameInserted,
std::set<TFrameId> framesForRedo)
: m_level(level)
, m_oldFrames(oldFrames)
- , m_frameInserted(frameInserted)
- , m_framesForRedo(framesForRedo) {
+ , m_frameInserted(std::move(frameInserted))
+ , m_framesForRedo(std::move(framesForRedo)) {
m_updateXSheet =
Preferences::instance()->isSyncLevelRenumberWithXsheetEnabled();
}
@@ -2372,6 +2145,9 @@ public:
.arg(QString::fromStdWString(m_level->getName()));
}
int getHistoryType() override { return HistoryType::FilmStrip; }
+
+private:
+ Q_DISABLE_COPY_MOVE(UndoDuplicateDrawing);
};
} // namespace
@@ -2387,20 +2163,21 @@ void FilmstripCmd::duplicateFrameWithoutUndo(TXshSimpleLevel *sl,
if (srcFrame.isEmptyFrame()) return;
std::set<TFrameId> frames;
-
frames.insert(srcFrame);
- DrawingData *data = new DrawingData();
+ auto *data = new DrawingData();
data->setLevelFrames(sl, frames);
frames.clear();
frames.insert(targetFrame);
bool keepOriginalPalette = true;
-
pasteFramesWithoutUndo(data, sl, frames, DrawingData::OVER_SELECTION, true,
keepOriginalPalette);
+ delete data;
}
+//-----------------------------------------------------------------------------
+
void FilmstripCmd::duplicate(TXshSimpleLevel *sl, std::set<TFrameId> &frames,
bool withUndo) {
if (frames.empty() || !sl || sl->isSubsequence() || sl->isReadOnly()) return;
@@ -2410,15 +2187,15 @@ void FilmstripCmd::duplicate(TXshSimpleLevel *sl, std::set<TFrameId> &frames,
std::map<TFrameId, QString> framesToInsert;
std::set<TFrameId> newFrames;
int i = 0;
- for (auto const &fid : frames) {
+ for (const TFrameId &fid : frames) {
TImageP img = sl->getFrame(fid, false);
- TImageP imgClone = (img) ? img->cloneImage() : 0;
+ TImageP imgClone = (img) ? img->cloneImage() : nullptr;
QString id = "dupFrames" + QString::number((uintptr_t)sl) + "-" +
QString::number(fid.getNumber());
TImageCache::instance()->add(id, imgClone);
framesToInsert[insertPoint + i] = id;
newFrames.insert(insertPoint + i);
- i++;
+ ++i;
}
std::vector<TFrameId> oldFrames;
sl->getFids(oldFrames);
@@ -2433,7 +2210,6 @@ void FilmstripCmd::duplicate(TXshSimpleLevel *sl, std::set<TFrameId> &frames,
//-----------------------------------------------------------------------------
namespace {
-//-----------------------------------------------------------------------------
void moveToSceneFrames(TXshLevel *level, const std::set<TFrameId> &frames) {
if (frames.empty() || !level) return;
@@ -2442,13 +2218,12 @@ void moveToSceneFrames(TXshLevel *level, const std::set<TFrameId> &frames) {
TXsheet *xsh = xh->getXsheet();
int row = 0;
int col = xsh->getFirstFreeColumnIndex();
- std::set<TFrameId>::const_iterator it;
if (level->getPaletteLevel()) {
- TXshPaletteColumn *column = new TXshPaletteColumn;
+ auto *column = new TXshPaletteColumn;
xsh->insertColumn(col, column);
}
- for (it = frames.begin(); it != frames.end(); ++it) {
- xsh->setCell(row, col, TXshCell(level, *it));
+ for (const TFrameId &fid : frames) {
+ xsh->setCell(row, col, TXshCell(level, fid));
++row;
}
xh->notifyXsheetChanged();
@@ -2463,7 +2238,9 @@ class MoveLevelToSceneUndo final : public TUndo {
public:
MoveLevelToSceneUndo(std::wstring levelName, int col, std::set<TFrameId> fids)
- : m_levelName(levelName), m_col(col), m_fids(fids) {}
+ : m_levelName(std::move(levelName))
+ , m_col(col)
+ , m_fids(std::move(fids)) {}
void undo() const override {
TApp *app = TApp::instance();
@@ -2471,7 +2248,7 @@ public:
ToonzScene *scene = app->getCurrentScene()->getScene();
TXshLevel *xl = scene->getLevelSet()->getLevel(m_levelName);
if (xl->getPaletteLevel()) xsh->removeColumn(m_col);
- xsh->clearCells(0, m_col, m_fids.size());
+ xsh->clearCells(0, m_col, int(m_fids.size()));
app->getCurrentXsheet()->notifyXsheetChanged();
}
void redo() const override {
@@ -2481,13 +2258,16 @@ public:
if (!xl) return;
moveToSceneFrames(xl, m_fids);
}
- int getSize() const override { return sizeof *this; }
+ int getSize() const override { return sizeof(*this); }
QString getHistoryString() override {
return QObject::tr("Move Level to Scene : Level %1")
.arg(QString::fromStdWString(m_levelName));
}
int getHistoryType() override { return HistoryType::FilmStrip; }
+
+private:
+ Q_DISABLE_COPY_MOVE(MoveLevelToSceneUndo);
};
} // namespace
@@ -2503,9 +2283,8 @@ void FilmstripCmd::moveToScene(TXshLevel *sl, std::set<TFrameId> &frames) {
TXsheet *xsh = xh->getXsheet();
int row = 0;
int col = xsh->getFirstFreeColumnIndex();
- std::set<TFrameId>::const_iterator it;
- for (it = frames.begin(); it != frames.end(); ++it) {
- xsh->setCell(row, col, TXshCell(sl, *it));
+ for (const TFrameId &fid : frames) {
+ xsh->setCell(row, col, TXshCell(sl, fid));
++row;
}
xh->notifyXsheetChanged();
@@ -2530,20 +2309,19 @@ void FilmstripCmd::moveToScene(TXshPaletteLevel *pl) {
std::set<TFrameId> fidsSet;
fidsSet.insert(TFrameId(1));
- TXsheetHandle *xh = TApp::instance()->getCurrentXsheet();
- TXsheet *xsh = xh->getXsheet();
- int row = 0;
- int col = xsh->getFirstFreeColumnIndex();
- TXshPaletteColumn *column = new TXshPaletteColumn;
+ TXsheetHandle *xh = TApp::instance()->getCurrentXsheet();
+ TXsheet *xsh = xh->getXsheet();
+ int row = 0;
+ int col = xsh->getFirstFreeColumnIndex();
+ auto *column = new TXshPaletteColumn;
xsh->insertColumn(col, column);
- std::set<TFrameId>::const_iterator it;
- for (it = fidsSet.begin(); it != fidsSet.end(); ++it) {
- xsh->setCell(row, col, TXshCell(pl, *it));
+ for (const TFrameId &fid : fidsSet) {
+ xsh->setCell(row, col, TXshCell(pl, fid));
++row;
}
xh->notifyXsheetChanged();
TUndoManager::manager()->add(
- new MoveLevelToSceneUndo(pl->getName(), col, fidsSet));
+ new MoveLevelToSceneUndo(pl->getName(), col, std::move(fidsSet)));
TApp::instance()->getCurrentScene()->setDirtyFlag(true);
}
@@ -2571,37 +2349,33 @@ class UndoInbetween final : public TUndo {
public:
UndoInbetween(TXshSimpleLevel *xl, std::vector<TFrameId> fids,
FilmstripCmd::InbetweenInterpolation interpolation)
- : m_level(xl), m_fids(fids), m_interpolation(interpolation) {
- std::vector<TFrameId>::iterator it = fids.begin();
- // mi salvo tutte le immagine
- for (; it != fids.end(); ++it)
+ : m_level(xl), m_fids(std::move(fids)), m_interpolation(interpolation) {
+ for (const TFrameId &fid : m_fids) {
m_images.push_back(m_level->getFrame(
- *it, false)); // non si fa clone perche' il livello subito dopo
- // rilascia queste immagini a causa dell'inbetweener
+ fid, false)); // no clone, level releases these images
+ }
}
void undo() const override {
- UINT levelSize = m_fids.size() - 1;
- for (UINT count = 1; count != levelSize; count++) {
+ for (size_t count = 1; count < m_fids.size(); ++count) {
TVectorImageP vImage = m_images[count];
m_level->setFrame(m_fids[count], vImage);
IconGenerator::instance()->invalidate(m_level.getPointer(),
m_fids[count]);
}
-
TApp::instance()->getCurrentLevel()->notifyLevelChange();
}
void redo() const override {
- TFrameId fid0 = *m_fids.begin();
- TFrameId fid1 = *(--m_fids.end());
+ TFrameId fid0 = m_fids.front();
+ TFrameId fid1 = m_fids.back();
FilmstripCmd::inbetweenWithoutUndo(m_level.getPointer(), fid0, fid1,
m_interpolation);
}
int getSize() const override {
assert(!m_images.empty());
- return m_images.size() * m_images.front()->getStrokeCount() * 100;
+ return int(m_images.size() * m_images.front()->getStrokeCount() * 100);
}
QString getHistoryString() override {
@@ -2624,6 +2398,9 @@ public:
return str;
}
int getHistoryType() override { return HistoryType::FilmStrip; }
+
+private:
+ Q_DISABLE_COPY_MOVE(UndoInbetween);
};
} // namespace
@@ -2638,20 +2415,19 @@ void FilmstripCmd::inbetweenWithoutUndo(
if (!sl) return;
std::vector<TFrameId> fids;
sl->getFids(fids);
- std::vector<TFrameId>::iterator it;
- it = std::find(fids.begin(), fids.end(), fid0);
- if (it == fids.end()) return;
- int ia = std::distance(fids.begin(), it);
- it = std::find(fids.begin(), fids.end(), fid1);
- if (it == fids.end()) return;
- int ib = std::distance(fids.begin(), it);
+ auto it0 = std::find(fids.begin(), fids.end(), fid0);
+ if (it0 == fids.end()) return;
+ int ia = int(std::distance(fids.begin(), it0));
+ auto it1 = std::find(fids.begin(), fids.end(), fid1);
+ if (it1 == fids.end()) return;
+ int ib = int(std::distance(fids.begin(), it1));
if (ib - ia < 2) return;
TVectorImageP img0 = sl->getFrame(fid0, false);
TVectorImageP img1 = sl->getFrame(fid1, false);
if (!img0 || !img1) return;
- enum TInbetween::TweenAlgorithm algorithm;
+ TInbetween::TweenAlgorithm algorithm;
switch (interpolation) {
case II_Linear:
algorithm = TInbetween::LinearInterpolation;
@@ -2668,11 +2444,9 @@ void FilmstripCmd::inbetweenWithoutUndo(
}
TInbetween inbetween(img0, img1);
- int i;
- for (i = ia + 1; i < ib; i++) {
- double t = (double)(i - ia) / (double)(ib - ia);
- double s = TInbetween::interpolation(t, algorithm);
-
+ for (int i = ia + 1; i < ib; ++i) {
+ double t = double(i - ia) / double(ib - ia);
+ double s = TInbetween::interpolation(t, algorithm);
TVectorImageP vi = inbetween.tween(s);
sl->setFrame(fids[i], vi);
IconGenerator::instance()->invalidate(sl, fids[i]);
@@ -2689,7 +2463,7 @@ void FilmstripCmd::inbetween(
std::vector<TFrameId> fids;
std::vector<TFrameId> levelFids;
sl->getFids(levelFids);
- for (auto const &fid : levelFids) {
+ for (const TFrameId &fid : levelFids) {
int curFid = fid.getNumber();
if (fid0.getNumber() <= curFid && curFid <= fid1.getNumber())
fids.push_back(fid);
@@ -2706,12 +2480,10 @@ void FilmstripCmd::inbetween(
void FilmstripCmd::renumberDrawing(TXshSimpleLevel *sl, const TFrameId &oldFid,
const TFrameId &desiredNewFid) {
if (oldFid == desiredNewFid) return;
- std::vector<TFrameId> fids;
- std::vector<TFrameId> oldFrames;
+ std::vector<TFrameId> fids, oldFrames;
sl->getFids(oldFrames);
- sl->getFids(fids);
- std::vector<TFrameId>::iterator it =
- std::find(fids.begin(), fids.end(), oldFid);
+ fids = oldFrames;
+ auto it = std::find(fids.begin(), fids.end(), oldFid);
if (it == fids.end()) return;
TFrameId newFid = desiredNewFid;
while (std::find(fids.begin(), fids.end(), newFid) != fids.end()) {
diff --git a/toonz/sources/toonz/filmstripcommand.h b/toonz/sources/toonz/filmstripcommand.h
index a30b61269..35db15e2f 100644
--- a/toonz/sources/toonz/filmstripcommand.h
+++ b/toonz/sources/toonz/filmstripcommand.h
@@ -7,7 +7,9 @@
#include "tfilepath.h"
#include <set>
+#include <vector>
+// Forward declarations
class TXshSimpleLevel;
class TXshLevel;
class TXshPaletteLevel;
@@ -18,14 +20,18 @@ class TXshSoundLevel;
//-----------------------------------------------------------------------------
namespace FilmstripCmd {
+
+// Add empty frames to the level
void addFrames(TXshSimpleLevel *sl, int start, int end, int step);
+// Renumber frames in the level
void renumber(TXshSimpleLevel *sl, std::set<TFrameId> &frames, int startFrame,
int stepFrame);
void renumber(TXshSimpleLevel *sl,
const std::vector<std::pair<TFrameId, TFrameId>> &table,
bool forceCallUpdateXSheet = false);
+// Copy/paste operations for frames
void copy(TXshSimpleLevel *sl, std::set<TFrameId> &frames);
void paste(TXshSimpleLevel *sl, std::set<TFrameId> &frames);
void merge(TXshSimpleLevel *sl, std::set<TFrameId> &frames);
@@ -36,34 +42,42 @@ void remove(TXshSimpleLevel *sl, std::set<TFrameId> &frames);
void insert(TXshSimpleLevel *sl, const std::set<TFrameId> &frames,
bool withUndo);
+// Frame manipulation operations
void reverse(TXshSimpleLevel *sl, std::set<TFrameId> &frames);
void swing(TXshSimpleLevel *sl, std::set<TFrameId> &frames);
void step(TXshSimpleLevel *sl, std::set<TFrameId> &frames, int step);
void each(TXshSimpleLevel *sl, std::set<TFrameId> &frames, int each);
+// Duplicate operations
void duplicateFrameWithoutUndo(TXshSimpleLevel *sl, TFrameId srcFrame,
TFrameId targetFrame);
void duplicate(TXshSimpleLevel *sl, std::set<TFrameId> &frames, bool withUndo);
-// TODO vanno spostati in un altro posto
+// // TODO: Need to be moved to another location - Level to scene operations
void moveToScene(TXshLevel *sl, std::set<TFrameId> &frames);
void moveToScene(TXshSimpleLevel *sl);
void moveToScene(TXshPaletteLevel *pl);
void moveToScene(TXshSoundLevel *sl);
+// Inbetween interpolation types and functions
enum InbetweenInterpolation { II_Linear, II_EaseIn, II_EaseOut, II_EaseInOut };
+
void inbetweenWithoutUndo(TXshSimpleLevel *sl, const TFrameId &fid0,
const TFrameId &fid1,
InbetweenInterpolation interpolation);
void inbetween(TXshSimpleLevel *sl, const TFrameId &fid0, const TFrameId &fid1,
InbetweenInterpolation interpolation);
+// Renumber a single drawing
void renumberDrawing(TXshSimpleLevel *sl, const TFrameId &oldFid,
const TFrameId &desiredNewFid);
+
} // namespace FilmstripCmd
+// Operator overload for TFrameId
TFrameId operator+(const TFrameId &fid, int d);
+// Utility function to make space for frame IDs in a level
void makeSpaceForFids(TXshSimpleLevel *sl,
const std::set<TFrameId> &framesToInsert);
diff --git a/toonz/sources/toonz/menubarpopup.cpp b/toonz/sources/toonz/menubarpopup.cpp
index bc1678785..763366f26 100644
--- a/toonz/sources/toonz/menubarpopup.cpp
+++ b/toonz/sources/toonz/menubarpopup.cpp
@@ -1,3 +1,5 @@
+
+
#include "menubarpopup.h"
// Tnz includes
@@ -33,13 +35,14 @@
#include <QPainter>
#include <QApplication>
#include <QLabel>
+#include <QMenu>
//=============================================================================
// MenuBarSubmenuItem
//-----------------------------------------------------------------------------
class MenuBarSubmenuItem final : public QTreeWidgetItem {
- /*- title before translation -*/
+ /*- Title before translation -*/
QString m_orgTitle;
public:
@@ -89,9 +92,7 @@ MenuBarTree::MenuBarTree(TFilePath& path, QWidget* parent)
loadMenuTree(fp);
- bool ret = connect(this, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this,
- SLOT(onItemChanged(QTreeWidgetItem*, int)));
- assert(ret);
+ connect(this, &QTreeWidget::itemChanged, this, &MenuBarTree::onItemChanged);
}
//-----------------------------------------------------------------------------
@@ -110,16 +111,15 @@ void MenuBarTree::loadMenuTree(const TFilePath& fp) {
while (reader.readNextStartElement()) {
if (reader.name() == "menu") {
QString title = reader.attributes().value("title").toString();
- MenuBarSubmenuItem* menu = new MenuBarSubmenuItem(0, title);
+ auto* menu = new MenuBarSubmenuItem(nullptr, title); // use auto
addTopLevelItem(menu);
loadMenuRecursive(reader, menu);
} else if (reader.name() == "command") {
QString cmdName = reader.readElementText();
-
QAction* action = CommandManager::instance()->getAction(
- cmdName.toStdString().c_str());
+ cmdName.toStdString().c_str()); // keep as is
if (action) {
- CommandItem* item = new CommandItem(0, action);
+ auto* item = new CommandItem(nullptr, action);
addTopLevelItem(item);
}
} else
@@ -141,24 +141,30 @@ void MenuBarTree::loadMenuRecursive(QXmlStreamReader& reader,
while (reader.readNextStartElement()) {
if (reader.name() == "menu") {
QString title = reader.attributes().value("title").toString();
- MenuBarSubmenuItem* subMenu = new MenuBarSubmenuItem(parentItem, title);
+ auto* subMenu = new MenuBarSubmenuItem(parentItem, title);
loadMenuRecursive(reader, subMenu);
} else if (reader.name() == "command") {
QString cmdName = reader.readElementText();
QAction* action =
CommandManager::instance()->getAction(cmdName.toStdString().c_str());
- if (action) CommandItem* item = new CommandItem(parentItem, action);
+ if (action) {
+ // Create the item without storing the pointer - it's automatically
+ // added to parent
+ new CommandItem(parentItem, action);
+ }
} else if (reader.name() == "command_debug") {
#ifndef NDEBUG
QString cmdName = reader.readElementText();
QAction* action =
CommandManager::instance()->getAction(cmdName.toStdString().c_str());
- if (action) CommandItem* item = new CommandItem(parentItem, action);
+ if (action) {
+ new CommandItem(parentItem, action);
+ }
#else
reader.skipCurrentElement();
#endif
} else if (reader.name() == "separator") {
- SeparatorItem* sep = new SeparatorItem(parentItem);
+ new SeparatorItem(parentItem);
reader.skipCurrentElement();
} else
reader.skipCurrentElement();
@@ -189,11 +195,11 @@ void MenuBarTree::saveMenuTree() {
void MenuBarTree::saveMenuRecursive(QXmlStreamWriter& writer,
QTreeWidgetItem* parentItem) {
- for (int c = 0; c < parentItem->childCount(); c++) {
- CommandItem* command = dynamic_cast<CommandItem*>(parentItem->child(c));
- SeparatorItem* sep = dynamic_cast<SeparatorItem*>(parentItem->child(c));
- MenuBarSubmenuItem* subMenu =
- dynamic_cast<MenuBarSubmenuItem*>(parentItem->child(c));
+ for (int c = 0; c < parentItem->childCount(); ++c) {
+ auto* command = dynamic_cast<CommandItem*>(parentItem->child(c));
+ auto* sep = dynamic_cast<SeparatorItem*>(parentItem->child(c));
+ auto* subMenu = dynamic_cast<MenuBarSubmenuItem*>(parentItem->child(c));
+
if (command)
writer.writeTextElement(
"command",
@@ -205,11 +211,10 @@ void MenuBarTree::saveMenuRecursive(QXmlStreamWriter& writer,
writer.writeStartElement("menu");
// save original title instead of translated one
writer.writeAttribute("title", subMenu->getOrgTitle());
-
saveMenuRecursive(writer, subMenu);
-
writer.writeEndElement(); // menu
} else {
+ // ignore unknown item types
}
}
}
@@ -222,12 +227,12 @@ bool MenuBarTree::dropMimeData(QTreeWidgetItem* parent, int index,
QString txt = data->text();
QTreeWidgetItem* item;
if (txt == "separator")
- item = new SeparatorItem(0);
+ item = new SeparatorItem(nullptr);
else {
QAction* act =
CommandManager::instance()->getAction(txt.toStdString().c_str());
if (!act) return false;
- item = new CommandItem(0, act);
+ item = new CommandItem(nullptr, act);
}
if (parent)
@@ -254,30 +259,32 @@ QStringList MenuBarTree::mimeTypes() const {
void MenuBarTree::contextMenuEvent(QContextMenuEvent* event) {
QTreeWidgetItem* item = itemAt(event->pos());
if (item != currentItem()) setCurrentItem(item);
- QMenu* menu = new QMenu(this);
- QAction* action;
+
+ // --- STACK-ALLOCATED QMenu, NO MANUAL DELETE ---
+ QMenu menu(this);
+ QAction* action = nullptr;
+
if (!item || indexOfTopLevelItem(item) >= 0)
- action = menu->addAction(tr("Insert Menu"));
+ action = menu.addAction(tr("Insert Menu"));
else
- action = menu->addAction(tr("Insert Submenu"));
+ action = menu.addAction(tr("Insert Submenu"));
- connect(action, SIGNAL(triggered()), this, SLOT(insertMenu()));
+ connect(action, &QAction::triggered, this, [this] { insertMenu(); });
if (item) {
- action = menu->addAction(tr("Remove \"%1\"").arg(item->text(0)));
- connect(action, SIGNAL(triggered()), this, SLOT(removeItem()));
+ action = menu.addAction(tr("Remove \"%1\"").arg(item->text(0)));
+ connect(action, &QAction::triggered, this, [this] { removeItem(); });
}
- menu->exec(event->globalPos());
- delete menu;
+ menu.exec(event->globalPos());
}
//-----------------------------------------------------------------------------
void MenuBarTree::insertMenu() {
- QTreeWidgetItem* item = currentItem();
- QString title = tr("New Menu");
- MenuBarSubmenuItem* insItem = new MenuBarSubmenuItem(0, title);
+ QTreeWidgetItem* item = currentItem();
+ QString title = tr("New Menu");
+ auto* insItem = new MenuBarSubmenuItem(nullptr, title);
if (!item)
addTopLevelItem(insItem);
else if (indexOfTopLevelItem(item) >= 0)
@@ -303,7 +310,7 @@ void MenuBarTree::removeItem() {
//-----------------------------------------------------------------------------
void MenuBarTree::onItemChanged(QTreeWidgetItem* item, int column) {
- MenuBarSubmenuItem* submenuItem = dynamic_cast<MenuBarSubmenuItem*>(item);
+ auto* submenuItem = dynamic_cast<MenuBarSubmenuItem*>(item);
if (!submenuItem) return;
submenuItem->setOrgTitle(submenuItem->text(0));
}
@@ -317,7 +324,7 @@ MenuBarPopup::MenuBarPopup(Room* room)
"CustomizeMenuBar") {
setWindowTitle(tr("Customize Menu Bar of Room \"%1\"").arg(room->getName()));
- /*- get menubar setting file path -*/
+ /*- Get menubar setting file path -*/
std::string mbFileName = room->getPath().getName() + "_menubar.xml";
TFilePath mbPath = ToonzFolder::getMyRoomsDir() + mbFileName;
@@ -338,7 +345,7 @@ MenuBarPopup::MenuBarPopup(Room* room)
menuBarLabel->setFont(f);
menuItemListLabel->setFont(f);
- QLineEdit* searchEdit = new QLineEdit(this);
+ auto* searchEdit = new QLineEdit(this);
QLabel* noticeLabel = new QLabel(
tr("N.B. If you put unique title to submenu, it may not be translated to "
@@ -350,11 +357,10 @@ MenuBarPopup::MenuBarPopup(Room* room)
noticeLabel->setFont(nf);
//--- layout
- QVBoxLayout* mainLay = new QVBoxLayout();
m_topLayout->setContentsMargins(0, 0, 0, 0);
m_topLayout->setSpacing(0);
{
- QGridLayout* mainUILay = new QGridLayout();
+ auto* mainUILay = new QGridLayout();
mainUILay->setContentsMargins(5, 5, 5, 5);
mainUILay->setHorizontalSpacing(8);
mainUILay->setVerticalSpacing(5);
@@ -363,7 +369,7 @@ MenuBarPopup::MenuBarPopup(Room* room)
mainUILay->addWidget(menuItemListLabel, 0, 1);
mainUILay->addWidget(m_menuBarTree, 1, 0, 2, 1);
- QHBoxLayout* searchLay = new QHBoxLayout();
+ auto* searchLay = new QHBoxLayout();
searchLay->setContentsMargins(0, 0, 0, 0);
searchLay->setSpacing(5);
{
@@ -393,29 +399,25 @@ MenuBarPopup::MenuBarPopup(Room* room)
m_buttonLayout->addStretch(1);
}
- //--- signal/slot connections
-
- bool ret = connect(okBtn, SIGNAL(clicked()), this, SLOT(onOkPressed()));
- ret = ret && connect(cancelBtn, SIGNAL(clicked()), this, SLOT(reject()));
- ret = ret && connect(searchEdit, SIGNAL(textChanged(const QString&)), this,
- SLOT(onSearchTextChanged(const QString&)));
- assert(ret);
+ connect(okBtn, &QPushButton::clicked, this, &MenuBarPopup::onOkPressed);
+ connect(cancelBtn, &QPushButton::clicked, this, &MenuBarPopup::reject);
+ connect(searchEdit, &QLineEdit::textChanged, this,
+ &MenuBarPopup::onSearchTextChanged);
}
//-----------------------------------------------------------------------------
void MenuBarPopup::onOkPressed() {
m_menuBarTree->saveMenuTree();
-
accept();
}
//-----------------------------------------------------------------------------
void MenuBarPopup::onSearchTextChanged(const QString& text) {
- static bool busy = false;
- if (busy) return;
- busy = true;
+ // --- USE MEMBER FLAG INSTEAD OF STATIC ---
+ if (m_searchBusy) return;
+ m_searchBusy = true;
m_commandListTree->searchItems(text);
- busy = false;
-}
\ No newline at end of file
+ m_searchBusy = false;
+}
diff --git a/toonz/sources/toonz/menubarpopup.h b/toonz/sources/toonz/menubarpopup.h
index 902c57e54..5638e39c4 100644
--- a/toonz/sources/toonz/menubarpopup.h
+++ b/toonz/sources/toonz/menubarpopup.h
@@ -29,7 +29,14 @@ class MenuBarTree final : public QTreeWidget {
void saveMenuRecursive(QXmlStreamWriter& writer, QTreeWidgetItem* parentItem);
public:
- MenuBarTree(TFilePath& path, QWidget* parent = 0);
+ explicit MenuBarTree(TFilePath& path, QWidget* parent = nullptr);
+
+ // Prohibit copying and moving
+ MenuBarTree(const MenuBarTree&) = delete;
+ MenuBarTree& operator=(const MenuBarTree&) = delete;
+ MenuBarTree(MenuBarTree&&) = delete;
+ MenuBarTree& operator=(MenuBarTree&&) = delete;
+
void saveMenuTree();
protected:
@@ -37,6 +44,7 @@ protected:
Qt::DropAction action) override;
QStringList mimeTypes() const override;
void contextMenuEvent(QContextMenuEvent* event) override;
+
protected slots:
void insertMenu();
void removeItem();
@@ -49,14 +57,23 @@ protected slots:
class MenuBarPopup final : public DVGui::Dialog {
Q_OBJECT
- CommandListTree* m_commandListTree;
- MenuBarTree* m_menuBarTree;
+
+ CommandListTree* m_commandListTree = nullptr;
+ MenuBarTree* m_menuBarTree = nullptr;
+ bool m_searchBusy = false; // prevent reentrant search
public:
- MenuBarPopup(Room* room);
+ explicit MenuBarPopup(Room* room);
+
+ // Prohibit copying and moving
+ MenuBarPopup(const MenuBarPopup&) = delete;
+ MenuBarPopup& operator=(const MenuBarPopup&) = delete;
+ MenuBarPopup(MenuBarPopup&&) = delete;
+ MenuBarPopup& operator=(MenuBarPopup&&) = delete;
+
protected slots:
void onOkPressed();
void onSearchTextChanged(const QString& text);
};
-#endif
\ No newline at end of file
+#endif
diff --git a/toonz/sources/toonz/pane.cpp b/toonz/sources/toonz/pane.cpp
index e52130499..d1e75ba82 100644
--- a/toonz/sources/toonz/pane.cpp
+++ b/toonz/sources/toonz/pane.cpp
@@ -21,22 +21,20 @@
// Qt includes
#include <QPainter>
-#include <QStyleOptionDockWidget>
#include <QMouseEvent>
#include <QMainWindow>
#include <QSettings>
-#include <QToolBar>
#include <QMap>
#include <QMenu>
#include <QApplication>
-#include <QFile>
-#include <qdrawutil.h>
#include <assert.h>
-#include <QDesktopWidget>
#include <QDialog>
#include <QLineEdit>
#include <QTextEdit>
#include <QScreen>
+#include <QGlobalStatic>
+#include <memory>
+#include <utility>
extern TEnv::StringVar EnvSafeAreaName;
extern TEnv::IntVar EnvViewerPreviewBehavior;
@@ -51,27 +49,23 @@ TPanel::TPanel(QWidget *parent, Qt::WindowFlags flags,
, m_panelType("")
, m_isMaximizable(true)
, m_isMaximized(false)
- , m_panelTitleBar(0)
+ , m_panelTitleBar(nullptr)
, m_multipleInstancesAllowed(true)
, m_isRoomBound(false)
, m_boundRoomName("")
- , m_roomBindButton(0) {
- // setFeatures(QDockWidget::DockWidgetMovable |
- // QDockWidget::DockWidgetFloatable);
- // setFloating(false);
+ , m_roomBindButton(nullptr) {
m_panelTitleBar = new TPanelTitleBar(this, orientation);
setTitleBarWidget(m_panelTitleBar);
- // connect(m_panelTitleBar,SIGNAL(doubleClick()),this,SLOT(onDoubleClick()));
- connect(m_panelTitleBar, SIGNAL(doubleClick(QMouseEvent *)), this,
- SIGNAL(doubleClick(QMouseEvent *)));
- connect(m_panelTitleBar, SIGNAL(closeButtonPressed()), this,
- SLOT(onCloseButtonPressed()));
+ connect(m_panelTitleBar, &TPanelTitleBar::doubleClick, this,
+ &TPanel::doubleClick);
+ connect(m_panelTitleBar, &TPanelTitleBar::closeButtonPressed, this,
+ &TPanel::onCloseButtonPressed);
setOrientation(orientation);
-
+
// Enable context menu for room binding
setContextMenuPolicy(Qt::CustomContextMenu);
- connect(this, &QWidget::customContextMenuRequested,
- this, &TPanel::onCustomContextMenuRequested);
+ connect(this, &QWidget::customContextMenuRequested, this,
+ &TPanel::onCustomContextMenuRequested);
}
//-----------------------------------------------------------------------------
@@ -80,15 +74,14 @@ TPanel::~TPanel() {
// On quitting, save the floating panel's geometry and state in order to
// restore them when opening the floating panel next time
if (isFloating()) {
- TFilePath savePath =
+ const TFilePath savePath =
ToonzFolder::getMyModuleDir() + TFilePath("popups.ini");
QSettings settings(QString::fromStdWString(savePath.getWideString()),
QSettings::IniFormat);
- settings.beginGroup("Panels");
+ settings.beginGroup(QStringLiteral("Panels"));
settings.beginGroup(QString::fromStdString(m_panelType));
- settings.setValue("geometry", geometry());
- if (SaveLoadQSettings *persistent =
- dynamic_cast<SaveLoadQSettings *>(widget()))
+ settings.setValue(QStringLiteral("geometry"), geometry());
+ if (auto *persistent = dynamic_cast<SaveLoadQSettings *>(widget()))
persistent->save(settings);
}
}
@@ -100,7 +93,6 @@ void TPanel::paintEvent(QPaintEvent *e) {
if (widget()) {
QRect dockRect = widget()->geometry();
-
dockRect.adjust(0, 0, -1, -1);
painter.fillRect(dockRect, m_bgcolor);
painter.setPen(Qt::black);
@@ -116,7 +108,7 @@ void TPanel::onCloseButtonPressed() {
emit closeButtonPressed();
// Currently, Toonz panels that get closed indeed just remain hidden -
- // ready to reappair if they are needed again. However, the user expects
+ // ready to reappear if they are needed again. However, the user expects
// a new panel to be created - so we just reset the panel here.
// reset(); //Moved to panel invocation in floatingpanelcommand.cpp
@@ -127,21 +119,20 @@ void TPanel::onCloseButtonPressed() {
//-----------------------------------------------------------------------------
void TPanel::onCustomContextMenuRequested(const QPoint &pos) {
- QMenu *menu = new QMenu(this);
-
+ QMenu menu(this);
+
// Add "Bind to Current Room" option
- QAction *bindAction = menu->addAction(tr("Bind to Current Room"));
+ QAction *bindAction = menu.addAction(tr("Bind to Current Room"));
bindAction->setCheckable(true);
bindAction->setChecked(m_isRoomBound);
-
+
connect(bindAction, &QAction::triggered, [this](bool checked) {
- MainWindow *mw = dynamic_cast<MainWindow *>(
- TApp::instance()->getMainWindow());
+ auto *mw = dynamic_cast<MainWindow *>(TApp::instance()->getMainWindow());
if (!mw) return;
-
+
Room *currentRoom = mw->getCurrentRoom();
if (!currentRoom) return;
-
+
// Update binding state
setRoomBound(checked);
if (checked) {
@@ -151,16 +142,14 @@ void TPanel::onCustomContextMenuRequested(const QPoint &pos) {
mw->updatePanelVisibility();
} else {
// Unbind panel from room
- setBoundRoomName("");
+ setBoundRoomName(QString());
// Show panel if it was hidden
- if (isHidden()) {
- show();
- }
+ if (isHidden()) show();
}
});
-
- menu->exec(mapToGlobal(pos));
- delete menu;
+
+ menu.exec(mapToGlobal(pos));
+ // menu is automatically deleted by unique_ptr
}
//-----------------------------------------------------------------------------
@@ -168,12 +157,12 @@ void TPanel::onCustomContextMenuRequested(const QPoint &pos) {
*/
void TPanel::enterEvent(QEvent *event) {
// Only when Toonz application is active
- QWidget *w = qApp->activeWindow();
+ QWidget *w = QApplication::activeWindow();
if (w) {
// grab the focus, unless a line-edit is focused currently
- QWidget *focusWidget = qApp->focusWidget();
- if (focusWidget && (dynamic_cast<QLineEdit *>(focusWidget) ||
- dynamic_cast<QTextEdit *>(focusWidget))) {
+ QWidget *focusWidget = QApplication::focusWidget();
+ if (focusWidget && (qobject_cast<QLineEdit *>(focusWidget) ||
+ qobject_cast<QTextEdit *>(focusWidget))) {
event->accept();
return;
}
@@ -184,7 +173,7 @@ void TPanel::enterEvent(QEvent *event) {
// activated when mouse enters. Viewer is activatable only when being
// docked.
// Active windows will NOT switch when the current active window is dialog.
- if (qobject_cast<QDialog *>(w) == 0 && isActivatableOnEnter())
+ if (qobject_cast<QDialog *>(w) == nullptr && isActivatableOnEnter())
activateWindow();
event->accept();
} else
@@ -195,8 +184,9 @@ void TPanel::enterEvent(QEvent *event) {
/*! clear focus when mouse leaves
*/
void TPanel::leaveEvent(QEvent *event) {
- QWidget *focusWidget = qApp->focusWidget();
- if (focusWidget && dynamic_cast<QLineEdit *>(focusWidget)) {
+ QWidget *focusWidget = QApplication::focusWidget();
+ if (focusWidget && (qobject_cast<QLineEdit *>(focusWidget) ||
+ qobject_cast<QTextEdit *>(focusWidget))) {
return;
}
widgetClearFocusOnLeave();
@@ -208,23 +198,31 @@ void TPanel::leaveEvent(QEvent *event) {
in floatingpanelcommand.cpp
*/
void TPanel::restoreFloatingPanelState() {
- TFilePath savePath = ToonzFolder::getMyModuleDir() + TFilePath("popups.ini");
+ const TFilePath savePath =
+ ToonzFolder::getMyModuleDir() + TFilePath("popups.ini");
QSettings settings(QString::fromStdWString(savePath.getWideString()),
QSettings::IniFormat);
- settings.beginGroup("Panels");
+ settings.beginGroup(QStringLiteral("Panels"));
if (!settings.childGroups().contains(QString::fromStdString(m_panelType)))
return;
settings.beginGroup(QString::fromStdString(m_panelType));
- QRect geom = settings.value("geometry", saveGeometry()).toRect();
- // check if it can be visible in the current screen
- if (!(geom & QApplication::desktop()->availableGeometry(this)).isEmpty())
- setGeometry(geom);
+ QRect geom = settings.value(QStringLiteral("geometry"), geometry()).toRect();
+
+ // Check if the geometry is visible on any available screen (modern API)
+ bool visible = false;
+ for (QScreen *screen : QGuiApplication::screens()) {
+ if (screen->availableGeometry().intersects(geom)) {
+ visible = true;
+ break;
+ }
+ }
+ if (visible) setGeometry(geom);
+
// load optional settings
- if (SaveLoadQSettings *persistent =
- dynamic_cast<SaveLoadQSettings *>(widget()))
+ if (auto *persistent = dynamic_cast<SaveLoadQSettings *>(widget()))
persistent->load(settings);
}
@@ -232,9 +230,9 @@ void TPanel::restoreFloatingPanelState() {
// if the panel has no contents to be zoomed, simply resize the panel here
// currently only Flipbook and Color Model panels support resizing of contents
void TPanel::zoomContentsAndFitGeometry(bool forward) {
- if (!m_floating) return;
+ if (!isFloating()) return;
- auto getScreen = [&]() {
+ auto getScreen = [&]() -> QScreen * {
QScreen *ret = nullptr;
ret = QGuiApplication::screenAt(geometry().topLeft());
if (ret) return ret;
@@ -251,7 +249,7 @@ void TPanel::zoomContentsAndFitGeometry(bool forward) {
// Get screen geometry
QScreen *screen = getScreen();
if (!screen) return;
- QRect screenGeom = screen->availableGeometry();
+ const QRect screenGeom = screen->availableGeometry();
QSize newSize;
if (forward)
@@ -284,9 +282,7 @@ void TPanel::zoomContentsAndFitGeometry(bool forward) {
void TPanel::setRoomBound(bool bound) {
m_isRoomBound = bound;
- if (m_roomBindButton) {
- m_roomBindButton->setPressed(bound);
- }
+ if (m_roomBindButton) m_roomBindButton->setPressed(bound);
}
//-----------------------------------------------------------------------------
@@ -300,48 +296,47 @@ void TPanel::setBoundRoomName(const QString &roomName) {
void TPanel::addRoomBindButton() {
// Prevent adding button twice
if (m_roomBindButton) return;
-
+
// Check preference to see if room bind buttons should be shown
Preferences *prefs = Preferences::instance();
if (!prefs->getBoolValue(showRoomBindButtons)) return;
-
- TPanelTitleBar *titleBar = getTitleBar();
+
+ auto *titleBar = getTitleBar();
if (!titleBar) return;
-
+
// Create toggle button with simple circle indicator
m_roomBindButton = new TPanelTitleBarButtonForBindToRoom(titleBar);
m_roomBindButton->setToolTip(QObject::tr("Bind to Current Room"));
- m_roomBindButton->setPressed(m_isRoomBound); // Restore state if loaded from file
-
+ m_roomBindButton->setPressed(
+ m_isRoomBound); // Restore state if loaded from file
+
// Position: -60 pixels from right edge (before close button)
titleBar->add(QPoint(-60, 0), m_roomBindButton);
-
- // Connect toggle signal to handle room binding state changes
- QObject::connect(m_roomBindButton, &TPanelTitleBarButton::toggled,
- [this](bool checked) {
- MainWindow *mw = dynamic_cast<MainWindow *>(
- TApp::instance()->getMainWindow());
- if (!mw) return;
-
- Room *currentRoom = mw->getCurrentRoom();
- if (!currentRoom) return;
-
- // Update binding state
- setRoomBound(checked);
- if (checked) {
- // Bind panel to current room
- setBoundRoomName(currentRoom->getName());
- // Update visibility immediately for all bound panels
- mw->updatePanelVisibility();
- } else {
- // Unbind panel from room
- setBoundRoomName("");
- // Show panel if it was hidden
- if (isHidden()) {
- show();
- }
- }
- });
+
+ // Connect toggle signal to handle room binding state changes (modern lambda)
+ connect(m_roomBindButton, &TPanelTitleBarButton::toggled,
+ [this](bool checked) {
+ auto *mw =
+ dynamic_cast<MainWindow *>(TApp::instance()->getMainWindow());
+ if (!mw) return;
+
+ Room *currentRoom = mw->getCurrentRoom();
+ if (!currentRoom) return;
+
+ // Update binding state
+ setRoomBound(checked);
+ if (checked) {
+ // Bind panel to current room
+ setBoundRoomName(currentRoom->getName());
+ // Update visibility immediately for all bound panels
+ mw->updatePanelVisibility();
+ } else {
+ // Unbind panel from room
+ setBoundRoomName(QString());
+ // Show panel if it was hidden
+ if (isHidden()) show();
+ }
+ });
}
//=============================================================================
@@ -354,13 +349,14 @@ TPanelTitleBarButton::TPanelTitleBarButton(QWidget *parent,
, m_standardPixmapName(standardPixmapName)
, m_rollover(false)
, m_pressed(false)
- , m_buttonSet(0)
+ , m_buttonSet(nullptr)
, m_id(0) {
setMouseTracking(true);
// Determine button size
m_baseSize = QSize(20, 18);
- if (m_standardPixmapName.contains("preview", Qt::CaseInsensitive)) {
+ if (m_standardPixmapName.contains(QLatin1String("preview"),
+ Qt::CaseInsensitive)) {
m_baseSize = QSize(30, 18);
}
@@ -436,6 +432,25 @@ void TPanelTitleBarButton::setPreviewColor(const QColor &color) {
QColor TPanelTitleBarButton::getPreviewColor() const { return m_previewColor; }
+//=============================================================================
+// Implementation of the Constructors of the Specialized Classes
+//-----------------------------------------------------------------------------
+
+// Constructor for BindToRoom
+TPanelTitleBarButtonForBindToRoom::TPanelTitleBarButtonForBindToRoom(
+ QWidget *parent)
+ : TPanelTitleBarButton(parent, QStringLiteral()) {}
+
+// Constructor for SafeArea
+TPanelTitleBarButtonForSafeArea::TPanelTitleBarButtonForSafeArea(
+ QWidget *parent, const QString &standardPixmapName)
+ : TPanelTitleBarButton(parent, standardPixmapName) {}
+
+// Constructor for Preview
+TPanelTitleBarButtonForPreview::TPanelTitleBarButtonForPreview(
+ QWidget *parent, const QString &standardPixmapName)
+ : TPanelTitleBarButton(parent, standardPixmapName) {}
+
//-----------------------------------------------------------------------------
void TPanelTitleBarButton::paintEvent(QPaintEvent *event) {
@@ -448,14 +463,13 @@ void TPanelTitleBarButton::paintEvent(QPaintEvent *event) {
QIcon::State state = m_pressed ? QIcon::On : QIcon::Off;
// Get DPR and sizes
- qreal dpr = getDevicePixelRatio(this);
- auto &tm = ThemeManager::getInstance();
- QSize iconSz = tm.getIconSize(m_standardPixmapName);
- QSize physSz = iconSz * dpr;
- QSize btnSz = size() * dpr;
+ const qreal dpr = getDevicePixelRatio(this);
+ auto &tm = ThemeManager::getInstance();
+ const QSize iconSz = tm.getIconSize(m_standardPixmapName);
+ const QSize btnSz = size() * dpr;
// Cache key with DPR
- QString cacheKey =
+ const QString cacheKey =
generateCacheKey(m_standardPixmapName, btnSz, mode, state) +
QString::number(dpr);
@@ -464,14 +478,13 @@ void TPanelTitleBarButton::paintEvent(QPaintEvent *event) {
if (finalPm.isNull()) {
QPixmap pm = SvgIconEngine(m_standardPixmapName, false, dpr, iconSz)
.pixmap(iconSz, mode, state);
- pm.scaled(iconSz, Qt::KeepAspectRatio);
if (!pm.isNull()) {
QColor bgColor = getOffColor();
if (m_pressed) {
- if (m_standardPixmapName.contains("freeze")) {
+ if (m_standardPixmapName.contains(QLatin1String("freeze"))) {
bgColor = getFreezeColor();
- } else if (m_standardPixmapName.contains("preview")) {
+ } else if (m_standardPixmapName.contains(QLatin1String("preview"))) {
bgColor = getPreviewColor();
} else {
bgColor = getPressedColor();
@@ -535,30 +548,31 @@ void TPanelTitleBarButton::mousePressEvent(QMouseEvent *e) {
void TPanelTitleBarButtonForBindToRoom::paintEvent(QPaintEvent *) {
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing);
-
+
// Get title bar to access theme colors
- TPanelTitleBar *titleBar = qobject_cast<TPanelTitleBar *>(parentWidget());
-
+ auto *titleBar = qobject_cast<TPanelTitleBar *>(parentWidget());
+
// Determine circle color based on state
QColor circleColor;
if (m_pressed) {
// When bound, use active title color
- circleColor = titleBar ? titleBar->getActiveTitleColor() : QColor(0, 150, 255);
+ circleColor =
+ titleBar ? titleBar->getActiveTitleColor() : QColor(0, 150, 255);
} else {
// When not bound, use dimmed title color
circleColor = titleBar ? titleBar->getTitleColor() : QColor(160, 160, 160);
circleColor.setAlpha(m_rollover ? 200 : 120); // Fade when not hovering
}
-
+
// Draw small circle in the center of the button
- QRect rect = this->rect();
- int diameter = 8; // Small circle (8px diameter)
- int centerX = rect.center().x();
- int centerY = rect.center().y();
-
+ const QRect rect = this->rect();
+ const int diameter = 8; // Small circle (8px diameter)
+ const int centerX = rect.center().x();
+ const int centerY = rect.center().y();
+
p.setPen(Qt::NoPen);
p.setBrush(circleColor);
- p.drawEllipse(QPoint(centerX, centerY), diameter/2, diameter/2);
+ p.drawEllipse(QPoint(centerX, centerY), diameter / 2, diameter / 2);
}
//=============================================================================
@@ -566,11 +580,11 @@ void TPanelTitleBarButtonForBindToRoom::paintEvent(QPaintEvent *) {
//-----------------------------------------------------------------------------
void TPanelTitleBarButtonForSafeArea::getSafeAreaNameList(
- QList<QString> &nameList) {
- TFilePath fp = TEnv::getConfigDir();
- QString currentSafeAreaName = QString::fromStdString(EnvSafeAreaName);
+ QList<QString> &nameList) const {
+ TFilePath fp = TEnv::getConfigDir();
+ const QString currentSafeAreaName = QString::fromStdString(EnvSafeAreaName);
- std::string safeAreaFileName = "safearea.ini";
+ const std::string safeAreaFileName = "safearea.ini";
while (!TFileStatus(fp + safeAreaFileName).doesExist() && !fp.isRoot() &&
fp.getParentDir() != TFilePath())
@@ -582,10 +596,11 @@ void TPanelTitleBarButtonForSafeArea::getSafeAreaNameList(
QSettings settings(toQString(fp), QSettings::IniFormat);
// find the current safearea name from the list
- QStringList groups = settings.childGroups();
- for (int g = 0; g < groups.size(); g++) {
- settings.beginGroup(groups.at(g));
- nameList.push_back(settings.value("name", "").toString());
+ const QStringList groups = settings.childGroups();
+ for (const QString &group : groups) {
+ settings.beginGroup(group);
+ nameList.push_back(
+ settings.value(QStringLiteral("name"), QString()).toString());
settings.endGroup();
}
}
@@ -608,15 +623,15 @@ void TPanelTitleBarButtonForSafeArea::contextMenuEvent(QContextMenuEvent *e) {
QList<QString> safeAreaNameList;
getSafeAreaNameList(safeAreaNameList);
- for (int i = 0; i < safeAreaNameList.size(); i++) {
- QAction *action = new QAction(safeAreaNameList.at(i), this);
- action->setData(safeAreaNameList.at(i));
- connect(action, SIGNAL(triggered()), this, SLOT(onSetSafeArea()));
- if (safeAreaNameList.at(i) == QString::fromStdString(EnvSafeAreaName)) {
+ for (const QString &name : safeAreaNameList) {
+ QAction *action = menu.addAction(name);
+ action->setData(name);
+ connect(action, &QAction::triggered, this,
+ &TPanelTitleBarButtonForSafeArea::onSetSafeArea);
+ if (name == QString::fromStdString(EnvSafeAreaName)) {
action->setCheckable(true);
action->setChecked(true);
}
- menu.addAction(action);
}
menu.exec(e->globalPos());
@@ -625,7 +640,8 @@ void TPanelTitleBarButtonForSafeArea::contextMenuEvent(QContextMenuEvent *e) {
//-----------------------------------------------------------------------------
void TPanelTitleBarButtonForSafeArea::onSetSafeArea() {
- QString safeAreaName = qobject_cast<QAction *>(sender())->data().toString();
+ const QString safeAreaName =
+ qobject_cast<QAction *>(sender())->data().toString();
// change safearea if the different one is selected
if (QString::fromStdString(EnvSafeAreaName) != safeAreaName) {
EnvSafeAreaName = safeAreaName.toStdString();
@@ -656,16 +672,19 @@ void TPanelTitleBarButtonForPreview::contextMenuEvent(QContextMenuEvent *e) {
// 0: current frame
// 1: all frames in the preview range
// 2: selected cell, auto play once & stop
- QStringList behaviorsStrList = {tr("Current frame"),
- tr("All preview range frames"),
- tr("Selected cells - Auto play")};
+ const QStringList behaviorsStrList = {tr("Current frame"),
+ tr("All preview range frames"),
+ tr("Selected cells - Auto play")};
- QActionGroup *behaviorGroup = new QActionGroup(this);
+ // QActionGroup with menu as parent ensures proper cleanup
+ auto *behaviorGroup = new QActionGroup(&menu);
+ behaviorGroup->setExclusive(true);
- for (int i = 0; i < behaviorsStrList.size(); i++) {
+ for (int i = 0; i < behaviorsStrList.size(); ++i) {
QAction *action = menu.addAction(behaviorsStrList.at(i));
action->setData(i);
- connect(action, SIGNAL(triggered()), this, SLOT(onSetPreviewBehavior()));
+ connect(action, &QAction::triggered, this,
+ &TPanelTitleBarButtonForPreview::onSetPreviewBehavior);
action->setCheckable(true);
behaviorGroup->addAction(action);
if (i == EnvViewerPreviewBehavior) action->setChecked(true);
@@ -677,7 +696,7 @@ void TPanelTitleBarButtonForPreview::contextMenuEvent(QContextMenuEvent *e) {
//-----------------------------------------------------------------------------
void TPanelTitleBarButtonForPreview::onSetPreviewBehavior() {
- int behaviorId = qobject_cast<QAction *>(sender())->data().toInt();
+ const int behaviorId = qobject_cast<QAction *>(sender())->data().toInt();
// change safearea if the different one is selected
if (EnvViewerPreviewBehavior != behaviorId) {
EnvViewerPreviewBehavior = behaviorId;
@@ -692,18 +711,14 @@ void TPanelTitleBarButtonForPreview::onSetPreviewBehavior() {
// TPanelTitleBarButtonSet
//-----------------------------------------------------------------------------
-TPanelTitleBarButtonSet::TPanelTitleBarButtonSet() {}
-
-TPanelTitleBarButtonSet::~TPanelTitleBarButtonSet() {}
+TPanelTitleBarButtonSet::TPanelTitleBarButtonSet() = default;
void TPanelTitleBarButtonSet::add(TPanelTitleBarButton *button) {
m_buttons.push_back(button);
}
void TPanelTitleBarButtonSet::select(TPanelTitleBarButton *button) {
- int i;
- for (i = 0; i < (int)m_buttons.size(); i++)
- m_buttons[i]->setPressed(button == m_buttons[i]);
+ for (auto *btn : m_buttons) btn->setPressed(button == btn);
emit selected(button->getId());
}
@@ -726,11 +741,11 @@ QSize TPanelTitleBar::minimumSizeHint() const { return QSize(20, 18); }
void TPanelTitleBar::paintEvent(QPaintEvent *) {
QPainter painter(this);
- QRect rect = this->rect();
+ const QRect rect = this->rect();
bool isPanelActive;
- TPanel *dw = qobject_cast<TPanel *>(parentWidget());
- Q_ASSERT(dw != 0);
+ auto *dw = qobject_cast<TPanel *>(parentWidget());
+ Q_ASSERT(dw != nullptr);
if (!dw->isFloating()) { // docked panel
isPanelActive = dw->widgetInThisPanelIsFocused();
@@ -739,7 +754,7 @@ void TPanelTitleBar::paintEvent(QPaintEvent *) {
}
if (dw->getOrientation() == TDockWidget::vertical) {
- QString titleText = painter.fontMetrics().elidedText(
+ const QString titleText = painter.fontMetrics().elidedText(
dw->windowTitle(), Qt::ElideRight, rect.width() - 50);
painter.setBrush(Qt::NoBrush);
@@ -748,20 +763,20 @@ void TPanelTitleBar::paintEvent(QPaintEvent *) {
}
if (dw->isFloating()) {
- QPoint btnPos(rect.right() - 19, rect.top());
- qreal dpr = getDevicePixelRatio(this);
- QSize btnSz = minimumSizeHint() * dpr;
- QSize iconSz = QSize(16, 16);
+ const QPoint btnPos(rect.right() - 19, rect.top());
+ const qreal dpr = getDevicePixelRatio(this);
+ const QSize btnSz = minimumSizeHint() * dpr;
+ const QSize iconSz = QSize(16, 16);
// Icon mode and background color
- bool highlighted = m_closeButtonHighlighted;
- QIcon::Mode mode = highlighted ? QIcon::Active : QIcon::Normal;
- QColor bgColor = highlighted ? getCloseOverColor() : Qt::transparent;
+ const bool highlighted = m_closeButtonHighlighted;
+ const QIcon::Mode mode = highlighted ? QIcon::Active : QIcon::Normal;
+ const QColor bgColor = highlighted ? getCloseOverColor() : Qt::transparent;
// Cache key
- QString cacheKey =
- generateCacheKey("closewindow", btnSz, mode, QIcon::Off) +
- QString::number(dpr);
+ const QString cacheKey = generateCacheKey(QStringLiteral("closewindow"),
+ btnSz, mode, QIcon::Off) +
+ QString::number(dpr);
// Check cache first
QPixmap finalPm = getFromPixmapCache(cacheKey);
@@ -771,8 +786,9 @@ void TPanelTitleBar::paintEvent(QPaintEvent *) {
}
// Load icon at logical size
- QPixmap pm = SvgIconEngine("closewindow", false, dpr, iconSz)
- .pixmap(iconSz, mode, QIcon::Off);
+ QPixmap pm =
+ SvgIconEngine(QStringLiteral("closewindow"), false, dpr, iconSz)
+ .pixmap(iconSz, mode, QIcon::Off);
if (pm.isNull()) return;
pm.setDevicePixelRatio(dpr);
@@ -798,8 +814,8 @@ QColor TPanelTitleBar::getCloseOverColor() const { return m_closeOverColor; }
//-----------------------------------------------------------------------------
void TPanelTitleBar::leaveEvent(QEvent *) {
- TPanel *dw = qobject_cast<TPanel *>(parentWidget());
- Q_ASSERT(dw != 0);
+ auto *dw = qobject_cast<TPanel *>(parentWidget());
+ Q_ASSERT(dw != nullptr);
// Mouse left the widget, reset the highlighted flag
if (dw->isFloating()) {
@@ -811,13 +827,13 @@ void TPanelTitleBar::leaveEvent(QEvent *) {
//-----------------------------------------------------------------------------
void TPanelTitleBar::mousePressEvent(QMouseEvent *event) {
- TDockWidget *dw = static_cast<TDockWidget *>(parentWidget());
+ auto *dw = static_cast<TDockWidget *>(parentWidget());
- QPoint pos = event->pos();
+ const QPoint pos = event->pos();
if (dw->isFloating()) {
- QRect rect = this->rect();
- QRect closeButtonRect(rect.right() - 20, rect.top() + 1, 20, 18);
+ const QRect rect = this->rect();
+ const QRect closeButtonRect(rect.right() - 20, rect.top() + 1, 20, 18);
if (closeButtonRect.contains(pos) && dw->isFloating()) {
event->accept();
dw->hide();
@@ -832,12 +848,12 @@ void TPanelTitleBar::mousePressEvent(QMouseEvent *event) {
//-----------------------------------------------------------------------------
void TPanelTitleBar::mouseMoveEvent(QMouseEvent *event) {
- TDockWidget *dw = static_cast<TDockWidget *>(parentWidget());
+ auto *dw = static_cast<TDockWidget *>(parentWidget());
if (dw->isFloating()) {
- QPoint pos = event->pos();
- QRect rect = this->rect();
- QRect closeButtonRect(rect.right() - 18, rect.top() + 1, 18, 18);
+ const QPoint pos = event->pos();
+ const QRect rect = this->rect();
+ const QRect closeButtonRect(rect.right() - 18, rect.top() + 1, 18, 18);
if (closeButtonRect.contains(pos) && dw->isFloating())
m_closeButtonHighlighted = true;
@@ -859,80 +875,79 @@ void TPanelTitleBar::mouseDoubleClickEvent(QMouseEvent *me) {
//-----------------------------------------------------------------------------
void TPanelTitleBar::add(const QPoint &pos, QWidget *widget) {
- m_buttons.push_back(std::make_pair(pos, widget));
+ m_buttons.emplace_back(pos, widget);
}
//-----------------------------------------------------------------------------
void TPanelTitleBar::resizeEvent(QResizeEvent *e) {
QWidget::resizeEvent(e);
- int i;
- for (i = 0; i < (int)m_buttons.size(); i++) {
- QPoint p = m_buttons[i].first;
- QWidget *w = m_buttons[i].second;
+ for (const auto &[pos, widget] : m_buttons) {
+ QPoint p = pos;
if (p.x() < 0) p.setX(p.x() + width());
- w->move(p);
+ widget->move(p);
}
}
//=============================================================================
-// TPanelFactory
+// TPanelFactory - using Q_GLOBAL_STATIC for thread-safe singleton map
//-----------------------------------------------------------------------------
-TPanelFactory::TPanelFactory(QString panelType) : m_panelType(panelType) {
- assert(tableInstance().count(panelType) == 0);
- tableInstance()[m_panelType] = this;
-}
+typedef QMap<QString, TPanelFactory *> FactoryTable;
+Q_GLOBAL_STATIC(FactoryTable, factoryTable)
//-----------------------------------------------------------------------------
-TPanelFactory::~TPanelFactory() { tableInstance().remove(m_panelType); }
+QMap<QString, TPanelFactory *> &TPanelFactory::tableInstance() {
+ return *factoryTable();
+}
//-----------------------------------------------------------------------------
-QMap<QString, TPanelFactory *> &TPanelFactory::tableInstance() {
- static QMap<QString, TPanelFactory *> table;
- return table;
+TPanelFactory::TPanelFactory(const QString &panelType)
+ : m_panelType(panelType) {
+ assert(tableInstance().count(panelType) == 0);
+ tableInstance()[m_panelType] = this;
}
//-----------------------------------------------------------------------------
-TPanel *TPanelFactory::createPanel(QWidget *parent, QString panelType) {
- TPanel *panel = 0;
+TPanelFactory::~TPanelFactory() { tableInstance().remove(m_panelType); }
- QMap<QString, TPanelFactory *>::iterator it = tableInstance().find(panelType);
- if (it == tableInstance().end()) {
- if (panelType.startsWith("Custom_")) {
- panelType = panelType.right(panelType.size() - 7);
- return CustomPanelManager::instance()->createCustomPanel(panelType,
- parent);
- }
+//-----------------------------------------------------------------------------
- // Fallback: create generic TPanel for unknown panel types
- TPanel *panel = new TPanel(parent);
- panel->setPanelType(panelType.toStdString());
- // Enable room binding feature for generic panels
- panel->addRoomBindButton();
- return panel;
- } else {
- TPanelFactory *factory = it.value();
- TPanel *panel = factory->createPanel(parent);
+TPanel *TPanelFactory::createPanel(QWidget *parent, const QString &panelType) {
+ auto it = tableInstance().find(panelType);
+ if (it != tableInstance().end()) {
+ TPanel *panel = it.value()->createPanel(parent);
panel->setPanelType(panelType.toStdString());
return panel;
}
+
+ if (panelType.startsWith(QStringLiteral("Custom_"))) {
+ QString customType = panelType.mid(7);
+ return CustomPanelManager::instance()->createCustomPanel(customType,
+ parent);
+ }
+
+ // Fallback: generic panel
+ TPanel *panel = new TPanel(parent);
+ panel->setPanelType(panelType.toStdString());
+ panel->addRoomBindButton();
+ return panel;
}
//-----------------------------------------------------------------------------
TPanel *TPanelFactory::createPanel(QWidget *parent) {
- TPanel *panel = new TPanel(parent);
+ auto *panel = new TPanel(parent);
panel->setObjectName(getPanelType());
panel->setWindowTitle(getPanelType());
initialize(panel);
-
+
// Enable room binding feature for all native panels
panel->addRoomBindButton();
-
+
return panel;
}
diff --git a/toonz/sources/toonz/pane.h b/toonz/sources/toonz/pane.h
index 98422c868..d61154282 100644
--- a/toonz/sources/toonz/pane.h
+++ b/toonz/sources/toonz/pane.h
@@ -3,57 +3,47 @@
#ifndef PANE_H
#define PANE_H
-// TODO: cambiare il nome del file in tpanel.h
+// TODO: change the file name to tpanel.h
-// #include <QDockWidget>
#include "../toonzqt/tdockwindows.h"
+#include <QMap>
+#include <QStringList>
+#include <QtGlobal>
+#include <QColor>
+#include <vector>
+#include <utility>
+
class TPanelTitleBarButtonSet;
class TPanelTitleBarButton;
class Room;
+//-----------------------------------------------------------------------------
//! icon buttons placed on the panel titlebar (cfr. viewerpane.h)
class TPanelTitleBarButton : public QWidget {
Q_OBJECT
-
- // Filepath
- QString m_standardPixmapName;
-
- // Colors
- QColor m_offColor;
- QColor m_overColor;
- QColor m_pressedColor;
- QColor m_freezeColor;
- QColor m_previewColor;
-
- QSize m_baseSize;
- QColor m_bgColor;
-
- // Methods
- void updatePixmaps();
-
- // Stylesheet
- Q_PROPERTY(QColor OffColor READ getOffColor WRITE setOffColor);
- Q_PROPERTY(QColor OverColor READ getOverColor WRITE setOverColor);
- Q_PROPERTY(QColor PressedColor READ getPressedColor WRITE setPressedColor);
- Q_PROPERTY(QColor FreezeColor READ getFreezeColor WRITE setFreezeColor);
- Q_PROPERTY(QColor PreviewColor READ getPreviewColor WRITE setPreviewColor);
-
- TPanelTitleBarButtonSet *m_buttonSet;
- int m_id;
-
-protected:
- bool m_rollover;
- bool m_pressed;
+ Q_PROPERTY(QColor OffColor READ getOffColor WRITE setOffColor)
+ Q_PROPERTY(QColor OverColor READ getOverColor WRITE setOverColor)
+ Q_PROPERTY(QColor PressedColor READ getPressedColor WRITE setPressedColor)
+ Q_PROPERTY(QColor FreezeColor READ getFreezeColor WRITE setFreezeColor)
+ Q_PROPERTY(QColor PreviewColor READ getPreviewColor WRITE setPreviewColor)
public:
- TPanelTitleBarButton(QWidget *parent, const QString &standardPixmapName);
+ explicit TPanelTitleBarButton(QWidget *parent,
+ const QString &standardPixmapName);
+ ~TPanelTitleBarButton() override = default;
+
+ // Prohibit copy and move (Qt doesn't support move for QWidget)
+ TPanelTitleBarButton(const TPanelTitleBarButton &) = delete;
+ TPanelTitleBarButton &operator=(const TPanelTitleBarButton &) = delete;
+ TPanelTitleBarButton(TPanelTitleBarButton &&) = delete;
+ TPanelTitleBarButton &operator=(TPanelTitleBarButton &&) = delete;
//! call this method to make a radio button. id is the button identifier
void setButtonSet(TPanelTitleBarButtonSet *buttonSet, int id);
- int getId() const { return m_id; }
+ int getId() const noexcept { return m_id; }
- // Stylesheet
+ // Stylesheet properties
void setOffColor(const QColor &color);
QColor getOffColor() const;
@@ -70,35 +60,44 @@ public:
QColor getPreviewColor() const;
public slots:
- void setPressed(bool pressed); // n.b. doesn't emit signals. calls update()
+ // n.b. doesn't emit signals, only calls update()
+ void setPressed(bool pressed);
+
+signals:
+ //! emitted when the user press the button
+ //! n.b. the signal is not emitted if the button is part of a buttonset
+ void toggled(bool pressed);
protected:
void paintEvent(QPaintEvent *event) override;
-
void mouseMoveEvent(QMouseEvent *event) override;
void enterEvent(QEvent *) override;
void leaveEvent(QEvent *) override;
void mousePressEvent(QMouseEvent *event) override;
-signals:
- //! emitted when the user press the button
- //! n.b. the signal is not emitted if the button is part of a buttonset
- void toggled(bool pressed);
+ QString m_standardPixmapName;
+ QColor m_offColor;
+ QColor m_overColor;
+ QColor m_pressedColor;
+ QColor m_freezeColor;
+ QColor m_previewColor;
+ QSize m_baseSize;
+ TPanelTitleBarButtonSet *m_buttonSet;
+ int m_id;
+ bool m_rollover;
+ bool m_pressed;
};
//-----------------------------------------------------------------------------
/*! specialized button for Bind to Room feature with a simple circle indicator
*/
-
class TPanelTitleBarButtonForBindToRoom final : public TPanelTitleBarButton {
Q_OBJECT
+ Q_DISABLE_COPY(TPanelTitleBarButtonForBindToRoom)
+
public:
- TPanelTitleBarButtonForBindToRoom(QWidget *parent)
- : TPanelTitleBarButton(parent, "") {
- // Set a small size similar to close button
- setFixedSize(20, 18);
- setMouseTracking(true);
- }
+ explicit TPanelTitleBarButtonForBindToRoom(QWidget *parent);
+ ~TPanelTitleBarButtonForBindToRoom() override = default;
protected:
void paintEvent(QPaintEvent *) override;
@@ -108,53 +107,57 @@ protected:
/*! specialized button for safe area which enables to choose safe area size by
* context menu
*/
-
class TPanelTitleBarButtonForSafeArea final : public TPanelTitleBarButton {
Q_OBJECT
+ Q_DISABLE_COPY(TPanelTitleBarButtonForSafeArea)
+
public:
- TPanelTitleBarButtonForSafeArea(QWidget *parent,
- const QString &standardPixmapName)
- : TPanelTitleBarButton(parent, standardPixmapName) {}
- void getSafeAreaNameList(QList<QString> &nameList);
+ explicit TPanelTitleBarButtonForSafeArea(QWidget *parent,
+ const QString &standardPixmapName);
+ ~TPanelTitleBarButtonForSafeArea() override = default;
+
+ void getSafeAreaNameList(QList<QString> &nameList) const;
protected:
void contextMenuEvent(QContextMenuEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
+
protected slots:
void onSetSafeArea();
};
//-----------------------------------------------------------------------------
-/*! specialized button for safe area which enables to choose safe area size by
+/*! specialized button for preview which enables to choose preview behavior by
* context menu
*/
-
class TPanelTitleBarButtonForPreview final : public TPanelTitleBarButton {
Q_OBJECT
+ Q_DISABLE_COPY(TPanelTitleBarButtonForPreview)
+
public:
- TPanelTitleBarButtonForPreview(QWidget *parent,
- const QString &standardPixmapName)
- : TPanelTitleBarButton(parent, standardPixmapName) {}
+ explicit TPanelTitleBarButtonForPreview(QWidget *parent,
+ const QString &standardPixmapName);
+ ~TPanelTitleBarButtonForPreview() override = default;
- bool isChecked() { return m_pressed; }
+ bool isChecked() const noexcept { return m_pressed; }
protected:
void contextMenuEvent(QContextMenuEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
+
protected slots:
void onSetPreviewBehavior();
};
//-----------------------------------------------------------------------------
-
//! a buttonset can group different TPanelTitleBarButton
class TPanelTitleBarButtonSet final : public QObject {
Q_OBJECT
- std::vector<TPanelTitleBarButton *> m_buttons;
+ Q_DISABLE_COPY(TPanelTitleBarButtonSet)
public:
TPanelTitleBarButtonSet();
- ~TPanelTitleBarButtonSet();
+ ~TPanelTitleBarButtonSet() override = default;
void add(TPanelTitleBarButton *button);
void select(TPanelTitleBarButton *button);
@@ -162,122 +165,107 @@ public:
signals:
//! emitted when the current button changes. id is the button identifier
void selected(int id);
+
+private:
+ std::vector<TPanelTitleBarButton *> m_buttons;
};
//-----------------------------------------------------------------------------
-
class TPanelTitleBar final : public QFrame {
Q_OBJECT
+ Q_DISABLE_COPY(TPanelTitleBar)
- bool m_closeButtonHighlighted;
- std::vector<std::pair<QPoint, QWidget *>> m_buttons;
-
- QColor m_titleColor, m_activeTitleColor, m_closeOverColor;
+ Q_PROPERTY(QColor TitleColor READ getTitleColor WRITE setTitleColor)
+ Q_PROPERTY(QColor ActiveTitleColor READ getActiveTitleColor WRITE
+ setActiveTitleColor)
+ Q_PROPERTY(
+ QColor CloseOverColor READ getCloseOverColor WRITE setCloseOverColor)
public:
- TPanelTitleBar(QWidget *parent = 0,
- TDockWidget::Orientation orientation = TDockWidget::vertical);
+ explicit TPanelTitleBar(
+ QWidget *parent = nullptr,
+ TDockWidget::Orientation orientation = TDockWidget::vertical);
+ ~TPanelTitleBar() override = default;
QSize sizeHint() const override { return minimumSizeHint(); }
QSize minimumSizeHint() const override;
- // pos = widget position. n.b. if pos.x()<0 then origin is topright corner
+ // pos = widget position. n.b. if pos.x()<0 then origin is top‑right corner
void add(const QPoint &pos, QWidget *widget);
- QColor getTitleColor() const { return m_titleColor; }
- void setTitleColor(const QColor &color) { m_titleColor = color; }
- QColor getActiveTitleColor() const { return m_activeTitleColor; }
- void setActiveTitleColor(const QColor &color) { m_activeTitleColor = color; }
+ QColor getTitleColor() const noexcept { return m_titleColor; }
+ void setTitleColor(const QColor &color) noexcept { m_titleColor = color; }
+
+ QColor getActiveTitleColor() const noexcept { return m_activeTitleColor; }
+ void setActiveTitleColor(const QColor &color) noexcept {
+ m_activeTitleColor = color;
+ }
QColor getCloseOverColor() const;
void setCloseOverColor(const QColor &color);
+signals:
+ void closeButtonPressed();
+ void doubleClick(QMouseEvent *me);
+
protected:
void resizeEvent(QResizeEvent *e) override;
-
- // To Disable the default context Menu
- void contextMenuEvent(QContextMenuEvent *) override {}
-
+ void contextMenuEvent(QContextMenuEvent *) override {
+ } // disable default menu
void paintEvent(QPaintEvent *event) override;
void leaveEvent(QEvent *) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseDoubleClickEvent(QMouseEvent *) override;
- Q_PROPERTY(QColor TitleColor READ getTitleColor WRITE setTitleColor);
- Q_PROPERTY(QColor ActiveTitleColor READ getActiveTitleColor WRITE
- setActiveTitleColor);
- Q_PROPERTY(
- QColor CloseOverColor READ getCloseOverColor WRITE setCloseOverColor);
-
-signals:
-
- void closeButtonPressed();
- void doubleClick(QMouseEvent *me);
+private:
+ bool m_closeButtonHighlighted;
+ std::vector<std::pair<QPoint, QWidget *>> m_buttons;
+ QColor m_titleColor, m_activeTitleColor, m_closeOverColor;
};
//-----------------------------------------------------------------------------
-
class TPanel : public TDockWidget {
Q_OBJECT
-
- QColor
- m_bgcolor; // overrides palette background color in paint event - Mac fix
+ Q_DISABLE_COPY(TPanel)
Q_PROPERTY(QColor BGColor READ getBGColor WRITE setBGColor)
- QColor getBGColor() const { return m_bgcolor; }
- void setBGColor(const QColor &color) { m_bgcolor = color; }
-
- std::string m_panelType;
- bool m_isMaximizable;
- bool m_isMaximized;
- bool m_multipleInstancesAllowed;
-
- TPanelTitleBar *m_panelTitleBar;
-
- QList<TPanel *> m_hiddenDockWidgets;
- QByteArray m_currentRoomOldState;
-
- // Room binding for custom panels
- bool m_isRoomBound;
- QString m_boundRoomName;
- TPanelTitleBarButton *m_roomBindButton;
-
public:
- TPanel(QWidget *parent = 0, Qt::WindowFlags flags = Qt::WindowFlags(),
- TDockWidget::Orientation orientation = TDockWidget::vertical);
- ~TPanel();
+ explicit TPanel(QWidget *parent = nullptr,
+ Qt::WindowFlags flags = Qt::WindowFlags(),
+ TDockWidget::Orientation orientation = TDockWidget::vertical);
+ ~TPanel() override;
+ // Panel type identification
void setPanelType(const std::string &panelType) { m_panelType = panelType; }
- std::string getPanelType() { return m_panelType; }
+ std::string getPanelType() const { return m_panelType; }
- void setIsMaximizable(bool value) { m_isMaximizable = value; }
- bool isMaximizable() { return m_isMaximizable; }
- // bool isMaximized() { return m_isMaximized; }
- // void setMaximized(bool isMaximized, Room *room = 0);
+ // Maximize support
+ void setIsMaximizable(bool value) noexcept { m_isMaximizable = value; }
+ bool isMaximizable() const noexcept { return m_isMaximizable; }
+ // Hidden dock widgets management
QList<TPanel *> getHiddenDockWidget() const { return m_hiddenDockWidgets; }
QByteArray getSavedOldState() const { return m_currentRoomOldState; }
- // void setTitleBarWidget(TPanelTitleBar *newTitleBar);
-
- // si riferisce a istanze multiple dei pannelli floating; default = true
- void allowMultipleInstances(bool allowed) {
+ // Multiple instances of floating panels; default = true
+ void allowMultipleInstances(bool allowed) noexcept {
m_multipleInstancesAllowed = allowed;
}
- bool areMultipleInstancesAllowed() const {
+ bool areMultipleInstancesAllowed() const noexcept {
return m_multipleInstancesAllowed;
}
- TPanelTitleBar *getTitleBar() const { return m_panelTitleBar; }
+ // Title bar access
+ TPanelTitleBar *getTitleBar() const noexcept { return m_panelTitleBar; }
// Room binding methods (for all panels)
- bool isRoomBound() const { return m_isRoomBound; }
+ bool isRoomBound() const noexcept { return m_isRoomBound; }
void setRoomBound(bool bound);
QString getBoundRoomName() const { return m_boundRoomName; }
void setBoundRoomName(const QString &roomName);
- void setRoomBindButton(TPanelTitleBarButton *button) {
+ void setRoomBindButton(TPanelTitleBarButton *button) noexcept {
m_roomBindButton = button;
}
@@ -285,19 +273,13 @@ public:
// This enables the "Bind to Room" feature for any panel
void addRoomBindButton();
- virtual void reset() {};
-
- virtual int getViewType() { return -1; };
- virtual void setViewType(int viewType) {};
-
+ // Virtuals that may be overridden
+ virtual void reset() {}
+ virtual int getViewType() { return -1; }
+ virtual void setViewType(int viewType) {}
virtual bool widgetInThisPanelIsFocused() {
- // by default, check if the panel content itself has focus
- if (widget())
- return widget()->hasFocus();
- else
- return false;
- };
-
+ return widget() ? widget()->hasFocus() : false;
+ }
virtual void restoreFloatingPanelState();
virtual void zoomContentsAndFitGeometry(bool forward);
@@ -305,42 +287,59 @@ protected:
void paintEvent(QPaintEvent *) override;
void enterEvent(QEvent *) override;
void leaveEvent(QEvent *) override;
-
virtual bool isActivatableOnEnter() { return false; }
protected slots:
-
void onCloseButtonPressed();
void onCustomContextMenuRequested(const QPoint &pos);
virtual void widgetFocusOnEnter() {
- // by default, focus the panel content
if (widget()) widget()->setFocus();
- };
+ }
virtual void widgetClearFocusOnLeave() {
if (widget()) widget()->clearFocus();
- };
+ }
signals:
-
void doubleClick(QMouseEvent *me);
void closeButtonPressed();
+
+private:
+ QColor
+ m_bgcolor; // overrides palette background color in paint event - Mac fix
+ std::string m_panelType;
+ bool m_isMaximizable;
+ bool m_isMaximized; // currently unused
+ bool m_multipleInstancesAllowed;
+ TPanelTitleBar *m_panelTitleBar;
+ QList<TPanel *> m_hiddenDockWidgets;
+ QByteArray m_currentRoomOldState;
+
+ // Room binding for custom panels
+ bool m_isRoomBound;
+ QString m_boundRoomName;
+ TPanelTitleBarButton *m_roomBindButton;
+
+ QColor getBGColor() const { return m_bgcolor; }
+ void setBGColor(const QColor &color) { m_bgcolor = color; }
};
//-----------------------------------------------------------------------------
-
class TPanelFactory {
- QString m_panelType;
- static QMap<QString, TPanelFactory *> &tableInstance();
+ Q_DISABLE_COPY(TPanelFactory)
public:
- TPanelFactory(QString panelType);
- ~TPanelFactory();
+ explicit TPanelFactory(const QString &panelType);
+ virtual ~TPanelFactory();
QString getPanelType() const { return m_panelType; }
virtual void initialize(TPanel *panel) = 0;
virtual TPanel *createPanel(QWidget *parent);
- static TPanel *createPanel(QWidget *parent, QString panelType);
+ static TPanel *createPanel(QWidget *parent, const QString &panelType);
+
+private:
+ static QMap<QString, TPanelFactory *> &tableInstance();
+ QString m_panelType;
};
//-----------------------------------------------------------------------------
diff --git a/toonz/sources/toonz/previewer.cpp b/toonz/sources/toonz/previewer.cpp
index 0902d9440..55287eb0b 100644
--- a/toonz/sources/toonz/previewer.cpp
+++ b/toonz/sources/toonz/previewer.cpp
@@ -58,6 +58,10 @@
#include "previewer.h"
+// C++ includes
+#include <memory>
+#include <utility>
+
//------------------------------------------------
/*! \class Previewer
@@ -97,8 +101,8 @@ so that the following getRaster() will forcibly recalculate the requested frame.
namespace {
bool suspendedRendering = false;
-Previewer *previewerInstance = 0;
-Previewer *previewerInstanceSC = 0;
+Previewer *previewerInstance = nullptr;
+Previewer *previewerInstanceSC = nullptr;
QTimer levelChangedTimer, fxChangedTimer, xsheetChangedTimer,
objectChangedTimer;
@@ -112,7 +116,13 @@ void buildNodeTreeDescription(std::string &desc, const TFxP &root);
// Qt's contains actually returns QRegion::intersected... I wonder why...
inline bool contains(const QRegion &region, const TRect &rect) {
- return QRegion(toQRect(rect)).subtracted(region).isEmpty();
+ const QRect qrect = toQRect(rect);
+
+ // Fast path: check if region's bounding rect contains the rect
+ if (!region.boundingRect().contains(qrect)) return false;
+
+ // Only do expensive operation if needed
+ return QRegion(qrect).subtracted(region).isEmpty();
}
} // namespace
@@ -179,25 +189,21 @@ public:
// on their own. The refreshFrame() method must be manually invoked if
// necessary.
void updateRenderSettings();
-
void updateAliases();
void updateAliasKeyword(const std::string &keyword);
-
// There are dependencies among the following updaters. Invoke them in the
// specified order.
void updateFrameRange();
void updateProgressBarStatus();
-
void updateCamera();
void updatePreviewRect(); // This is automatically invoked by refreshFrame()
// Use this method to re-render the passed frame. Infos specified with the
- // update* methods
- // are assumed correct.
+ // update* methods are assumed correct.
void refreshFrame(int frame);
void addRenderData(std::vector<TRenderer::RenderData> &datas, int frame);
- void addFramesToRenderQueue(const std::vector<int> frames);
+ void addFramesToRenderQueue(const std::vector<int> &frames);
// TRenderPort methods
void onRenderRasterStarted(const RenderData &renderData) override;
@@ -215,7 +221,10 @@ public:
public:
void saveFrame();
- bool doSaveRenderedFrames(const TFilePath fp);
+ bool doSaveRenderedFrames(const TFilePath &fp);
+
+private:
+ Q_DISABLE_COPY_MOVE(Imp);
};
//======================================================================================
@@ -262,10 +271,9 @@ Previewer::Imp::Imp(Previewer *owner)
Previewer::Imp::~Imp() {
m_renderer.removePort(this);
- // for(std::map<int, FrameInfo*>::iterator it=m_frames.begin();
- // it!=m_frames.end(); ++it)
- // delete it->second; //crash on exit! not a serious leak, Previewer is a
- // singleton
+ // for(auto &frame : m_frames)
+ // delete frame.second; //crash on exit! not a serious leak, Previewer is a
+ // singleton
}
//-----------------------------------------------------------------------------
@@ -334,10 +342,8 @@ void Previewer::Imp::updateCamera() {
m_cameraPos = cameraPos;
// All previously rendered frames must be erased
- std::map<int, FrameInfo>::iterator it;
- for (it = m_frames.begin(); it != m_frames.end(); ++it)
- TImageCache::instance()->remove(m_cachePrefix +
- std::to_string(it->first));
+ for (auto &[frame, info] : m_frames)
+ TImageCache::instance()->remove(m_cachePrefix + std::to_string(frame));
m_frames.clear();
}
@@ -359,10 +365,8 @@ void Previewer::Imp::updateRenderSettings() {
if (renderSettings != m_renderSettings) {
m_renderSettings = renderSettings;
- std::map<int, FrameInfo>::iterator it;
- for (it = m_frames.begin(); it != m_frames.end(); ++it)
- TImageCache::instance()->remove(m_cachePrefix +
- std::to_string(it->first));
+ for (auto &[frame, info] : m_frames)
+ TImageCache::instance()->remove(m_cachePrefix + std::to_string(frame));
m_frames.clear();
}
@@ -375,28 +379,25 @@ void Previewer::Imp::updateFrameRange() {
int newFrameCount =
TApp::instance()->getCurrentScene()->getScene()->getFrameCount();
- std::map<int, FrameInfo>::iterator it,
- jt = m_frames.lower_bound(newFrameCount);
- for (it = jt; it != m_frames.end(); ++it)
- // Release all associated cached images
- TImageCache::instance()->remove(m_cachePrefix + std::to_string(it->first));
+ auto it = m_frames.lower_bound(newFrameCount);
+ for (auto jt = it; jt != m_frames.end(); ++jt)
+ TImageCache::instance()->remove(m_cachePrefix + std::to_string(jt->first));
- m_frames.erase(jt, m_frames.end());
+ m_frames.erase(it, m_frames.end());
// Resize the progress bar status
- int i, oldSize = m_pbStatus.size();
+ int oldSize = int(m_pbStatus.size());
m_pbStatus.resize(newFrameCount);
- for (i = oldSize; i < newFrameCount; ++i)
+ for (int i = oldSize; i < newFrameCount; ++i)
m_pbStatus[i] = FlipSlider::PBFrameNotStarted;
}
//-----------------------------------------------------------------------------
void Previewer::Imp::updateProgressBarStatus() {
- unsigned int i, pbSize = m_pbStatus.size();
- std::map<int, FrameInfo>::iterator it;
- for (i = 0; i < pbSize; ++i) {
- it = m_frames.find(i);
+ int pbSize = int(m_pbStatus.size());
+ for (int i = 0; i < pbSize; ++i) {
+ auto it = m_frames.find(i);
m_pbStatus[i] = (it == m_frames.end()) ? FlipSlider::PBFrameNotStarted
: ::contains(it->second.m_renderedRegion, m_previewRect)
? FlipSlider::PBFrameFinished
@@ -412,46 +413,56 @@ void Previewer::Imp::updatePreviewRect() {
TRectD previewRectD;
/*--
- * SubCameraPreviewではない場合、Viewerの表示エリアに関係なく全画面で計算を行う
+ * If it is not a SubCameraPreview, calculations are performed
+ * in full screen regardless of the Viewer display area.
* --*/
- if (!m_subcamera)
+ if (!m_subcamera) {
previewRectD = m_renderArea;
- else {
- // Retrieve the view rects from each listener. Their union will form the
- // rect to be rendered.
- std::set<Previewer::Listener *>::iterator it;
- for (it = m_listeners.begin(); it != m_listeners.end(); ++it) {
- // Retrieve the listener's viewRect and add it to the preview rect
- previewRectD += (*it)->getPreviewRect();
+ } else {
+ // Use range‑based for loop for clarity
+ for (auto *listener : m_listeners) {
+ previewRectD += listener->getPreviewRect();
}
}
+ // Intersection with render area
previewRectD *= m_renderArea;
- int shrinkX = m_renderSettings.m_shrinkX;
- int shrinkY = m_renderSettings.m_shrinkY;
+ // Cache local variables to avoid multiple pointer accesses
+ const int shrinkX = m_renderSettings.m_shrinkX;
+ const int shrinkY = m_renderSettings.m_shrinkY;
+ const TPointD camPos = m_cameraPos;
+
+ // Compute offset once
+ previewRectD -= camPos;
+
+ // Scale transformation (Shrink)
+ if (shrinkX > 1) {
+ previewRectD.x0 /= shrinkX;
+ previewRectD.x1 /= shrinkX;
+ }
+ if (shrinkY > 1) {
+ previewRectD.y0 /= shrinkY;
+ previewRectD.y1 /= shrinkY;
+ }
- // Ensure that rect has the same pixel geometry as the preview camera
- previewRectD -= m_cameraPos;
- previewRectD.x0 = previewRectD.x0 / shrinkX;
- previewRectD.y0 = previewRectD.y0 / shrinkY;
- previewRectD.x1 = previewRectD.x1 / shrinkX;
- previewRectD.y1 = previewRectD.y1 / shrinkY;
+ // Coordinates relative to camera resolution
+ TPointD shrinkedRelPos((m_renderArea.x0 - camPos.x) / shrinkX,
+ (m_renderArea.y0 - camPos.y) / shrinkY);
- // Now, pass to m_cameraRes-relative coordinates
- TPointD shrinkedRelPos((m_renderArea.x0 - m_cameraPos.x) / shrinkX,
- (m_renderArea.y0 - m_cameraPos.y) / shrinkY);
previewRectD -= shrinkedRelPos;
- previewRectD.x0 = tfloor(previewRectD.x0);
- previewRectD.y0 = tfloor(previewRectD.y0);
- previewRectD.x1 = tceil(previewRectD.x1);
- previewRectD.y1 = tceil(previewRectD.y1);
+ // Direct rounding to int to avoid extra function calls
+ int x0 = tfloor(previewRectD.x0);
+ int y0 = tfloor(previewRectD.y0);
+ int x1 = tceil(previewRectD.x1);
+ int y1 = tceil(previewRectD.y1);
- m_previewRect = TRect(previewRectD.x0, previewRectD.y0, previewRectD.x1 - 1,
- previewRectD.y1 - 1);
+ // m_previewRect is the final pixel rectangle
+ m_previewRect = TRect(x0, y0, x1 - 1, y1 - 1);
- previewRectD += m_cameraPos + shrinkedRelPos;
+ // Restore global coordinates for the renderer
+ previewRectD = TRectD(x0, y0, x1, y1) + (camPos + shrinkedRelPos);
setRenderArea(previewRectD);
}
@@ -459,20 +470,19 @@ void Previewer::Imp::updatePreviewRect() {
//-----------------------------------------------------------------------------
void Previewer::Imp::updateAliases() {
- std::map<int, FrameInfo>::iterator it;
- for (it = m_frames.begin(); it != m_frames.end(); ++it) {
- TFxPair fxPair = buildSceneFx(it->first);
+ for (auto &[frame, info] : m_frames) {
+ TFxPair fxPair = buildSceneFx(frame);
std::string newAlias =
- fxPair.m_frameA ? fxPair.m_frameA->getAlias(it->first, m_renderSettings)
+ fxPair.m_frameA ? fxPair.m_frameA->getAlias(frame, m_renderSettings)
: "";
- newAlias = newAlias + (fxPair.m_frameB ? fxPair.m_frameB->getAlias(
- it->first, m_renderSettings)
- : "");
+ newAlias +=
+ (fxPair.m_frameB ? fxPair.m_frameB->getAlias(frame, m_renderSettings)
+ : "");
- if (newAlias != it->second.m_alias) {
+ if (newAlias != info.m_alias) {
// Clear the remaining frame infos
- it->second.m_renderedRegion = QRegion();
+ info.m_renderedRegion = QRegion();
}
}
}
@@ -480,24 +490,22 @@ void Previewer::Imp::updateAliases() {
//-----------------------------------------------------------------------------
void Previewer::Imp::updateAliasKeyword(const std::string &keyword) {
- std::map<int, FrameInfo>::iterator it;
- for (it = m_frames.begin(); it != m_frames.end(); ++it) {
- if (it->second.m_alias.find(keyword) != std::string::npos) {
- TFxPair fxPair = buildSceneFx(it->first);
- it->second.m_alias = fxPair.m_frameA ? fxPair.m_frameA->getAlias(
- it->first, m_renderSettings)
- : "";
- it->second.m_alias = it->second.m_alias +
- (fxPair.m_frameB ? fxPair.m_frameB->getAlias(
- it->first, m_renderSettings)
- : "");
+ for (auto &[frame, info] : m_frames) {
+ if (info.m_alias.find(keyword) != std::string::npos) {
+ TFxPair fxPair = buildSceneFx(frame);
+ info.m_alias = fxPair.m_frameA
+ ? fxPair.m_frameA->getAlias(frame, m_renderSettings)
+ : "";
+ info.m_alias +=
+ (fxPair.m_frameB ? fxPair.m_frameB->getAlias(frame, m_renderSettings)
+ : "");
// Clear the remaining frame infos
- it->second.m_renderedRegion = QRegion();
+ info.m_renderedRegion = QRegion();
- // No need to release the cached image... eventually, clear it
+ // Release the cached image; eventually clear it
TRasterImageP ri = TImageCache::instance()->get(
- m_cachePrefix + std::to_string(it->first), true);
+ m_cachePrefix + std::to_string(frame), true);
if (ri) ri->getRaster()->clear();
}
}
@@ -515,7 +523,7 @@ void Previewer::Imp::refreshFrame(int frame) {
if (m_previewRect.getLx() <= 0 || m_previewRect.getLy() <= 0) return;
// Retrieve the FrameInfo for passed frame
- std::map<int, FrameInfo>::iterator it = m_frames.find(frame);
+ auto it = m_frames.find(frame);
if (it != m_frames.end()) {
// In case the rect we would render is contained in the frame's rendered
// region, quit
@@ -528,12 +536,11 @@ void Previewer::Imp::refreshFrame(int frame) {
// Stop any frame's previously running render process
m_renderer.abortRendering(it->second.m_renderId);
} else {
- it = m_frames.insert(std::make_pair(frame, FrameInfo())).first;
+ it = m_frames.insert({frame, FrameInfo()}).first;
// In case the frame is not in the frame range, we add a temporary
- // supplement
- // to the progress bar.
- if (frame >= (int)m_pbStatus.size()) m_pbStatus.resize(frame + 1);
+ // supplement to the progress bar.
+ if (frame >= int(m_pbStatus.size())) m_pbStatus.resize(frame + 1);
}
// Build the TFxPair to be passed to TRenderer
@@ -543,8 +550,7 @@ void Previewer::Imp::refreshFrame(int frame) {
it->second.m_rectUnderRender = m_previewRect;
it->second.m_alias = fxPair.m_frameA->getAlias(frame, m_renderSettings);
if (fxPair.m_frameB)
- it->second.m_alias =
- it->second.m_alias + fxPair.m_frameB->getAlias(frame, m_renderSettings);
+ it->second.m_alias += fxPair.m_frameB->getAlias(frame, m_renderSettings);
// Retrieve the renderId of the rendering instance
it->second.m_renderId = m_renderer.nextRenderId();
@@ -562,7 +568,7 @@ void Previewer::Imp::refreshFrame(int frame) {
void Previewer::Imp::remove(int frame) {
// Search the frame among rendered ones
- std::map<int, FrameInfo>::iterator it = m_frames.find(frame);
+ auto it = m_frames.find(frame);
if (it != m_frames.end()) {
m_renderer.abortRendering(it->second.m_renderId);
m_frames.erase(frame);
@@ -578,9 +584,8 @@ void Previewer::Imp::remove() {
m_renderer.stopRendering(false);
// Remove all cached images
- std::map<int, FrameInfo>::iterator it;
- for (it = m_frames.begin(); it != m_frames.end(); ++it)
- TImageCache::instance()->remove(m_cachePrefix + std::to_string(it->first));
+ for (const auto &[frame, info] : m_frames)
+ TImageCache::instance()->remove(m_cachePrefix + std::to_string(frame));
m_frames.clear();
}
@@ -588,33 +593,25 @@ void Previewer::Imp::remove() {
//-----------------------------------------------------------------------------
inline void Previewer::Imp::notifyStarted(int frame) {
- std::set<Previewer::Listener *>::iterator it;
- for (it = m_listeners.begin(); it != m_listeners.end(); ++it)
- (*it)->onRenderStarted(frame);
+ for (auto *listener : m_listeners) listener->onRenderStarted(frame);
}
//-----------------------------------------------------------------------------
inline void Previewer::Imp::notifyCompleted(int frame) {
- std::set<Previewer::Listener *>::iterator it;
- for (it = m_listeners.begin(); it != m_listeners.end(); ++it)
- (*it)->onRenderCompleted(frame);
+ for (auto *listener : m_listeners) listener->onRenderCompleted(frame);
}
//-----------------------------------------------------------------------------
inline void Previewer::Imp::notifyFailed(int frame) {
- std::set<Previewer::Listener *>::iterator it;
- for (it = m_listeners.begin(); it != m_listeners.end(); ++it)
- (*it)->onRenderFailed(frame);
+ for (auto *listener : m_listeners) listener->onRenderFailed(frame);
}
//-----------------------------------------------------------------------------
inline void Previewer::Imp::notifyUpdate() {
- std::set<Previewer::Listener *>::iterator it;
- for (it = m_listeners.begin(); it != m_listeners.end(); ++it)
- (*it)->onPreviewUpdate();
+ for (auto *listener : m_listeners) listener->onPreviewUpdate();
}
//-----------------------------------------------------------------------------
@@ -633,7 +630,8 @@ void Previewer::Imp::doOnRenderRasterStarted(const RenderData &renderData) {
m_computingFrameCount++;
// Update the progress bar status
- if (frame < m_pbStatus.size()) m_pbStatus[frame] = FlipSlider::PBFrameStarted;
+ if (frame < int(m_pbStatus.size()))
+ m_pbStatus[frame] = FlipSlider::PBFrameStarted;
// Notify listeners
notifyStarted(frame);
@@ -684,7 +682,7 @@ void Previewer::Imp::doOnRenderRasterCompleted(const RenderData &renderData) {
m_computingFrameCount--;
// Find the render infos in the Previewer
- std::map<int, FrameInfo>::iterator it = m_frames.find(frame);
+ auto it = m_frames.find(frame);
if (it == m_frames.end()) return;
// Ensure that the render process id is the same
@@ -718,10 +716,8 @@ void Previewer::Imp::doOnRenderRasterCompleted(const RenderData &renderData) {
}
// Submit the image to the cache, for all cluster's frames
- unsigned int i, size = renderData.m_frames.size();
- for (i = 0; i < size; ++i) {
- int f = renderData.m_frames[i];
- std::map<int, FrameInfo>::iterator f_it = m_frames.find(f);
+ for (int f : renderData.m_frames) {
+ auto f_it = m_frames.find(f);
if (f_it == m_frames.end()) continue;
if (cachedRas) {
@@ -734,7 +730,7 @@ void Previewer::Imp::doOnRenderRasterCompleted(const RenderData &renderData) {
f_it->second.m_rectUnderRender = TRect();
// Update the progress bar status
- if (f < m_pbStatus.size()) m_pbStatus[f] = FlipSlider::PBFrameFinished;
+ if (f < int(m_pbStatus.size())) m_pbStatus[f] = FlipSlider::PBFrameFinished;
// Notify listeners
notifyCompleted(f);
@@ -756,9 +752,9 @@ void Previewer::Imp::onRenderFailure(const RenderData &renderData,
void Previewer::Imp::doOnRenderRasterFailed(const RenderData &renderData) {
m_computingFrameCount--;
- int frame = (int)renderData.m_frames[0];
+ int frame = renderData.m_frames[0];
- std::map<int, FrameInfo>::iterator it = m_frames.find(frame);
+ auto it = m_frames.find(frame);
if (it == m_frames.end()) return;
if (renderData.m_renderId != it->second.m_renderId) return;
@@ -767,7 +763,7 @@ void Previewer::Imp::doOnRenderRasterFailed(const RenderData &renderData) {
it->second.m_rectUnderRender = TRect();
// Update the progress bar status
- if (frame < m_pbStatus.size())
+ if (frame < int(m_pbStatus.size()))
m_pbStatus[frame] = FlipSlider::PBFrameNotStarted;
notifyCompleted(frame); // Completed!?
@@ -778,7 +774,7 @@ void Previewer::Imp::doOnRenderRasterFailed(const RenderData &renderData) {
namespace {
enum { eBegin, eIncrement, eEnd };
-static DVGui::ProgressDialog *Pd = 0;
+static DVGui::ProgressDialog *Pd = nullptr;
//-----------------------------------------------------------------------------
@@ -787,8 +783,10 @@ public:
int m_choice;
int m_val;
QString m_str;
- ProgressBarMessager(int choice, int val, const QString &str = "")
+
+ ProgressBarMessager(int choice, int val, const QString &str = {})
: m_choice(choice), m_val(val), m_str(str) {}
+
void onDeliver() override {
switch (m_choice) {
case eBegin:
@@ -803,16 +801,15 @@ public:
case eIncrement:
if (Pd->wasCanceled()) {
delete Pd;
- Pd = 0;
+ Pd = nullptr;
} else {
- // if (m_val==Pd->maximum()) Pd->hide();
Pd->setValue(m_val);
}
break;
case eEnd: {
DVGui::info(m_str);
delete Pd;
- Pd = 0;
+ Pd = nullptr;
} break;
default:
assert(false);
@@ -820,8 +817,11 @@ public:
}
TThread::Message *clone() const override {
- return new ProgressBarMessager(*this);
+ return new ProgressBarMessager(m_choice, m_val, m_str);
}
+
+private:
+ Q_DISABLE_COPY_MOVE(ProgressBarMessager);
};
} // namespace
@@ -829,7 +829,7 @@ public:
//-----------------------------------------------------------------------------
class SavePreviewedPopup final : public FileBrowserPopup {
- Previewer *m_p;
+ Previewer *m_p = nullptr;
public:
SavePreviewedPopup()
@@ -841,9 +841,11 @@ public:
bool execute() override {
if (m_selectedPaths.empty()) return false;
-
return m_p->doSaveRenderedFrames(*m_selectedPaths.begin());
}
+
+private:
+ Q_DISABLE_COPY_MOVE(SavePreviewedPopup);
};
//=============================================================================
@@ -856,7 +858,7 @@ bool Previewer::doSaveRenderedFrames(TFilePath fp) {
using namespace DVGui;
-bool Previewer::Imp::doSaveRenderedFrames(TFilePath fp) {
+bool Previewer::Imp::doSaveRenderedFrames(const TFilePath &fp) {
ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();
TOutputProperties *outputSettings =
scene->getProperties()->getOutputProperties();
@@ -866,11 +868,12 @@ bool Previewer::Imp::doSaveRenderedFrames(TFilePath fp) {
Tiio::Writer::getSupportedFormats(formats, true);
std::string ext = fp.getType();
- if (ext == "") {
+ if (ext.empty()) {
ext = outputSettings->getPath().getType();
- fp = fp.withType(ext);
+ // fp = fp.withType(ext); // not used? we'll reassign fp below
}
- if (fp.getName() == "") {
+ TFilePath localFp = fp;
+ if (localFp.getName().empty()) {
DVGui::warning(QObject::tr(
"The file name cannot be empty or contain any of the following "
"characters:(new line) \\ / : * ? \" |"));
@@ -878,49 +881,48 @@ bool Previewer::Imp::doSaveRenderedFrames(TFilePath fp) {
}
if (!formats.contains(QString::fromStdString(ext))) {
- DVGui::warning(QObject::tr("Unsopporter raster format, cannot save"));
+ DVGui::warning(QObject::tr("Unsupported raster format, cannot save"));
return false;
}
- if (fp.getWideName() == L"") fp = fp.withName(scene->getSceneName());
- if (TFileType::getInfo(fp) == TFileType::RASTER_IMAGE || ext == "pct" ||
- fp.getType() == "pic" || ext == "pict") // pct e' un formato"livello" (ha
- // i settings di quicktime) ma
- // fatto di diversi frames
- fp = fp.withFrame(TFrameId::EMPTY_FRAME);
+ if (localFp.getWideName().empty())
+ localFp = localFp.withName(scene->getSceneName());
+ if (TFileType::getInfo(localFp) == TFileType::RASTER_IMAGE || ext == "pct" ||
+ localFp.getType() == "pic" || ext == "pict")
+ localFp = localFp.withFrame(TFrameId::EMPTY_FRAME);
- fp = scene->decodeFilePath(fp);
- bool exists = TFileStatus(fp.getParentDir()).doesExist();
+ TFilePath decodedFp = scene->decodeFilePath(localFp);
+ bool exists = TFileStatus(decodedFp.getParentDir()).doesExist();
if (!exists) {
try {
- TFilePath parent = fp.getParentDir();
+ TFilePath parent = decodedFp.getParentDir();
TSystem::mkDir(parent);
DvDirModel::instance()->refreshFolder(parent.getParentDir());
} catch (TException &e) {
error(QObject::tr("Cannot create %1 : %2",
"Previewer warning %1:path %2:message")
- .arg(toQString(fp.getParentDir()))
+ .arg(toQString(decodedFp.getParentDir()))
.arg(QString(::to_string(e.getMessage()).c_str())));
return false;
} catch (...) {
error(QObject::tr("Cannot create %1", "Previewer warning %1:path")
- .arg(toQString(fp.getParentDir())));
+ .arg(toQString(decodedFp.getParentDir())));
return false;
}
}
- if (TSystem::doesExistFileOrLevel(fp)) {
- QString question(
+ if (TSystem::doesExistFileOrLevel(decodedFp)) {
+ QString question =
QObject::tr("File %1 already exists.\nDo you want to overwrite it?")
- .arg(toQString(fp)));
+ .arg(toQString(decodedFp));
int ret = DVGui::MsgBox(question, QObject::tr("Overwrite"),
QObject::tr("Cancel"), 0);
if (ret == 2) return false;
}
try {
- m_lw = TLevelWriterP(fp,
- outputSettings->getFileFormatProperties(fp.getType()));
+ m_lw =
+ TLevelWriterP(decodedFp, outputSettings->getFileFormatProperties(ext));
} catch (TImageException &e) {
error(QString::fromStdString(::to_string(e.getMessage())));
return false;
@@ -935,7 +937,7 @@ bool Previewer::Imp::doSaveRenderedFrames(TFilePath fp) {
TApp::instance()->getCurrentXsheet()->getXsheet()->getFrameCount())
.sendBlocking();
- QTimer::singleShot(50, m_owner, SLOT(saveFrame()));
+ QTimer::singleShot(50, m_owner, &Previewer::saveFrame);
return true;
}
@@ -949,16 +951,16 @@ void Previewer::Imp::saveFrame() {
assert(Pd);
- for (; m_currentFrameToSave <= frameCount; m_currentFrameToSave++) {
+ for (; m_currentFrameToSave <= frameCount; ++m_currentFrameToSave) {
ProgressBarMessager(eIncrement, m_currentFrameToSave).sendBlocking();
if (!Pd) break;
// Ensure that current frame actually have to be saved
- int currFrameToSave = m_currentFrameToSave - 1;
- std::map<int, FrameInfo>::iterator it = m_frames.find(currFrameToSave);
+ int currFrameToSave = m_currentFrameToSave - 1;
+ auto it = m_frames.find(currFrameToSave);
if (it == m_frames.end()) continue;
- if (m_pbStatus.size() < currFrameToSave ||
+ if (m_pbStatus.size() <= currFrameToSave ||
m_pbStatus[currFrameToSave] != FlipSlider::PBFrameFinished)
continue;
@@ -968,13 +970,12 @@ void Previewer::Imp::saveFrame() {
// Save the frame
TImageWriterP writer = m_lw->getFrameWriter(TFrameId(m_currentFrameToSave));
- bool failureOnSaving = false;
if (!writer) continue;
writer->save(img);
- savedFrames++;
- m_currentFrameToSave++;
- QTimer::singleShot(50, m_owner, SLOT(saveFrame()));
+ ++savedFrames;
+ ++m_currentFrameToSave;
+ QTimer::singleShot(50, m_owner, &Previewer::saveFrame);
return;
}
@@ -982,9 +983,9 @@ void Previewer::Imp::saveFrame() {
QString str =
QObject::tr("Saved %1 frames out of %2 in %3",
"Previewer %1:savedframes %2:framecount %3:filepath")
- .arg(QString(std::to_string(savedFrames).c_str()))
- .arg(QString(std::to_string(frameCount).c_str()))
- .arg(QString(::to_string(m_lw->getFilePath()).c_str()));
+ .arg(QString::number(savedFrames))
+ .arg(QString::number(frameCount))
+ .arg(toQString(m_lw->getFilePath()));
if (!Pd) str = QObject::tr("Canceled! ", "Previewer") + str;
@@ -1006,8 +1007,7 @@ void Previewer::Imp::addRenderData(std::vector<TRenderer::RenderData> &datas,
m_frames[frame].m_rectUnderRender = m_previewRect;
m_frames[frame].m_alias = fxPair.m_frameA->getAlias(frame, m_renderSettings);
if (fxPair.m_frameB)
- m_frames[frame].m_alias =
- m_frames[frame].m_alias +
+ m_frames[frame].m_alias +=
fxPair.m_frameB->getAlias(frame, m_renderSettings);
// Retrieve the renderId of the rendering instance
@@ -1018,67 +1018,65 @@ void Previewer::Imp::addRenderData(std::vector<TRenderer::RenderData> &datas,
TPassiveCacheManager::instance()->setContextName(m_frames[frame].m_renderId,
contextName);
- datas.push_back(TRenderer::RenderData(frame, m_renderSettings, fxPair));
+ datas.emplace_back(frame, m_renderSettings, fxPair);
}
//-----------------------------------------------------------------------------
-void Previewer::Imp::addFramesToRenderQueue(const std::vector<int> frames) {
+void Previewer::Imp::addFramesToRenderQueue(const std::vector<int> &frames) {
if (suspendedRendering) return;
// Build the region to render
updatePreviewRect();
if (m_previewRect.getLx() <= 0 || m_previewRect.getLy() <= 0) return;
- RenderDataVector *renderDatas = new RenderDataVector;
+ // Use unique_ptr for automatic cleanup in case of early return
+ auto renderDatas = std::make_unique<std::vector<TRenderer::RenderData>>();
- for (const auto &f : frames) {
- std::map<int, FrameInfo>::iterator it = m_frames.find(f);
+ for (int f : frames) {
+ auto it = m_frames.find(f);
if (it == m_frames.end()) {
- it = m_frames.insert(std::make_pair(f, FrameInfo())).first;
+ it = m_frames.insert({f, FrameInfo()}).first;
// In case the frame is not in the frame range, we add a temporary
- // supplement
- // to the progress bar.
- if (f >= (int)m_pbStatus.size()) m_pbStatus.resize(f + 1);
+ // supplement to the progress bar.
+ if (f >= int(m_pbStatus.size())) m_pbStatus.resize(f + 1);
addRenderData(*renderDatas, f);
- } else if (f < m_pbStatus.size() &&
+ } else if (f < int(m_pbStatus.size()) &&
m_pbStatus[f] == FlipSlider::PBFrameNotStarted) {
// In case the rect we would render is contained in the frame's rendered
- // region, quit
- if (::contains(it->second.m_renderedRegion, m_previewRect)) return;
+ // region, skip this frame
+ if (::contains(it->second.m_renderedRegion, m_previewRect)) continue;
// Then, check the m_previewRect against the frame's m_rectUnderRendering.
// Ensure that we're not re-launching the very same render.
- if (it->second.m_rectUnderRender == m_previewRect) return;
+ if (it->second.m_rectUnderRender == m_previewRect) continue;
// Stop any frame's previously running render process
m_renderer.abortRendering(it->second.m_renderId);
addRenderData(*renderDatas, f);
}
}
- // Finally, start rendering all frames which were not found in cache
- m_renderer.startRendering(renderDatas);
+ // Only start rendering if we have data to render
+ if (!renderDatas->empty()) {
+ // release() transfers ownership to m_renderer
+ m_renderer.startRendering(renderDatas.release());
+ }
+ // else: unique_ptr automatically deletes renderDatas on scope exit
}
//=============================================================================
// Previewer
//-----------------------------------------------------------------------------
-Previewer::Previewer(bool subcamera) : m_imp(new Imp(this)) {
+Previewer::Previewer(bool subcamera) : m_imp(std::make_unique<Imp>(this)) {
m_imp->m_subcamera = subcamera;
m_imp->m_cachePrefix = CACHEID + std::string(subcamera ? "SC" : "");
TApp *app = TApp::instance();
- bool ret = true;
-
- // ret = ret && connect(app->getPaletteController()->getCurrentPalette(),
- // SIGNAL(colorStyleChangedOnMouseRelease()),SLOT(onLevelChanged()));
- // ret = ret && connect(app->getPaletteController()->getCurrentPalette(),
- // SIGNAL(paletteChanged()), SLOT(onLevelChanged()));
- ret = ret && connect(app->getPaletteController()->getCurrentLevelPalette(),
- SIGNAL(colorStyleChangedOnMouseRelease()),
- SLOT(onLevelChanged()));
- ret = ret && connect(app->getPaletteController()->getCurrentLevelPalette(),
- SIGNAL(paletteChanged()), SLOT(onLevelChanged()));
+ connect(app->getPaletteController()->getCurrentLevelPalette(),
+ &TPaletteHandle::colorStyleChangedOnMouseRelease, this,
+ &Previewer::onLevelChanged);
+ connect(app->getPaletteController()->getCurrentLevelPalette(),
+ &TPaletteHandle::paletteChanged, this, &Previewer::onLevelChanged);
levelChangedTimer.setInterval(notificationDelay);
fxChangedTimer.setInterval(notificationDelay);
@@ -1089,34 +1087,28 @@ Previewer::Previewer(bool subcamera) : m_imp(new Imp(this)) {
xsheetChangedTimer.setSingleShot(true);
objectChangedTimer.setSingleShot(true);
- ret = ret && connect(app->getCurrentLevel(), SIGNAL(xshLevelChanged()),
- &levelChangedTimer, SLOT(start()));
- ret = ret && connect(app->getCurrentFx(), SIGNAL(fxChanged()),
- &fxChangedTimer, SLOT(start()));
- ret = ret && connect(app->getCurrentXsheet(), SIGNAL(xsheetChanged()),
- &xsheetChangedTimer, SLOT(start()));
- ret = ret && connect(app->getCurrentObject(), SIGNAL(objectChanged(bool)),
- &objectChangedTimer, SLOT(start()));
-
- ret = ret && connect(&levelChangedTimer, SIGNAL(timeout()), this,
- SLOT(onLevelChanged()));
- ret = ret &&
- connect(&fxChangedTimer, SIGNAL(timeout()), this, SLOT(onFxChanged()));
- ret = ret && connect(&xsheetChangedTimer, SIGNAL(timeout()), this,
- SLOT(onXsheetChanged()));
- ret = ret && connect(&objectChangedTimer, SIGNAL(timeout()), this,
- SLOT(onObjectChanged()));
+ connect(app->getCurrentLevel(), &TXshLevelHandle::xshLevelChanged, this,
+ [this]() { levelChangedTimer.start(); });
+ connect(app->getCurrentFx(), &TFxHandle::fxChanged, this,
+ [this]() { fxChangedTimer.start(); });
+ connect(app->getCurrentXsheet(), &TXsheetHandle::xsheetChanged, this,
+ [this]() { xsheetChangedTimer.start(); });
+ connect(app->getCurrentObject(), &TObjectHandle::objectChanged, this,
+ [this](bool) { objectChangedTimer.start(); });
+
+ connect(&levelChangedTimer, &QTimer::timeout, this,
+ &Previewer::onLevelChanged);
+ connect(&fxChangedTimer, &QTimer::timeout, this, &Previewer::onFxChanged);
+ connect(&xsheetChangedTimer, &QTimer::timeout, this,
+ &Previewer::onXsheetChanged);
+ connect(&objectChangedTimer, &QTimer::timeout, this,
+ &Previewer::onObjectChanged);
qRegisterMetaType<TRenderPort::RenderData>("TRenderPort::RenderData");
- ret = ret && connect(this, SIGNAL(startedFrame(TRenderPort::RenderData)),
- this, SLOT(onStartedFrame(TRenderPort::RenderData)));
-
- ret = ret && connect(this, SIGNAL(renderedFrame(TRenderPort::RenderData)),
- this, SLOT(onRenderedFrame(TRenderPort::RenderData)));
-
- ret = ret && connect(this, SIGNAL(failedFrame(TRenderPort::RenderData)), this,
- SLOT(onFailedFrame(TRenderPort::RenderData)));
+ connect(this, &Previewer::startedFrame, this, &Previewer::onStartedFrame);
+ connect(this, &Previewer::renderedFrame, this, &Previewer::onRenderedFrame);
+ connect(this, &Previewer::failedFrame, this, &Previewer::onFailedFrame);
// As a result of performing the connections above in the Previewer
// constructor, no instance()
@@ -1127,17 +1119,15 @@ Previewer::Previewer(bool subcamera) : m_imp(new Imp(this)) {
previewerInstanceSC = this;
else
previewerInstance = this;
-
- assert(ret);
}
//-----------------------------------------------------------------------------
-Previewer::~Previewer() {}
+Previewer::~Previewer() = default; // unique_ptr handles deletion
//-----------------------------------------------------------------------------
-//! Ritorna l'istanza del \b Previewer
+//! Returns the \b Previewer instance
Previewer *Previewer::instance(bool subcameraPreview) {
static Previewer _instance(false);
static Previewer _instanceSC(true);
@@ -1155,16 +1145,16 @@ std::vector<UCHAR> &Previewer::getProgressBarStatus() const {
void Previewer::addListener(Listener *listener) {
m_imp->m_listeners.insert(listener);
- connect(&listener->m_refreshTimer, SIGNAL(timeout()), this,
- SLOT(updateView()));
+ connect(&listener->m_refreshTimer, &QTimer::timeout, this,
+ &Previewer::updateView);
}
//-----------------------------------------------------------------------------
void Previewer::removeListener(Listener *listener) {
m_imp->m_listeners.erase(listener);
- disconnect(&listener->m_refreshTimer, SIGNAL(timeout()), this,
- SLOT(updateView()));
+ disconnect(&listener->m_refreshTimer, &QTimer::timeout, this,
+ &Previewer::updateView);
if (m_imp->m_listeners.empty()) {
m_imp->m_renderer.stopRendering(false);
@@ -1192,7 +1182,7 @@ void Previewer::saveRenderedFrames() {
return;
}
- static SavePreviewedPopup *savePopup = 0;
+ static SavePreviewedPopup *savePopup = nullptr;
if (!savePopup) savePopup = new SavePreviewedPopup;
savePopup->setPreview(this);
@@ -1207,7 +1197,7 @@ void Previewer::saveRenderedFrames() {
TFilePath name = outpath.withoutParentDir();
savePopup->setFilename(
- name.getName() == ""
+ name.getName().empty()
? name.withName(
TApp::instance()->getCurrentScene()->getScene()->getSceneName())
: name);
@@ -1223,9 +1213,9 @@ void Previewer::saveRenderedFrames() {
otherwise start calculating it */
TRasterP Previewer::getRaster(int frame, bool renderIfNeeded) const {
if (frame < 0) return TRasterP();
- std::map<int, Imp::FrameInfo>::iterator it = m_imp->m_frames.find(frame);
+ auto it = m_imp->m_frames.find(frame);
if (it != m_imp->m_frames.end()) {
- if (frame < m_imp->m_pbStatus.size()) {
+ if (frame < int(m_imp->m_pbStatus.size())) {
if (m_imp->m_pbStatus[frame] == FlipSlider::PBFrameFinished ||
!renderIfNeeded) {
std::string str = m_imp->m_cachePrefix + std::to_string(frame);
@@ -1265,24 +1255,23 @@ TRasterP Previewer::getRaster(int frame, bool renderIfNeeded) const {
//-----------------------------------------------------------------------------
-void Previewer::addFramesToRenderQueue(const std::vector<int> frames) const {
+void Previewer::addFramesToRenderQueue(const std::vector<int> &frames) const {
if (suspendedRendering) return;
m_imp->addFramesToRenderQueue(frames);
}
//-----------------------------------------------------------------------------
-//! Verifica se \b frame e' nella cache, cioe' se il frame e' disponibile
+//! Checks if \b frame is in cache, i.e., if the frame is available
bool Previewer::isFrameReady(int frame) const {
- if (frame < 0 || frame >= (int)m_imp->m_pbStatus.size()) return false;
-
+ if (frame < 0 || frame >= int(m_imp->m_pbStatus.size())) return false;
return m_imp->m_pbStatus[frame] == FlipSlider::PBFrameFinished;
}
//-----------------------------------------------------------------------------
void Previewer::clearAllUnfinishedFrames() {
- for (int f = 0; f < m_imp->m_pbStatus.size(); f++) {
+ for (int f = 0; f < int(m_imp->m_pbStatus.size()); ++f) {
if (m_imp->m_pbStatus[f] == FlipSlider::PBFrameStarted) {
m_imp->remove(f);
}
@@ -1302,8 +1291,7 @@ bool Previewer::isBusy() const {
//-----------------------------------------------------------------------------
-//! Richiama IMP::invalidateFrames(string aliasKeyframe) per aggiornare il frame
-//! \b fid.
+//! Calls IMP::invalidateFrames(string aliasKeyframe) to update frame \b fid.
void Previewer::onImageChange(TXshLevel *xl, const TFrameId &fid) {
TFilePath fp = xl->getPath().withFrame(fid);
std::string levelKeyword = ::to_string(fp);
@@ -1492,7 +1480,7 @@ void Previewer::onFailedFrame(TRenderPort::RenderData renderData) {
//! no
//! longer active.
//! NOTE: This method is currently static declared, since the Previewer must be
-//! be instanced only after a consistent scene has been initialized. This method
+//! instanced only after a consistent scene has been initialized. This method
//! is allowed to bypass such limitation.
void Previewer::suspendRendering(bool suspend) {
suspendedRendering = suspend;
diff --git a/toonz/sources/toonz/previewer.h b/toonz/sources/toonz/previewer.h
index 046ec3870..3b9a39e58 100644
--- a/toonz/sources/toonz/previewer.h
+++ b/toonz/sources/toonz/previewer.h
@@ -4,25 +4,20 @@
#define PREVIEWER_INCLUDED
#include <memory>
+#include <vector>
#include "traster.h"
#include "tfx.h"
-
#include "trenderer.h"
#include <QObject>
#include <QTimer>
-// forward declarations
+// Forward declarations
class TRenderSettings;
class TXshLevel;
class TFrameId;
class TFilePath;
-// class TRenderPort
-// {
-// class RenderData;
-// };
-// class TRenderPort::RenderData;
//=============================================================================
// Previewer
@@ -37,9 +32,8 @@ class Previewer final : public QObject, public TFxObserver {
Previewer(bool subcamera);
~Previewer();
- // not implemented
- Previewer(const Previewer &);
- void operator=(const Previewer &);
+ // Prohibit copying and moving
+ Q_DISABLE_COPY_MOVE(Previewer)
public:
class Listener {
@@ -47,34 +41,31 @@ public:
QTimer m_refreshTimer;
Listener();
- virtual ~Listener() {}
+ virtual ~Listener() = default;
void requestTimedRefresh();
virtual TRectD getPreviewRect() const = 0;
- virtual void onRenderStarted(int frame){};
- virtual void onRenderCompleted(int frame){};
- virtual void onRenderFailed(int frame){};
+ virtual void onRenderStarted(int frame) {}
+ virtual void onRenderCompleted(int frame) {}
+ virtual void onRenderFailed(int frame) {}
virtual void onPreviewUpdate() {}
};
public:
static Previewer *instance(bool subcameraPreview = false);
-
static void clearAll();
-
static void suspendRendering(bool suspend);
- void addListener(Listener *);
- void removeListener(Listener *);
+ void addListener(Listener *listener);
+ void removeListener(Listener *listener);
TRasterP getRaster(int frame, bool renderIfNeeded = true) const;
- void addFramesToRenderQueue(const std::vector<int> frames) const;
+ void addFramesToRenderQueue(const std::vector<int> &frames) const;
bool isFrameReady(int frame) const;
bool doSaveRenderedFrames(TFilePath fp);
-
bool isActive() const;
bool isBusy() const;
@@ -87,7 +78,6 @@ public:
void clear();
std::vector<UCHAR> &getProgressBarStatus() const;
-
void clearAllUnfinishedFrames();
private:
@@ -97,14 +87,12 @@ private:
void emitFailedFrame(const TRenderPort::RenderData &renderData);
signals:
-
void activedChanged();
void startedFrame(TRenderPort::RenderData renderData);
void renderedFrame(TRenderPort::RenderData renderData);
void failedFrame(TRenderPort::RenderData renderData);
public slots:
-
void saveFrame();
void saveRenderedFrames();
@@ -117,7 +105,6 @@ public slots:
void onObjectChanged();
protected slots:
-
void onStartedFrame(TRenderPort::RenderData renderData);
void onRenderedFrame(TRenderPort::RenderData renderData);
void onFailedFrame(TRenderPort::RenderData renderData);