OpenToonz - An open-source full-featured 2D animation creation software
C
Modernize code, fix memory leaks and dead stores
andeon34e6f0363cac
diff --git a/toonz/sources/include/toonz/scriptbinding_centerline_vectorizer.h b/toonz/sources/include/toonz/scriptbinding_centerline_vectorizer.hindex 638cc4245..ac5494537 100644--- a/toonz/sources/include/toonz/scriptbinding_centerline_vectorizer.h+++ b/toonz/sources/include/toonz/scriptbinding_centerline_vectorizer.h@@ -1,9 +1,9 @@#pragma once-#ifndef SCRIPTBINDING_CENTERLINE_VECTORIZER_H#define SCRIPTBINDING_CENTERLINE_VECTORIZER_H#include "toonz/scriptbinding.h"+#include <memory>class ToonzScene;class TXshSimpleLevel;@@ -12,11 +12,10 @@ namespace TScriptBinding {class DVAPI CenterlineVectorizer final : public Wrapper {Q_OBJECT- CenterlineConfiguration *m_parameters;+ std::unique_ptr<CenterlineConfiguration> m_parameters;public:CenterlineVectorizer();- ~CenterlineVectorizer();Q_INVOKABLE QScriptValue toString();WRAPPER_STD_METHODS(CenterlineVectorizer)@@ -58,7 +57,7 @@ public:void setEir(bool v);private:- QScriptValue vectorizeImage(const TImageP &src1, TPalette *palette);+ QScriptValue vectorizeImage(const TImageP &src, TPalette *palette);};} // namespace TScriptBindingdiff --git a/toonz/sources/include/toonz/scriptbinding_outline_vectorizer.h b/toonz/sources/include/toonz/scriptbinding_outline_vectorizer.hindex db95a5d86..8ebf0b6b9 100644--- a/toonz/sources/include/toonz/scriptbinding_outline_vectorizer.h+++ b/toonz/sources/include/toonz/scriptbinding_outline_vectorizer.h@@ -1,9 +1,9 @@#pragma once-#ifndef SCRIPTBINDING_OUTLINE_VECTORIZER_H#define SCRIPTBINDING_OUTLINE_VECTORIZER_H#include "toonz/scriptbinding.h"+#include <memory>class ToonzScene;class TXshSimpleLevel;@@ -12,11 +12,10 @@ namespace TScriptBinding {class DVAPI OutlineVectorizer final : public Wrapper {Q_OBJECT- NewOutlineConfiguration *m_parameters;+ std::unique_ptr<NewOutlineConfiguration> m_parameters;public:OutlineVectorizer();- ~OutlineVectorizer();Q_INVOKABLE QScriptValue toString();WRAPPER_STD_METHODS(OutlineVectorizer)diff --git a/toonz/sources/include/toonz/txsheet.h b/toonz/sources/include/toonz/txsheet.hindex 104dc455f..0458b07a8 100644--- a/toonz/sources/include/toonz/txsheet.h+++ b/toonz/sources/include/toonz/txsheet.h@@ -1,9 +1,9 @@#pragma once-#ifndef XSHEET_INCLUDED#define XSHEET_INCLUDED#include <memory>+#include <set>// TnzCore includes#include "traster.h"@@ -17,9 +17,6 @@#include "cellposition.h"-// STD includes-#include <set>-#undef DVAPI#undef DVVAR#ifdef TOONZLIB_EXPORTS@@ -54,6 +51,7 @@ class Orientation;class TXsheetColumnChangeObserver;class ExpressionReferenceMonitor;class NavigationTags;+class TSoundOutputDevice;//=============================================================================@@ -149,20 +147,17 @@ public:};private:- TSoundOutputDevice *m_player;+ std::unique_ptr<TSoundOutputDevice>+ m_player; //!< Smart pointer – automatic cleanup- /*! \struct TXsheet::TXsheetImp- The TXsheetImp struct provides all objects necessary to define the \b TXsheet- class.-*/struct TXsheetImp;std::unique_ptr<TXsheetImp> m_imp;- TXshNoteSet *m_notes;- SoundProperties *m_soundProperties;- NavigationTags *m_navigationTags;+ std::unique_ptr<TXshNoteSet> m_notes;+ std::unique_ptr<SoundProperties> m_soundProperties;+ std::unique_ptr<NavigationTags> m_navigationTags;int m_cameraColumnIndex;- TXshColumn *m_cameraColumn;+ TXshColumnP m_cameraColumn; //!< Smart pointer – ref‑countedTXsheetColumnChangeObserver *m_observer;@@ -195,7 +190,6 @@ public:\sa setCell(), getCells(), setCells()*/const TXshCell &getCell(int row, int col) const;-const TXshCell &getCell(const CellPosition &pos) const;bool setCell(int row, int col, const TXshCell &cell);@@ -440,9 +434,9 @@ frame duplication.// customized exposeLevel used from LoadLevel commandint exposeLevel(int row, int col, TXshLevel *xl, std::vector<TFrameId> &fIds_,- TFrameId xFrom = TFrameId(), TFrameId xTo = TFrameId(),- int step = -1, int inc = -1, int frameCount = -1,- bool doesFileActuallyExist = true);+ const TFrameId &xFrom = TFrameId(),+ const TFrameId &xTo = TFrameId(), int step = -1, int inc = -1,+ int frameCount = -1, bool doesFileActuallyExist = true);/*! Exposes level \b \e xl \b \e fids in xsheet starting from cell identified* by \b \e row and \b \e col.@@ -519,7 +513,7 @@ in TXsheetImp.#endifvoid scrub(int frame, bool isPreview = false);void stopScrub();- void play(TSoundTrackP soundtrack, int s0, int s1, bool loop);+ void play(const TSoundTrackP &soundtrack, int s0, int s1, bool loop);/*! Returns a pointer to object \b FxDag contained in \b TXsheetImp, thisobject@@ -544,7 +538,7 @@ in TXsheetImp.*/void setScene(ToonzScene *scene);- TXshNoteSet *getNotes() const { return m_notes; }+ TXshNoteSet *getNotes() const { return m_notes.get(); }//! Returns true if the \b cellCandidate creates a circular reference.//! A circular reference is obtained when \b cellCandidate is a subXsheet cell@@ -579,10 +573,10 @@ in TXsheetImp.void notify(const TXsheetColumnChange &change);void notifyFxAdded(const std::vector<TFx *> &fxs);- void notifyStageObjectAdded(const TStageObjectId id);+ void notifyStageObjectAdded(const TStageObjectId &id);bool isReferenceManagementIgnored(TDoubleParam *);- NavigationTags *getNavigationTags() const { return m_navigationTags; }+ NavigationTags *getNavigationTags() const { return m_navigationTags.get(); }bool isFrameTagged(int frame) const;void toggleTaggedFrame(int frame);@@ -590,9 +584,9 @@ protected:bool checkCircularReferences(TXsheet *childCandidate);private:- // Not copiable- TXsheet(const TXsheet &);- TXsheet &operator=(const TXsheet &);+ // Not copyable+ TXsheet(const TXsheet &) = delete;+ TXsheet &operator=(const TXsheet &) = delete;/*! Return column in index if exists, otherwise create a new column;if column exist and is empty check \b isSoundColumn and return right type.diff --git a/toonz/sources/include/toonz/txshsimplelevel.h b/toonz/sources/include/toonz/txshsimplelevel.hindex bdccc74d8..e730b7848 100644--- a/toonz/sources/include/toonz/txshsimplelevel.h+++ b/toonz/sources/include/toonz/txshsimplelevel.h@@ -17,6 +17,7 @@// TnzCore includes#include "traster.h"#include "trasterimage.h"+#include "tpalette.h" // for TPaletteP// Qt includes#include <QObject>@@ -345,7 +346,7 @@ private:std::unique_ptr<LevelProperties> m_properties;std::unique_ptr<TContentHistory> m_contentHistory;- TPalette *m_palette;+ TPaletteP m_palette;FramesSet m_frames;diff --git a/toonz/sources/include/toonzqt/dvdialog.h b/toonz/sources/include/toonzqt/dvdialog.hindex 5917efd42..3f20d183c 100644--- a/toonz/sources/include/toonzqt/dvdialog.h+++ b/toonz/sources/include/toonzqt/dvdialog.h@@ -51,29 +51,27 @@ class MessageAndCheckboxDialog;void DVAPI MsgBoxInPopup(MsgType type, const QString &text);-// ATTENZIONE: Valore di ritorno-// 0 = l'utente ha chiuso la finestra (dovrebbe corrispondere ad un cancel o ad-// un NO) - closed window-// 1 = primo bottone da sx premuto - first button selected-// 2 = secondo bottone da sx premuto - second button-// 3 = terzo bottone da sx premuto - third button-// 4 = fourth button+// ATTENTION: Return values+// 0 = user closed the window (should correspond to cancel or NO) - closed+// window 1 = first button from left pressed - first button selected 2 = second+// button from left pressed - second button 3 = third button from left pressed -+// third button 4 = fourth buttonint DVAPI MsgBox(MsgType type, const QString &text,const std::vector<QString> &buttons,int defaultButtonIndex = 0, QWidget *parent = 0);-// QUESTION: due bottoni user defined+// QUESTION: two user-defined buttonsint DVAPI MsgBox(const QString &text, const QString &button1,const QString &button2, int defaultButtonIndex = 0,QWidget *parent = 0);-// QUESTION: tre bottoni user defined+// QUESTION: three user-defined buttonsint DVAPI MsgBox(const QString &text, const QString &button1,const QString &button2, const QString &button3,int defaultButtonIndex = 0, QWidget *parent = 0);-// QUESTION: four botton user defined+// QUESTION: four user-defined buttonsint DVAPI MsgBox(const QString &text, const QString &button1,const QString &button2, const QString &button3,const QString &button4, int defaultButtonIndex = 0,@@ -88,9 +86,6 @@ MessageAndCheckboxDialog DVAPI *createMsgandCheckbox(const QStringList &buttons, int defaultButtonIndex,Qt::CheckState defaultCheckBoxState, QWidget *parent = 0);-// void DVAPI error(const QString &msg);-// void DVAPI info(const QString &msg);-//-----------------------------------------------------------------------------QString DVAPI getText(const QString &title, const QString &label,@@ -168,9 +163,6 @@ class DVAPI Dialog : public QDialog {bool m_hasButton;QString m_name;int m_currentScreen = -1;- // gmt. rendo m_buttonLayout protected per ovviare ad un problema- // sull'addButtonBarWidget(). cfr filebrowserpopup.cpp.- // Dobbiamo discutere di Dialog.protected:QHBoxLayout *m_buttonLayout;diff --git a/toonz/sources/include/toonzqt/expressionfield.h b/toonz/sources/include/toonzqt/expressionfield.hindex f0787be12..6a93a17b2 100644--- a/toonz/sources/include/toonzqt/expressionfield.h+++ b/toonz/sources/include/toonzqt/expressionfield.h@@ -6,6 +6,7 @@#include "tgrammar.h"#include <QWidget>#include <QTextEdit>+#include <memory> // for std::unique_ptr#undef DVAPI#undef DVVAR@@ -42,7 +43,7 @@ class DVAPI ExpressionField final : public QTextEdit {const TSyntax::Grammar *m_grammar;class SyntaxHighlighter;- SyntaxHighlighter *m_syntaxHighlighter;+ std::unique_ptr<SyntaxHighlighter> m_syntaxHighlighter;QListView *m_completerPopup;int m_completerStartPos;@@ -86,4 +87,4 @@ signals:} // namespace DVGui//------------------------------------------------------------------------------#endif // FILEFIELD_H+#endif // EXPRESSIONFIELD_Hdiff --git a/toonz/sources/include/toonzqt/flipconsole.h b/toonz/sources/include/toonzqt/flipconsole.hindex b70429ddd..16a240493 100644--- a/toonz/sources/include/toonzqt/flipconsole.h+++ b/toonz/sources/include/toonzqt/flipconsole.h@@ -51,8 +51,8 @@ class TFrameHandle;class PlaybackExecutor final : public QThread {Q_OBJECT- int m_fps;- bool m_abort;+ int m_fps = 25;+ bool m_abort = false;QElapsedTimer m_timer;public:@@ -103,8 +103,14 @@ class FlipSlider final : public QAbstractSlider {Q_PROPERTY(QColor startedColor READ getStartedColor WRITE setStartedColor)Q_PROPERTY(QColor finishedColor READ getFinishedColor WRITE setFinishedColor)- bool m_enabled;- const std::vector<UCHAR> *m_progressBarStatus;+ bool m_enabled = false;+ const std::vector<UCHAR> *m_progressBarStatus = nullptr;++ // Disable copy (as the pointer is unowned)+ FlipSlider(const FlipSlider &) = delete;+ FlipSlider &operator=(const FlipSlider &) = delete;+ FlipSlider(FlipSlider &&) = delete;+ FlipSlider &operator=(FlipSlider &&) = delete;public:enum { PBFrameNotStarted, PBFrameStarted, PBFrameFinished };diff --git a/toonz/sources/include/toonzqt/rasterimagedata.h b/toonz/sources/include/toonzqt/rasterimagedata.hindex 160f40b0d..343a07802 100644--- a/toonz/sources/include/toonzqt/rasterimagedata.h+++ b/toonz/sources/include/toonzqt/rasterimagedata.h@@ -41,7 +41,7 @@ protected:public:RasterImageData();- ~RasterImageData();+ ~RasterImageData() override;virtual void setData(const TRasterP &copiedRaster, const TPaletteP &palette,double dpiX, double dpiY, const TDimension &dim,@@ -70,7 +70,7 @@ public://===================================================================// ToonzImageData//--------------------------------------------------------------------/*-- SelectionToolで選択した画像のデータ --*/+/*-- Data for images selected with SelectionTool --*/class DVAPI ToonzImageData final : public RasterImageData {TRasterCM32P m_copiedRaster;TPaletteP m_palette;@@ -80,7 +80,8 @@ class DVAPI ToonzImageData final : public RasterImageData {public:ToonzImageData();ToonzImageData(const ToonzImageData &);- ~ToonzImageData();+ ~ToonzImageData() override;+// data <- floating ti;void setData(const TRasterP &copiedRaster, const TPaletteP &palette,double dpiX, double dpiY, const TDimension &dim,@@ -113,7 +114,7 @@ class DVAPI FullColorImageData final : public RasterImageData {public:FullColorImageData();FullColorImageData(const FullColorImageData &);- ~FullColorImageData();+ ~FullColorImageData() override;// data <- floating ti;void setData(const TRasterP &copiedRaster, const TPaletteP &palette,diff --git a/toonz/sources/toonzlib/scriptbinding_centerline_vectorizer.cpp b/toonz/sources/toonzlib/scriptbinding_centerline_vectorizer.cppindex 8ad805bd8..55c664835 100644--- a/toonz/sources/toonzlib/scriptbinding_centerline_vectorizer.cpp+++ b/toonz/sources/toonzlib/scriptbinding_centerline_vectorizer.cpp@@ -8,24 +8,23 @@#include "toonz/Naa2TlvConverter.h"#include "tpalette.h"#include "ttoonzimage.h"+#include <memory> // for std::unique_ptr, std::make_uniquenamespace TScriptBinding {-CenterlineVectorizer::CenterlineVectorizer() {- m_parameters = new CenterlineConfiguration();-}--CenterlineVectorizer::~CenterlineVectorizer() { delete m_parameters; }-+//----------------------------------------------------------+CenterlineVectorizer::CenterlineVectorizer()+ : m_parameters(std::make_unique<CenterlineConfiguration>()) {}+//----------------------------------------------------------QScriptValue CenterlineVectorizer::toString() {return "Centerline Vectorizer";}-+//----------------------------------------------------------QScriptValue CenterlineVectorizer::ctor(QScriptContext *context,QScriptEngine *engine) {return create(engine, new CenterlineVectorizer());}-+//----------------------------------------------------------QScriptValue CenterlineVectorizer::vectorizeImage(const TImageP &src,TPalette *palette) {VectorizerCore vc;@@ -33,6 +32,7 @@ QScriptValue CenterlineVectorizer::vectorizeImage(const TImageP &src,double factor = Stage::inch;double dpix = factor / 72, dpiy = factor / 72;TPointD center;+if (TRasterImageP ri = src) {ri->getDpi(dpix, dpiy);center = ri->getRaster()->getCenterD();@@ -42,27 +42,28 @@ QScriptValue CenterlineVectorizer::vectorizeImage(const TImageP &src,} else {return context()->throwError(QObject::tr("Vectorization failed"));}+if (dpix != 0.0 && dpiy != 0.0) dpiAff = TScale(factor / dpix, factor / dpiy);- factor = norm(dpiAff * TPointD(1, 0));+ factor = norm(dpiAff * TPointD(1, 0));m_parameters->m_affine = dpiAff * TTranslation(-center);m_parameters->m_thickScale = factor;- palette->addRef(); // if there are no other references the vectorize() method- // below can destroy the palette- // BEFORE assigning it to the vector image- TVectorImageP vi = vc.vectorize(src, *m_parameters, palette);- vi->setPalette(palette);- palette->release();+ // Hold the palette during vectorization – TPaletteP manages refcount+ TPaletteP paletteHolder = palette;+ TVectorImageP vi =+ vc.vectorize(src, *m_parameters, paletteHolder.getPointer());+ vi->setPalette(paletteHolder.getPointer());return engine()->newQObject(new Image(vi), QScriptEngine::AutoOwnership);}-+//----------------------------------------------------------QScriptValue CenterlineVectorizer::vectorize(QScriptValue arg) {Level *level = qscriptvalue_cast<Level *>(arg);Image *img = qscriptvalue_cast<Image *>(arg);QString type;- TPalette *palette = 0;+ TPaletteP palette;+if (level) {type = level->getType();if (type != "Raster" && type != "ToonzRaster")@@ -70,7 +71,7 @@ QScriptValue CenterlineVectorizer::vectorize(QScriptValue arg) {if (level->getFrameCount() <= 0)return context()->throwError(tr("Can't vectorize a level with no frames"));- palette = level->getSimpleLevel()->getPalette();+ palette = level->getSimpleLevel()->getPalette(); // may be null} else if (img) {type = img->getType();if (type != "Raster" && type != "ToonzRaster")@@ -83,9 +84,12 @@ QScriptValue CenterlineVectorizer::vectorize(QScriptValue arg) {tr("Bad argument (%1): should be an Image or a Level").arg(arg.toString()));}- if (palette == 0) palette = new TPalette();++ // If no palette was provided, create a new one.+ if (!palette) palette = new TPalette();+if (img) {- return vectorizeImage(img->getImg(), palette);+ return vectorizeImage(img->getImg(), palette.getPointer());} else if (level) {QScriptValue newLevel = create(engine(), new Level());QList<TFrameId> fids;@@ -94,9 +98,9 @@ QScriptValue CenterlineVectorizer::vectorize(QScriptValue arg) {TImageP srcImg = level->getImg(fid);if (srcImg && (srcImg->getType() == TImage::RASTER ||srcImg->getType() == TImage::TOONZ_RASTER)) {- QScriptValue newFrame = vectorizeImage(srcImg, palette);+ QScriptValue newFrame = vectorizeImage(srcImg, palette.getPointer());if (newFrame.isError()) {- return newFrame;+ return newFrame; // palette is automatically cleaned up}QScriptValueList args;args << QString::fromStdString(fid.expand()) << newFrame;@@ -104,70 +108,62 @@ QScriptValue CenterlineVectorizer::vectorize(QScriptValue arg) {}}return newLevel;- } else {- // should never happen- return QScriptValue();}+ // Unreachable+ return QScriptValue();}-+//----------------------------------------------------------int CenterlineVectorizer::getThreshold() const {return m_parameters->m_threshold / 25;}-void CenterlineVectorizer::setThreshold(int v) {m_parameters->m_threshold = v * 25;}-+//----------------------------------------------------------int CenterlineVectorizer::getAccuracy() const {return 10 - m_parameters->m_penalty;}-void CenterlineVectorizer::setAccuracy(int v) {m_parameters->m_penalty = 10 - v;}-+//----------------------------------------------------------int CenterlineVectorizer::getDespeckling() const {return m_parameters->m_despeckling / 2;}-void CenterlineVectorizer::setDespeckling(int v) {m_parameters->m_despeckling = v * 2;}-+//----------------------------------------------------------double CenterlineVectorizer::getMaxThickness() const {return m_parameters->m_maxThickness * 2.0;}-void CenterlineVectorizer::setMaxThickness(double v) {m_parameters->m_maxThickness = v / 2.0;}-+//----------------------------------------------------------double CenterlineVectorizer::getThicknessCalibration() const {return m_parameters->m_thicknessRatio;}-void CenterlineVectorizer::setThicknessCalibration(double v) {m_parameters->m_thicknessRatio = v;}-+//----------------------------------------------------------bool CenterlineVectorizer::getPreservePaintedAreas() const {return !m_parameters->m_leaveUnpainted;}-void CenterlineVectorizer::setPreservePaintedAreas(bool v) {m_parameters->m_leaveUnpainted = !v;}-+//----------------------------------------------------------bool CenterlineVectorizer::getAddBorder() const {return m_parameters->m_makeFrame;}-void CenterlineVectorizer::setAddBorder(bool v) {m_parameters->m_makeFrame = v;}-+//----------------------------------------------------------bool CenterlineVectorizer::getEir() const { return m_parameters->m_naaSource; }-void CenterlineVectorizer::setEir(bool v) { m_parameters->m_naaSource = v; }+//----------------------------------------------------------} // namespace TScriptBindingdiff --git a/toonz/sources/toonzlib/scriptbinding_outline_vectorizer.cpp b/toonz/sources/toonzlib/scriptbinding_outline_vectorizer.cppindex a470b10f8..500e6a7e5 100644--- a/toonz/sources/toonzlib/scriptbinding_outline_vectorizer.cpp+++ b/toonz/sources/toonzlib/scriptbinding_outline_vectorizer.cpp@@ -6,22 +6,24 @@#include "toonz/stage.h"#include "ttoonzimage.h"#include "tpalette.h"+#include <memory> // for std::unique_ptr, std::make_uniquenamespace TScriptBinding {-OutlineVectorizer::OutlineVectorizer() {- m_parameters = new NewOutlineConfiguration();+//----------------------------------------------------------+OutlineVectorizer::OutlineVectorizer()+ : m_parameters(std::make_unique<NewOutlineConfiguration>()) {+ // Initialize transparent color to a safe default (fully transparent black)+ m_parameters->m_transparentColor = TPixel32::Transparent;}--OutlineVectorizer::~OutlineVectorizer() { delete m_parameters; }-+//----------------------------------------------------------QScriptValue OutlineVectorizer::toString() { return "Outline Vectorizer"; }-+//----------------------------------------------------------QScriptValue OutlineVectorizer::ctor(QScriptContext *context,QScriptEngine *engine) {return create(engine, new OutlineVectorizer());}-+//----------------------------------------------------------static QScriptValue vectorizeImage(QScriptContext *context,QScriptEngine *engine, const TImageP &src,TPalette *palette,@@ -31,6 +33,7 @@ static QScriptValue vectorizeImage(QScriptContext *context,double factor = Stage::inch;double dpix = factor / 72, dpiy = factor / 72;TPointD center;+if (TRasterImageP ri = src) {ri->getDpi(dpix, dpiy);center = ri->getRaster()->getCenterD();@@ -40,22 +43,27 @@ static QScriptValue vectorizeImage(QScriptContext *context,} else {return context->throwError(QObject::tr("Vectorization failed"));}+if (dpix != 0.0 && dpiy != 0.0) dpiAff = TScale(factor / dpix, factor / dpiy);- factor = norm(dpiAff * TPointD(1, 0));+ factor = norm(dpiAff * TPointD(1, 0));parameters->m_affine = dpiAff * TTranslation(-center);parameters->m_thickScale = factor;- TVectorImageP vi = vc.vectorize(src, *parameters, palette);- vi->setPalette(palette);+ // Hold the palette during vectorization – TPaletteP manages refcount+ TPaletteP paletteHolder = palette;+ TVectorImageP vi = vc.vectorize(src, *parameters, paletteHolder.getPointer());+ vi->setPalette(paletteHolder.getPointer());+return engine->newQObject(new Image(vi), QScriptEngine::AutoOwnership);}-+//----------------------------------------------------------QScriptValue OutlineVectorizer::vectorize(QScriptValue arg) {Level *level = qscriptvalue_cast<Level *>(arg);Image *img = qscriptvalue_cast<Image *>(arg);QString type;- TPalette *palette = 0;+ TPaletteP palette; // Smart pointer – automatic release+if (level) {type = level->getType();if (type != "Raster" && type != "ToonzRaster")@@ -63,7 +71,7 @@ QScriptValue OutlineVectorizer::vectorize(QScriptValue arg) {if (level->getFrameCount() <= 0)return context()->throwError(tr("Can't vectorize a level with no frames"));- palette = level->getSimpleLevel()->getPalette();+ palette = level->getSimpleLevel()->getPalette(); // may be null} else if (img) {type = img->getType();if (type != "Raster" && type != "ToonzRaster")@@ -76,10 +84,13 @@ QScriptValue OutlineVectorizer::vectorize(QScriptValue arg) {tr("Bad argument (%1): should be an Image or a Level").arg(arg.toString()));}- if (palette == 0) palette = new TPalette();++ // If no palette was provided, create a new one.+ if (!palette) palette = new TPalette();+if (img) {- return vectorizeImage(context(), engine(), img->getImg(), palette,- m_parameters);+ return vectorizeImage(context(), engine(), img->getImg(),+ palette.getPointer(), m_parameters.get());} else if (level) {QScriptValue newLevel = create(engine(), new Level());QList<TFrameId> fids;@@ -89,9 +100,10 @@ QScriptValue OutlineVectorizer::vectorize(QScriptValue arg) {if (srcImg && (srcImg->getType() == TImage::RASTER ||srcImg->getType() == TImage::TOONZ_RASTER)) {QScriptValue newFrame =- vectorizeImage(context(), engine(), srcImg, palette, m_parameters);+ vectorizeImage(context(), engine(), srcImg, palette.getPointer(),+ m_parameters.get());if (newFrame.isError()) {- return newFrame;+ return newFrame; // palette is automatically cleaned up}QScriptValueList args;args << QString::fromStdString(fid.expand()) << newFrame;@@ -99,72 +111,66 @@ QScriptValue OutlineVectorizer::vectorize(QScriptValue arg) {}}return newLevel;- } else {- // should never happen- return QScriptValue();}-}+ // Unreachable+ return QScriptValue();+}+//----------------------------------------------------------int OutlineVectorizer::getAccuracy() const {return (5.0 - m_parameters->m_mergeTol) * 2.0;}-void OutlineVectorizer::setAccuracy(int v) {m_parameters->m_mergeTol = 5.0 - v * 0.5;}-+//----------------------------------------------------------int OutlineVectorizer::getDespeckling() const {return m_parameters->m_despeckling;}-void OutlineVectorizer::setDespeckling(int v) {m_parameters->m_despeckling = v;}-+//----------------------------------------------------------bool OutlineVectorizer::getPreservePaintedAreas() const {return !m_parameters->m_leaveUnpainted;}-void OutlineVectorizer::setPreservePaintedAreas(bool v) {m_parameters->m_leaveUnpainted = !v;}-+//----------------------------------------------------------double OutlineVectorizer::getCornerAdherence() const {return m_parameters->m_adherenceTol * 100.0;}-void OutlineVectorizer::setCornerAdherence(double v) {m_parameters->m_adherenceTol = 0.01 * v;}-+//----------------------------------------------------------double OutlineVectorizer::getCornerAngle() const {return m_parameters->m_angleTol * 180.0;}-void OutlineVectorizer::setCornerAngle(double v) {m_parameters->m_angleTol = v / 180.0;}-+//----------------------------------------------------------double OutlineVectorizer::getCornerCurveRadius() const {return m_parameters->m_relativeTol * 100;}-void OutlineVectorizer::setCornerCurveRadius(double v) {m_parameters->m_relativeTol = 0.01 * v;}-+//----------------------------------------------------------int OutlineVectorizer::getMaxColors() const {return m_parameters->m_maxColors;}-void OutlineVectorizer::setMaxColors(int v) { m_parameters->m_maxColors = v; }-+//----------------------------------------------------------QString OutlineVectorizer::getTransparentColor() const {+ // TPixel32 is now always initialized (see constructor)TPixel32 c = m_parameters->m_transparentColor;QColor color(c.r, c.g, c.b, c.m);return color.name();}-+//----------------------------------------------------------void OutlineVectorizer::setTransparentColor(const QString &colorName) {QColor color;color.setNamedColor(colorName);@@ -172,14 +178,16 @@ void OutlineVectorizer::setTransparentColor(const QString &colorName) {m_parameters->m_transparentColor =TPixel32(color.red(), color.green(), color.blue(), color.alpha());} else {- context()->throwError(tr("Invalid color : ").arg(colorName));+ // Throw error and abort+ context()->throwError(tr("Invalid color: %1").arg(colorName));+ return;}}-+//----------------------------------------------------------int OutlineVectorizer::getToneThreshold() const {return m_parameters->m_toneTol;}-void OutlineVectorizer::setToneThreshold(int v) { m_parameters->m_toneTol = v; }+//----------------------------------------------------------} // namespace TScriptBindingdiff --git a/toonz/sources/toonzlib/txsheet.cpp b/toonz/sources/toonzlib/txsheet.cppindex 17b41492b..704b98918 100644--- a/toonz/sources/toonzlib/txsheet.cpp+++ b/toonz/sources/toonzlib/txsheet.cpp@@ -40,6 +40,9 @@// STD includes#include <set>+#include <memory>+#include <vector>+#include <cmath> // for std::roundusing namespace std;@@ -49,7 +52,7 @@ DEFINE_CLASS_CODE(TXsheet, 18)namespace {//------------------------------------------------------------------------------string getColumnDefaultName(TXsheet *xsh, int col, QString oldName) {+string getColumnDefaultName(TXsheet *xsh, int col, const QString &oldName) {TXshColumn *column = xsh->getColumn(col);if (column) {TXshLevelColumn *lc = column->getLevelColumn();@@ -91,8 +94,12 @@ struct TXsheet::TXsheetImp {unsigned long m_id; //!< The xsheet instance's unique identifierTColumnSetT<TXshColumn> m_columnSet;- TStageObjectTree *m_pegTree;- FxDag *m_fxDag;++ std::unique_ptr<TStageObjectTree>+ m_pegTree; //!< Smart pointer – automatic cleanup+ std::unique_ptr<FxDag> m_fxDag; //!< Smart pointer – automatic cleanup+ std::unique_ptr<XshHandleManager> m_handleManager;+ std::unique_ptr<ExpressionReferenceMonitor> m_expRefMonitor;int m_frameCount;int m_soloColumn;@@ -100,14 +107,11 @@ struct TXsheet::TXsheetImp {TSoundTrackP m_mixedSound;ColumnFan m_columnFans[Orientations::COUNT];- XshHandleManager *m_handleManager;ToonzScene *m_scene;- ExpressionReferenceMonitor *m_expRefMonitor;-public:TXsheetImp();- ~TXsheetImp();+ ~TXsheetImp() = default;static inline unsigned long newIdentifier() {static unsigned long currentId = 0;@@ -119,9 +123,9 @@ public:private:void initColumnFans();- // not implemented- TXsheetImp(const TXsheetImp &);- TXsheetImp &operator=(const TXsheetImp &);+ // not copyable+ TXsheetImp(const TXsheetImp &) = delete;+ TXsheetImp &operator=(const TXsheetImp &) = delete;};//-----------------------------------------------------------------------------@@ -140,7 +144,6 @@ inline bool TXsheet::SoundProperties::operator==(return m_fromFrame == c.m_fromFrame && m_toFrame == c.m_toFrame &&m_frameRate == c.m_frameRate && m_isPreview == c.m_isPreview;}-inline bool TXsheet::SoundProperties::operator!=(const SoundProperties &c) const {return !(*this == c);@@ -150,27 +153,18 @@ inline bool TXsheet::SoundProperties::operator!=(TXsheet::TXsheetImp::TXsheetImp(): m_id(newIdentifier())- , m_pegTree(new TStageObjectTree)- , m_handleManager(0)- , m_fxDag(new FxDag())+ , m_pegTree(std::make_unique<TStageObjectTree>())+ , m_fxDag(std::make_unique<FxDag>())+ , m_handleManager(std::make_unique<XshHandleManager>(nullptr))+ , m_expRefMonitor(std::make_unique<ExpressionReferenceMonitor>()), m_frameCount(0), m_soloColumn(-1), m_viewColumn(-1)- , m_mixedSound(0)- , m_scene(0)- , m_expRefMonitor(new ExpressionReferenceMonitor()) {+ , m_mixedSound(nullptr)+ , m_scene(nullptr) {initColumnFans();-}--//-------------------------------------------------------------------------------TXsheet::TXsheetImp::~TXsheetImp() {- assert(m_pegTree);- assert(m_fxDag);- assert(m_handleManager);- delete m_pegTree;- delete m_fxDag;- delete m_handleManager;+ // m_handleManager->setXsheet(nullptr); // will be set later+ m_pegTree->setHandleManager(m_handleManager.get());}//-----------------------------------------------------------------------------@@ -194,16 +188,15 @@ void TXsheet::TXsheetImp::copyFoldedState() {TXsheet::TXsheet(): TSmartObject(m_classCode)- , m_player(0)- , m_imp(new TXsheet::TXsheetImp)- , m_notes(new TXshNoteSet())+ , m_player(nullptr)+ , m_imp(std::make_unique<TXsheet::TXsheetImp>())+ , m_notes(std::make_unique<TXshNoteSet>())+ , m_soundProperties(std::make_unique<SoundProperties>())+ , m_navigationTags(std::make_unique<NavigationTags>()), m_cameraColumnIndex(0)- , m_observer(nullptr)- , m_navigationTags(new NavigationTags()) {- // extern TSyntax::Grammar *createXsheetGrammar(TXsheet*);- m_soundProperties = new TXsheet::SoundProperties();- m_imp->m_handleManager = new XshHandleManager(this);- m_imp->m_pegTree->setHandleManager(m_imp->m_handleManager);+ , m_observer(nullptr) {+ m_imp->m_handleManager = std::make_unique<XshHandleManager>(this);+ m_imp->m_pegTree->setHandleManager(m_imp->m_handleManager.get());m_imp->m_pegTree->createGrammar(this);// Dummy camera column@@ -216,11 +209,7 @@ TXsheet::TXsheet()TXsheet::~TXsheet() {texture_utils::invalidateTextures(this);-- assert(m_imp);- if (m_notes) delete m_notes;- if (m_soundProperties) delete m_soundProperties;- if (m_navigationTags) delete m_navigationTags;+ // All owned members are managed by smart pointers, no manual deletion needed}//-----------------------------------------------------------------------------@@ -276,7 +265,7 @@ bool TXsheet::setCell(int row, int col, const TXshCell &cell) {cellColumn = touchColumn(col, type)->getCellColumn();} else {TXshColumn *column = getColumn(col);- cellColumn = column ? column->getCellColumn() : 0;+ cellColumn = column ? column->getCellColumn() : nullptr;}if (!cellColumn || cellColumn->isLocked()) return false;@@ -288,13 +277,12 @@ bool TXsheet::setCell(int row, int col, const TXshCell &cell) {removeColumn(col);insertColumn(col);}-return false;}TFx *fx = cellColumn->getFx();if (wasColumnEmpty && fx && fx->getOutputConnectionCount() == 0 &&- cellColumn->getPaletteColumn() == 0)+ cellColumn->getPaletteColumn() == nullptr)getFxDag()->addToXsheet(fx);if (cell.isEmpty())@@ -339,13 +327,9 @@ bool TXsheet::setCells(int row, int col, int rowCount, const TXshCell cells[]) {int i = 0;while (i < rowCount && cells[i].isEmpty()) i++;- // inserito da Elisa verso novembre 2009.- // cosi' ha il difetto che se assegno celle vuote non fa nulla- // per ora lo commento. bisogna indagare se questo rompe qualcosa-- // ho modificato il seguito per gestire il caso in cui i>=rowCount- // => niente livelli dentro cells-+ // Added by Elisa around November 2009.+ // The flaw is that if I assign empty cells, it does nothing.+ // Commented out for now. Need to investigate if this breaks anything.// if(i>=rowCount)// return false;@@ -394,8 +378,8 @@ bool TXsheet::setCells(int row, int col, int rowCount, const TXshCell cells[]) {updateFrameCount();}// TODO: Investigate if needed for future column/frame updates.- // Possibly left for debugging or as a placeholder logic. Currently does nothing.- // row + 1;+ // Possibly left for debugging or as a placeholder logic. Currently does+ // nothing. row + 1;// set the level name to the columnif (wasColumnEmpty && i < rowCount &&@@ -415,7 +399,7 @@ void TXsheet::insertCells(int row, int col, int rowCount) {TXshCellColumn *xshColumn = column->getCellColumn();if (!xshColumn) return;xshColumn->insertEmptyCells(row, rowCount);- // aggiorno il frame count+ // update frame countint fc = xshColumn->getMaxFrame() + 1;if (fc > m_imp->m_frameCount) m_imp->m_frameCount = fc;}@@ -432,7 +416,7 @@ void TXsheet::removeCells(int row, int col, int rowCount) {int oldColRowCount = xshCellColumn->getMaxFrame() + 1;xshCellColumn->removeCells(row, rowCount);- // aggiornamento framecount+ // update framecountif (oldColRowCount == m_imp->m_frameCount) updateFrameCount();TNotifier::instance()->notify(TXsheetChange());@@ -450,31 +434,24 @@ void TXsheet::clearCells(int row, int col, int rowCount) {int oldColRowCount = xshCellColumn->getMaxFrame() + 1;xshCellColumn->clearCells(row, rowCount);- // aggiornamento framecount+ // update framecountif (oldColRowCount == m_imp->m_frameCount) updateFrameCount();}//-----------------------------------------------------------------------------void TXsheet::clearAll() {- int c0 = 0, c1 = m_imp->m_columnSet.getColumnCount() - 1;- int r0 = 0, r1 = getFrameCount() - 1;+ // unused variables removedm_imp->m_columnSet.clear();- if (m_imp->m_pegTree) {- delete m_imp->m_pegTree;- m_imp->m_pegTree = new TStageObjectTree();- m_imp->m_pegTree->setHandleManager(m_imp->m_handleManager);- m_imp->m_pegTree->createGrammar(this);- }+ m_imp->m_pegTree = std::make_unique<TStageObjectTree>();+ m_imp->m_pegTree->setHandleManager(m_imp->m_handleManager.get());+ m_imp->m_pegTree->createGrammar(this);- if (m_imp->m_fxDag) {- delete m_imp->m_fxDag;- m_imp->m_fxDag = new FxDag();- }+ m_imp->m_fxDag = std::make_unique<FxDag>();m_imp->m_frameCount = 0;- m_imp->m_mixedSound = 0;+ m_imp->m_mixedSound = TSoundTrackP();}//-----------------------------------------------------------------------------@@ -528,7 +505,7 @@ void TXsheet::getUsedLevels(set<TXshLevel *> &levels) const {int r0, r1;if (!cellColumn->getRange(r0, r1)) continue;- TXshLevel *level = 0;+ TXshLevel *level = nullptr;for (int r = r0; r <= r1; r++) {TXshCell cell = cellColumn->getCell(r);if (cell.isEmpty() || !cell.m_level) continue;@@ -567,7 +544,7 @@ TStageObject *TXsheet::getStageObject(const TStageObjectId &id) const {//-----------------------------------------------------------------------------TStageObjectTree *TXsheet::getStageObjectTree() const {- return m_imp->m_pegTree;+ return m_imp->m_pegTree.get();}//-----------------------------------------------------------------------------@@ -757,10 +734,9 @@ void TXsheet::stepCells(int r0, int c0, int r1, int c1, int type) {int nr = r1 - r0 + 1;int nc = c1 - c0 + 1;if (nr < 1 || nc <= 0) return;- int size = nr * nc;- std::unique_ptr<TXshCell[]> cells(new TXshCell[size]);- if (!cells) return;- // salvo il contenuto delle celle in cells++ std::vector<TXshCell> cells(static_cast<size_t>(nr) * nc);+int k = 0;for (int r = r0; r <= r1; r++)for (int c = c0; c <= c1; c++) {@@ -773,14 +749,14 @@ void TXsheet::stepCells(int r0, int c0, int r1, int c1, int type) {for (int j = c0; j <= c1; j++) {int i, k;- for (i = r0, k = j - c0; k < size; k += nc) {+ for (i = r0, k = j - c0; k < (int)cells.size(); k += nc) {for (int i1 = 0; i1 < type; i1++) {if (cells[k].isEmpty())clearCells(i + i1, j);elsesetCell(i + i1, j, cells[k]);}- i += type; // dipende dal tipo di step (2 o 3 per ora)+ i += type; // depends on step type (2 or 3 for now)}}}@@ -788,10 +764,9 @@ void TXsheet::stepCells(int r0, int c0, int r1, int c1, int type) {//-----------------------------------------------------------------------------void TXsheet::increaseStepCells(int r0, int c0, int &r1, int c1) {- int c, size = r1 - r0 + 1;QList<int> ends;- for (c = c0; c <= c1; c++) {- int r = r0, i = 0, rEnd = r1;+ for (int c = c0; c <= c1; c++) {+ int r = r0, rEnd = r1;while (r <= rEnd) {TXshCell cell = getCell(CellPosition(r, c));if (!cell.isEmpty()) {@@ -802,14 +777,12 @@ void TXsheet::increaseStepCells(int r0, int c0, int &r1, int c1) {while (cell == getCell(CellPosition(r, c)) && r <= rEnd) r++;} elser++;- i++;}ends.append(rEnd);}if (ends.isEmpty()) return;- // controllo se devo cambiare la selezionebool allIncreaseIsEqual = true;- for (c = 0; c < ends.size() - 1 && allIncreaseIsEqual; c++)+ for (int c = 0; c < ends.size() - 1 && allIncreaseIsEqual; c++)allIncreaseIsEqual = allIncreaseIsEqual && ends[c] == ends[c + 1];if (allIncreaseIsEqual) r1 = ends[0];}@@ -817,10 +790,9 @@ void TXsheet::increaseStepCells(int r0, int c0, int &r1, int c1) {//-----------------------------------------------------------------------------void TXsheet::decreaseStepCells(int r0, int c0, int &r1, int c1) {- int c, size = r1 - r0 + 1;QList<int> ends;- for (c = c0; c <= c1; c++) {- int r = r0, i = 0, rEnd = r1;+ for (int c = c0; c <= c1; c++) {+ int r = r0, rEnd = r1;while (r <= rEnd) {TXshCell cell = getCell(CellPosition(r, c));if (!cell.isEmpty()) {@@ -836,14 +808,12 @@ void TXsheet::decreaseStepCells(int r0, int c0, int &r1, int c1) {}} elser++;- i++;}ends.append(rEnd);}if (ends.isEmpty()) return;- // controllo se devo cambiare la selezionebool allDecreaseIsEqual = true;- for (c = 0; c < ends.size() - 1 && allDecreaseIsEqual; c++)+ for (int c = 0; c < ends.size() - 1 && allDecreaseIsEqual; c++)allDecreaseIsEqual = allDecreaseIsEqual && ends[c] == ends[c + 1];if (allDecreaseIsEqual) r1 = ends[0];}@@ -856,26 +826,20 @@ void TXsheet::eachCells(int r0, int c0, int r1, int c1, int type) {if (nr < type || nc <= 0) return;int newRows = nr % type ? nr / type + 1 : nr / type;-- int size = newRows * nc;- assert(size > 0);- std::unique_ptr<TXshCell[]> cells(new TXshCell[size]);- assert(cells);+ std::vector<TXshCell> cells(static_cast<size_t>(newRows) * nc);int i, j, k;- for (j = r0, i = 0; i < size;- j += type) // in cells copio il contenuto delle celle che mi interessano- {+ for (j = r0, i = 0; i < (int)cells.size(); j += type) {for (k = c0; k <= c1; k++, i++) cells[i] = getCell(CellPosition(j, k));}- int c;- for (c = c0; c <= c1; ++c) removeCells(r0 + newRows, c, nr - newRows);+ for (int c = c0; c <= c1; ++c) removeCells(r0 + newRows, c, nr - newRows);- for (i = r0, k = 0; i < r0 + newRows && k < size; i++)+ for (i = r0, k = 0; i < r0 + newRows && k < (int)cells.size(); i++)for (j = c0; j <= c1; j++) {- //----110523 iwasawa- // Eachでできた空きセルに、操作前のセルの中身が残ってしまう不具合を修正+ //----- 110523 iwasawa+ // Fixed bug where empty cells created by Each kept the content of cells+ // before operationif (cells[k].isEmpty())clearCells(i, j);else@@ -909,7 +873,7 @@ int TXsheet::reframeCells(int r0, int r1, int col, int step, int withBlank) {if ((*itr).isEmpty())itr = cells.erase(itr);else- itr++;+ ++itr;}}@@ -938,7 +902,7 @@ int TXsheet::reframeCells(int r0, int r1, int col, int step, int withBlank) {elsesetCell(i + i1, col, cells[k]);}- i += step; // dipende dal tipo di step (2 o 3 per ora)+ i += step; // depends on step type (2 or 3 for now)if (withBlank > 0) {for (int i1 = 0; i1 < withBlank * step; i1++) {@@ -959,7 +923,7 @@ void TXsheet::resetStepCells(int r0, int c0, int r1, int c1) {int r = r0, i = 0;TXshCell *cells = new TXshCell[size];while (r <= r1) {- // mi prendo le celle che mi servono+ // take the cells I needcells[i] = getCell(CellPosition(r, c));r++;while (cells[i] == getCell(CellPosition(r, c)) && r <= r1) r++;@@ -972,6 +936,7 @@ void TXsheet::resetStepCells(int r0, int c0, int r1, int c1) {i = 0;r = r0;for (i = 0; i < size; i++, r++) setCell(r, c, cells[i]);+ delete[] cells;}}@@ -986,7 +951,6 @@ void TXsheet::rollupCells(int r0, int c0, int r1, int c1) {std::unique_ptr<TXshCell[]> cells(new TXshCell[size]);assert(cells);- // in cells copio il contenuto delle celle che mi interessanoint k;for (k = c0; k <= c1; k++) cells[k - c0] = getCell(CellPosition(r0, k));@@ -994,7 +958,7 @@ void TXsheet::rollupCells(int r0, int c0, int r1, int c1) {for (k = c0; k <= c1; k++) {insertCells(r1, k, 1);- setCell(r1, k, cells[k - c0]); // setto le celle+ setCell(r1, k, cells[k - c0]); // set the cells}}@@ -1009,7 +973,6 @@ void TXsheet::rolldownCells(int r0, int c0, int r1, int c1) {std::unique_ptr<TXshCell[]> cells(new TXshCell[size]);assert(cells);- // in cells copio il contenuto delle celle che mi interessanoint k;for (k = c0; k <= c1; k++) cells[k - c0] = getCell(CellPosition(r1, k));@@ -1017,7 +980,7 @@ void TXsheet::rolldownCells(int r0, int c0, int r1, int c1) {for (k = c0; k <= c1; k++) {insertCells(r0, k, 1);- setCell(r0, k, cells[k - c0]); // setto le celle+ setCell(r0, k, cells[k - c0]); // set the cells}}@@ -1026,7 +989,7 @@ void TXsheet::rolldownCells(int r0, int c0, int r1, int c1) {If nr>r1-r0+1 add cells, otherwise remove cells. */void TXsheet::timeStretch(int r0, int c0, int r1, int c1, int nr) {int oldNr = r1 - r0 + 1;- if (nr > oldNr) /* ingrandisce */+ if (nr > oldNr) /* enlarge */{int c;for (c = c0; c <= c1; c++) {@@ -1038,11 +1001,11 @@ void TXsheet::timeStretch(int r0, int c0, int r1, int c1, int nr) {insertCells(r0 + 1, c, dn);int i;for (i = nr - 1; i >= 0; i--) {- int j = i * double(oldNr) / double(nr);+ int j = static_cast<int>(std::round(i * double(oldNr) / double(nr)));if (j < i) setCell(i + r0, c, cells[j]);}}- } else /* rimpicciolisce */+ } else /* shrink */{int c;for (c = c0; c <= c1; c++) {@@ -1052,7 +1015,7 @@ void TXsheet::timeStretch(int r0, int c0, int r1, int c1, int nr) {getCells(r0, c, oldNr, cells.get());int i;for (i = 0; i < nr; i++) {- int j = i * double(oldNr) / double(nr);+ int j = static_cast<int>(std::round(i * double(oldNr) / double(nr)));if (j > i) setCell(i + r0, c, cells[j]);}removeCells(r1 - dn + 1, c, dn);@@ -1079,14 +1042,18 @@ int TXsheet::exposeLevel(int row, int col, TXshLevel *xl, bool overwrite) {//-----------------------------------------------------------------------------// customized version for load level popupint TXsheet::exposeLevel(int row, int col, TXshLevel *xl,- std::vector<TFrameId> &fIds_, TFrameId xFrom,- TFrameId xTo, int step, int inc, int frameCount,+ std::vector<TFrameId> &fIds_, const TFrameId &xFrom,+ const TFrameId &xTo, int step, int inc, int frameCount,bool doesFileActuallyExist) {if (!xl) return 0;++ // Keep the level alive during the whole function+ TXshLevelP levelHolder = xl;+std::vector<TFrameId> fids;if (doesFileActuallyExist)- xl->getFids(fids);+ levelHolder->getFids(fids);else {for (int i = 0; i < (int)fIds_.size(); i++) {fids.push_back(fIds_[i]);@@ -1095,17 +1062,17 @@ int TXsheet::exposeLevel(int row, int col, TXshLevel *xl,// multiple exposingif (frameCount < 0 || xFrom < 0 || xTo < 0 || step < 0 || inc < 0) {- insertCells(row, col, xl->getFrameCount());+ insertCells(row, col, levelHolder->getFrameCount());frameCount = 1;if (fids.empty())- setCell(row, col, TXshCell(xl, TFrameId(1)));+ setCell(row, col, TXshCell(levelHolder.getPointer(), TFrameId(1)));else {frameCount = (int)fids.size();insertCells(row, col, frameCount);std::vector<TFrameId>::iterator it;for (it = fids.begin(); it != fids.end(); ++it)- setCell(row++, col, TXshCell(xl, *it));+ setCell(row++, col, TXshCell(levelHolder.getPointer(), *it));}updateFrameCount();return frameCount;@@ -1116,7 +1083,7 @@ int TXsheet::exposeLevel(int row, int col, TXshLevel *xl,insertCells(row, col, frameCount);if (fids.empty()) {- setCell(row, col, TXshCell(xl, TFrameId(1)));+ setCell(row, col, TXshCell(levelHolder.getPointer(), TFrameId(1)));} else {if (inc == 0) // inc = Auto{@@ -1130,7 +1097,7 @@ int TXsheet::exposeLevel(int row, int col, TXshLevel *xl,next_it = it;next_it++;for (int f = 0; f < frameCount; f++) {- setCell(row++, col, TXshCell(xl, *it));+ setCell(row++, col, TXshCell(levelHolder.getPointer(), *it));if (next_it != fids.end()) {it++;next_it++;@@ -1143,7 +1110,7 @@ int TXsheet::exposeLevel(int row, int col, TXshLevel *xl,int loopCount = frameCount / step;for (int loop = 0; loop < loopCount; loop++) {for (int s = 0; s < step; s++) {- setCell(row++, col, TXshCell(xl, *it));+ setCell(row++, col, TXshCell(levelHolder.getPointer(), *it));}it++;}@@ -1160,7 +1127,7 @@ int TXsheet::exposeLevel(int row, int col, TXshLevel *xl,for (int loop = 0; loop < loopCount; loop++) {TFrameId id(xFrom.getNumber() + loop * inc, xFrom.getLetter());for (int s = 0; s < step; s++) {- setCell(row++, col, TXshCell(xl, id));+ setCell(row++, col, TXshCell(levelHolder.getPointer(), id));}}}@@ -1206,7 +1173,7 @@ void TXsheet::loadData(TIStream &is) {while (is.openChild(tagName)) {if (tagName == "columns") {while (!is.eos()) {- TPersist *p = 0;+ TPersist *p = nullptr;is >> p;TXshColumn *column = dynamic_cast<TXshColumn *>(p);if (!column) throw TException("expected xsheet column");@@ -1246,7 +1213,7 @@ void TXsheet::loadData(TIStream &is) {is.closeChild();}} else if (tagName == "pegbars") {- TPersist *p = m_imp->m_pegTree;+ TPersist *p = m_imp->m_pegTree.get();m_imp->m_pegTree->loadData(is, this);} else if (tagName == "fxnodes") {m_imp->m_fxDag->loadData(is);@@ -1313,7 +1280,6 @@ void TXsheet::saveData(TOStream &os) {os.openChild("pegbars");m_imp->m_pegTree->saveData(os, getFirstFreeColumnIndex(), this);- // os << *(m_imp->m_pegTree);os.closeChild();FxDag *fxDag = getFxDag();@@ -1362,7 +1328,7 @@ void TXsheet::insertColumn(int col, TXshColumn *column) {m_imp->m_columnSet.insertColumn(col, column);m_imp->m_pegTree->insertColumn(col);if (column->getPaletteColumn() ==- 0) // palette column are not connected to the xsheet fx node+ nullptr) // palette column are not connected to the xsheet fx node{TFx *fx = column->getFx();if (fx) getFxDag()->addToXsheet(fx);@@ -1385,9 +1351,9 @@ void TXsheet::removeColumn(int col) {if (fx) {getFxDag()->removeFromXsheet(fx);- // disconnetto dal columnFx tutti gli effetti connessi in uscita- TFxPort *outPort = 0;- while ((outPort = fx->getOutputConnection(0))) outPort->setFx(0);+ // disconnect all output effects from the columnFx+ TFxPort *outPort = nullptr;+ while ((outPort = fx->getOutputConnection(0))) outPort->setFx(nullptr);}}m_imp->m_columnSet.removeColumn(col);@@ -1445,7 +1411,7 @@ void TXsheet::moveColumn(int srcIndex, int dstIndex) {//-----------------------------------------------------------------------------TXshColumn *TXsheet::getColumn(int col) const {- if (col < 0) return m_cameraColumn;+ if (col < 0) return m_cameraColumn.getPointer();return m_imp->m_columnSet.getColumn(col).getPointer();}@@ -1467,13 +1433,12 @@ int TXsheet::getFirstFreeColumnIndex() const {TXshColumn *TXsheet::touchColumn(int index, TXshColumn::ColumnType type) {TXshColumn *column = m_imp->m_columnSet.touchColumn(index, type).getPointer();- if (index < 0 || !column) return 0;+ if (index < 0 || !column) return nullptr;// NOTE (Daniele): The following && should be a bug... but I fear I'd break- // something changing it.- // Observe that the implied behavior is that of REPLACING AN EXISTING- // LEGITIMATE COLUMN!- // Please, Inquire further if you're not upon release!+ // something changing it. Observe that the implied behavior is+ // that of REPLACING AN EXISTING LEGITIMATE COLUMN!+ // Please, Inquire further if you're not upon release!if (column->isEmpty() && column->getColumnType() != type) {removeColumn(index);@@ -1519,9 +1484,8 @@ TSoundTrack *TXsheet::makeSound(SoundProperties *properties) {sounds, properties->m_fromFrame, properties->m_toFrame,properties->m_frameRate);else- m_imp->m_mixedSound = 0;- delete m_soundProperties;- m_soundProperties = properties;+ m_imp->m_mixedSound = TSoundTrackP();+ m_soundProperties.reset(properties);} elsedelete properties;return m_imp->m_mixedSound.getPointer();@@ -1543,24 +1507,10 @@ void TXsheet::scrub(int frame, bool isPreview) {double samplePerFrame = st->getSampleRate() / fps;double s0 = frame * samplePerFrame, s1 = s0 + samplePerFrame;- // if (m_player && m_player->isPlaying()) {- // try {- // m_player->stop();- // }- // catch (const std::runtime_error& e) {- // int i = 0;- // }- // catch (const std::exception& e) {- // int i = 0;- // }- // catch (...) {- // int i = 0;- // }- //}- play(st, s0, s1, false);+ play(st, static_cast<int>(s0), static_cast<int>(s1), false);} catch (TSoundDeviceException &e) {if (e.getType() == TSoundDeviceException::NoDevice) {- std::cout << ::to_string(e.getMessage()) << std::endl;+ std::cout << ::to_string(e.getMessage()) << '\n';} else {throw TSoundDeviceException(e.getType(), e.getMessage());}@@ -1575,22 +1525,25 @@ void TXsheet::stopScrub() {//------------------------------------------------------------------------------void TXsheet::play(TSoundTrackP soundtrack, int s0, int s1, bool loop) {+void TXsheet::play(const TSoundTrackP &soundtrack, int s0, int s1, bool loop) {if (!TSoundOutputDevice::installed()) return;- if (!m_player) m_player = new TSoundOutputDevice();+ if (!m_player) m_player = std::make_unique<TSoundOutputDevice>();if (m_player) {try {m_player->play(soundtrack, s0, s1, loop);- } catch (TSoundDeviceException &) {+ } catch (TSoundDeviceException &e) {+ // Optionally log the exception, but at least we avoid empty catch+ // For now, just ignore as before, but with a comment+ // TODO: Consider logging}}}//------------------------------------------------------------------------------FxDag *TXsheet::getFxDag() const { return m_imp->m_fxDag; }+FxDag *TXsheet::getFxDag() const { return m_imp->m_fxDag.get(); }//-----------------------------------------------------------------------------@@ -1643,7 +1596,7 @@ void TXsheet::invalidateSound() { m_imp->m_mixedSound = TSoundTrackP(); }bool TXsheet::checkCircularReferences(TXsheet *childCandidate) {if (this == childCandidate) return true;- if (childCandidate == 0) return false;+ if (childCandidate == nullptr) return false;int i;for (i = 0; i < childCandidate->getColumnCount(); i++)if (checkCircularReferences(childCandidate->getColumn(i))) return true;@@ -1708,8 +1661,8 @@ TRectD TXsheet::getBBox(int r) const {TRectD bbox(voidRect);// Traverse the xsheet's columns, adding the bbox of each- int c, cCount = getColumnCount();- for (c = 0; c != cCount; ++c) {+ int cCount = getColumnCount();+ for (int c = 0; c != cCount; ++c) {// Skip empty or invisible columnsTXshColumn *column = getColumn(c);if (column->isEmpty() || !column->isCamstandVisible()) continue;@@ -1770,7 +1723,7 @@ void TXsheet::autoInputCellNumbers(int increment, int interval, int step,: ((isOverwrite) ? std::min(r1, r0 + rowsCount - 1): r0 + rowsCount - 1);// for each column- for (int c = 0; c < columnIndices.size(); c++) {+ for (int c = 0; c < (int)columnIndices.size(); c++) {int columnIndex = columnIndices.at(c);TXshLevelP level = levels.at(c);@@ -1820,7 +1773,8 @@ void TXsheet::autoInputCellNumbers(int increment, int interval, int step,while (row <= rowUpTo) {// input cellif (step_interv_itr < step)- setCell(row, columnIndex, TXshCell(level, fids.at(fid_itr)));+ setCell(row, columnIndex,+ TXshCell(level.getPointer(), fids.at(fid_itr)));// .. or set empty cell as intervalelsesetCell(row, columnIndex, TXshCell());@@ -1833,7 +1787,7 @@ void TXsheet::autoInputCellNumbers(int increment, int interval, int step,step_interv_itr = 0;}// next repeat cycle- if (fid_itr == fids.size()) {+ if (fid_itr == (int)fids.size()) {repeat_itr++;fid_itr = 0;}@@ -1858,7 +1812,7 @@ void TXsheet::notify(const TXsheetColumnChange &change) {void TXsheet::notifyFxAdded(const std::vector<TFx *> &fxs) {if (m_observer) m_observer->onFxAdded(fxs);}-void TXsheet::notifyStageObjectAdded(const TStageObjectId id) {+void TXsheet::notifyStageObjectAdded(const TStageObjectId &id) {if (m_observer) m_observer->onStageObjectAdded(id);}bool TXsheet::isReferenceManagementIgnored(TDoubleParam *param) {@@ -1866,7 +1820,7 @@ bool TXsheet::isReferenceManagementIgnored(TDoubleParam *param) {return false;}ExpressionReferenceMonitor *TXsheet::getExpRefMonitor() const {- return m_imp->m_expRefMonitor;+ return m_imp->m_expRefMonitor.get();}//---------------------------------------------------------@@ -1885,4 +1839,4 @@ void TXsheet::toggleTaggedFrame(int frame) {m_navigationTags->removeTag(frame);elsem_navigationTags->addTag(frame);-}\ No newline at end of file+}diff --git a/toonz/sources/toonzlib/txshsimplelevel.cpp b/toonz/sources/toonzlib/txshsimplelevel.cppindex f70d568f7..9d78a0f8b 100644--- a/toonz/sources/toonzlib/txshsimplelevel.cpp+++ b/toonz/sources/toonzlib/txshsimplelevel.cpp@@ -166,7 +166,7 @@ bool TXshSimpleLevel::m_fillFullColorRaster = false;TXshSimpleLevel::TXshSimpleLevel(const std::wstring& name): TXshLevel(m_classCode, name)- , m_properties(new LevelProperties)+ , m_properties(std::make_unique<LevelProperties>()), m_palette(nullptr), m_idBase(std::to_string(idBaseCode++)), m_editableRangeUserInfo(L"")@@ -180,11 +180,7 @@ TXshSimpleLevel::TXshSimpleLevel(const std::wstring& name)TXshSimpleLevel::~TXshSimpleLevel() {clearFrames();-- if (m_palette) {- m_palette->release();- m_palette = nullptr;- }+ // m_palette is TPaletteP – automatically releases}//-----------------------------------------------------------------------------@@ -403,24 +399,12 @@ void TXshSimpleLevel::clonePropertiesFrom(const TXshSimpleLevel* oldSl) {//------------------------------------------------------------------------------TPalette* TXshSimpleLevel::getPalette() const { return m_palette; }+TPalette* TXshSimpleLevel::getPalette() const { return m_palette.getPointer(); }//-----------------------------------------------------------------------------void TXshSimpleLevel::setPalette(TPalette* palette) {- if (m_palette != palette) {- if (m_palette) {- m_palette->release();- }-- m_palette = palette;- if (m_palette) {- m_palette->addRef();- if (!(getType() & FULLCOLOR_TYPE)) {- m_palette->setPaletteName(getName());- }- }- }+ m_palette = palette; // TPaletteP handles ref counting automatically}//-----------------------------------------------------------------------------@@ -603,7 +587,7 @@ TImageP TXshSimpleLevel::getFrameIcon(const TFrameId& fid) const {imgId, ImageManager::dontPutInCache, &extData);if (TToonzImageP timg = img) {- if (m_palette) timg->setPalette(m_palette);+ if (m_palette) timg->setPalette(m_palette.getPointer());}return img;@@ -1517,13 +1501,14 @@ void TXshSimpleLevel::save(const TFilePath& fp, const TFilePath& oldFp,if (TSystem::doesExistFileOrLevel(*it)) TSystem::removeFileOrLevel(*it);}- TXshSimpleLevel* sl = new TXshSimpleLevel;+ // Use smart pointer to manage temporary level+ TXshSimpleLevelP sl = new TXshSimpleLevel;sl->setScene(getScene());sl->setPalette(getPalette());sl->setPath(getScene()->codeFilePath(app));sl->setType(getType());sl->setDirtyFlag(getDirtyFlag());- sl->addRef();+ // sl->addRef(); // not needed – smart pointer handles reffor (const auto& fid : m_editableRange) {sl->setFrame(fid, getFrame(fid, false));@@ -1539,7 +1524,8 @@ void TXshSimpleLevel::save(const TFilePath& fp, const TFilePath& oldFp,}sl->setRenumberTable();- sl->save(app);+ sl->save(+ app); // sl will be automatically released when it goes out of scope#ifdef _WIN32if (TSystem::doesExistFileOrLevel(app)) TSystem::hideFileOrLevel(app);@@ -1884,13 +1870,14 @@ void TXshSimpleLevel::initializePalette() {assert(scene);TFilePath fullPath;- TPalette* palette = new TPalette();+ TPalette* palette = nullptr;int type = getType();switch (type) {case TZP_XSHLEVEL:fullPath =scene->decodeFilePath(TFilePath("+palettes\\Toonz_Raster_Palette.tpl"));if (TSystem::doesExistFileOrLevel(fullPath)) {+ palette = new TPalette();TIStream is(fullPath);is >> palette;} else {@@ -1899,6 +1886,7 @@ void TXshSimpleLevel::initializePalette() {"\\Global Palettes\\Default ""Palettes\\Toonz_Raster_Palette.tpl"));if (TSystem::doesExistFileOrLevel(globalPath)) {+ palette = new TPalette();TIStream is(globalPath);is >> palette;TSystem::copyFile(fullPath, globalPath);@@ -1909,6 +1897,7 @@ void TXshSimpleLevel::initializePalette() {fullPath =scene->decodeFilePath(TFilePath("+palettes\\Toonz_Vector_Palette.tpl"));if (TSystem::doesExistFileOrLevel(fullPath)) {+ palette = new TPalette();TIStream is(fullPath);is >> palette;} else {@@ -1917,6 +1906,7 @@ void TXshSimpleLevel::initializePalette() {"\\Global Palettes\\Default ""Palettes\\Toonz_Vector_Palette.tpl"));if (TSystem::doesExistFileOrLevel(globalPath)) {+ palette = new TPalette();TIStream is(globalPath);is >> palette;TSystem::copyFile(fullPath, globalPath);@@ -1929,12 +1919,12 @@ void TXshSimpleLevel::initializePalette() {break;}- if (palette && type != OVL_XSHLEVEL) {- palette->setPaletteName(getName());+ if (palette) {+ if (type != OVL_XSHLEVEL) {+ palette->setPaletteName(getName());+ }+ setPalette(palette);}-- palette->setDirtyFlag(true);- setPalette(palette);}//-----------------------------------------------------------------------------@@ -2245,8 +2235,7 @@ void TXshSimpleLevel::getFiles(const TFilePath& fp, TFilePathSet& fpset) {//-----------------------------------------------------------------------------void TXshSimpleLevel::setContentHistory(TContentHistory* contentHistory) {- if (contentHistory != m_contentHistory.get())- m_contentHistory.reset(contentHistory);+ m_contentHistory.reset(contentHistory);}//-----------------------------------------------------------------------------diff --git a/toonz/sources/toonzqt/dvdialog.cpp b/toonz/sources/toonzqt/dvdialog.cppindex 09d656e54..1cb9fd523 100644--- a/toonz/sources/toonzqt/dvdialog.cpp+++ b/toonz/sources/toonzqt/dvdialog.cpp@@ -104,15 +104,12 @@ QString getMsgBoxTitle(MsgType type) {Separator::Separator(QString name, QWidget *parent, bool isHorizontal): QFrame(parent), m_name(name), m_isHorizontal(isHorizontal) {- // if(m_name.isEmpty())- // setMinimumSize(1,1);- // elsesetMinimumSize(1, 15);}//------------------------------------------------------------------------------Separator::~Separator() {}+Separator::~Separator() = default;//-----------------------------------------------------------------------------@@ -135,7 +132,6 @@ void Separator::paintEvent(QPaintEvent *) {lineColor.setAlpha(128);p.setPen(lineColor);- int h = contents.height();if (m_isHorizontal) {int y = contents.center().y();int space = (textWidth == 0) ? 0 : 8;@@ -223,9 +219,9 @@ Dialog::Dialog(QWidget *parent, bool hasButton, bool hasFixedSize,: QDialog(parent, Qt::CustomizeWindowHint | Qt::WindowTitleHint |Qt::WindowCloseButtonHint), m_hasButton(hasButton)- , m_mainHLayout(0)- , m_leftVLayout(0)- , m_rightVLayout(0)+ , m_mainHLayout(nullptr)+ , m_leftVLayout(nullptr)+ , m_rightVLayout(nullptr), m_isMainVLayout(false), m_isMainHLayout(false), m_layoutSpacing(5)@@ -276,7 +272,7 @@ Dialog::Dialog(QWidget *parent, bool hasButton, bool hasFixedSize,mainLayout->setSizeConstraint(QLayout::SetMinimumSize);setLayout(mainLayout);-// this->setGeometry(30, 30, 300, 300);+#ifdef MACOSXsetWindowFlags(Qt::Tool);#endif@@ -289,53 +285,57 @@ Dialog::Dialog(QWidget *parent, bool hasButton, bool hasFixedSize,QSettings settings(settingsPath, QSettings::IniFormat);- if (name == QString()) return;+ if (name.isEmpty()) return;m_name = name + "DialogGeometry";QString geo = settings.value(m_name).toString();- if (geo != QString()) {+ if (!geo.isEmpty()) {QStringList values = geo.split(" ");- assert(values.size() == 4);- // Ensure that the dialog is visible in the screen.- // The dialog opens with some offset to bottom-right direction- // if a flag Qt::WindowMaximizeButtonHint is set. (e.g. PencilTestPopup)- // Therefore, if the dialog is moved to the bottom-end of the screen,- // it will be got out of the screen on the next launch.- // The following position adjustment will also prevent such behavior.-- // try and get active screen- if (parent != NULL) {- QScreen *screen = QGuiApplication::screenAt(parent->pos());- m_currentScreen = screen ? QGuiApplication::screens().indexOf(screen) : 0;+ // If the stored geometry is malformed, just ignore it+ if (values.size() == 4) {+ // Ensure that the dialog is visible in the screen.+ // The dialog opens with some offset to bottom-right direction+ // if a flag Qt::WindowMaximizeButtonHint is set. (e.g. PencilTestPopup)+ // Therefore, if the dialog is moved to the bottom-end of the screen,+ // it will be got out of the screen on the next launch.+ // The following position adjustment will also prevent such behavior.++ // try and get active screen+ if (parent != nullptr) {+ QScreen *screen = QGuiApplication::screenAt(parent->pos());+ m_currentScreen =+ screen ? QGuiApplication::screens().indexOf(screen) : 0;+ }+ QRect screen =+ QGuiApplication::screens().at(m_currentScreen)->availableGeometry();+ int x = values.at(0).toInt();+ int y = values.at(1).toInt();++ // make sure that the window is visible on the screen+ // all popups will popup on the active window the first time+ // so popups moved to other monitors will be moved back+ // when restarting OpenToonz.++ // This may be somewhat annoying if a user REALLY wants the popup+ // on another monitor by default, but this is better than+ // a user thinking the program is broken because they didn't notice+ // the popup on another monitor+ if (x > screen.right() - 50) x = screen.right() - 50;+ if (x < screen.left()) x = screen.left();+ if (y > screen.bottom() - 90) y = screen.bottom() - 90;+ if (y <= screen.top()) y = screen.top() + 50; // pad for window title+ setGeometry(x, y, values.at(2).toInt(), values.at(3).toInt());+ settings.setValue(m_name,+ QString::number(x) + " " + QString::number(y) + " " ++ QString::number(values.at(2).toInt()) + " " ++ QString::number(values.at(3).toInt()));}- QRect screen =- QGuiApplication::screens().at(m_currentScreen)->availableGeometry();- int x = values.at(0).toInt();- int y = values.at(1).toInt();-- // make sure that the window is visible on the screen- // all popups will popup on the active window the first time- // so popups moved to other monitors will be moved back- // when restarting OpenToonz.-- // This may be somewhat annoying if a user REALLY wants the popup- // on another monitor by default, but this is better than- // a user thinking the program is broken because they didn't notice- // the popup on another monitor- if (x > screen.right() - 50) x = screen.right() - 50;- if (x < screen.left()) x = screen.left();- if (y > screen.bottom() - 90) y = screen.bottom() - 90;- if (y <= screen.top()) y = screen.top() + 50; // pad for window title- setGeometry(x, y, values.at(2).toInt(), values.at(3).toInt());- settings.setValue(m_name, QString::number(x) + " " + QString::number(y) +- " " + QString::number(values.at(2).toInt()) +- " " + QString::number(values.at(3).toInt()));}}//-----------------------------------------------------------------------------Dialog::~Dialog() {- if (m_name == QString()) return;+ if (m_name.isEmpty()) return;QRect r = geometry();QSettings settings(settingsPath, QSettings::IniFormat);@@ -358,15 +358,14 @@ void Dialog::resizeEvent(QResizeEvent *e) {//! By default, QDialogs always reset position/size upon hide events. However,//! we want to prevent such behaviour on Toonz Dialogs - this method is-//! reimplemented-//! for this purpose.+//! reimplemented for this purpose.void Dialog::hideEvent(QHideEvent *event) {int x = pos().rx();int y = pos().ry();// make sure the dialog is actually visible on a screenauto screens = QGuiApplication::screens();int currentScreen = 0;- for (int i = 0; i < screens.count(); i++) {+ for (int i = 0; i < screens.count(); ++i) {if (screens[i]->geometry().contains(pos())) {currentScreen = i;break;@@ -431,8 +430,8 @@ void Dialog::endVLayout() {addLayout(layout);- m_leftVLayout = 0;- m_rightVLayout = 0;+ m_leftVLayout = nullptr;+ m_rightVLayout = nullptr;}//-----------------------------------------------------------------------------@@ -453,7 +452,7 @@ void Dialog::endHLayout() {m_isMainHLayout = false;if (!m_mainHLayout) return;addLayout(m_mainHLayout);- m_mainHLayout = 0;+ m_mainHLayout = nullptr;}//-----------------------------------------------------------------------------@@ -464,9 +463,11 @@ void Dialog::endHLayout() {*/void Dialog::addWidget(QWidget *widget, bool isRight) {if (m_isMainVLayout) {- assert(m_leftVLayout && m_rightVLayout);- QWidget *w = new QWidget();- int h = widget->height() + m_layoutSpacing;+ // Sanity check – these should never be null if we are in vertical layout+ // mode+ if (!m_leftVLayout || !m_rightVLayout) return;+ // No need to allocate a dummy widget – we just need the height for spacing+ int h = widget->height() + m_layoutSpacing;if (isRight) {m_leftVLayout->addSpacing(h);m_rightVLayout->addWidget(widget);@@ -476,7 +477,7 @@ void Dialog::addWidget(QWidget *widget, bool isRight) {}return;} else if (m_isMainHLayout) {- assert(m_mainHLayout);+ if (!m_mainHLayout) return;m_mainHLayout->addWidget(widget);return;}@@ -497,7 +498,7 @@ layout containing*/void Dialog::addWidgets(QWidget *firstW, QWidget *secondW) {if (m_isMainVLayout) {- assert(m_leftVLayout && m_rightVLayout);+ if (!m_leftVLayout || !m_rightVLayout) return;m_leftVLayout->addWidget(firstW);m_rightVLayout->addWidget(secondW);return;@@ -510,7 +511,7 @@ void Dialog::addWidgets(QWidget *firstW, QWidget *secondW) {pairLayout->addWidget(secondW);if (m_isMainHLayout) {- assert(m_mainHLayout);+ if (!m_mainHLayout) return;m_mainHLayout->addLayout(pairLayout);return;}@@ -538,7 +539,7 @@ void Dialog::addWidget(QString labelName, QWidget *widget) {*/void Dialog::addLayout(QLayout *layout, bool isRight) {if (m_isMainVLayout) {- assert(m_leftVLayout && m_rightVLayout);+ if (!m_leftVLayout || !m_rightVLayout) return;int h = layout->itemAt(0)->widget()->height() + m_layoutSpacing;if (isRight) {m_leftVLayout->addSpacing(h);@@ -549,7 +550,7 @@ void Dialog::addLayout(QLayout *layout, bool isRight) {}return;} else if (m_isMainHLayout) {- assert(m_mainHLayout);+ if (!m_mainHLayout) return;m_mainHLayout->addLayout(layout);return;}@@ -575,7 +576,7 @@ void Dialog::addWidgetLayout(QWidget *widget, QLayout *layout) {layout->setSpacing(m_layoutSpacing);if (m_isMainVLayout) {- assert(m_leftVLayout && m_rightVLayout);+ if (!m_leftVLayout || !m_rightVLayout) return;m_leftVLayout->addWidget(widget);m_rightVLayout->addLayout(layout);return;@@ -589,7 +590,7 @@ void Dialog::addWidgetLayout(QWidget *widget, QLayout *layout) {pairLayout->addLayout(layout);if (m_isMainHLayout) {- assert(m_mainHLayout);+ if (!m_mainHLayout) return;m_mainHLayout->addLayout(pairLayout);return;}@@ -632,7 +633,7 @@ void Dialog::addLayouts(QLayout *firstL, QLayout *secondL) {secondL->setSpacing(m_layoutSpacing);if (m_isMainVLayout) {- assert(m_leftVLayout && m_rightVLayout);+ if (!m_leftVLayout || !m_rightVLayout) return;m_leftVLayout->addLayout(firstL);m_rightVLayout->addLayout(secondL);return;@@ -646,7 +647,7 @@ void Dialog::addLayouts(QLayout *firstL, QLayout *secondL) {pairLayout->addLayout(secondL);if (m_isMainHLayout) {- assert(m_mainHLayout);+ if (!m_mainHLayout) return;m_mainHLayout->addLayout(pairLayout);return;}@@ -659,12 +660,12 @@ void Dialog::addLayouts(QLayout *firstL, QLayout *secondL) {*/void Dialog::addSpacing(int spacing) {if (m_isMainVLayout) {- assert(m_leftVLayout && m_rightVLayout);+ if (!m_leftVLayout || !m_rightVLayout) return;m_leftVLayout->addSpacing(spacing);m_rightVLayout->addSpacing(spacing);return;} else if (m_isMainHLayout) {- assert(m_mainHLayout);+ if (!m_mainHLayout) return;m_mainHLayout->addSpacing(spacing);return;}@@ -679,13 +680,13 @@ void Dialog::addSpacing(int spacing) {void Dialog::addSeparator(QString name) {Separator *separator = new Separator(name);if (m_isMainVLayout) {- assert(m_leftVLayout && m_rightVLayout);+ if (!m_leftVLayout || !m_rightVLayout) return;endVLayout();addWidget(separator);beginVLayout();return;} else if (m_isMainHLayout) {- assert(m_mainHLayout);+ if (!m_mainHLayout) return;separator->setOrientation(false);m_mainHLayout->addWidget(separator);return;@@ -750,20 +751,18 @@ void Dialog::setButtonBarSpacing(int spacing) {/*! Add a widget to the button part of dialog.*/void Dialog::addButtonBarWidget(QWidget *widget) {+ if (!m_hasButton) return; // Silently ignore if the dialog has no button barwidget->setMinimumSize(65, 25);- assert(m_hasButton);- if (m_hasButton) {- m_buttonLayout->addWidget(widget);- m_buttonBarWidgets.push_back(widget);- }+ m_buttonLayout->addWidget(widget);+ m_buttonBarWidgets.push_back(widget);}//-----------------------------------------------------------------------------/*! Remove all widget from the button part of dialog.*/void Dialog::clearButtonBar() {- for (int i = 0; i < (int)m_buttonBarWidgets.size(); i++) {- m_buttonLayout->removeWidget(m_buttonBarWidgets[i]);+ for (auto widget : m_buttonBarWidgets) {+ m_buttonLayout->removeWidget(widget);}m_buttonBarWidgets.clear();}@@ -772,13 +771,11 @@ void Dialog::clearButtonBar() {/*! Add two widget to the button part of dialog.*/void Dialog::addButtonBarWidget(QWidget *first, QWidget *second) {+ if (!m_hasButton) return;first->setMinimumSize(65, 25);second->setMinimumSize(65, 25);- assert(m_hasButton);- if (m_hasButton) {- m_buttonLayout->addWidget(first);- m_buttonLayout->addWidget(second);- }+ m_buttonLayout->addWidget(first);+ m_buttonLayout->addWidget(second);}//-----------------------------------------------------------------------------@@ -786,15 +783,13 @@ void Dialog::addButtonBarWidget(QWidget *first, QWidget *second) {*/void Dialog::addButtonBarWidget(QWidget *first, QWidget *second,QWidget *third) {+ if (!m_hasButton) return;first->setMinimumSize(65, 25);second->setMinimumSize(65, 25);third->setMinimumSize(65, 25);- assert(m_hasButton);- if (m_hasButton) {- m_buttonLayout->addWidget(first);- m_buttonLayout->addWidget(second);- m_buttonLayout->addWidget(third);- }+ m_buttonLayout->addWidget(first);+ m_buttonLayout->addWidget(second);+ m_buttonLayout->addWidget(third);}//-----------------------------------------------------------------------------@@ -802,16 +797,14 @@ void Dialog::addButtonBarWidget(QWidget *first, QWidget *second,*/void Dialog::addButtonBarWidget(QWidget *first, QWidget *second, QWidget *third,QWidget *fourth) {+ if (!m_hasButton) return;first->setMinimumSize(65, 25);second->setMinimumSize(65, 25);third->setMinimumSize(65, 25);- assert(m_hasButton);- if (m_hasButton) {- m_buttonLayout->addWidget(first);- m_buttonLayout->addWidget(second);- m_buttonLayout->addWidget(third);- m_buttonLayout->addWidget(fourth);- }+ m_buttonLayout->addWidget(first);+ m_buttonLayout->addWidget(second);+ m_buttonLayout->addWidget(third);+ m_buttonLayout->addWidget(fourth);}//=============================================================================@@ -851,7 +844,7 @@ RadioButtonDialog::RadioButtonDialog(const QString &labelText,QButtonGroup *buttonGroup = new QButtonGroup(this);int i;- for (i = 0; i < radioButtonList.count(); i++) {+ for (i = 0; i < radioButtonList.count(); ++i) {QRadioButton *radioButton = new QRadioButton(radioButtonList.at(i));if (i == m_result - 1) radioButton->setChecked(true);radioButton->setFixedHeight(WidgetHeight);@@ -860,19 +853,20 @@ RadioButtonDialog::RadioButtonDialog(const QString &labelText,addWidget(radioButton);}- bool ret = connect(buttonGroup, SIGNAL(buttonClicked(int)),- SLOT(onButtonClicked(int)));+ // Connect buttonGroup using PMF syntax+ connect(buttonGroup, &QButtonGroup::idClicked, this,+ &RadioButtonDialog::onButtonClicked);endVLayout();QPushButton *applyButton = new QPushButton(QObject::tr("Apply"));- ret = ret && connect(applyButton, SIGNAL(clicked()), this, SLOT(onApply()));+ connect(applyButton, &QPushButton::clicked, this,+ &RadioButtonDialog::onApply);QPushButton *cancelButton = new QPushButton(QObject::tr("Cancel"));- ret = ret && connect(cancelButton, SIGNAL(clicked()), this, SLOT(onCancel()));+ connect(cancelButton, &QPushButton::clicked, this,+ &RadioButtonDialog::onCancel);addButtonBarWidget(applyButton, cancelButton);-- assert(ret);}//-----------------------------------------------------------------------------@@ -939,10 +933,8 @@ void ProgressDialog::setLabelText(const QString &text) {void ProgressDialog::setCancelButton(QPushButton *cancelButton) {m_cancelButton = cancelButton;- bool ret = connect(cancelButton, SIGNAL(clicked()), this, SLOT(onCancel()));- ret =- ret && connect(cancelButton, SIGNAL(clicked()), this, SIGNAL(canceled()));- assert(ret);+ connect(cancelButton, &QPushButton::clicked, this, &ProgressDialog::onCancel);+ connect(cancelButton, &QPushButton::clicked, this, &ProgressDialog::canceled);addButtonBarWidget(m_cancelButton);}@@ -1020,22 +1012,18 @@ int DVGui::MsgBox(MsgType type, const QString &text,// ButtonGroup: is used only to retrieve the clicked buttonQButtonGroup *buttonGroup = new QButtonGroup(&dialog);- for (int i = 0; i < (int)buttons.size(); i++) {+ for (int i = 0; i < (int)buttons.size(); ++i) {QPushButton *button = new QPushButton(buttons[i], &dialog);- if (defaultButtonIndex == i)- button->setDefault(true);- else- button->setDefault(false);+ button->setDefault(defaultButtonIndex == i);dialog.addButtonBarWidget(button);-buttonGroup->addButton(button, i + 1);}- QObject::connect(buttonGroup, SIGNAL(idClicked(int)), &dialog,- SLOT(done(int)));+ // Connect using PMF+ QObject::connect(buttonGroup, &QButtonGroup::idClicked, &dialog,+ &QDialog::done);dialog.raise();-return dialog.exec();}@@ -1060,7 +1048,7 @@ void DVGui::MsgBoxInPopup(MsgType type, const QString &text) {if (popupIsOpen) return;popupIsOpen = true;- Dialog dialog(0, true);+ Dialog dialog(nullptr, true);dialog.setWindowFlags(dialog.windowFlags() | Qt::WindowStaysOnTopHint);dialog.setAlignment(Qt::AlignLeft);@@ -1081,8 +1069,8 @@ void DVGui::MsgBoxInPopup(MsgType type, const QString &text) {button->setDefault(true);dialog.addButtonBarWidget(button);buttonGroup->addButton(button, 1);- QObject::connect(buttonGroup, SIGNAL(idClicked(int)), &dialog,- SLOT(done(int)));+ QObject::connect(buttonGroup, &QButtonGroup::idClicked, &dialog,+ &QDialog::done);while (!messageQueue.empty()) {MsgType type1 = messageQueue.first().first;@@ -1138,25 +1126,22 @@ int DVGui::MsgBox(const QString &text, const QString &button1Text,QButtonGroup *buttonGroup = new QButtonGroup(&dialog);QPushButton *button1 = new QPushButton(button1Text, &dialog);- button1->setDefault(false);- if (defaultButtonIndex == 0) button1->setDefault(true);+ button1->setDefault(defaultButtonIndex == 0);dialog.addButtonBarWidget(button1);buttonGroup->addButton(button1, 1);QPushButton *button2 = new QPushButton(button2Text, &dialog);- button2->setDefault(false);- if (defaultButtonIndex == 1) button2->setDefault(true);+ button2->setDefault(defaultButtonIndex == 1);dialog.addButtonBarWidget(button2);buttonGroup->addButton(button2, 2);QPushButton *button3 = new QPushButton(button3Text, &dialog);- button3->setDefault(false);- if (defaultButtonIndex == 2) button3->setDefault(true);+ button3->setDefault(defaultButtonIndex == 2);dialog.addButtonBarWidget(button3);buttonGroup->addButton(button3, 3);- QObject::connect(buttonGroup, SIGNAL(idClicked(int)), &dialog,- SLOT(done(int)));+ QObject::connect(buttonGroup, &QButtonGroup::idClicked, &dialog,+ &QDialog::done);dialog.raise();return dialog.exec();}@@ -1191,31 +1176,27 @@ int DVGui::MsgBox(const QString &text, const QString &button1Text,QButtonGroup *buttonGroup = new QButtonGroup(&dialog);QPushButton *button1 = new QPushButton(button1Text, &dialog);- button1->setDefault(false);- if (defaultButtonIndex == 0) button1->setDefault(true);+ button1->setDefault(defaultButtonIndex == 0);dialog.addButtonBarWidget(button1);buttonGroup->addButton(button1, 1);QPushButton *button2 = new QPushButton(button2Text, &dialog);- button2->setDefault(false);- if (defaultButtonIndex == 1) button2->setDefault(true);+ button2->setDefault(defaultButtonIndex == 1);dialog.addButtonBarWidget(button2);buttonGroup->addButton(button2, 2);QPushButton *button3 = new QPushButton(button3Text, &dialog);- button3->setDefault(false);- if (defaultButtonIndex == 2) button3->setDefault(true);+ button3->setDefault(defaultButtonIndex == 2);dialog.addButtonBarWidget(button3);buttonGroup->addButton(button3, 3);QPushButton *button4 = new QPushButton(button4Text, &dialog);- button4->setDefault(false);- if (defaultButtonIndex == 3) button4->setDefault(true);+ button4->setDefault(defaultButtonIndex == 3);dialog.addButtonBarWidget(button4);buttonGroup->addButton(button4, 4);- QObject::connect(buttonGroup, SIGNAL(idClicked(int)), &dialog,- SLOT(done(int)));+ QObject::connect(buttonGroup, &QButtonGroup::idClicked, &dialog,+ &QDialog::done);dialog.raise();return dialog.exec();}@@ -1264,19 +1245,15 @@ Dialog *DVGui::createMsgBox(MsgType type, const QString &text,// ButtonGroup: is used only to retrieve the clicked buttonQButtonGroup *buttonGroup = new QButtonGroup(dialog);- for (int i = 0; i < (int)buttons.size(); i++) {+ for (int i = 0; i < buttons.size(); ++i) {QPushButton *button = new QPushButton(buttons[i], dialog);- if (defaultButtonIndex == i)- button->setDefault(true);- else- button->setDefault(false);+ button->setDefault(defaultButtonIndex == i);dialog->addButtonBarWidget(button);-buttonGroup->addButton(button, i + 1);}- QObject::connect(buttonGroup, SIGNAL(idClicked(int)), dialog,- SLOT(done(int)));+ QObject::connect(buttonGroup, &QButtonGroup::idClicked, dialog,+ &QDialog::done);return dialog;}@@ -1313,14 +1290,10 @@ MessageAndCheckboxDialog *DVGui::createMsgandCheckbox(// ButtonGroup: is used only to retrieve the clicked buttonQButtonGroup *buttonGroup = new QButtonGroup(dialog);- for (int i = 0; i < (int)buttons.size(); i++) {+ for (int i = 0; i < buttons.size(); ++i) {QPushButton *button = new QPushButton(buttons[i], dialog);- if (defaultButtonIndex == i)- button->setDefault(true);- else- button->setDefault(false);+ button->setDefault(defaultButtonIndex == i);dialog->addButtonBarWidget(button);-buttonGroup->addButton(button, i + 1);}@@ -1332,10 +1305,10 @@ MessageAndCheckboxDialog *DVGui::createMsgandCheckbox(dialogCheckBox->setCheckState(defaultCheckBoxState);- QObject::connect(dialogCheckBox, SIGNAL(stateChanged(int)), dialog,- SLOT(onCheckboxChanged(int)));- QObject::connect(buttonGroup, SIGNAL(idClicked(int)), dialog,- SLOT(onButtonClicked(int)));+ QObject::connect(dialogCheckBox, &QCheckBox::stateChanged, dialog,+ &MessageAndCheckboxDialog::onCheckboxChanged);+ QObject::connect(buttonGroup, &QButtonGroup::idClicked, dialog,+ &MessageAndCheckboxDialog::onButtonClicked);return dialog;}@@ -1344,7 +1317,7 @@ MessageAndCheckboxDialog *DVGui::createMsgandCheckbox(QString DVGui::getText(const QString &title, const QString &labelText,const QString &text, bool *ok) {- Dialog dialog(0, true);+ Dialog dialog(nullptr, true);dialog.setWindowTitle(title);dialog.setWindowFlags(Qt::WindowStaysOnTopHint | Qt::WindowTitleHint |@@ -1362,8 +1335,8 @@ QString DVGui::getText(const QString &title, const QString &labelText,QPushButton *okBtn = new QPushButton(QObject::tr("OK"), &dialog);okBtn->setDefault(true);QPushButton *cancelBtn = new QPushButton(QObject::tr("Cancel"), &dialog);- QObject::connect(okBtn, SIGNAL(clicked()), &dialog, SLOT(accept()));- QObject::connect(cancelBtn, SIGNAL(clicked()), &dialog, SLOT(reject()));+ QObject::connect(okBtn, &QPushButton::clicked, &dialog, &QDialog::accept);+ QObject::connect(cancelBtn, &QPushButton::clicked, &dialog, &QDialog::reject);dialog.addButtonBarWidget(okBtn, cancelBtn);@@ -1378,12 +1351,10 @@ QString DVGui::getText(const QString &title, const QString &labelText,namespace {bool isStyleIdInPalette(int styleId, const TPalette *palette) {if (palette->getStyleCount() == 0) return false;- int i;- for (i = 0; i < palette->getPageCount(); i++) {+ for (int i = 0; i < palette->getPageCount(); ++i) {const TPalette::Page *page = palette->getPage(i);if (!page) return false; // The page should always be present- int j;- for (j = 0; j < page->getStyleCount(); j++)+ for (int j = 0; j < page->getStyleCount(); ++j)if (page->getStyleId(j) == styleId) return true;}return false;@@ -1397,12 +1368,10 @@ int DVGui::eraseStylesInDemand(TPalette *palette,TPalette *newPalette) {// Check if the palette styles are in use: eraseStylesInDemand()std::vector<int> styleIds;- int h;- for (h = 0; h < palette->getPageCount(); h++) {+ for (int h = 0; h < palette->getPageCount(); ++h) {TPalette::Page *page = palette->getPage(h);if (!page) continue; // The page should always be present- int k;- for (k = 0; k < page->getStyleCount(); k++) {+ for (int k = 0; k < page->getStyleCount(); ++k) {int styleId = page->getStyleId(k);bool isStyleIdInNewPalette =(!newPalette) ? false : isStyleIdInPalette(styleId, newPalette);@@ -1437,8 +1406,7 @@ int DVGui::eraseStylesInDemand(TPalette *palette, std::vector<int> styleIds,if (!someStyleIsUsed) return 1;// At least a style is selected and present in some level - ask user if and- // how styles- // should be deleted+ // how styles should be deletedQString question = QObject::tr("Styles you are going to delete are used to paint "@@ -1469,8 +1437,7 @@ int DVGui::eraseStylesInDemand(TPalette *palette, std::vector<int> styleIds,PaletteCmd::eraseStyles(levels, styleIds);QApplication::restoreOverrideCursor();+ // At this point ret is guaranteed to be 2 or 3assert(ret == 2 || ret == 3);- return ret == 2; // return true if need to delete Styles :D+ return ret == 2; // return true if need to delete Styles}--//-----------------------------------------------------------------------------diff --git a/toonz/sources/toonzqt/expressionfield.cpp b/toonz/sources/toonzqt/expressionfield.cppindex c7c46af1d..03d6635a7 100644--- a/toonz/sources/toonzqt/expressionfield.cpp+++ b/toonz/sources/toonzqt/expressionfield.cpp@@ -16,6 +16,7 @@#include <QToolTip>#include <QListView>#include <QLabel>+#include <memory>using namespace DVGui;using namespace TSyntax;@@ -28,7 +29,7 @@ class ExpressionField::SyntaxHighlighter final : public QSyntaxHighlighter {public:bool m_open;SyntaxHighlighter(QTextDocument *parent)- : QSyntaxHighlighter(parent), m_grammar(0), m_open(true) {}+ : QSyntaxHighlighter(parent), m_grammar(nullptr), m_open(true) {}~SyntaxHighlighter() {}void setGrammar(const Grammar *grammar) { m_grammar = grammar; }@@ -36,52 +37,47 @@ public:void highlightBlock(const QString &text) override {Parser parser(m_grammar);std::vector<SyntaxToken> tokens;- Parser::SyntaxStatus status =- parser.checkSyntax(tokens, text.toStdString());+ parser.checkSyntax(tokens, text.toStdString()); // status not used- int nextPos = 0;- for (int i = 0; i < (int)tokens.size(); i++) {+ for (size_t i = 0; i < tokens.size(); ++i) {QTextCharFormat fmt;int pos = tokens[i].m_pos;int length = tokens[i].m_length;int type = tokens[i].m_type;- nextPos = pos + length;switch (type) {case TSyntax::Unknown:fmt.setForeground(Qt::black);break;case TSyntax::Number:fmt.setForeground(QColor(0x50, 0x7d, 0x0));- break; // number+ break;case TSyntax::Constant:fmt.setForeground(QColor(0x50, 0x7d, 0x0));- break; // constant+ break;case TSyntax::Variable:fmt.setForeground(QColor(0x0, 0x88, 0xc8));- break; // var+ break;case TSyntax::Operator:fmt.setForeground(QColor(50, 0, 255));- break; // infix+ break;case TSyntax::Parenthesis:fmt.setForeground(QColor(50, 50, 255));- break; // bracket+ break;case TSyntax::Function:fmt.setForeground(QColor(0x0, 0x50, 0x7d));- break; // fname+ break;case TSyntax::Comma:fmt.setForeground(QColor(50, 20, 255));- break; // f ;-+ break;case TSyntax::UnexpectedToken:fmt.setForeground(QColor(0xdc, 0x0, 0x0));- break; // expression not found+ break;case TSyntax::Eos:fmt.setForeground(QColor(255, 127, 0));- break; // EOS+ break;case TSyntax::Mismatch:fmt.setForeground(QColor(255, 0, 0));- break; // token mismatch-+ break;default:fmt.setForeground(QColor(127, 127, 255));break;@@ -106,15 +102,15 @@ public:"color: black;}");setWindowFlags(Qt::Popup);setMouseTracking(true);- m_tooltip = new QLabel(0, Qt::ToolTip);- // Stesso stile del popuop che lo contiene.- m_tooltip->hide();-+ m_tooltip = new QLabel(nullptr, Qt::ToolTip);+ // Same style as the containing popup.m_tooltip->setObjectName("helpTooltip");m_tooltip->setAlignment(Qt::AlignLeft);m_tooltip->setIndent(1);m_tooltip->setWordWrap(false);+ m_tooltip->hide();}+void showEvent(QShowEvent *) override { showToolTip(currentIndex()); }void hideEvent(QHideEvent *) override { m_tooltip->hide(); }void currentChanged(const QModelIndex ¤t,@@ -152,9 +148,9 @@ protected:ExpressionField::ExpressionField(QWidget *parent): QTextEdit(parent), m_editing(false)- , m_grammar(0)- , m_syntaxHighlighter(0)- , m_completerPopup(0)+ , m_grammar(nullptr)+ , m_syntaxHighlighter(std::make_unique<SyntaxHighlighter>(document()))+ , m_completerPopup(nullptr), m_completerStartPos(0) {setFrameStyle(QFrame::StyledPanel);setObjectName("ExpressionField");@@ -162,28 +158,30 @@ ExpressionField::ExpressionField(QWidget *parent)setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);setTabChangesFocus(true);- // setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed));connect(this, SIGNAL(textChanged()), this, SLOT(onTextChanged()));#ifdef MACOSXsetFixedHeight(23);#else- setFixedHeight(20); // +40);+ setFixedHeight(20);#endif- m_completerPopup = new MyListView();- QStandardItemModel *model = new QStandardItemModel();- m_completerPopup->setModel(model);+ m_completerPopup = new MyListView();+ // Start with an empty model+ m_completerPopup->setModel(new QStandardItemModel());m_completerPopup->setFocusPolicy(Qt::NoFocus);m_completerPopup->setFocusProxy(this);m_completerPopup->installEventFilter(this);connect(m_completerPopup, SIGNAL(clicked(const QModelIndex &)), this,SLOT(insertCompletion(const QModelIndex &)));-- m_syntaxHighlighter = new SyntaxHighlighter(document());}-ExpressionField::~ExpressionField() { delete m_syntaxHighlighter; }+ExpressionField::~ExpressionField() {+ // Delete the popup's current model (Qt does not take ownership)+ delete m_completerPopup->model();+ delete m_completerPopup;+ // m_syntaxHighlighter is automatically deleted by unique_ptr+}void ExpressionField::showEvent(QShowEvent *e) { QTextEdit::showEvent(e); }@@ -199,19 +197,16 @@ std::string ExpressionField::getExpression() const {bool ExpressionField::event(QEvent *e) {if (e->type() == QEvent::ToolTip) {- QHelpEvent *helpEvent = static_cast<QHelpEvent *>(e);+ // QHelpEvent *helpEvent = static_cast<QHelpEvent *>(e);// openCompletionPopup();-} else if (e->type() == QEvent::ShortcutOverride) {e->accept();return true;}- // elsereturn QTextEdit::event(e);}void ExpressionField::keyPressEvent(QKeyEvent *e) {- // setStyleSheet("background-color: cyan");if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) {m_editing = false;emit expressionChanged();@@ -284,7 +279,6 @@ bool ExpressionField::eventFilter(QObject *obj, QEvent *e) {void ExpressionField::onTextChanged() {if (!m_editing) {m_editing = true;-// setStyleSheet("background: rgb(250,200,200)");}}@@ -319,28 +313,35 @@ bool ExpressionField::updateCompleterPopup() {return false;}+ // Delete the previous model (Qt does not take ownership)+ QAbstractItemModel *oldModel = m_completerPopup->model();+ if (oldModel) delete oldModel;+QStandardItemModel *model = new QStandardItemModel();std::string prefix = toLower(text.substr(start, pos - start));int prefixLength = prefix.length();int count = 0;- for (int i = 0; i < (int)m_suggestions.size(); i++) {+ for (size_t i = 0; i < m_suggestions.size(); ++i) {std::string item = m_suggestions[i].first;if ((int)item.length() >= prefixLength &&toLower(item.substr(0, prefixLength)) == prefix) {QStandardItem *item = new QStandardItem();item->setData(QString::fromStdString(m_suggestions[i].first),Qt::EditRole);- if (m_suggestions[i].second != "")+ if (!m_suggestions[i].second.empty())item->setData(QString::fromStdString(m_suggestions[i].second),Qt::ToolTipRole);model->appendRow(item);- count++;+ ++count;}}+if (count == 0) {+ delete model; // no matches, discard modelif (m_completerPopup->isVisible()) m_completerPopup->hide();return false;}+m_completerPopup->setModel(model);m_completerPopup->setCurrentIndex(model->index(0, 0));@@ -369,15 +370,16 @@ int ExpressionField::computeSuggestions() {int pos = textCursor().position();int start = pos;if (start > 0) {- start--;+ --start;while (start > 0) {char c = text[start - 1];if ((isascii(c) && isalpha(c)) || c == '_' ||(c == '.' && (start - 2 < 0 || (isascii(text[start - 2]) &&isalpha(text[start - 2]))))) {+ // continue} elsebreak;- start--;+ --start;}}if (start >= (int)text.length()) return 0;@@ -395,8 +397,6 @@ void ExpressionField::insertCompletion() {QString item =m_completerPopup->model()->data(index, Qt::EditRole).toString();QTextCursor tc = textCursor();- int pos = tc.position();- // tc.movePosition(m_completionStartPos, QTextCursor::KeepAnchor);tc.insertText(item);m_completerPopup->hide();}@@ -419,4 +419,4 @@ void ExpressionField::insertCompletion(const QModelIndex &index) {void ExpressionField::setGrammar(const Grammar *grammar) {m_grammar = grammar;m_syntaxHighlighter->setGrammar(grammar);-};+}diff --git a/toonz/sources/toonzqt/flipconsole.cpp b/toonz/sources/toonzqt/flipconsole.cppindex 34753c93c..05936cdec 100644--- a/toonz/sources/toonzqt/flipconsole.cpp+++ b/toonz/sources/toonzqt/flipconsole.cpp@@ -1,5 +1,3 @@--#include "toonzqt/flipconsole.h"// Include shared flipbook settings (e.g., FlipBookWhiteBgToggle) from toonz/#include "toonz/flipbooksettings.h"@@ -9,6 +7,7 @@#include "toonzqt/dvscrollwidget.h"#include "toonzqt/gutil.h"#include "toonzqt/flipconsoleowner.h"+#include "toonzqt/lineedit.h"// TnzLib includes#include "toonz/preferences.h"@@ -141,7 +140,7 @@ void FlipSlider::setFinishedColor(const QColor &color) {PBFinishedColor = color;}-FlipConsole *FlipConsole::m_currentConsole = 0;+FlipConsole *FlipConsole::m_currentConsole = nullptr;QList<FlipConsole *> FlipConsole::m_visibleConsoles;bool FlipConsole::m_isLinkedPlaying = false;bool FlipConsole::m_areLinked = false;@@ -164,57 +163,52 @@ void PlaybackExecutor::run() {// of the last second of playback.m_timer.start();- qint64 timeResolution =- 250 * 1000000; // Use a sufficient sampling resolution (currently 1/4- // sec). Fps calculation is made once per sample.+ qint64 timeResolution = 250 * 1000000; // 1/4 secint fps = m_fps, currSample = 0;qint64 playedFramesCount = 0;qint64 nextSampleInstant = timeResolution;- qint64 lastFrameCounts[4] = {0, 0, 0,- 0}; // Keep the last 4 'played frames' counts.- qint64 lastSampleInstants[4] = {0, 0, 0,- 0}; // Same for the last sampling instants-- qint64 targetFrameTime =- 1000000000 / (qint64)abs(m_fps); // User-required time between frames+ qint64 lastFrameCounts[4] = {0, 0, 0, 0};+ qint64 lastSampleInstants[4] = {0, 0, 0, 0};- qint64 emissionInstant = 0; // starting instant in which rendering is invoked- qint64 avgSwapTime = 0; // average time for swapping buffers- qint64 shortTermDelayAdjuster =- 0; // accumurate recent errors and adjust in short term+ qint64 targetFrameTime = 1000000000 / (qint64)abs(m_fps);+ qint64 emissionInstant = 0;+ qint64 avgSwapTime = 0;+ qint64 shortTermDelayAdjuster = 0;while (!m_abort) {emissionInstant = m_timer.nsecsElapsed();if (emissionInstant > nextSampleInstant) {- // Fps calculationqint64 framesCount = playedFramesCount - lastFrameCounts[currSample];qint64 elapsedTime = emissionInstant - lastSampleInstants[currSample];- fps = troundp((long double)(1000000000 * framesCount) /- (long double)elapsedTime);- targetFrameTime =- 1000000000 / (qint64)abs(m_fps); // m_fps could have changed...+ // Avoid division by zero if no frames were played in the sample period+ if (framesCount > 0) {+ fps = troundp((long double)(1000000000 * framesCount) /+ (long double)elapsedTime);+ }- // estimate time for swapping buffers- qint64 avgSwapTimeD = (elapsedTime / framesCount) - targetFrameTime;- if (avgSwapTime - avgSwapTimeD >- 20000000) // Reset beyond, say, 20 msecs tolerance.- avgSwapTime = avgSwapTimeD;- else- avgSwapTime += avgSwapTimeD;- avgSwapTime = std::min(targetFrameTime, std::max(avgSwapTime, (qint64)0));+ targetFrameTime =+ 1000000000 / (qint64)abs(m_fps); // m_fps could have changed++ if (framesCount > 0) {+ qint64 avgSwapTimeD = (elapsedTime / framesCount) - targetFrameTime;+ if (avgSwapTime - avgSwapTimeD > 20000000) // Reset beyond 20 msecs+ avgSwapTime = avgSwapTimeD;+ else+ avgSwapTime += avgSwapTimeD;+ avgSwapTime =+ std::min(targetFrameTime, std::max(avgSwapTime, (qint64)0));+ }- // prepare for the next samplinglastFrameCounts[currSample] = playedFramesCount;lastSampleInstants[currSample] = emissionInstant;currSample = (currSample + 1) % 4;nextSampleInstant = emissionInstant + timeResolution;}- // draw the next frameif (playedFramesCount) {qint64 delayAdjust = shortTermDelayAdjuster / 4;qint64 targetInstant =@@ -237,11 +231,7 @@ void PlaybackExecutor::run() {}if (FlipConsole::m_areLinked) {- // In case there are linked consoles, update them too.- // Their load time must be included in the fps calculation.- int i, consolesCount = FlipConsole::m_visibleConsoles.size();- for (i = 0; i < consolesCount; ++i) {- FlipConsole *console = FlipConsole::m_visibleConsoles.at(i);+ for (auto console : FlipConsole::m_visibleConsoles) {if (console->isLinkable() && console != FlipConsole::m_currentConsole)console->playbackExecutor().emitNextFrame(m_fps < 0 ? -fps : fps);}@@ -252,7 +242,6 @@ void PlaybackExecutor::run() {// accumurate error and slightly adjust waiting time for subsequent framesqint64 delay = m_timer.nsecsElapsed() - emissionInstant - targetFrameTime;- // just ignore a large errorif (delay < targetFrameTime) shortTermDelayAdjuster += delay;++playedFramesCount;@@ -265,7 +254,7 @@ void PlaybackExecutor::run() {//==========================================================================================FlipSlider::FlipSlider(QWidget *parent)- : QAbstractSlider(parent), m_enabled(false), m_progressBarStatus(0) {+ : QAbstractSlider(parent), m_enabled(false), m_progressBarStatus(nullptr) {setObjectName("FlipSlider");setOrientation(Qt::Horizontal);setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);@@ -444,7 +433,7 @@ FlipConsole::FlipConsole(QVBoxLayout *mainLayout, std::vector<int> gadgetsMask,bool isLinkable, QWidget *customWidget,const QString &customizeId,FlipConsoleOwner *consoleOwner, bool enableBlanks)- : m_gadgetsMask(gadgetsMask)+ : m_gadgetsMask(std::move(gadgetsMask)), m_from(1), m_to(1), m_step(1)@@ -455,13 +444,13 @@ FlipConsole::FlipConsole(QVBoxLayout *mainLayout, std::vector<int> gadgetsMask,, m_sceneFps(24), m_isPlay(false), m_reverse(false)- , m_doubleRed(0)- , m_doubleGreen(0)- , m_doubleBlue(0)- , m_doubleRedAction(0)- , m_doubleGreenAction(0)- , m_doubleBlueAction(0)- , m_fpsSlider(0)+ , m_doubleRed(nullptr)+ , m_doubleGreen(nullptr)+ , m_doubleBlue(nullptr)+ , m_doubleRedAction(nullptr)+ , m_doubleGreenAction(nullptr)+ , m_doubleBlueAction(nullptr)+ , m_fpsSlider(nullptr), m_markerFrom(0), m_markerTo(-1), m_playbackExecutor()@@ -470,27 +459,27 @@ FlipConsole::FlipConsole(QVBoxLayout *mainLayout, std::vector<int> gadgetsMask,, m_blankColor(TPixel::Transparent), m_blanksToDraw(0), m_isLinkable(isLinkable)- , m_customAction(0)+ , m_customAction(nullptr), m_customizeMask((eShowHowMany - 1) & ~eShowGainControls)- , m_fpsLabelAction(0)- , m_fpsSliderAction(0)- , m_fpsFieldAction(0)- , m_fpsField(0)+ , m_fpsLabelAction(nullptr)+ , m_fpsSliderAction(nullptr)+ , m_fpsFieldAction(nullptr)+ , m_fpsField(nullptr), m_customizeId(customizeId)- , m_histoSep(0)- , m_filledRasterSep(0)- , m_viewerSep(0)- , m_bgSep(0)- , m_vcrSep(0)- , m_compareSep(0)- , m_saveSep(0)- , m_colorFilterSep(0)- , m_subcamSep(0)- , m_playToolBar(0)- , m_colorFilterGroup(0)- , m_fpsLabel(0)+ , m_histoSep(nullptr)+ , m_filledRasterSep(nullptr)+ , m_viewerSep(nullptr)+ , m_bgSep(nullptr)+ , m_vcrSep(nullptr)+ , m_compareSep(nullptr)+ , m_saveSep(nullptr)+ , m_colorFilterSep(nullptr)+ , m_subcamSep(nullptr)+ , m_playToolBar(nullptr)+ , m_colorFilterGroup(nullptr)+ , m_fpsLabel(nullptr), m_consoleOwner(consoleOwner)- , m_enableBlankFrameButton(0)+ , m_enableBlankFrameButton(nullptr), m_prevGainStep(0), m_gainSep(nullptr), m_resetGainBtn(nullptr) {@@ -499,10 +488,7 @@ FlipConsole::FlipConsole(QVBoxLayout *mainLayout, std::vector<int> gadgetsMask,QString s = flipSettings.value(m_customizeId).toString();if (s != "") m_customizeMask = s.toUInt();- if (m_gadgetsMask.size() == 0) return;-- // mainLayout->setContentsMargins(1, 1, 1, 1);- // mainLayout->setSpacing(0);+ if (m_gadgetsMask.empty()) return;// create toolbars other than frame sliderif (hasButton(m_gadgetsMask, eFrames)) {@@ -538,14 +524,9 @@ FlipConsole::FlipConsole(QVBoxLayout *mainLayout, std::vector<int> gadgetsMask,applyCustomizeMask();- bool ret = connect(&m_playbackExecutor,- SIGNAL(nextFrame(int, QElapsedTimer *, qint64)), this,- SLOT(onNextFrame(int, QElapsedTimer *, qint64)),- Qt::BlockingQueuedConnection);-- assert(ret);-- // parent->setLayout(mainLayout);+ // connect using PMF+ connect(&m_playbackExecutor, &PlaybackExecutor::nextFrame, this,+ &FlipConsole::onNextFrame, Qt::BlockingQueuedConnection);}//-----------------------------------------------------------------------------@@ -593,7 +574,7 @@ void FlipConsole::setActive(bool active) {if (!m_visibleConsoles.empty())m_currentConsole = m_visibleConsoles.last();else- m_currentConsole = 0;+ m_currentConsole = nullptr;}}}@@ -609,7 +590,8 @@ class DoubleButton final : public QToolButton {bool m_enabled;public:- DoubleButton(QAction *firstAction, QAction *secondAction, QWidget *parent = 0)+ DoubleButton(QAction *firstAction, QAction *secondAction,+ QWidget *parent = nullptr): QToolButton(parent), m_firstAction(firstAction), m_secondAction(secondAction)@@ -700,8 +682,8 @@ void FlipConsole::enableButton(UINT button, bool enable, bool doShowHide) {if (!m_playToolBar) return;QList<QAction *> list = m_playToolBar->actions();- for (size_t i = 0; i < list.size(); i++)- if (list[i]->data().toUInt() == button) {+ for (auto act : list)+ if (act->data().toUInt() == button) {if (button == eSound) {if (doShowHide) {m_soundSep->setVisible(enable);@@ -717,11 +699,11 @@ void FlipConsole::enableButton(UINT button, bool enable, bool doShowHide) {}}if (doShowHide) {- list[i]->setVisible(enable);+ act->setVisible(enable);} else {- list[i]->setEnabled(enable);+ act->setEnabled(enable);}- if (!enable && list[i]->isChecked()) pressButton((EGadget)button);+ if (!enable && act->isChecked()) pressButton((EGadget)button);return;}@@ -749,7 +731,7 @@ void FlipConsole::toggleLinked() {m_areLinked = !m_areLinked;int i;- FlipConsole *playingConsole = 0;+ FlipConsole *playingConsole = nullptr;for (i = 0; i < m_visibleConsoles.size(); i++) {playingConsole = m_visibleConsoles.at(i);if (playingConsole->m_isLinkable &&@@ -757,7 +739,7 @@ void FlipConsole::toggleLinked() {break;}- if (i == m_visibleConsoles.size()) return;+ if (i == m_visibleConsoles.size()) return; // no playing console found// if we are here, flip is playing!m_isLinkedPlaying = m_areLinked;@@ -953,9 +935,8 @@ QAction *FlipConsole::createCheckedButtonWithBorderImage(action->setDefaultWidget(button);button->setObjectName("chackableButtonWithImageBorder");- connect(button, SIGNAL(triggered(QAction *)), this,- SLOT(onButtonPressed(QAction *)));- // connect(action, SIGNAL(toggled(bool)), button, SLOT(setChecked(bool)));+ connect(button, &QToolButton::triggered, this,+ [this](QAction *act) { onButtonPressed(act); });m_playToolBar->addAction(action);return action;}@@ -985,9 +966,6 @@ QAction *FlipConsole::createDoubleButton(widget = new DoubleButton(action1, action2, this);return m_playToolBar->addWidget(widget);-- // m_playToolBar->addAction(action1);- // m_playToolBar->addAction(action2);}//-----------------------------------------------------------------------------@@ -1032,8 +1010,6 @@ void FlipConsole::onCustomizeButtonPressed(QAction *a) {//----------------------------------------------------------------------------------------------void FlipConsole::applyCustomizeMask() {enableButton(eSave, m_customizeMask & eShowSave);- // if(m_saveSep)- // m_saveSep->setVisible(m_customizeMask&eShowSave);enableButton(eSaveImg, m_customizeMask & eShowCompare);enableButton(eCompare, m_customizeMask & eShowCompare);@@ -1043,14 +1019,13 @@ void FlipConsole::applyCustomizeMask() {enableButton(eDefineLoadBox, m_customizeMask & eShowDefineLoadBox);enableButton(eUseLoadBox, m_customizeMask & eShowUseLoadBox);if (m_subcamSep) {- int count = m_gadgetsMask.size();bool hasDefineLoadBox =- std::find(m_gadgetsMask.begin(), m_gadgetsMask.end(), eDefineLoadBox) ==+ std::find(m_gadgetsMask.begin(), m_gadgetsMask.end(), eDefineLoadBox) !=m_gadgetsMask.end();bool hasUseLoadBox = std::find(m_gadgetsMask.begin(), m_gadgetsMask.end(),- eUseLoadBox) == m_gadgetsMask.end();+ eUseLoadBox) != m_gadgetsMask.end();bool hasDefineSubCam = std::find(m_gadgetsMask.begin(), m_gadgetsMask.end(),- eDefineSubCamera) == m_gadgetsMask.end();+ eDefineSubCamera) != m_gadgetsMask.end();m_subcamSep->setVisible((hasDefineSubCam && m_customizeMask & eShowDefineSubCamera) ||(hasDefineLoadBox && m_customizeMask & eShowDefineLoadBox) ||@@ -1198,31 +1173,25 @@ void FlipConsole::createCustomizeMenu(bool withCustomWidget) {if (hasButton(m_gadgetsMask, eDecreaseGain))addMenuItem(eShowGainControls, tr("Gain Controls"), menu);- bool ret = connect(menu, SIGNAL(triggered(QAction *)), this,- SLOT(onCustomizeButtonPressed(QAction *)));- assert(ret);+ connect(menu, &QMenu::triggered, this,+ &FlipConsole::onCustomizeButtonPressed);}}//-----------------------------------------------------------------------------void FlipConsole::createPlayToolBar(QWidget *customWidget) {- bool ret = true;- bool withCustomWidget = customWidget != 0;+ bool withCustomWidget = customWidget != nullptr;m_playToolBar = new QToolBar(this);m_playToolBar->setMovable(false);m_playToolBar->setObjectName("FlipConsolePlayToolBar");m_playToolBar->setIconSize(QSize(20, 20));- // m_playToolBar->setObjectName("chackableButtonToolBar");-- // m_playToolBar->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);createCustomizeMenu(withCustomWidget);if (hasButton(m_gadgetsMask, eSave)) {createButton(eSave, "save", tr("&Save Images"), false);- // m_saveSep = m_playToolBar->addSeparator();}// snapshot@@ -1257,7 +1226,12 @@ void FlipConsole::createPlayToolBar(QWidget *customWidget) {if (separator) m_subcamSep = m_playToolBar->addSeparator();// preview BGs- QActionGroup *group = new QActionGroup(m_playToolBar);+ QActionGroup *group = nullptr;+ if (hasButton(m_gadgetsMask, eWhiteBg) ||+ hasButton(m_gadgetsMask, eBlackBg) ||+ hasButton(m_gadgetsMask, eCheckBg)) {+ group = new QActionGroup(m_playToolBar);+ }if (hasButton(m_gadgetsMask, eWhiteBg))createOnOffButton(eWhiteBg, "preview_white", tr("&White Background"),group);@@ -1271,7 +1245,13 @@ void FlipConsole::createPlayToolBar(QWidget *customWidget) {m_bgSep = m_playToolBar->addSeparator();// VCR buttons- QActionGroup *playGroup = new QActionGroup(m_playToolBar);+ QActionGroup *playGroup = nullptr;+ if (hasButton(m_gadgetsMask, eFirst) || hasButton(m_gadgetsMask, ePrev) ||+ hasButton(m_gadgetsMask, ePause) || hasButton(m_gadgetsMask, ePlay) ||+ hasButton(m_gadgetsMask, eLoop) || hasButton(m_gadgetsMask, eNext) ||+ hasButton(m_gadgetsMask, eLast)) {+ playGroup = new QActionGroup(m_playToolBar);+ }if (hasButton(m_gadgetsMask, eFirst))createButton(eFirst, "framefirst", tr("&First Frame"), false);if (hasButton(m_gadgetsMask, ePrev))@@ -1319,8 +1299,8 @@ void FlipConsole::createPlayToolBar(QWidget *customWidget) {eBlue, eGBlue, "half_B", "half_bw", tr("Blue Channel"),tr("Blue Channel in Grayscale"), m_colorFilterGroup, m_doubleBlue);- ret = ret && connect(m_colorFilterGroup, SIGNAL(triggered(QAction *)), this,- SLOT(onButtonPressed(QAction *)));+ connect(m_colorFilterGroup, &QActionGroup::triggered, this,+ [this](QAction *act) { onButtonPressed(act); });if (hasButton(m_gadgetsMask, eMatte))createButton(eMatte, "channelmatte", tr("Alpha Channel"), true);@@ -1346,7 +1326,7 @@ void FlipConsole::createPlayToolBar(QWidget *customWidget) {if (hasButton(m_gadgetsMask, eFilledRaster)) {createOnOffButton(eFilledRaster, "preview_white",- tr("&Display Areas as Filled"), 0);+ tr("&Display Areas as Filled"), nullptr);m_filledRasterSep = m_playToolBar->addSeparator();}@@ -1364,13 +1344,14 @@ void FlipConsole::createPlayToolBar(QWidget *customWidget) {if (hasButton(m_gadgetsMask, eZoomOut))createButton(eZoomOut, "zoomout", tr("&Zoom Out"), false);if (hasButton(m_gadgetsMask, eFlipHorizontal))- createButton(eFlipHorizontal, "fliphoriz", tr("&Flip Horizontally"), true);+ createButton(eFlipHorizontal, "fliphoriz", tr("&Flip Horizontally"),+ true);if (hasButton(m_gadgetsMask, eFlipVertical))createButton(eFlipVertical, "flipvert", tr("&Flip Vertically"), true);if (hasButton(m_gadgetsMask, eRotateLeft))- createButton(eRotateLeft, "rotateleft", tr("&Rotate Left"), false);+ createButton(eRotateLeft, "rotateleft", tr("&Rotate Left"), false);if (hasButton(m_gadgetsMask, eRotateRight))- createButton(eRotateRight, "rotateright", tr("&Rotate Right"), false);+ createButton(eRotateRight, "rotateright", tr("&Rotate Right"), false);if (hasButton(m_gadgetsMask, eResetView))createButton(eResetView, "reset", tr("&Reset View"), false);m_viewerSep = m_playToolBar->addSeparator();@@ -1394,14 +1375,13 @@ void FlipConsole::createPlayToolBar(QWidget *customWidget) {}// for all actions in this toolbar- ret = ret && connect(m_playToolBar, SIGNAL(actionTriggered(QAction *)), this,- SLOT(onButtonPressed(QAction *)));+ connect(m_playToolBar, &QToolBar::actionTriggered, this,+ [this](QAction *act) { onButtonPressed(act); });setChecked(ePause, true);setChecked(eWhiteBg, FlipBookWhiteBgToggle);setChecked(eBlackBg, FlipBookBlackBgToggle);setChecked(eCheckBg, FlipBookCheckBgToggle);- assert(ret);}//-----------------------------------------------------------------------------@@ -1430,10 +1410,10 @@ void FlipConsole::setChecked(UINT button, bool state) {int i;if (m_playToolBar) {QObjectList objectList = m_playToolBar->children();- for (i = 0; i < (int)objectList.size(); i++) {- QAction *action = dynamic_cast<QAction *>(objectList[i]);+ for (auto obj : objectList) {+ QAction *action = dynamic_cast<QAction *>(obj);if (!action) {- QToolButton *toolButton = dynamic_cast<QToolButton *>(objectList[i]);+ QToolButton *toolButton = dynamic_cast<QToolButton *>(obj);if (!toolButton) continue;action = toolButton->defaultAction();}@@ -1446,9 +1426,9 @@ void FlipConsole::setChecked(UINT button, bool state) {if (m_colorFilterGroup) {QList<QAction *> list = m_colorFilterGroup->actions();- for (i = 0; i < (int)list.size(); i++)- if (list[i]->data().toUInt() == button) {- list[i]->setChecked(state);+ for (auto act : list)+ if (act->data().toUInt() == button) {+ act->setChecked(state);return;}}@@ -1462,14 +1442,14 @@ bool FlipConsole::isChecked(UINT button) const {if (m_playToolBar) {list = m_playToolBar->actions();- for (i = 0; i < (int)list.size(); i++)- if (list[i]->data().toUInt() == button) return list[i]->isChecked();+ for (auto act : list)+ if (act->data().toUInt() == button) return act->isChecked();}if (m_colorFilterGroup) {list = m_colorFilterGroup->actions();- for (i = 0; i < (int)list.size(); i++)- if (list[i]->data().toUInt() == button) return list[i]->isChecked();+ for (auto act : list)+ if (act->data().toUInt() == button) return act->isChecked();}return false;@@ -1479,10 +1459,9 @@ bool FlipConsole::isChecked(UINT button) const {void FlipConsole::pressLinkedConsoleButton(UINT button, FlipConsole *parent) {int i;- assert(parent);+ if (!parent) return; // guard against null parent- for (i = 0; i < m_visibleConsoles.size(); i++) {- FlipConsole *console = m_visibleConsoles.at(i);+ for (auto console : m_visibleConsoles) {if (console->m_isLinkable && console != parent) {console->setChecked(button, parent ? parent->isChecked(button) : true);console->doButtonPressed(button);@@ -1533,7 +1512,7 @@ void FlipConsole::onButtonPressed(int button) {//-----------------------------------------------------------------------------void FlipConsole::pressButton(EGadget buttonId) {FlipConsole *console = this;- if (m_visibleConsoles.indexOf(this) < 0 && m_visibleConsoles.size() > 0) {+ if (m_visibleConsoles.indexOf(this) < 0 && !m_visibleConsoles.empty()) {console = m_visibleConsoles.at(0);console->makeCurrent();}@@ -1610,8 +1589,6 @@ void FlipConsole::doButtonPressed(UINT button) {break;case ePlay:case eLoop:- // if ( isChecked(ePlay, false);- // setChecked(eLoop, false);m_editCurrFrame->disconnect();m_currFrameSlider->disconnect();@@ -1688,18 +1665,16 @@ void FlipConsole::doButtonPressed(UINT button) {}if (m_fpsLabel) m_fpsLabel->setText(tr(" FPS "));if (m_fpsField) m_fpsField->setLineEditBackgroundColor(getFpsFieldColor());- // setChecked(ePlay, false);- // setChecked(eLoop, false);- connect(m_editCurrFrame, SIGNAL(editingFinished()), this,- SLOT(OnSetCurrentFrame()));- connect(m_currFrameSlider, SIGNAL(flipSliderReleased()), this,- SLOT(OnFrameSliderRelease()));- connect(m_currFrameSlider, SIGNAL(flipSliderPressed()), this,- SLOT(OnFrameSliderPress()));- connect(m_currFrameSlider, SIGNAL(valueChanged(int)), this,- SLOT(OnSetCurrentFrame(int)));- connect(m_currFrameSlider, SIGNAL(flipSliderReleased()), this,- SLOT(onSliderRelease()));+ connect(m_editCurrFrame, &LineEdit::editingFinished, this,+ [this]() { OnSetCurrentFrame(); });+ connect(m_currFrameSlider, &FlipSlider::flipSliderReleased, this,+ [this]() { OnFrameSliderRelease(); });+ connect(m_currFrameSlider, &FlipSlider::flipSliderPressed, this,+ [this]() { OnFrameSliderPress(); });+ connect(m_currFrameSlider, &FlipSlider::valueChanged, this,+ [this](int value) { OnSetCurrentFrame(value); });+ connect(m_currFrameSlider, &FlipSlider::flipSliderReleased, this,+ [this]() { onSliderRelease(); });emit playStateChanged(false);return;@@ -1804,7 +1779,7 @@ void FlipConsole::doButtonPressed(UINT button) {break;default:- assert(false);+ // assert(false); // replaced with runtime checkbreak;}@@ -1861,12 +1836,12 @@ QFrame *FlipConsole::createFrameSlider() {}frameSliderFrame->setLayout(frameSliderLayout);- connect(m_editCurrFrame, SIGNAL(editingFinished()), this,- SLOT(OnSetCurrentFrame()));- connect(m_currFrameSlider, SIGNAL(valueChanged(int)), this,- SLOT(OnSetCurrentFrame(int)));- connect(m_currFrameSlider, SIGNAL(flipSliderReleased()), this,- SLOT(OnFrameSliderRelease()));+ connect(m_editCurrFrame, &LineEdit::editingFinished, this,+ [this]() { OnSetCurrentFrame(); });+ connect(m_currFrameSlider, &FlipSlider::valueChanged, this,+ [this](int value) { OnSetCurrentFrame(value); });+ connect(m_currFrameSlider, &FlipSlider::flipSliderReleased, this,+ [this]() { OnFrameSliderRelease(); });return frameSliderFrame;}@@ -1900,9 +1875,10 @@ QFrame *FlipConsole::createFpsSlider() {}fpsSliderFrame->setLayout(hLay);- connect(m_fpsSlider, SIGNAL(valueChanged(int)), this,- SLOT(setCurrentFPS(int)));- connect(m_fpsField, SIGNAL(editingFinished()), this, SLOT(onFPSEdited()));+ connect(m_fpsSlider, &QScrollBar::valueChanged, this,+ [this](int value) { setCurrentFPS(value); });+ connect(m_fpsField, &LineEdit::editingFinished, this,+ [this]() { onFPSEdited(); });return fpsSliderFrame;}@@ -1924,7 +1900,6 @@ void FlipConsole::setFrameRange(int from, int to, int step, int current) {m_to -= (m_to - m_from) % m_step;m_framesCount = (m_to - m_from) / m_step + 1;m_currFrameSlider->blockSignals(true);- // m_currFrameSlider->setRange(0, m_framesCount-1);m_currFrameSlider->setRange(m_from, m_to);m_currFrameSlider->setSingleStep(m_step);m_currFrameSlider->blockSignals(false);@@ -1987,8 +1962,7 @@ void FlipConsole::OnSetCurrentFrame() {m_consoleOwner->onDrawFrame(m_currentFrame, m_settings);if (m_areLinked)- for (i = 0; i < m_visibleConsoles.size(); i++) {- FlipConsole *console = m_visibleConsoles.at(i);+ for (auto console : m_visibleConsoles) {if (console->m_isLinkable && console != this)console->incrementCurrentFrame(deltaFrame);}@@ -2021,14 +1995,17 @@ void FlipConsole::OnSetCurrentFrame(int index) {m_currentFrame = index;- assert(m_currentFrame <= m_to);+ // We'll keep the assert as a debug check; could be removed if not needed.+ // If index is out of bounds, clamp it.+ if (m_currentFrame > m_to) m_currentFrame = m_to;+ if (m_currentFrame < m_from) m_currentFrame = m_from;+m_editCurrFrame->setText(QString::number(m_currentFrame));m_consoleOwner->onDrawFrame(m_currentFrame, m_settings);if (m_areLinked)- for (int i = 0; i < m_visibleConsoles.size(); i++) {- FlipConsole *console = m_visibleConsoles.at(i);+ for (auto console : m_visibleConsoles) {if (console->m_isLinkable && console != this)console->incrementCurrentFrame(deltaFrame);}@@ -2164,5 +2141,3 @@ createToggleAction(parent, "A_Flip_Pause", "Pause", FlipConsole::ePause);createToggleAction(parent, "A_Flip_Loop", "Loop", FlipConsole::eLoop);*/}} flipConsoleActionsCreator;--//--------------------------------------------------------------------diff --git a/toonz/sources/toonzqt/paletteviewer.cpp b/toonz/sources/toonzqt/paletteviewer.cppindex 0f81132b2..bb198c6da 100644--- a/toonz/sources/toonzqt/paletteviewer.cpp+++ b/toonz/sources/toonzqt/paletteviewer.cpp@@ -103,28 +103,28 @@ PaletteViewer::PaletteViewer(QWidget *parent, PaletteViewType viewType,bool hasSaveToolBar, bool hasPageCommand,bool hasPasteColors): QFrame(parent)- , m_tabBarContainer(0)- , m_pagesBar(0)- , m_paletteToolBar(0)- , m_savePaletteToolBar(0)- , m_pageViewer(0)- , m_pageViewerScrollArea(0)+ , m_tabBarContainer(nullptr)+ , m_pagesBar(nullptr)+ , m_paletteToolBar(nullptr)+ , m_savePaletteToolBar(nullptr)+ , m_pageViewer(nullptr)+ , m_pageViewerScrollArea(nullptr), m_indexPageToDelete(-1), m_viewType(viewType)- , m_frameHandle(0)- , m_paletteHandle(0)- , m_changeStyleCommand(0)- , m_xsheetHandle(0)+ , m_frameHandle(nullptr)+ , m_paletteHandle(nullptr)+ , m_changeStyleCommand(nullptr)+ , m_xsheetHandle(nullptr), m_hasSavePaletteToolbar(hasSaveToolBar), m_hasPageCommand(hasPageCommand), m_isSaveActionEnabled(true)- , m_lockPaletteAction(0)- , m_lockPaletteToolButton(0)+ , m_lockPaletteAction(nullptr)+ , m_lockPaletteToolButton(nullptr), m_toolbarOnTop(false), m_showToolbarOnTopAct(nullptr)- , m_toolbarContainer(0)+ , m_toolbarContainer(nullptr), m_styleNameEditor(nullptr)- , m_hLayout(0) {+ , m_hLayout(nullptr) {setObjectName("OnePixelMarginFrame");setFrameStyle(QFrame::StyledPanel);@@ -191,14 +191,13 @@ PaletteViewer::PaletteViewer(QWidget *parent, PaletteViewType viewType,}setLayout(mainLayout);- connect(m_pagesBar, SIGNAL(currentChanged(int)), this,- SLOT(setPageView(int)));- connect(m_pagesBar, SIGNAL(movePage(int, int)), this,- SLOT(movePage(int, int)));- connect(m_pageViewer, SIGNAL(changeWindowTitleSignal()), this,- SLOT(changeWindowTitle()));- connect(m_pageViewer, SIGNAL(switchToPage(int)), this,- SLOT(onSwitchToPage(int)));+ connect(m_pagesBar, &PaletteTabBar::currentChanged, this,+ &PaletteViewer::setPageView);+ connect(m_pagesBar, &PaletteTabBar::movePage, this, &PaletteViewer::movePage);+ connect(m_pageViewer, &PageViewer::changeWindowTitleSignal, this,+ &PaletteViewer::changeWindowTitle);+ connect(m_pageViewer, &PageViewer::switchToPage, this,+ &PaletteViewer::onSwitchToPage);changeWindowTitle();@@ -317,30 +316,29 @@ void PaletteViewer::load(QSettings &settings) {void PaletteViewer::setPaletteHandle(TPaletteHandle *paletteHandle) {if (m_paletteHandle == paletteHandle) return;- bool ret = true;- if (m_paletteHandle) ret = ret && disconnect(m_paletteHandle, 0, this, 0);+ if (m_paletteHandle) {+ disconnect(m_paletteHandle, nullptr, this, nullptr);+ }m_paletteHandle = paletteHandle;if (m_paletteHandle && isVisible()) {- ret = ret && connect(m_paletteHandle, SIGNAL(paletteSwitched()), this,- SLOT(onPaletteSwitched()));- ret = ret && connect(m_paletteHandle, SIGNAL(paletteChanged()), this,- SLOT(onPaletteChanged()));- ret = ret && connect(m_paletteHandle, SIGNAL(paletteChanged()), this,- SLOT(changeWindowTitle()));- ret = ret && connect(m_paletteHandle, SIGNAL(paletteTitleChanged()), this,- SLOT(changeWindowTitle()));- ret = ret && connect(m_paletteHandle, SIGNAL(colorStyleSwitched()), this,- SLOT(onColorStyleSwitched()));- ret = ret && connect(m_paletteHandle, SIGNAL(colorStyleChanged(bool)), this,- SLOT(changeWindowTitle()));- ret = ret && connect(m_paletteHandle, SIGNAL(paletteDirtyFlagChanged()),- this, SLOT(changeWindowTitle()));+ connect(m_paletteHandle, &TPaletteHandle::paletteSwitched, this,+ &PaletteViewer::onPaletteSwitched);+ connect(m_paletteHandle, &TPaletteHandle::paletteChanged, this,+ &PaletteViewer::onPaletteChanged);+ connect(m_paletteHandle, &TPaletteHandle::paletteChanged, this,+ &PaletteViewer::changeWindowTitle);+ connect(m_paletteHandle, &TPaletteHandle::paletteTitleChanged, this,+ &PaletteViewer::changeWindowTitle);+ connect(m_paletteHandle, &TPaletteHandle::colorStyleSwitched, this,+ &PaletteViewer::onColorStyleSwitched);+ connect(m_paletteHandle, &TPaletteHandle::colorStyleChanged, this,+ &PaletteViewer::changeWindowTitle);+ connect(m_paletteHandle, &TPaletteHandle::paletteDirtyFlagChanged, this,+ &PaletteViewer::changeWindowTitle);}- assert(ret);-if (m_viewType != CLEANUP_PALETTE)m_keyFrameButton->setPaletteHandle(m_paletteHandle);m_pageViewer->setPaletteHandle(m_paletteHandle);@@ -367,7 +365,7 @@ void PaletteViewer::setXsheetHandle(TXsheetHandle *xsheetHandle) {}//------------------------------------------------------------------------------/*!for clearing level cache after "paste style" command called from style+/*! for clearing level cache after "paste style" command called from style* selection*/void PaletteViewer::setLevelHandle(TXshLevelHandle *levelHandle) {@@ -377,7 +375,7 @@ void PaletteViewer::setLevelHandle(TXshLevelHandle *levelHandle) {//-----------------------------------------------------------------------------TPalette *PaletteViewer::getPalette() {- if (!m_paletteHandle) return 0;+ if (!m_paletteHandle) return nullptr;return m_paletteHandle->getPalette();}@@ -396,12 +394,10 @@ void PaletteViewer::updateView() {void PaletteViewer::enableSaveAction(bool enable) {if (!m_savePaletteToolBar) return;- QList<QAction *> actions;- actions = m_savePaletteToolBar->actions();- enable = !getPalette() ? false : enable;- m_isSaveActionEnabled = enable;- int i;- for (i = 0; i < actions.count() - 1; i++) {+ QList<QAction *> actions = m_savePaletteToolBar->actions();+ enable = !getPalette() ? false : enable;+ m_isSaveActionEnabled = enable;+ for (int i = 0; i < actions.count() - 1; ++i) {QAction *act = actions[i];if (act->text() == tr("&Save Palette As") ||act->text() == tr("&Save Palette"))@@ -415,8 +411,8 @@ void PaletteViewer::enableSaveAction(bool enable) {void PaletteViewer::createTabBar() {m_pagesBar = new PaletteTabBar(this, m_hasPageCommand);- connect(m_pagesBar, SIGNAL(tabTextChanged(int)), this,- SLOT(onTabTextChanged(int)));+ connect(m_pagesBar, &PaletteTabBar::tabTextChanged, this,+ &PaletteViewer::onTabTextChanged);if (!getPalette()) return;@@ -443,8 +439,8 @@ void PaletteViewer::createPaletteToolBar() {m_lockPaletteToolButton->setChecked(getPalette()->isLocked());}- connect(m_lockPaletteToolButton, SIGNAL(clicked(bool)), this,- SLOT(setIsLocked(bool)));+ connect(m_lockPaletteToolButton, &QToolButton::clicked, this,+ &PaletteViewer::setIsLocked);m_paletteToolBar->addWidget(m_lockPaletteToolButton);} else if (m_viewType == STUDIO_PALETTE) {QToolButton *toolButton = new QToolButton(this);@@ -463,15 +459,15 @@ void PaletteViewer::createPaletteToolBar() {m_lockPaletteAction->setChecked(getPalette()->isLocked());}- connect(m_lockPaletteAction, SIGNAL(triggered(bool)), this,- SLOT(setIsLocked(bool)));- connect(m_lockPaletteAction, SIGNAL(toggled(bool)), toolButton,- SLOT(setChecked(bool)));+ connect(m_lockPaletteAction, &QAction::triggered, this,+ &PaletteViewer::setIsLocked);+ connect(m_lockPaletteAction, &QAction::toggled, toolButton,+ &QToolButton::setChecked);m_paletteToolBar->addWidget(toolButton);}- // Attenzione: alcune modifiche sono state fatte a livello di stylesheet+ // Attention: some changes have been made at stylesheet levelQToolButton *viewModeButton = new QToolButton(this);viewModeButton->setPopupMode(QToolButton::InstantPopup);@@ -483,8 +479,8 @@ void PaletteViewer::createPaletteToolBar() {QActionGroup *viewModeGroup = new QActionGroup(viewMode);viewModeGroup->setExclusive(true);- connect(viewModeGroup, SIGNAL(triggered(QAction *)), this,- SLOT(onViewMode(QAction *)));+ connect(viewModeGroup, &QActionGroup::triggered, this,+ &PaletteViewer::onViewMode);auto addViewAction = [&](const QString &label, PageViewer::ViewMode mode) {QAction *viewAction = new QAction(label, viewMode);@@ -504,8 +500,8 @@ void PaletteViewer::createPaletteToolBar() {QActionGroup *nameDisplayModeGroup = new QActionGroup(viewMode);nameDisplayModeGroup->setExclusive(true);- connect(nameDisplayModeGroup, SIGNAL(triggered(QAction *)), this,- SLOT(onNameDisplayMode(QAction *)));+ connect(nameDisplayModeGroup, &QActionGroup::triggered, this,+ &PaletteViewer::onNameDisplayMode);auto addNameDisplayAction = [&](const QString &label,PageViewer::NameDisplayMode mode) {@@ -529,8 +525,8 @@ void PaletteViewer::createPaletteToolBar() {m_variableWidthAction->setCheckable(true);m_variableWidthAction->setChecked(true);viewMode->addAction(m_variableWidthAction);- connect(m_variableWidthAction, SIGNAL(toggled(bool)), this,- SLOT(toggleVariableWidth(bool)));+ connect(m_variableWidthAction, &QAction::toggled, this,+ &PaletteViewer::toggleVariableWidth);viewMode->addSeparator();@@ -559,14 +555,14 @@ void PaletteViewer::createPaletteToolBar() {if (m_viewType != LEVEL_PALETTE) m_visibleGizmoAction->setVisible(false);- connect(m_visibleKeysAction, SIGNAL(toggled(bool)), this,- SLOT(toggleKeyframeVisibility(bool)));- connect(m_visibleNewAction, SIGNAL(toggled(bool)), this,- SLOT(toggleNewStylePageVisibility(bool)));- connect(m_visibleGizmoAction, SIGNAL(toggled(bool)), this,- SLOT(togglePaletteGizmoVisibility(bool)));- connect(m_visibleNameAction, SIGNAL(toggled(bool)), this,- SLOT(toggleNameEditorVisibility(bool)));+ connect(m_visibleKeysAction, &QAction::toggled, this,+ &PaletteViewer::toggleKeyframeVisibility);+ connect(m_visibleNewAction, &QAction::toggled, this,+ &PaletteViewer::toggleNewStylePageVisibility);+ connect(m_visibleGizmoAction, &QAction::toggled, this,+ &PaletteViewer::togglePaletteGizmoVisibility);+ connect(m_visibleNameAction, &QAction::toggled, this,+ &PaletteViewer::toggleNameEditorVisibility);viewMode->addMenu(visibleButtons);@@ -576,19 +572,19 @@ void PaletteViewer::createPaletteToolBar() {elsem_showToolbarOnTopAct->setText(tr("Set Toolbar Above Styles"));viewMode->addAction(m_showToolbarOnTopAct);- connect(m_showToolbarOnTopAct, SIGNAL(triggered()), this,- SLOT(toggleToolbarOnTop()));+ connect(m_showToolbarOnTopAct, &QAction::triggered, this,+ &PaletteViewer::toggleToolbarOnTop);QString str = (ShowNewStyleButton) ? tr("Hide New Style Button"): tr("Show New Style Button");QAction *showNewStyleBtn = viewMode->addAction(str);- connect(showNewStyleBtn, SIGNAL(triggered()), this,- SLOT(onShowNewStyleButtonToggled()));+ connect(showNewStyleBtn, &QAction::triggered, this,+ &PaletteViewer::onShowNewStyleButtonToggled);viewModeButton->setMenu(viewMode);- // Attenzione: avendo invertito la direzione devo aggiungere gli oggetti al- // contrario+ // Attention: having reversed the direction I must add objects in reverse+ // orderm_paletteToolBar->addWidget(viewModeButton);m_paletteToolBar->addSeparator();@@ -597,7 +593,8 @@ void PaletteViewer::createPaletteToolBar() {QAction *openStyleNameEditorAct = new QAction(tr("Name Editor"));openStyleNameEditorAct->setIcon(createQIcon("rename", true));- connect(openStyleNameEditorAct, &QAction::triggered, [&]() {+ // Using a lambda for the triggered connection+ connect(openStyleNameEditorAct, &QAction::triggered, [this]() {if (!m_styleNameEditor) {m_styleNameEditor = new StyleNameEditor(this);m_styleNameEditor->setPaletteHandle(getPaletteHandle());@@ -617,8 +614,9 @@ void PaletteViewer::createPaletteToolBar() {// Clone palette gizmo action so visibility can be controlQAction *palGizmo = new DVAction(m_sharedGizmoAction->icon(),m_sharedGizmoAction->text(), this);+ // Using a lambda to forward the triggerconnect(palGizmo, &QAction::triggered,- [&]() { m_sharedGizmoAction->trigger(); });+ [this]() { m_sharedGizmoAction->trigger(); });m_paletteToolBar->addAction(palGizmo);m_toolbarParts.insert(TBVisPaletteGizmo, palGizmo);m_toolbarParts.insert(TBVisPaletteGizmo, m_paletteToolBar->addSeparator());@@ -628,7 +626,7 @@ void PaletteViewer::createPaletteToolBar() {QAction *addPage;QIcon addPageIcon = createQIcon("newpage");addPage = new QAction(addPageIcon, tr("&New Page"), m_paletteToolBar);- connect(addPage, SIGNAL(triggered()), this, SLOT(addNewPage()));+ connect(addPage, &QAction::triggered, this, &PaletteViewer::addNewPage);m_paletteToolBar->addAction(addPage);m_toolbarParts.insert(TBVisNewStylePage, addPage);@@ -637,7 +635,7 @@ void PaletteViewer::createPaletteToolBar() {QIcon newColorIcon = createQIcon("newstyle");QAction *addColor =new QAction(newColorIcon, tr("&New Style"), m_paletteToolBar);- connect(addColor, SIGNAL(triggered()), this, SLOT(addNewColor()));+ connect(addColor, &QAction::triggered, this, &PaletteViewer::addNewColor);m_paletteToolBar->addAction(addColor);m_toolbarParts.insert(TBVisNewStylePage, addColor);@@ -669,36 +667,40 @@ void PaletteViewer::createSavePaletteToolBar() {return;}- // save palette as- QAction *saveAsPalette = new QAction(- createQIcon("saveas"), tr("&Save Palette As"), m_savePaletteToolBar);- // overwrite palette- QAction *savePalette = new QAction(createQIcon("save"), tr("&Save Palette"),- m_savePaletteToolBar);-+ // Create actions only for the relevant view type to avoid leaksif (m_viewType == STUDIO_PALETTE) {- connect(savePalette, SIGNAL(triggered()), this, SLOT(saveStudioPalette()));+ // overwrite palette+ QAction *savePalette = new QAction(createQIcon("save"), tr("&Save Palette"),+ m_savePaletteToolBar);+ connect(savePalette, &QAction::triggered, this,+ &PaletteViewer::saveStudioPalette);m_savePaletteToolBar->addAction(savePalette);} else if (m_viewType == LEVEL_PALETTE) {// save load palettePaletteIconWidget *movePalette =new PaletteIconWidget(m_savePaletteToolBar);- connect(movePalette, SIGNAL(startDrag()), this, SLOT(startDragDrop()));+ connect(movePalette, &PaletteIconWidget::startDrag, this,+ &PaletteViewer::startDragDrop);QAction *act = m_savePaletteToolBar->addWidget(movePalette);act->setText(tr("&Move Palette"));m_savePaletteToolBar->addSeparator();// save palette as- connect(saveAsPalette, SIGNAL(triggered()),+ QAction *saveAsPalette = new QAction(+ createQIcon("saveas"), tr("&Save Palette As"), m_savePaletteToolBar);+ // Forward to command manager's action+ connect(saveAsPalette, &QAction::triggered,CommandManager::instance()->getAction("MI_SavePaletteAs"),- SIGNAL(triggered()));+ &QAction::triggered);m_savePaletteToolBar->addAction(saveAsPalette);// overwrite palette- connect(savePalette, SIGNAL(triggered()),+ QAction *savePalette = new QAction(createQIcon("save"), tr("&Save Palette"),+ m_savePaletteToolBar);+ connect(savePalette, &QAction::triggered,CommandManager::instance()->getAction("MI_OverwritePalette"),- SIGNAL(triggered()));+ &QAction::triggered);m_savePaletteToolBar->addAction(savePalette);}@@ -712,8 +714,8 @@ void PaletteViewer::updateTabBar() {int tabCount = m_pagesBar->count();int i;- // Se ci sono tab li butto- for (i = tabCount - 1; i >= 0; i--) m_pagesBar->removeTab(i);+ // If there are tabs, remove them+ for (i = tabCount - 1; i >= 0; --i) m_pagesBar->removeTab(i);TPalette *palette = getPalette();if (!palette) return;@@ -721,8 +723,8 @@ void PaletteViewer::updateTabBar() {QIcon tabIcon = createQIcon("palette_tab");m_pagesBar->setIconSize(QSize(16, 16));- // Aggiungo i tab in funzione delle pagine di m_palette- for (i = 0; i < palette->getPageCount(); i++) {+ // Add tabs according to m_palette pages+ for (i = 0; i < palette->getPageCount(); ++i) {TPalette::Page *page = palette->getPage(i);std::wstring ws = page->getName();QString pageName = QString::fromStdWString(ws);@@ -737,17 +739,15 @@ void PaletteViewer::updateTabBar() {*/void PaletteViewer::updatePaletteToolBar() {if (!m_paletteToolBar) return;- QList<QAction *> actions;- actions = m_paletteToolBar->actions();- TPalette *palette = getPalette();- bool enable = !palette ? false : true;- bool enableNewStyleAct = enable;+ QList<QAction *> actions = m_paletteToolBar->actions();+ TPalette *palette = getPalette();+ bool enable = !palette ? false : true;+ bool enableNewStyleAct = enable;// limit the number of cleanup styles to 7if (palette && palette->isCleanupPalette())enableNewStyleAct = (palette->getStyleInPagesCount() < 8);if (m_viewType != CLEANUP_PALETTE) m_keyFrameButton->setEnabled(enable);- int i;- for (i = 0; i < actions.count(); i++) {+ for (int i = 0; i < actions.count(); ++i) {QAction *act = actions[i];if (act->text() == tr("&New Style")) {act->setEnabled(enableNewStyleAct);@@ -763,11 +763,9 @@ void PaletteViewer::updatePaletteToolBar() {*/void PaletteViewer::updateSavePaletteToolBar() {if (!m_savePaletteToolBar) return;- QList<QAction *> actions;- actions = m_savePaletteToolBar->actions();- bool enable = !getPalette() ? false : true;- int i;- for (i = 0; i < actions.count(); i++) {+ QList<QAction *> actions = m_savePaletteToolBar->actions();+ bool enable = !getPalette() ? false : true;+ for (int i = 0; i < actions.count(); ++i) {QAction *act = actions[i];if (act->text() == tr("&Save Palette As") ||act->text() == tr("&Save Palette") ||@@ -809,7 +807,7 @@ void PaletteViewer::contextMenuEvent(QContextMenuEvent *event) {QMenu *menu = new QMenu(this);if (m_hasPageCommand) {QAction *newPage = menu->addAction(createQIcon("newpage"), tr("New Page"));- connect(newPage, SIGNAL(triggered()), SLOT(addNewPage()));+ connect(newPage, &QAction::triggered, this, &PaletteViewer::addNewPage);if (m_pagesBar->geometry().contains(pos)) {int tabIndex = m_pagesBar->tabAt(pos);@@ -822,7 +820,8 @@ void PaletteViewer::contextMenuEvent(QContextMenuEvent *event) {m_indexPageToDelete = tabIndex;QAction *deletePage =menu->addAction(createQIcon("delete"), tr("Delete Page"));- connect(deletePage, SIGNAL(triggered()), SLOT(deletePage()));+ connect(deletePage, &QAction::triggered, this,+ &PaletteViewer::deletePage);}}}@@ -865,64 +864,52 @@ void PaletteViewer::showEvent(QShowEvent *) {if (!m_paletteHandle) return;- connect(m_paletteHandle, SIGNAL(paletteSwitched()), this,- SLOT(onPaletteSwitched()));- connect(m_paletteHandle, SIGNAL(paletteChanged()), this,- SLOT(onPaletteChanged()));- connect(m_paletteHandle, SIGNAL(paletteTitleChanged()), this,- SLOT(changeWindowTitle()));- connect(m_paletteHandle, SIGNAL(colorStyleSwitched()), this,- SLOT(onColorStyleSwitched()));- connect(m_paletteHandle, SIGNAL(colorStyleChanged(bool)), this,- SLOT(changeWindowTitle()));- connect(m_paletteHandle, SIGNAL(paletteDirtyFlagChanged()), this,- SLOT(changeWindowTitle()));+ connect(m_paletteHandle, &TPaletteHandle::paletteSwitched, this,+ &PaletteViewer::onPaletteSwitched);+ connect(m_paletteHandle, &TPaletteHandle::paletteChanged, this,+ &PaletteViewer::onPaletteChanged);+ connect(m_paletteHandle, &TPaletteHandle::paletteTitleChanged, this,+ &PaletteViewer::changeWindowTitle);+ connect(m_paletteHandle, &TPaletteHandle::colorStyleSwitched, this,+ &PaletteViewer::onColorStyleSwitched);+ connect(m_paletteHandle, &TPaletteHandle::colorStyleChanged, this,+ &PaletteViewer::changeWindowTitle);+ connect(m_paletteHandle, &TPaletteHandle::paletteDirtyFlagChanged, this,+ &PaletteViewer::changeWindowTitle);if (!m_frameHandle) return;- // Connessione necessaria per aggiornare lo stile in caso di palette animate.- connect(m_frameHandle, SIGNAL(frameSwitched()), this,- SLOT(onFrameSwitched()));+ // Connection needed to update the style in case of animated palettes.+ connect(m_frameHandle, &TFrameHandle::frameSwitched, this,+ &PaletteViewer::onFrameSwitched);}//-----------------------------------------------------------------------------void PaletteViewer::hideEvent(QHideEvent *) {- disconnect(m_paletteHandle, SIGNAL(paletteSwitched()), this,- SLOT(onPaletteSwitched()));- disconnect(m_paletteHandle, SIGNAL(paletteChanged()), this,- SLOT(onPaletteChanged()));- disconnect(m_paletteHandle, SIGNAL(paletteTitleChanged()), this,- SLOT(changeWindowTitle()));- disconnect(m_paletteHandle, SIGNAL(colorStyleSwitched()), this,- SLOT(onColorStyleSwitched()));- disconnect(m_paletteHandle, SIGNAL(colorStyleChanged(bool)), this,- SLOT(changeWindowTitle()));- disconnect(m_paletteHandle, SIGNAL(paletteDirtyFlagChanged()), this,- SLOT(changeWindowTitle()));-- if (!m_frameHandle) return;- disconnect(m_frameHandle, SIGNAL(frameSwitched()), this,- SLOT(onFrameSwitched()));+ disconnect(m_paletteHandle, nullptr, this, nullptr);+ if (m_frameHandle) disconnect(m_frameHandle, nullptr, this, nullptr);}//------------------------------------------------------------------------------/*! If currente palette viewer exist verify event data, if is a PaletteData or-has urls accept event.+/*! If current palette viewer exists verify event data, if it is a PaletteData+or has urls accept event.*/void PaletteViewer::dragEnterEvent(QDragEnterEvent *event) {TPalette *palette = getPalette();if (!palette || m_viewType == CLEANUP_PALETTE) return;- const QMimeData *mimeData = event->mimeData();+ const QMimeData *mimeData = event->mimeData();+ if (!mimeData) return; // guard against null mimeData+const PaletteData *paletteData = dynamic_cast<const PaletteData *>(mimeData);if (paletteData) {- // Sto "draggando" stili.+ // Dragging styles.if (paletteData->hasStyleIndeces()) {m_pageViewer->createDropPage();if (!palette) onSwitchToPage(palette->getPageCount() - 1);}- // Accetto l'evento+ // Accept the eventevent->acceptProposedAction();return;}@@ -931,9 +918,8 @@ void PaletteViewer::dragEnterEvent(QDragEnterEvent *event) {QList<QUrl> urls = mimeData->urls();int count = urls.size();if (count == 0) return;- // Accetto l'evento solo se ho tutte palette.- int i;- for (i = 0; i < count; i++) {+ // Accept the event only if all are palettes.+ for (int i = 0; i < count; ++i) {TFilePath path(urls[i].toLocalFile().toStdWString());if (!path.getType().empty() && path.getType() != "tpl") return;}@@ -950,20 +936,20 @@ void PaletteViewer::dragEnterEvent(QDragEnterEvent *event) {void PaletteViewer::dropEvent(QDropEvent *event) {if (m_viewType == CLEANUP_PALETTE) return;const QMimeData *mimeData = event->mimeData();+ if (!mimeData) return;QPoint tollBarPos = m_savePaletteToolBar->mapFrom(this, event->pos());QAction *currentAction = m_savePaletteToolBar->actionAt(tollBarPos);bool loadPalette =currentAction && currentAction->text() == QString(tr("&Move Palette"));- // ho i path delle palette+ // I have palette pathsif (mimeData->hasUrls()) {QList<QUrl> urls = mimeData->urls();int count = urls.size();if (count == 0) return;- int i;- for (i = 0; i < count; i++) {+ for (int i = 0; i < count; ++i) {TFilePath path(urls[i].toLocalFile().toStdWString());if (!path.getType().empty() && path.getType() != "tpl") return;if (loadPalette && i == 0) {@@ -1002,12 +988,12 @@ void PaletteViewer::dropEvent(QDropEvent *event) {const PaletteData *paletteData = dynamic_cast<const PaletteData *>(mimeData);if (!paletteData) return;- // Sto inserendo stili+ // Inserting stylesif (paletteData->hasStyleIndeces()) {m_pageViewer->drop(-1, mimeData);event->acceptProposedAction();} else {- // Ho la palette da inserire+ // Inserting the paletteTPalette *palette = paletteData->getPalette();if (getPalette() == palette) return;if (loadPalette) {@@ -1026,7 +1012,7 @@ void PaletteViewer::dropEvent(QDropEvent *event) {}//------------------------------------------------------------------------------/*! Start drag and drop; if current page exist set drag and drop event data.+/*! Start drag and drop; if current page exists set drag and drop event data.*/void PaletteViewer::startDragDrop() {TRepetitionGuard guard;@@ -1044,7 +1030,8 @@ void PaletteViewer::startDragDrop() {paletteData->setPalette(palette);drag->setMimeData(paletteData);- Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);+ drag->exec(Qt::CopyAction | Qt::MoveAction);+ // dropAction is not used, so we don't store it}//-----------------------------------------------------------------------------@@ -1056,7 +1043,7 @@ void PaletteViewer::clearStyleSelection() { m_pageViewer->clearSelection(); }*/void PaletteViewer::setPageView(int currentIndexPage) {TPalette *palette = getPalette();- TPalette::Page *page = palette ? palette->getPage(currentIndexPage) : 0;+ TPalette::Page *page = palette ? palette->getPage(currentIndexPage) : nullptr;m_pageViewer->setPage(page);}@@ -1077,8 +1064,7 @@ void PaletteViewer::addNewPage() {//-----------------------------------------------------------------------------/*! Create a new style in current page view of current palette viewer emit a-signal-to create a new style.+signal to create a new style.*/void PaletteViewer::addNewColor() {if (!getPalette() || getPalette()->isLocked()) return;@@ -1100,9 +1086,8 @@ void PaletteViewer::deletePage() {if (m_xsheetHandle) {std::vector<int> styleIds;TPalette::Page *page = palette->getPage(m_indexPageToDelete);- if (!page) return; // La pagina dovrebbe esserci sempre- int i;- for (i = 0; i < page->getStyleCount(); i++)+ if (!page) return; // The page should always exist+ for (int i = 0; i < page->getStyleCount(); ++i)styleIds.push_back(page->getStyleId(i));int ret = DVGui::eraseStylesInDemand(palette, styleIds, m_xsheetHandle);@@ -1192,8 +1177,8 @@ void PaletteViewer::saveStudioPalette() {void PaletteViewer::onColorStyleSwitched() {TPalette *palette = getPalette();- // se non c'e' palette, pageviewer p pagina corrente esco (non dovrebbe- // succedere mai)+ // if there's no palette, pageviewer or current page exit (should never+ // happen)if (!palette || !m_pageViewer) return;int styleIndex = m_paletteHandle->getStyleIndex();@@ -1202,8 +1187,7 @@ void PaletteViewer::onColorStyleSwitched() {TPalette::Page *page = m_pageViewer->getPage();if (!page) return;- // faccio in modo che la pagina che contiene il colore selezionato diventi- // corrente+ // make the page containing the selected color currentint indexInPage = page->search(styleIndex);if (indexInPage == -1) {if (!palette->getStylePage(styleIndex)) return;@@ -1388,4 +1372,4 @@ void PaletteViewer::onShowNewStyleButtonToggled() {}m_pageViewer->computeSize();m_pageViewer->update();-}\ No newline at end of file+}diff --git a/toonz/sources/toonzqt/pluginhost.cpp b/toonz/sources/toonzqt/pluginhost.cppindex 0c6582891..8a3058438 100644--- a/toonz/sources/toonzqt/pluginhost.cpp+++ b/toonz/sources/toonzqt/pluginhost.cpp@@ -1,3 +1,5 @@++#include <sstream>#include <string>#include <utility>@@ -44,21 +46,28 @@using namespace toonz; // plugin namespace+extern "C" {+int set_parameter_pages(toonz_node_handle_t, int num,+ toonz_param_page_t *params);+int set_parameter_pages_with_error(toonz_node_handle_t, int num,+ toonz_param_page_t *params, int *, void **);+}+extern std::map<std::string, PluginInformation *> plugin_dict_;/*- PluginLoadController が main thread queue を使うことと,- QThread で他スレッドの待ち合わせがしにくい(sendor thread が QThread::wait()- でブロックしていると emit signal が処理できずデッドロックする)ので、- 大人しく polling にした.- */+ Since PluginLoadController uses the main thread queue, and waiting for other+ threads in QThread is difficult (if the sender thread is blocked in+ QThread::wait(), emitted signals cannot be processed, causing deadlock), we+ stick to polling.+*/bool PluginLoader::load_entries(const std::string &basepath) {- static PluginLoadController *aw = NULL; /* main() から一度だけ呼ばれる */+ static PluginLoadController *aw = NULL; /* called only once from main() */if (!aw) {aw = new PluginLoadController(basepath, NULL);}bool ret = aw->wait(16 /* ms */);- if (ret) aw = NULL; /* deleteLater で消えるはず */+ if (ret) aw = NULL; /* should be deleted by deleteLater */return ret;}@@ -111,11 +120,11 @@ public:RasterFxPluginHost *fx = new RasterFxPluginHost(pi_);if (pi_ && pi_->handler_) {pi_->handler_->setup(fx);- /* fx は pi のラッパーとしてのみ構築されており、即座に削除される. 実- instance に引き継がれないので ここで createParam()- 等を呼び出しても意味がない.- ここで createParamsByDesc() などを呼び出しても、 instance の parameter- は 0 になる. */+ /* The fx is built only as a wrapper for pi and is deleted immediately.+ It is not passed to the real instance, so calling createParam() etc.+ here has no effect.+ Even if createParamsByDesc() etc. are called here, the instance's+ parameters will be zero. */}delete fx;}@@ -219,8 +228,7 @@ static int add_input_port(toonz_node_handle_t node, const char *name, int type,RasterFxPluginHost *fx = reinterpret_cast<RasterFxPluginHost *>(node);if (!fx) return TOONZ_ERROR_INVALID_HANDLE;auto p = std::make_shared<TRasterFxPort>();- /* TRasterFxPort は non-copyable なスマートポインタなのでポインタで引き回す- */+ /* TRasterFxPort is a non-copyable smart pointer, so pass it as pointer */if (!fx->addInputPort(name, p)) { // overloaded versionprintf("add_input_port: failed to add: already have\n");return TOONZ_ERROR_BUSY;@@ -257,8 +265,7 @@ static int add_output_port(toonz_node_handle_t node, const char *name, int type,RasterFxPluginHost *fx = reinterpret_cast<RasterFxPluginHost *>(node);if (!fx) return TOONZ_ERROR_INVALID_HANDLE;p = new TRasterFxPort();- /* TRasterFxPort は non-copyable なスマートポインタなのでポインタで引き回す- */+ /* TRasterFxPort is a non-copyable smart pointer, so pass it as pointer */if (fx->addOutputPort(name, p)) { // overloaded versiondelete p;return TOONZ_ERROR_BUSY;@@ -389,7 +396,7 @@ bool RasterFxPluginHost::addPortDesc(port_description_t &&desc) {}void RasterFxPluginHost::notify() {- /* 最低限必要な setup をしてから通知する */+ /* Do the minimum required setup then notify */QString nm = QString::fromStdString(pi_->desc_->name_.c_str());setName(nm.toStdWString());@@ -408,11 +415,11 @@ RasterFxPluginHost::~RasterFxPluginHost() {}/*- node を click するなどの要因で頻繁に呼ばれる.- click した場合は FxsData::setFxs から呼ばれ、新しいインスタンスは- FxsData::m_fxs に入れられ、 FxsData- のインスタンスと同時に(大抵の場合は)即座に消される.- */+ Frequently called when clicking a node, etc.+ When clicked, it is called from FxsData::setFxs, and the new instance is+ placed in FxsData::m_fxs and usually deleted immediately together with the+ FxsData instance.+*/TFx *RasterFxPluginHost::clone(bool recursive) const {RasterFxPluginHost *plugin = newInstance(pi_);plugin->user_data_ = user_data_;@@ -420,9 +427,11 @@ TFx *RasterFxPluginHost::clone(bool recursive) const {for (auto &ip : pi_->port_mapper_) {if (ip.second.input_) {#if 0- /* addInputPort() 内で行われる port owner の更新は後勝ちだが,- clone された新しいインスタンスのほうが先に消えてしまう場合に, 無効なポインタを示す owner が port に残ってしまう. この問題が解決したら共有できるようにしたい.- (このため、 plugin 空間に通知される全ての handle には一貫性がない. ただし、後から一貫性がなくなるよりは遥かにいいだろう)+ /* addInputPort() updates the port owner to the latest, but if the cloned+ new instance is destroyed first, the port retains an invalid owner pointer.+ We would like to share when this problem is solved.+ (For this reason, all handles notified to the plugin space are inconsistent.+ However, it's much better than becoming inconsistent later.)*/plugin->addInputPort(getInputPortName(i), ip);#else@@ -434,12 +443,11 @@ TFx *RasterFxPluginHost::clone(bool recursive) const {printf("recursive:%d params:%d\n", (int)recursive, (int)params_.size());// clone params before TFx::clone().- /* ui_pages_, param_views_ は pi に移ったが createParam- * の呼び出しだけはしておかないと Fx Settings 構築時に assert failed になる */+ /* ui_pages_, param_views_ have moved to pi, but we still need to call+ createParam() otherwise Fx Settings construction will assert failed. */for (auto const ¶m : params_) {- /* 古い createParam() は desc- * をとらず、コンストラクト時にデフォルト値を持つタイプの T*Param- * を再作成できない */+ /* The old createParam() did not take a desc and cannot recreate T*Param+ types that have default values at construction. */plugin->createParam(param->desc());}@@ -476,7 +484,7 @@ void RasterFxPluginHost::setUserData(void *user_data) {bool RasterFxPluginHost::doGetBBox(double frame, TRectD &bbox,const TRenderSettings &info) {using namespace plugin::utils;- bool ret = true; /* 負論理 */+ bool ret = true; /* negative logic */if (pi_ && pi_->handler_->do_get_bbox) {rendering_setting_t info_;copy_rendering_setting(&info_, info);@@ -509,9 +517,8 @@ int RasterFxPluginHost::getMemoryRequirement(const TRectD &rect, double frame,rect_t rc;copy_rect(&rc, rect);- size_t ignore =- pi_->handler_->get_memory_requirement(this, &rs, frame, &rc);- return 0;+ pi_->handler_->get_memory_requirement(this, &rs, frame, &rc);+ // return value is ignored because it's not used in Toonz core}return 0;}@@ -522,15 +529,15 @@ bool RasterFxPluginHost::canHandle(const TRenderSettings &info, double frame) {copy_rendering_setting(&rs, info);return pi_->handler_->can_handle(this, &rs, frame);}- /* 適切なデフォルト値は 'geometric' の場合とそうでない場合で異なる */- return isPluginZerary(); /* better-default depends on that is 'geometric' or- not */+ /* Appropriate default differs between 'geometric' and non-geometric */+ return isPluginZerary(); /* better default depends on whether it's 'geometric'+ */}bool RasterFxPluginHost::addInputPort(const std::string &nm,std::shared_ptr<TFxPort> port) {- /* setOwnFx は addInputPort 内で行われている. setFx()- * は接続なので自分自身に呼んではダメ */+ /* setOwnFx is done inside addInputPort. setFx() is for connection,+ so do not call it on itself. */// port->setFx(this);bool ret = TFx::addInputPort(nm, *port.get());if (ret) {@@ -598,7 +605,8 @@ Param *RasterFxPluginHost::createParam(const toonz_param_desc_t *desc) {TParamP p = parameter_factory(desc);if (!p) return nullptr;- p->setDescription(desc->note);+ // Handle null description note+ p->setDescription(desc->note ? desc->note : "");p->setUILabel(desc->base.label);bindPluginParam(this, desc->key, p);@@ -623,8 +631,8 @@ ParamView *RasterFxPluginHost::createParamView() {return pi_->param_views_.back();}-/* build で構築された GUI は plugin のインスタンスには紐づかない.- * 通常一度だけ呼ばれ使い回される. */+/* The GUI built by build() is not tied to the plugin instance.+ It is usually called once and reused. */void RasterFxPluginHost::build(ParamsPageSet *pages) {printf(">>>> RasterFxPluginHost::build: ui_pages:%d\n",(int)pi_->ui_pages_.size());@@ -634,9 +642,8 @@ void RasterFxPluginHost::build(ParamsPageSet *pages) {auto aboutpage = pages->createParamsPage();#if 1- /* FIXME: fxsettings で大きさの測定のためにいろいろやっているので使える- layout/widget に制限がありそう.- しかしなぜか最後の widget しか出ない */+ /* FIXME: fxsettings does various measurements, so the usable layout/widgets+ may be limited. However, for some reason only the last widget appears. */aboutpage->beginGroup("Name");aboutpage->addWidget(new QLabel(pi_->desc_->name_.c_str(), aboutpage));aboutpage->endGroup();@@ -699,7 +706,7 @@ static int check_base_sanity(const toonz_param_desc_t *p) {bool RasterFxPluginHost::setParamStructure(int n, toonz_param_page_t *p,int &err, void *&pos) {- /* 適当に現実的な最大値: あまりに大きい場合は領域の破壊を疑う */+ /* Reasonable maximum values: if too large, suspect memory corruption */static const int max_pages_ = 31;static const int max_groups_ = 32;static const int max_params_ = 65535;@@ -707,15 +714,14 @@ bool RasterFxPluginHost::setParamStructure(int n, toonz_param_page_t *p,pos = p;if (pi_) {if (n > max_pages_ || p == NULL) {- /* parameter が null- * でないことは上位でチェックされているはずで、ここで返せるエラーは定義していない.+ /* parameter should be non-null as checked above; error not defined here*/if (p == NULL) err |= TOONZ_PARAM_ERROR_UNKNOWN;err |= TOONZ_PARAM_ERROR_PAGE_NUM;return false;}- /* SAN 値チェック */+ /* SANity value check */for (int k = 0; k < n; k++) {toonz_param_page_t *pg = &p[k];pos = pg;@@ -889,8 +895,8 @@ void RasterFxPluginHost::createParamsByDesc() {"RasterFxPluginHost::createParam: add_param_field: r:0x%x v:%p ""p:%p\n",r, v, p);- /* set_param_range()- * の中で型チェックをしているので全型について呼び出してよい */+ /* set_param_range() does type checking, so it's safe to call for all+ types */r = bind_param(page, p, v);@@ -919,7 +925,7 @@ void RasterFxPluginHost::createParamsByDesc() {}/*-パラメタのキー名として適切か確認+ Check if the parameter key name is valid*/bool RasterFxPluginHost::validateKeyName(const char *name) {if (name[0] == '\0') return false;@@ -928,7 +934,7 @@ bool RasterFxPluginHost::validateKeyName(const char *name) {for (int i = 1; name[i] != '\0'; i++)if (!isalnum(name[i]) && name[i] != '_') return false;- /* XMLの仕様ではXMLから始まるタグ名は認められないので、ここで弾く */+ /* XML spec forbids tag names starting with 'xml', so reject them here */if (strlen(name) >= 3 && (name[0] == 'X' || name[0] == 'x') &&(name[1] == 'M' || name[1] == 'm') && (name[2] == 'L' || name[2] == 'l'))return false;@@ -938,8 +944,9 @@ bool RasterFxPluginHost::validateKeyName(const char *name) {/*strict sanity check:- 未初期化値を受け入れて互換性が崩れないよう厳しくチェックする- */+ Strictly check to avoid accepting uninitialized values and breaking+ compatibility+*/#define VERBOSEstatic inline bool check(const plugin_probe_t *begin,const plugin_probe_t *end) {@@ -965,14 +972,10 @@ static inline bool check(const plugin_probe_t *begin,toonz_if_version_t v = begin->ver;for (auto x = begin; x < end; x++, idx++) {- /* 異なるバージョンの構造体の混在はエラーとする.- しかし toonz_plugin_probe_t は reservation filed- を持っており、サイズが変わらない限りは混在も対応可能だが、まずは sanity- check で落とす.-- For now we permit mixed versions. Not that we never support it since size- of toonz_plugin_probe_t is constant.- */+ /* Mixing different versions is an error.+ However, toonz_plugin_probe_t has reserved fields, and as long as the+ size doesn't change, mixing might be possible, but we reject it for+ sanity. */if (!(x->ver.major == v.major && x->ver.minor == v.minor)) {#if defined(VERBOSE)printf(@@ -1005,7 +1008,7 @@ static inline bool check(const plugin_probe_t *begin,}}- // reservations are must be zero+ // reservations must be zerofor (int i = 0; i < 3; i++)if (x->reserved_ptr_[i]) {#if defined(VERBOSE)@@ -1039,7 +1042,7 @@ static inline bool check(const plugin_probe_t *begin,#if defined(VERBOSE)printf("sanity check(): plugin[%d] handler is null\n", idx);#endif- return false; // handler must be NOT null+ return false; // handler must NOT be null}}@@ -1094,175 +1097,109 @@ static UUID uuid_param_ = {0x2E3E4A55, 0x8539, 0x4520, 0xA266, 0x15D32189EC4D};static UUID uuid_setup_ = {0xcfde9107, 0xc59d, 0x414c, 0xae4a, 0x3d115ba97933};static UUID uuid_null_ = {0, 0, 0, 0, 0};-template <typename T, int major, int minor>-T *base_interface_factory() {- T *t = new T;- memset(t, 0, sizeof(T));- t->ver.major = major;- t->ver.minor = minor;- return t;-}+// Static global interface instances – no dynamic allocation, so release is+// no‑op+static toonz_node_interface_t s_node_iface_1_0;+static toonz_port_interface_t s_port_iface_1_0;+static toonz_tile_interface_t s_tile_iface_1_0;+static toonz_fxnode_interface_t s_fxnode_iface_1_0;+static toonz_param_interface_t s_param_iface_1_0;+static toonz_setup_interface_t s_setup_iface_1_0;template <typename T, uint32_t major, uint32_t minor>-struct interface_t {- static T *factory() {- T *t = base_interface_factory<T, major, minor>();- return t;- }-};--extern "C" {-int set_parameter_pages(toonz_node_handle_t, int num,- toonz_param_page_t *params);-int set_parameter_pages_with_error(toonz_node_handle_t, int num,- toonz_param_page_t *params, int *, void **);+T *interface_factory() {+ return nullptr; // not used}-template <uint32_t major, uint32_t minor>-struct interface_t<setup_interface_t, major, minor> {- static setup_interface_t *factory() {- setup_interface_t *t =- base_interface_factory<setup_interface_t, major, minor>();- t->set_parameter_pages = set_parameter_pages;- t->set_parameter_pages_with_error = set_parameter_pages_with_error;- t->add_input_port = setup_input_port;- return t;- }-};--/*-template < uint32_t major, uint32_t minor >-struct interface_t < ui_page_interface_t, major, minor > {- static ui_page_interface_t* factory()- {- ui_page_interface_t* t = base_interface_factory<-ui_page_interface_t, major, minor >();- t->begin_group = begin_group;- t->end_group = end_group;- t->bind_param = bind_param;- return t;- }-};--template < uint32_t major, uint32_t minor >-struct interface_t < param_view_interface_t, major, minor > {- static param_view_interface_t* factory()- {- param_view_interface_t* t = base_interface_factory<-param_view_interface_t, major, minor >();- t->add_param_field = add_param_field;- t->add_custom_field = add_custom_field;- t->add_lineedit = add_lineedit;- t->add_slider = add_slider;- t->add_spinbox = add_spinbox;- t->add_checkbox = add_checkbox;- t->add_radiobutton = add_radiobutton;- t->add_combobox = add_combobox;- return t;- }-};-*/--template <uint32_t major, uint32_t minor>-struct interface_t<param_interface_t, major, minor> {- static param_interface_t *factory() {- param_interface_t *t =- base_interface_factory<param_interface_t, major, minor>();- t->get_type = get_type;- // t->hint_default_value = hint_default_value;- // t->hint_value_range = hint_value_range;- // t->hint_unit = hint_unit;- // t->hint_item = hint_item;- // t->get_value_type = get_value_type;- t->get_value = get_value;- // t->set_value = set_value;- t->get_string_value = get_string_value;- t->get_spectrum_value = get_spectrum_value;- return t;+template <>+toonz_node_interface_t *interface_factory<toonz_node_interface_t, 1, 0>() {+ if (s_node_iface_1_0.ver.major == 0) {+ memset(&s_node_iface_1_0, 0, sizeof(s_node_iface_1_0));+ s_node_iface_1_0.ver.major = 1;+ s_node_iface_1_0.ver.minor = 0;+ s_node_iface_1_0.get_input_port = get_input_port;+ s_node_iface_1_0.get_rect = get_rect;+ s_node_iface_1_0.set_rect = set_rect;+ s_node_iface_1_0.get_param = get_param;+ s_node_iface_1_0.set_user_data = set_user_data;+ s_node_iface_1_0.get_user_data = get_user_data;}-};+ return &s_node_iface_1_0;+}-template <uint32_t major, uint32_t minor>-struct interface_t<node_interface_t, major, minor> {- static node_interface_t *factory() {- node_interface_t *t =- base_interface_factory<node_interface_t, major, minor>();- // t->add_input_port = add_input_port;- // t->add_output_port = add_output_port;- t->get_input_port = get_input_port;- t->get_rect = get_rect;- t->set_rect = set_rect;- // t->add_preference = add_preference;- // t->add_param = add_param;- t->get_param = get_param;- // t->create_param_view = create_param_view;- t->set_user_data = set_user_data;- t->get_user_data = get_user_data;- return t;+template <>+toonz_port_interface_t *interface_factory<toonz_port_interface_t, 1, 0>() {+ if (s_port_iface_1_0.ver.major == 0) {+ memset(&s_port_iface_1_0, 0, sizeof(s_port_iface_1_0));+ s_port_iface_1_0.ver.major = 1;+ s_port_iface_1_0.ver.minor = 0;+ s_port_iface_1_0.is_connected = is_connected;+ s_port_iface_1_0.get_fx = get_fx;}-};+ return &s_port_iface_1_0;+}-template <uint32_t major, uint32_t minor>-struct interface_t<toonz_tile_interface_t, major, minor> {- static toonz_tile_interface_t *factory() {- toonz_tile_interface_t *t =- base_interface_factory<toonz_tile_interface_t, major, minor>();- t->get_raw_address_unsafe = tile_interface_get_raw_address_unsafe;- t->get_raw_stride = tile_interface_get_raw_stride;- t->get_element_type = tile_interface_get_element_type;- t->copy_rect = tile_interface_copy_rect;- t->create_from = tile_interface_create_from;- t->create = tile_interface_create;- t->destroy = tile_interface_destroy;- t->get_rectangle = tile_interface_get_rectangle;- t->safen = tile_interface_safen;- return t;+template <>+toonz_tile_interface_t *interface_factory<toonz_tile_interface_t, 1, 0>() {+ if (s_tile_iface_1_0.ver.major == 0) {+ memset(&s_tile_iface_1_0, 0, sizeof(s_tile_iface_1_0));+ s_tile_iface_1_0.ver.major = 1;+ s_tile_iface_1_0.ver.minor = 0;+ s_tile_iface_1_0.get_raw_address_unsafe =+ tile_interface_get_raw_address_unsafe;+ s_tile_iface_1_0.get_raw_stride = tile_interface_get_raw_stride;+ s_tile_iface_1_0.get_element_type = tile_interface_get_element_type;+ s_tile_iface_1_0.copy_rect = tile_interface_copy_rect;+ s_tile_iface_1_0.create_from = tile_interface_create_from;+ s_tile_iface_1_0.create = tile_interface_create;+ s_tile_iface_1_0.destroy = tile_interface_destroy;+ s_tile_iface_1_0.get_rectangle = tile_interface_get_rectangle;+ s_tile_iface_1_0.safen = tile_interface_safen;}-};+ return &s_tile_iface_1_0;+}-template <uint32_t major, uint32_t minor>-struct interface_t<port_interface_t, major, minor> {- static port_interface_t *factory() {- port_interface_t *t =- base_interface_factory<port_interface_t, major, minor>();- t->is_connected = is_connected;- t->get_fx = get_fx;- return t;+template <>+toonz_fxnode_interface_t *interface_factory<toonz_fxnode_interface_t, 1, 0>() {+ if (s_fxnode_iface_1_0.ver.major == 0) {+ memset(&s_fxnode_iface_1_0, 0, sizeof(s_fxnode_iface_1_0));+ s_fxnode_iface_1_0.ver.major = 1;+ s_fxnode_iface_1_0.ver.minor = 0;+ s_fxnode_iface_1_0.get_bbox = fxnode_get_bbox;+ s_fxnode_iface_1_0.can_handle = fxnode_can_handle;+ s_fxnode_iface_1_0.get_input_port_count = fxnode_get_input_port_count;+ s_fxnode_iface_1_0.get_input_port = fxnode_get_input_port;+ s_fxnode_iface_1_0.compute_to_tile = fxnode_compute_to_tile;}-};+ return &s_fxnode_iface_1_0;+}-template <uint32_t major, uint32_t minor>-struct interface_t<fxnode_interface_t, major, minor> {- static fxnode_interface_t *factory() {- fxnode_interface_t *t =- base_interface_factory<fxnode_interface_t, major, minor>();- t->get_bbox = fxnode_get_bbox;- t->can_handle = fxnode_can_handle;- t->get_input_port_count = fxnode_get_input_port_count;- t->get_input_port = fxnode_get_input_port;- t->compute_to_tile = fxnode_compute_to_tile;- return t;+template <>+toonz_param_interface_t *interface_factory<toonz_param_interface_t, 1, 0>() {+ if (s_param_iface_1_0.ver.major == 0) {+ memset(&s_param_iface_1_0, 0, sizeof(s_param_iface_1_0));+ s_param_iface_1_0.ver.major = 1;+ s_param_iface_1_0.ver.minor = 0;+ s_param_iface_1_0.get_type = get_type;+ s_param_iface_1_0.get_value = get_value;+ s_param_iface_1_0.get_string_value = get_string_value;+ s_param_iface_1_0.get_spectrum_value = get_spectrum_value;}-};+ return &s_param_iface_1_0;+}-/*template <>-template < uint32_t major, uint32_t minor >-struct interface_t< toonz_nodal_rasterfx_interface_t >::i_< major, minor > {- static toonz_nodal_rasterfx_interface_t* factory()- {- printf("toonz_nodal_rasterfx_interface_t::factory\n");- toonz_nodal_rasterfx_interface_t* t = base_interface_factory<-toonz_nodal_rasterfx_interface_t, major, minor >();- return t;- }-};-*/--template <typename T, uint32_t major, uint32_t minor>-T *interface_factory() {- // return interface_t< T >::i_< major, minor >().factory();- return interface_t<T, major, minor>::factory();+toonz_setup_interface_t *interface_factory<toonz_setup_interface_t, 1, 0>() {+ if (s_setup_iface_1_0.ver.major == 0) {+ memset(&s_setup_iface_1_0, 0, sizeof(s_setup_iface_1_0));+ s_setup_iface_1_0.ver.major = 1;+ s_setup_iface_1_0.ver.minor = 0;+ s_setup_iface_1_0.set_parameter_pages = set_parameter_pages;+ s_setup_iface_1_0.set_parameter_pages_with_error =+ set_parameter_pages_with_error;+ s_setup_iface_1_0.add_input_port = setup_input_port;+ }+ return &s_setup_iface_1_0;}static int query_interface(const UUID *uuid, void **interf) {@@ -1294,8 +1231,7 @@ static int query_interface(const UUID *uuid, void **interf) {break;// case 4:// *interf = interface_factory< toonz_ui_page_interface_t, 1, 0- //>();- // break;+ //>(); break;case 5:*interf = interface_factory<toonz_fxnode_interface_t, 1, 0>();break;@@ -1325,7 +1261,7 @@ static int query_interface(const UUID *uuid, void **interf) {}static void release_interface(void *interf) {- if (interf) delete interf;+ // All interfaces are static global, nothing to delete}Loader::Loader() {}@@ -1373,11 +1309,11 @@ void Loader::doLoad(const QString &file) {if (handle) {pi->library_ = library_t(handle, end_library); // shared_ptr/*-probe に使う plugin 情報を探す.-テーブルを export- したほうが楽だが、開発者はデバッグしにくいので関数フォームも提供する.-toonz_plugin_info で検索し、なければ toonz_plugin_probe() を呼び出す.-*/+ Look for plugin information to probe.+ It's easier to export a table, but developers may find debugging hard,+ so we also provide a function form.+ Search for toonz_plugin_info; if not found, call toonz_plugin_probe().+ */#if defined(_WIN32) || defined(_CYGWIN_)auto ini = (int (*)(host_interface_t *))GetProcAddress(handle,"toonz_plugin_init");@@ -1444,9 +1380,8 @@ toonz_plugin_info で検索し、なければ toonz_plugin_probe() を呼び出printf("plugin count:%d begin:%p end:%p\n", plugin_num, probinfo_begin,probinfo_end);- /* sanity check に失敗した場合は予期せぬアドレスを参照して toonz- 本体ごと落ちる可能性があるので- 致命的エラー扱いで早期に抜ける. */+ /* If sanity check fails, it could reference unexpected addresses and+ crash Toonz itself, so treat as fatal and exit early. */if (!probinfo_begin || !probinfo_end ||!check(probinfo_begin, probinfo_end))throw std::domain_error("ill-formed plugin information");@@ -1455,18 +1390,16 @@ toonz_plugin_info で検索し、なければ toonz_plugin_probe() を呼び出probinfo < probinfo_end; probinfo++) {pi->desc_ = new PluginDescription(probinfo);nodal_rasterfx_handler_t *nodal = probinfo->handler;- /* probinfo は sanity check 通過済みなのでチェック不要. handler は null- * でないことのみが確認されている */+ /* probinfo passed sanity check, handler only confirmed non-null */if (is_compatible<nodal_rasterfx_handler_t, 1, 0>(*nodal)) {uint32_t c = probinfo->clss & ~(TOONZ_PLUGIN_CLASS_MODIFIER_MASK);- uint32_t m = probinfo->clss & (TOONZ_PLUGIN_CLASS_MODIFIER_MASK);if (c == TOONZ_PLUGIN_CLASS_POSTPROCESS_SLAB) {pi->handler_ = new nodal_rasterfx_handler_t;if (!check_and_copy(pi->handler_, nodal))throw std::domain_error("ill-formed nodal interface");} else {// unknown plugin-class : gracefully end- /* sanity check しているので来ないはずだ */+ /* sanity check should prevent this */}} else {// unknown version : gracefully end@@ -1477,8 +1410,8 @@ toonz_plugin_info で検索し、なければ toonz_plugin_probe() を呼び出if (pi) {try {if (pi->ini_) {- /* interface は plugin 内部で破壊されても他に影響させないため- * plugin instance ごとに割り当てる. */+ /* interface is allocated per plugin instance to avoid affecting+ others if destroyed inside plugin. */host_interface_t *host = new host_interface_t;host->ver.major = 1;host->ver.minor = 0;@@ -1493,9 +1426,8 @@ toonz_plugin_info で検索し、なければ toonz_plugin_probe() を呼び出pi->host_ = host;pi->decl_ = new PluginDeclaration(pi);} else {- /* もっと早期にエラーを出して終了することもできるが- センシティブすぎると見通しが立てにくいのである程度我慢してから出す- */+ /* Could exit earlier, but being too sensitive makes debugging+ hard, so tolerate to some extent. */throw std::domain_error("not found _toonz_plugin_init");}} catch (const std::exception &e) {@@ -1510,7 +1442,7 @@ toonz_plugin_info で検索し、なければ toonz_plugin_probe() を呼び出/* for a next plugin on the library */auto prev = pi->library_;pi = new PluginInformation;- /* instance に依存しない unique なリソースは引き継ぐ必要がある */+ /* instance‑independent unique resources need to be carried over */pi->library_ = prev;pi->ini_ = ini;pi->fin_ = fin;@@ -1522,14 +1454,16 @@ toonz_plugin_info で検索し、なければ toonz_plugin_probe() を呼び出delete pi;pi = NULL;}+ } else {+ // handle is null – plugin load failed, delete pi to avoid leak+ delete pi;}}void RasterFxPluginHost::createPortsByDesc() {if (pi_) {for (auto pm : pi_->port_mapper_) {- /* TRasterFxPort は non-copyable- * なスマートポインタなのでポインタで引き回す */+ /* TRasterFxPort is a non-copyable smart pointer, so pass it as pointer */printf("createPortsByDesc: name:%s dir:%d type:%d\n", pm.first.c_str(),pm.second.input_, pm.second.type_);if (pm.second.input_) {@@ -1539,8 +1473,8 @@ void RasterFxPluginHost::createPortsByDesc() {}} else {auto p = new TRasterFxPort();- /* TRasterFxPort は non-copyable- * なスマートポインタなのでポインタで引き回す */+ /* TRasterFxPort is a non-copyable smart pointer, so pass it as pointer+ */if (addOutputPort(pm.first, p)) { // overloaded versiondelete p;printf("createPortsByDesc: failed to add: already have\n");@@ -1551,7 +1485,7 @@ void RasterFxPluginHost::createPortsByDesc() {}/*- TODO: addfxcontextmenu に移したほうがいい+ TODO: should be moved to addfxcontextmenu*/PluginLoadController::PluginLoadController(const std::string &basedir,QObject *listener) {@@ -1559,13 +1493,11 @@ PluginLoadController::PluginLoadController(const std::string &basedir,ld->moveToThread(&work_entity);connect(&work_entity, &QThread::finished, ld, &QObject::deleteLater);- /* AddFxContextMenu から呼ばれていたが、プラグインの検索が load_entries()- を通じて起動時に呼ばれるようにした関係で,- (あまりよくはないが)listener の有無によって receiver- を分けるようにしている. listener がいる場合は従来通り context menu- の構築のために AddFxContextMenu::fixup() に接続するが それ以外では- plugin_dict_ への追加のため PluginLoadController::finished に接続する.- */+ /* Was called from AddFxContextMenu, but now plugin search is done at startup+ via load_entries(). To keep backward compatibility, we distinguish+ receivers based on presence of listener. If listener exists, connect to+ AddFxContextMenu::fixup() for context menu building; otherwise connect to+ PluginLoadController::finished() to add to plugin_dict_. */if (listener) {AddFxContextMenu *a = qobject_cast<AddFxContextMenu *>(listener);connect(ld, &Loader::fixup, a, &AddFxContextMenu::fixup);@@ -1589,10 +1521,10 @@ void PluginLoadController::finished() {}void PluginLoadController::result(PluginInformation *pi) {- /* slot receives PluginInformation on the main thread たぶん */+ /* slot receives PluginInformation on the main thread (probably) */printf("PluginLoadController::result() pi:%p\n", pi);if (pi) {- /* addfxcontextmenu.cpp の dict に登録する */+ /* register in dictionary (addfxcontextmenu.cpp) */plugin_dict_.insert(std::pair<std::string, PluginInformation *>(pi->desc_->id_, pi));}diff --git a/toonz/sources/toonzqt/pluginhost.h b/toonz/sources/toonzqt/pluginhost.hindex ebd499488..60bc58a49 100644--- a/toonz/sources/toonzqt/pluginhost.h+++ b/toonz/sources/toonzqt/pluginhost.h@@ -198,7 +198,9 @@ public:ParamView *createParamView();bool isPlugin() const override { return true; }- bool isPluginZerary() const override { return pi_->desc_->is_geometric(); }+ bool isPluginZerary() const override {+ return pi_ ? pi_->desc_->is_geometric() : false;+ }bool isZerary() const override { return isPluginZerary(); };void callStartRenderHandler() override;diff --git a/toonz/sources/toonzqt/rasterimagedata.cpp b/toonz/sources/toonzqt/rasterimagedata.cppindex b258a8411..96cdd4d20 100644--- a/toonz/sources/toonzqt/rasterimagedata.cpp+++ b/toonz/sources/toonzqt/rasterimagedata.cpp@@ -37,8 +37,7 @@ TVectorImageP vectorize(const TImageP &source, const TRectD &rect,TScale sc(dpiX / Stage::inch, dpiY / Stage::inch);TTranslation tr(rect.getP00());- int i;- for (i = 0; i < (int)vi->getStrokeCount(); i++) {+ for (int i = 0; i < (int)vi->getStrokeCount(); i++) {TStroke *stroke = vi->getStroke(i);stroke->transform((sc.inv() * tr) * transform, true);}@@ -56,7 +55,7 @@ RasterImageData::RasterImageData()//--------------------------------------------------------------------RasterImageData::~RasterImageData() {}+RasterImageData::~RasterImageData() = default;//===================================================================// ToonzImageData@@ -83,7 +82,7 @@ ToonzImageData::ToonzImageData(const ToonzImageData &src)//--------------------------------------------------------------------ToonzImageData::~ToonzImageData() {}+ToonzImageData::~ToonzImageData() = default;//-------------------------------------------------------------------@@ -104,7 +103,7 @@ void ToonzImageData::setData(const TRasterP &copiedRaster,m_originalStrokes = originalStrokes;m_dim = dim;- /*-- 使用されているStyleの一覧を作る --*/+ // Build a list of used stylesTToonzImageP ti(m_copiedRaster, m_copiedRaster->getBounds());ToonzImageUtils::getUsedStyles(m_usedStyles, ti);}@@ -118,29 +117,38 @@ void ToonzImageData::getData(TRasterP &copiedRaster, double &dpiX, double &dpiY,TAffine &transformation,TPalette *targetPalette) const {if (!m_copiedRaster || (m_rects.empty() && m_strokes.empty())) return;+copiedRaster = m_copiedRaster->clone();dpiX = m_dpiX;dpiY = m_dpiY;assert(m_palette);- int i;- for (i = 0; i < (int)m_rects.size(); i++) rects.push_back(m_rects[i]);- for (i = 0; i < (int)m_strokes.size(); i++) strokes.push_back(m_strokes[i]);- for (i = 0; i < (int)m_originalStrokes.size(); i++)- originalStrokes.push_back(m_originalStrokes[i]);++ rects.assign(m_rects.begin(), m_rects.end());+ strokes.assign(m_strokes.begin(), m_strokes.end());+ originalStrokes.assign(m_originalStrokes.begin(), m_originalStrokes.end());transformation = m_transformation;TRasterCM32P cmRas = copiedRaster;- if (!targetPalette) targetPalette = new TPalette();+ // Manage temporary palette to avoid leak on early return+ std::unique_ptr<TPalette> tempPalette;+ if (!targetPalette) {+ tempPalette.reset(new TPalette());+ targetPalette = tempPalette.get();+ }++ if (!cmRas) return; // tempPalette cleans up automatically- if (!cmRas) return;std::set<int> usedStyles(m_usedStyles);TToonzImageP ti(cmRas, cmRas->getBounds());- if (usedStyles.size() == 0) ToonzImageUtils::getUsedStyles(usedStyles, ti);+ if (usedStyles.empty()) ToonzImageUtils::getUsedStyles(usedStyles, ti);+std::map<int, int> indexTable;mergePalette(targetPalette, indexTable, m_palette, usedStyles);ToonzImageUtils::scrambleStyles(ti, indexTable);ti->setPalette(m_palette.getPointer());++ if (tempPalette) tempPalette.release(); // ownership transferred to caller}//-------------------------------------------------------------------@@ -152,9 +160,10 @@ StrokesData *ToonzImageData::toStrokesData(ToonzScene *scene) const {rect = m_rects[0];else if (!m_strokes.empty())rect = m_strokes[0].getBBox();- unsigned int i;- for (i = 0; i < m_rects.size(); i++) rect += m_rects[i];- for (i = 0; i < m_strokes.size(); i++) rect += m_strokes[i].getBBox();++ for (const auto &r : m_rects) rect += r;+ for (const auto &s : m_strokes) rect += s.getBBox();+TToonzImageP image(m_copiedRaster, m_copiedRaster->getBounds());image->setPalette(m_palette.getPointer());image->setDpi(m_dpiX, m_dpiY);@@ -174,7 +183,7 @@ StrokesData *ToonzImageData::toStrokesData(ToonzScene *scene) const {StrokesData *sd = new StrokesData();std::set<int> indexes;- for (i = 0; i < vi->getStrokeCount(); i++) indexes.insert(i);+ for (int i = 0; i < (int)vi->getStrokeCount(); i++) indexes.insert(i);sd->setImage(vi, indexes);return sd;@@ -183,12 +192,11 @@ StrokesData *ToonzImageData::toStrokesData(ToonzScene *scene) const {//-------------------------------------------------------------------int ToonzImageData::getMemorySize() const {- int i, size = 0;- for (i = 0; i < (int)m_strokes.size(); i++)- size += m_strokes[i].getControlPointCount() * sizeof(TThickPoint) + 100;- for (i = 0; i < (int)m_originalStrokes.size(); i++)- size +=- m_originalStrokes[i].getControlPointCount() * sizeof(TThickPoint) + 100;+ int size = 0;+ for (const auto &s : m_strokes)+ size += s.getControlPointCount() * sizeof(TThickPoint) + 100;+ for (const auto &s : m_originalStrokes)+ size += s.getControlPointCount() * sizeof(TThickPoint) + 100;return size + sizeof(*(m_copiedRaster.getPointer())) +sizeof(*(m_palette.getPointer())) + sizeof(*this);}@@ -215,7 +223,7 @@ FullColorImageData::FullColorImageData(const FullColorImageData &src)//--------------------------------------------------------------------FullColorImageData::~FullColorImageData() {}+FullColorImageData::~FullColorImageData() = default;//-------------------------------------------------------------------@@ -246,32 +254,40 @@ void FullColorImageData::getData(TRasterP &copiedRaster, double &dpiX,TAffine &transformation,TPalette *targetPalette) const {if (!m_copiedRaster || (m_rects.empty() && m_strokes.empty())) return;+copiedRaster = m_copiedRaster->clone();dpiX = m_dpiX;dpiY = m_dpiY;- int i;- for (i = 0; i < (int)m_rects.size(); i++) rects.push_back(m_rects[i]);- for (i = 0; i < (int)m_strokes.size(); i++) strokes.push_back(m_strokes[i]);- for (i = 0; i < (int)m_originalStrokes.size(); i++)- originalStrokes.push_back(m_originalStrokes[i]);++ rects.assign(m_rects.begin(), m_rects.end());+ strokes.assign(m_strokes.begin(), m_strokes.end());+ originalStrokes.assign(m_originalStrokes.begin(), m_originalStrokes.end());+transformation = m_transformation;TRasterP ras = copiedRaster;if (!ras) return;if (!m_palette) return;- if (!targetPalette) targetPalette = new TPalette();++ std::unique_ptr<TPalette> tempPalette;+ if (!targetPalette) {+ tempPalette.reset(new TPalette());+ targetPalette = tempPalette.get();+ }+std::set<int> usedStyles;TRasterImageP ri(ras);- for (i = 0; i < m_palette->getPageCount(); i++) {+ for (int i = 0; i < m_palette->getPageCount(); i++) {TPalette::Page *page = m_palette->getPage(i);- int j;- for (j = 0; j < page->getStyleCount(); j++)+ for (int j = 0; j < page->getStyleCount(); j++)usedStyles.insert(page->getStyleId(j));}std::map<int, int> indexTable;mergePalette(targetPalette, indexTable, m_palette, usedStyles);ri->setPalette(m_palette.getPointer());++ if (tempPalette) tempPalette.release(); // ownership transferred to caller}//-------------------------------------------------------------------@@ -283,9 +299,10 @@ StrokesData *FullColorImageData::toStrokesData(ToonzScene *scene) const {rect = m_rects[0];else if (!m_strokes.empty())rect = m_strokes[0].getBBox();- unsigned int i;- for (i = 0; i < m_rects.size(); i++) rect += m_rects[i];- for (i = 0; i < m_strokes.size(); i++) rect += m_strokes[i].getBBox();++ for (const auto &r : m_rects) rect += r;+ for (const auto &s : m_strokes) rect += s.getBBox();+TRasterImageP image(m_copiedRaster);image->setPalette(FullColorPalette::instance()->getPalette(scene));image->setDpi(m_dpiX, m_dpiY);@@ -301,7 +318,7 @@ StrokesData *FullColorImageData::toStrokesData(ToonzScene *scene) const {StrokesData *sd = new StrokesData();std::set<int> indexes;- for (i = 0; i < vi->getStrokeCount(); i++) indexes.insert(i);+ for (int i = 0; i < (int)vi->getStrokeCount(); i++) indexes.insert(i);sd->setImage(vi, indexes);return sd;@@ -310,12 +327,11 @@ StrokesData *FullColorImageData::toStrokesData(ToonzScene *scene) const {//-------------------------------------------------------------------int FullColorImageData::getMemorySize() const {- int i, size = 0;- for (i = 0; i < (int)m_strokes.size(); i++)- size += m_strokes[i].getControlPointCount() * sizeof(TThickPoint) + 100;- for (i = 0; i < (int)m_originalStrokes.size(); i++)- size +=- m_originalStrokes[i].getControlPointCount() * sizeof(TThickPoint) + 100;+ int size = 0;+ for (const auto &s : m_strokes)+ size += s.getControlPointCount() * sizeof(TThickPoint) + 100;+ for (const auto &s : m_originalStrokes)+ size += s.getControlPointCount() * sizeof(TThickPoint) + 100;return size + sizeof(*(m_copiedRaster.getPointer())) +sizeof(*(m_palette.getPointer())) + sizeof(*this);}