OpenToonz - An open-source full-featured 2D animation creation software
C
refactor: modern C++ improvements, RAII
Anderson Prado944266e5c159
diff --git a/toonz/sources/colorfx/flowlinestrokestyle.cpp b/toonz/sources/colorfx/flowlinestrokestyle.cppindex 4fb2cebde..6d98677db 100644--- a/toonz/sources/colorfx/flowlinestrokestyle.cpp+++ b/toonz/sources/colorfx/flowlinestrokestyle.cpp@@ -1,93 +1,105 @@+#include "flowlinestrokestyle.h"#include "tcolorfunctions.h"#include "tcurves.h"+#include <memory>+#include <vector>+#include <algorithm>+#include <cmath>#define BUFFER_OFFSET(bytes) ((GLubyte *)NULL + (bytes))#define V_BUFFER_SIZE 1000namespace {-double getMaxThickness(const TStroke *s) {- int count = s->getControlPointCount();- double maxThickness = -1;- for (int i = 0; i < s->getControlPointCount(); i++) {+// Returns the maximum thickness value among all control points of the stroke+double getMaxThickness(const TStroke *s) {+ double maxThickness = -1.0;+ int cpCount = s->getControlPointCount();+ for (int i = 0; i < cpCount; ++i) {double thick = s->getControlPoint(i).thick;if (thick > maxThickness) maxThickness = thick;}return maxThickness;}+// Simple structure for 2D floating point verticesstruct float2 {float x;float y;};+// Dot product of two 2D vectorsinline double dot(const TPointD &v1, const TPointD &v2) {return v1.x * v2.x + v1.y * v2.y;}-//------------------------------------------------------------------------------+// Returns true if the middle point is part of a nearly straight segment (very+// short handles)inline bool isLinearPoint(const TPointD &p0, const TPointD &p1,const TPointD &p2) {return (tdistance(p0, p1) < 0.02) && (tdistance(p1, p2) < 0.02);}-//-------------------------------------------------------------------------------//! Ritorna \b true se il punto \b p1 e' una cuspide.+// Returns true if the angle at p1 is sharp enough to be considered a cuspbool isCuspPoint(const TPointD &p0, const TPointD &p1, const TPointD &p2) {- TPointD p0_p1(p0 - p1), p2_p1(p2 - p1);+ TPointD p0_p1 = p0 - p1;+ TPointD p2_p1 = p2 - p1;+double n1 = norm(p0_p1), n2 = norm(p2_p1);- // Partial linear points are ALWAYS cusps (since directions from them are- // determined by neighbours, not by the points themselves)- if ((n1 < 0.02) || (n2 < 0.02)) return true;+ // Very short handles are always treated as cusps+ if (n1 < 0.02 || n2 < 0.02) return true;p0_p1 = p0_p1 * (1.0 / n1);p2_p1 = p2_p1 * (1.0 / n2);- return (p0_p1 * p2_p1 > 0) ||- (fabs(cross(p0_p1, p2_p1)) > 0.09); // more than 5° is yes-- // Distance-based check. Unscalable...- // return- // !areAlmostEqual(tdistance(p0,p2),tdistance(p0,p1)+tdistance(p1,p2),2);+ // Same direction or angle > ~5 degrees -> cusp+ return (dot(p0_p1, p2_p1) > 0) || (std::abs(cross(p0_p1, p2_p1)) > 0.09);}-//------------------------------------------------------------------------------/*! Insert a point in the most long chunk between chunk \b indexA and chunk \b- * indexB. */+// Inserts a control point in the middle of the longest chunk in the given rangevoid insertPoint(TStroke *stroke, int indexA, int indexB) {assert(stroke);- int j = 0;- int chunkCount = indexB - indexA;- if (chunkCount % 2 == 0) return;- double length = 0;+ if ((indexB - indexA) % 2 == 0) return;++ double bestLength = 0.0;double firstW = 0.0, lastW = 0.0;- for (j = indexA; j < indexB; j++) {- // search for the longest chunk++ for (int j = indexA; j < indexB; ++j) {double w0 = stroke->getW(stroke->getChunk(j)->getP0());- double w1;- if (j == stroke->getChunkCount() - 1)- w1 = 1;- else- w1 = stroke->getW(stroke->getChunk(j)->getP2());- double length0 = stroke->getLength(w0);- double length1 = stroke->getLength(w1);- if (length < length1 - length0) {- firstW = w0;- lastW = w1;- length = length1 - length0;+ double w1 = (j == stroke->getChunkCount() - 1)+ ? 1.0+ : stroke->getW(stroke->getChunk(j)->getP2());++ double segLen = stroke->getLength(w1) - stroke->getLength(w0);+ if (segLen > bestLength) {+ bestLength = segLen;+ firstW = w0;+ lastW = w1;}}- // Insert a control point at the midpoint of the longest chunk- stroke->insertControlPoints((firstW + lastW) * 0.5);++ if (bestLength > 0.0) stroke->insertControlPoints((firstW + lastW) * 0.5);}-}; // namespace-//-----------------------------------------------------------------------------++} // anonymous namespace++// RAII helper to ensure OpenGL vertex array state is properly restored+struct GLVertexArrayGuard {+ GLVertexArrayGuard() { glEnableClientState(GL_VERTEX_ARRAY); }+ ~GLVertexArrayGuard() { glDisableClientState(GL_VERTEX_ARRAY); }++ // Non-copyable+ GLVertexArrayGuard(const GLVertexArrayGuard &) = delete;+ GLVertexArrayGuard &operator=(const GLVertexArrayGuard &) = delete;+};++//=============================================================================+// FlowLineStrokeStyle Implementation+//=============================================================================FlowLineStrokeStyle::FlowLineStrokeStyle(): m_color(TPixel32(100, 200, 200, 255))@@ -96,23 +108,19 @@ FlowLineStrokeStyle::FlowLineStrokeStyle(), m_widthScale(5.0), m_straightenEnds(true) {}-//------------------------------------------------------------------------------TColorStyle *FlowLineStrokeStyle::clone() const {return new FlowLineStrokeStyle(*this);}-//------------------------------------------------------------------------------int FlowLineStrokeStyle::getParamCount() const { return ParamCount; }-//------------------------------------------------------------------------------TColorStyle::ParamType FlowLineStrokeStyle::getParamType(int index) const {assert(0 <= index && index < getParamCount());switch (index) {case Density:+ return TColorStyle::DOUBLE;case Extension:+ return TColorStyle::DOUBLE;case WidthScale:return TColorStyle::DOUBLE;case StraightenEnds:@@ -121,8 +129,6 @@ TColorStyle::ParamType FlowLineStrokeStyle::getParamType(int index) const {return TColorStyle::DOUBLE;}-//------------------------------------------------------------------------------QString FlowLineStrokeStyle::getParamNames(int index) const {assert(0 <= index && index < ParamCount);switch (index) {@@ -139,8 +145,6 @@ QString FlowLineStrokeStyle::getParamNames(int index) const {return QString();}-//------------------------------------------------------------------------------void FlowLineStrokeStyle::getParamRange(int index, double &min,double &max) const {assert(0 <= index && index < ParamCount);@@ -157,11 +161,13 @@ void FlowLineStrokeStyle::getParamRange(int index, double &min,min = 1.0;max = 50.0;break;+ default:+ min = 0.0;+ max = 1.0;+ break;}}-//------------------------------------------------------------------------------double FlowLineStrokeStyle::getParamValue(TColorStyle::double_tag,int index) const {assert(0 <= index && index < ParamCount);@@ -172,12 +178,11 @@ double FlowLineStrokeStyle::getParamValue(TColorStyle::double_tag,return m_extension;case WidthScale:return m_widthScale;+ default:+ return 0.0;}- return 0.0;}-//------------------------------------------------------------------------------void FlowLineStrokeStyle::setParamValue(int index, double value) {assert(0 <= index && index < ParamCount);switch (index) {@@ -194,172 +199,196 @@ void FlowLineStrokeStyle::setParamValue(int index, double value) {updateVersionNumber();}-//------------------------------------------------------------------------------bool FlowLineStrokeStyle::getParamValue(TColorStyle::bool_tag,int index) const {assert(index == StraightenEnds);return m_straightenEnds;}-//------------------------------------------------------------------------------void FlowLineStrokeStyle::setParamValue(int index, bool value) {assert(index == StraightenEnds);m_straightenEnds = value;}-//-----------------------------------------------------------------------------+//=============================================================================void FlowLineStrokeStyle::drawStroke(const TColorFunction *cf,const TStroke *stroke) const {- auto lerp = [](float val1, float val2, float ratio) {- return val1 * (1.0 - ratio) + val2 * ratio;- };- auto length2 = [](TPointD p) { return p.x * p.x + p.y * p.y; };+ // Lambda to compute squared length of a 2D vector+ auto length2 = [](const TPointD &p) { return p.x * p.x + p.y * p.y; };- // Length and position of the stroke is in "actual size" (i.e. not in pixels).- // 1unit = 1/53.3333inches- // Strokeの長さや座標は実寸(1単位=1/53.3333インチ)- double length = stroke->getLength();- if (length <= 0) return;+ // Early exit for degenerate strokes+ const double length = stroke->getLength();+ if (length <= 0.0) return;- double maxThickness = getMaxThickness(stroke) * m_widthScale;- if (maxThickness <= 0) return;+ // Calculate maximum thickness scaled by the width parameter+ const double maxThickness = getMaxThickness(stroke) * m_widthScale;+ if (maxThickness <= 0.0) return;- TStroke *tmpStroke = new TStroke(*stroke);+ // Work on a copy so we can safely modify control points+ auto tmpStroke = std::make_unique<TStroke>(*stroke);- // straighten ends. replace the control point only if the new handle will- // become longer+ // Straighten bezier handles at both ends for a cleaner flow effectif (m_straightenEnds && stroke->getControlPointCount() >= 5 &&!stroke->isSelfLoop()) {- TPointD newPos = tmpStroke->getControlPoint(0) * 0.75 +- tmpStroke->getControlPoint(3) * 0.25;- TPointD oldVec =- tmpStroke->getControlPoint(1) - tmpStroke->getControlPoint(0);- TPointD newVec = newPos - tmpStroke->getControlPoint(0);- if (length2(oldVec) < length2(newVec))- tmpStroke->setControlPoint(1, newPos);-- int lastId = stroke->getControlPointCount() - 1;- newPos = tmpStroke->getControlPoint(lastId) * 0.75 +- tmpStroke->getControlPoint(lastId - 3) * 0.25;- oldVec = tmpStroke->getControlPoint(lastId - 1) -- tmpStroke->getControlPoint(lastId);- newVec = newPos - tmpStroke->getControlPoint(lastId);- if (length2(oldVec) < length2(newVec))- tmpStroke->setControlPoint(lastId - 1, newPos);+ const int cpCount = stroke->getControlPointCount();+ const int lastId = cpCount - 1;++ // Start of stroke: adjust the first control handle+ {+ TPointD newPos = tmpStroke->getControlPoint(0) * 0.75 ++ tmpStroke->getControlPoint(3) * 0.25;+ TPointD oldVec =+ tmpStroke->getControlPoint(1) - tmpStroke->getControlPoint(0);+ TPointD newVec = newPos - tmpStroke->getControlPoint(0);+ if (length2(oldVec) < length2(newVec))+ tmpStroke->setControlPoint(1, newPos);+ }++ // End of stroke: adjust the last control handle+ {+ TPointD newPos = tmpStroke->getControlPoint(lastId) * 0.75 ++ tmpStroke->getControlPoint(lastId - 3) * 0.25;+ TPointD oldVec = tmpStroke->getControlPoint(lastId - 1) -+ tmpStroke->getControlPoint(lastId);+ TPointD newVec = newPos - tmpStroke->getControlPoint(lastId);+ if (length2(oldVec) < length2(newVec))+ tmpStroke->setControlPoint(lastId - 1, newPos);+ }}- // see ControlPointEditorStroke::adjustChunkParity() in- // controlpointselection.cpp- int firstChunk;+ // Ensure even chunk parity around cusps and linear points (required by some+ // renderers)int secondChunk = tmpStroke->getChunkCount();- int i;- for (i = tmpStroke->getChunkCount() - 1; i > 0; i--) {+ for (int i = secondChunk - 1; i > 0; --i) {+ // Skip if chunks are very close togetherif (tdistance(tmpStroke->getChunk(i - 1)->getP0(),tmpStroke->getChunk(i)->getP2()) < 0.5)continue;- TPointD p0 = tmpStroke->getChunk(i - 1)->getP1();- TPointD p1 = tmpStroke->getChunk(i - 1)->getP2();- TPointD p2 = tmpStroke->getChunk(i)->getP1();++ const TPointD p0 = tmpStroke->getChunk(i - 1)->getP1();+ const TPointD p1 = tmpStroke->getChunk(i - 1)->getP2();+ const TPointD p2 = tmpStroke->getChunk(i)->getP1();+if (isCuspPoint(p0, p1, p2) || isLinearPoint(p0, p1, p2)) {- firstChunk = i;- insertPoint(tmpStroke, firstChunk, secondChunk);- secondChunk = firstChunk;+ insertPoint(tmpStroke.get(), i, secondChunk);+ secondChunk = i;}}- insertPoint(tmpStroke, 0, secondChunk);+ insertPoint(tmpStroke.get(), 0, secondChunk);++ // Number of parallel thin lines (odd number ? symmetric around center)+ const int count =+ 2 * static_cast<int>(std::ceil(maxThickness * m_density)) - 1;- // thin lines amount 細線の本数- int count = 2 * (int)std::ceil(maxThickness * m_density) - 1;+ // Apply color function if present, otherwise use the base color+ TPixel32 color = m_color;+ if (cf) color = (*cf)(m_color);- TPixel32 color;- if (cf)- color = (*(cf))(m_color);- else- color = m_color;+ // Pre-allocated vertex buffer (stack-friendly when possible)+ std::vector<float2> vertBuf(V_BUFFER_SIZE);- float2 *vertBuf = new float2[V_BUFFER_SIZE];- int maxVertCount = 0;+ // RAII guard ensures OpenGL vertex array state is disabled even on early+ // returns+ GLVertexArrayGuard glGuard;- glEnableClientState(GL_VERTEX_ARRAY);+ // Calculate basic stroke metrics+ const TThickPoint tp0 = tmpStroke->getThickPoint(0.0);+ const TThickPoint tp1 = tmpStroke->getThickPoint(1.0);+ const double d01 = tdistance(tp0, tp1);+ if (d01 <= 0.0) return;- int centerId = (count - 1) / 2;+ // Determine number of subdivisions for smooth rendering+ const int baseDivisionsPerUnit = 5;+ int divAmount = static_cast<int>(d01) * baseDivisionsPerUnit;+ divAmount = std::min(divAmount, V_BUFFER_SIZE - 3);- TThickPoint p0 = tmpStroke->getThickPoint(0);- TThickPoint p1 = tmpStroke->getThickPoint(1);- double d01 = tdistance(p0, p1);- if (d01 == 0) return;+ // Calculate speed vectors at start and end for extension directions+ const TPointD speed0 = tmpStroke->getSpeed(0.0);+ const TPointD speed1 = tmpStroke->getSpeed(1.0);+ if (norm2(speed0) == 0.0 || norm2(speed1) == 0.0) return;- int len = (int)(d01);- if (len == 0) return;+ const TPointD startVec = -normalize(speed0);+ const TPointD endVec = normalize(speed1);- TPointD v0 = tmpStroke->getSpeed(0);- TPointD v1 = tmpStroke->getSpeed(1);+ // Center index for symmetric width distribution+ const int centerId = (count - 1) / 2;- if (norm2(v0) == 0 || norm2(v1) == 0) return;+ // Draw each parallel line+ for (int i = 0; i < count; ++i) {+ // Width ratio ranges from -1.0 (leftmost) to 1.0 (rightmost)+ const double widthRatio =+ (count == 1) ? 0.0 : (i - centerId) / static_cast<double>(centerId);- TPointD startVec = -normalize(v0);- TPointD endVec = normalize(v1);+ // Determine if this is the center line (optimization: no normal calculation+ // needed)+ const bool isCenterLine = (widthRatio == 0.0);- for (int i = 0; i < count; i++) {- double widthRatio =- (count == 1) ? 0.0 : (double)(i - centerId) / (double)centerId;- double extensionLength =+ // Extension length varies based on position (longer for center lines)+ const double extensionLength =(1.0 - std::abs(widthRatio)) * maxThickness * m_extension;+ // Set line color (all lines use the same color)glColor4ub(color.r, color.g, color.b, color.m);- int divAmount = len * 5;- if (divAmount + 3 > V_BUFFER_SIZE) divAmount = V_BUFFER_SIZE - 3;+ // Pointer to fill the vertex buffer+ float2 *vp = vertBuf.data();- float2 *vp = vertBuf;+ // Generate vertices for this line+ for (int j = 0; j <= divAmount; ++j) {+ const double t = j / static_cast<double>(divAmount);+ const double w = t;- for (int j = 0; j <= divAmount; j++, vp++) {- // current position ratio 今の座標の割合位置- double t = double(j) / double(divAmount);+ // Get position on the stroke at parameter w+ const TPointD position = tmpStroke->getPoint(w);- // position ratio on the stroke ストローク上のratio位置- double w = t;- // unit vector perpendicular to the stroke 鉛直方向の単位ベクトル- TPointD v = rotate90(normalize(tmpStroke->getSpeed(w)));- assert(0 <= w && w <= 1);- // position on the stroke ストローク上の位置- TPointD p = tmpStroke->getPoint(w);+ // Calculate offset position based on width ratio+ TPointD offsetPos = position;- TPointD pos = p + v * maxThickness * widthRatio;+ // Only calculate normal offset if not the center line+ if (!isCenterLine) {+ const TPointD tangent = normalize(tmpStroke->getSpeed(w));+ const TPointD normal = rotate90(tangent);+ offsetPos += normal * maxThickness * widthRatio;+ }+ // Add extension at the start of the lineif (j == 0) {- TPointD sPos = pos + startVec * extensionLength;- *vp = {float(sPos.x), float(sPos.y)};- vp++;+ const TPointD startPos = offsetPos + startVec * extensionLength;+ *(vp++) = {static_cast<float>(startPos.x),+ static_cast<float>(startPos.y)};}- *vp = {float(pos.x), float(pos.y)};++ // Main vertex position+ *(vp++) = {static_cast<float>(offsetPos.x),+ static_cast<float>(offsetPos.y)};++ // Add extension at the end of the lineif (j == divAmount) {- vp++;- TPointD ePos = pos + endVec * extensionLength;- *vp = {float(ePos.x), float(ePos.y)};+ const TPointD endPos = offsetPos + endVec * extensionLength;+ *vp = {static_cast<float>(endPos.x), static_cast<float>(endPos.y)};}}- glVertexPointer(2, GL_FLOAT, 0, vertBuf);- // draw+ // Draw this line as a GL line strip+ glVertexPointer(2, GL_FLOAT, 0, vertBuf.data());glDrawArrays(GL_LINE_STRIP, 0, divAmount + 3);}- glColor4d(0, 0, 0, 1);- glDisableClientState(GL_VERTEX_ARRAY);- delete[] vertBuf;- delete tmpStroke;++ // Restore default color (optional but good practice)+ glColor4d(0.0, 0.0, 0.0, 1.0);}-//-----------------------------------------------------------------------------+//=============================================================================TRectD FlowLineStrokeStyle::getStrokeBBox(const TStroke *stroke) const {+ // Get the base bounding box of the strokeTRectD rect = TColorStyle::getStrokeBBox(stroke);++ // Calculate margin based on maximum thickness and extension parameterdouble margin =getMaxThickness(stroke) * m_widthScale * std::max(1.0, m_extension);- return rect.enlarge(margin);-}-//-----------------------------------------------------------------------------+ // Return enlarged bounding box+ return rect.enlarge(margin);+}\ No newline at end of filediff --git a/toonz/sources/common/tfx/tfx.cpp b/toonz/sources/common/tfx/tfx.cppindex 4b3a70802..09ff7fb71 100644--- a/toonz/sources/common/tfx/tfx.cpp+++ b/toonz/sources/common/tfx/tfx.cpp@@ -13,6 +13,7 @@// STD includes#include <set>+#include <memory> // For std::unique_ptr#include "tfx.h"@@ -145,7 +146,7 @@ public:std::wstring m_name;std::wstring m_fxId;- PortTable m_portTable; //!< Name -> port map+ PortTable m_portTable; //!< Name -> port mapPortArray m_portArray; //!< Ports containerTParamContainer m_paramContainer;@@ -212,7 +213,7 @@ public:}void add(const TFxInfo &info, TFxDeclaration *decl) {- // check for dups ???+ // check for duplicates ???std::pair<TFxInfo, TFxDeclaration *> p(info, decl);m_table[info.m_name] = p;}@@ -335,14 +336,21 @@ TFx *TFx::clone(TFx *fx, bool recursive) const {const NamePort &namedPort = m_imp->m_portArray[p];int groupIdx = namedPort.second->getGroupIndex();- if (groupIdx >= 0 && !fx->getInputPort(namedPort.first))- fx->addInputPort(namedPort.first, new TRasterFxPort, groupIdx);+ if (groupIdx >= 0 && !fx->getInputPort(namedPort.first)) {+ // Fix: Use unique_ptr to prevent memory leak+ std::unique_ptr<TRasterFxPort> port(new TRasterFxPort());+ if (fx->addInputPort(namedPort.first, port.get(), groupIdx)) {+ // Successfully added, release ownership to fx+ port.release();+ }+ // If addInputPort fails, unique_ptr will automatically delete the port+ }}assert(pCount == fx->getInputPortCount());}- // copia ricorsiva sulle porte+ // Recursive copy on portsif (recursive) {int p, pCount = getInputPortCount();for (p = 0; p != pCount; ++p) {@@ -362,7 +370,7 @@ void TFx::linkParams(TFx *fx) {getParams()->link(fx->getParams());m_imp->m_activeTimeRegion = fx->m_imp->m_activeTimeRegion;- // aggiorno i link+ // Update linksassert(m_imp->checkLinks());assert(fx->m_imp->checkLinks());@@ -376,7 +384,7 @@ void TFx::linkParams(TFx *fx) {//--------------------------------------------------void TFx::unlinkParams() {- // clone dei parametri+ // Clone parametersgetParams()->unlink();assert(m_imp->m_prev);@@ -398,7 +406,7 @@ bool TFx::addInputPort(const std::string &name, TFxPort &port) {m_imp->m_portTable[name] = &port;m_imp->m_portArray.push_back(NamePort(name, &port));- port.setOwnerFx(this); // back pointer to the owner...+ port.setOwnerFx(this); // Back pointer to the ownerreturn true;}@@ -416,6 +424,9 @@ bool TFx::addInputPort(const std::string &name, TFxPort *port, int groupIndex) {return false;}+ // Use RAII to manage port memory in case of exceptions+ std::unique_ptr<TFxPort> portGuard(port);+if (!addInputPort(name, *port)) return false;// Assign the port to the associated group@@ -426,6 +437,8 @@ bool TFx::addInputPort(const std::string &name, TFxPort *port, int groupIndex) {assert(name.find(group->m_portsPrefix) == 0);+ // Success - release ownership from portGuard+ portGuard.release();return true;}@@ -701,12 +714,12 @@ void TFx::setNewIdentifier() { m_imp->m_id = ++m_imp->m_nextId; }//--------------------------------------------------void TFx::loadData(TIStream &is) {- // default version of fx is 1+ // Default version of fx is 1setFxVersion(1);std::string tagName;VersionNumber tnzVersion = is.getVersion();- // Prevent to load "params" tag under "super" tag on saving macro fx.+ // Prevent loading "params" tag under "super" tag when saving macro fx.// For now "params" tag is no longer saved under "super" tag.// This is for keeping compatibility with older versions.bool isInSuperTag = (is.getCurrentTagName() == "super");@@ -714,7 +727,7 @@ void TFx::loadData(TIStream &is) {QList<std::wstring> groupNames;while (is.openChild(tagName)) {if (tagName == "params") {- if (isInSuperTag) { // skip loading "params" tag under "super" tag+ if (isInSuperTag) { // Skip loading "params" tag under "super" tagis.skipCurrentTag();continue;}@@ -726,7 +739,7 @@ void TFx::loadData(TIStream &is) {paramVar->getParam()->loadData(is);if (paramVar->isObsolete())onObsoleteParamLoaded(paramVar->getParam()->getName());- } else // il parametro non e' presente -> skip+ } else // Parameter not present -> skipskipChild(is);is.closeChild();@@ -755,7 +768,15 @@ void TFx::loadData(TIStream &is) {TFxPortDG *group = const_cast<TFxPortDG *>(dynamicPortGroup(g));if (group->contains(portName)) {- addInputPort(portName, port = new TRasterFxPort, g);+ // Fix: Use unique_ptr to prevent memory leak+ std::unique_ptr<TRasterFxPort> tempPort(new TRasterFxPort());+ if (addInputPort(portName, tempPort.get(), g)) {+ // Successfully added, assign and release ownership+ port = tempPort.release();+ } else {+ // Failed to add, set port to nullptr (will throw below)+ port = nullptr;+ }break;}}@@ -791,9 +812,8 @@ void TFx::loadData(TIStream &is) {assert(passiveCacheId > 0);TPassiveCacheManager::instance()->declareCached(this, passiveCacheId);} else if (tagName == "name") {- // passo attraverso un filepath solo per evitare i problemi di blank- // o caratteri strani dentro il nome (sospetto che tfilepath sia gestito- // correttamente mentre wstring no+ // Use TFilePath to avoid issues with blanks or strange characters in the+ // name (suspect that TFilePath is handled correctly while wstring is not)TFilePath tmp;is >> tmp;setName(tmp.getWideName());@@ -843,10 +863,10 @@ void TFx::loadData(TIStream &is) {//--------------------------------------------------void TFx::saveData(TOStream &os) {- // Prevent to save "params" tag under "super" tag on saving macro fx.+ // Prevent saving "params" tag under "super" tag when saving macro fx.// Parameters for macro fx are saved in "nodes" tag and corrected upon// loading. Therefore, "params" tag is not needed and even causes crash if- // macrofx contains CurveFx (See the issue #2424)+ // macrofx contains CurveFx (See issue #2424)bool isInSuperTag = (os.getCurrentTagName() == "super");TFx *linkedSetRoot = this;if (m_imp->m_next != m_imp) {@@ -860,12 +880,12 @@ void TFx::saveData(TOStream &os) {assert(linkedSetRoot);}if (linkedSetRoot == this) {- if (!isInSuperTag) { // skip saving "params" tag under "super" tag+ if (!isInSuperTag) { // Skip saving "params" tag under "super" tagos.openChild("params");for (int i = 0; i < getParams()->getParamCount(); i++) {std::string paramName = getParams()->getParamName(i);const TParamVar *paramVar = getParams()->getParamVar(i);- // skip saving for the obsolete parameters+ // Skip saving for obsolete parametersif (paramVar->isObsolete()) continue;os.openChild(paramName);paramVar->getParam()->saveData(os);@@ -933,8 +953,8 @@ void TFx::loadPreset(TIStream &is) {try {TParamP param = getParams()->getParam(paramName);param->loadData(is);- } catch (TException &) { /*skip*/- } // il parametro non e' presente+ } catch (TException &) { /* Skip */+ } // Parameter not presentis.closeChild();}}@@ -1073,4 +1093,4 @@ int TFxTimeRegion::getLastFrame() const {return tceil(m_end) - 1;}-//===================================================+//===================================================\ No newline at end of filediff --git a/toonz/sources/toonzlib/txshsoundtextcolumn.cpp b/toonz/sources/toonzlib/txshsoundtextcolumn.cppindex 8226e4345..5525915e2 100644--- a/toonz/sources/toonzlib/txshsoundtextcolumn.cpp+++ b/toonz/sources/toonzlib/txshsoundtextcolumn.cpp@@ -9,12 +9,8 @@TXshSoundTextColumn::TXshSoundTextColumn() {}-//------------------------------------------------------------------------------TXshSoundTextColumn::~TXshSoundTextColumn() {}-//------------------------------------------------------------------------------TXshColumn::ColumnType TXshSoundTextColumn::getColumnType() const {return eSoundTextType;}@@ -23,22 +19,31 @@ TXshColumn::ColumnType TXshSoundTextColumn::getColumnType() const {void TXshSoundTextColumn::createSoundTextLevel(int row,QList<QString> textList) {- TXshSoundTextLevel *level = new TXshSoundTextLevel();+ if (textList.isEmpty()) return;++ // Level managed by smart pointer; refcount handled via TXshCell+ TSmartPointerT<TXshSoundTextLevel> level = new TXshSoundTextLevel();level->setType(SND_TXT_XSHLEVEL);+TXshCell cell;+for (int i = 0; i < textList.size(); i++, row++) {- QString str = textList.at(i);- QString precStr = (i > 0) ? level->getFrameText(i - 1) : QString();- if (str == QString("<none>")) {+ QString str = textList.at(i);++ // "<none>": reuse previous cell, except for first entry+ if (str == "<none>") {if (i > 0) {setCell(row, cell);continue;- } else- str = QString();+ }+ str = "";}+level->setFrameText(i, str);+TFrameId fid(i + 1);- cell = TXshCell(level, fid);+ cell = TXshCell(level.getPointer(), fid);+setCell(row, cell);}}@@ -64,6 +69,7 @@ TXshColumn *TXshSoundTextColumn::clone() const {void TXshSoundTextColumn::loadData(TIStream &is) {std::string tagName;+while (is.openChild(tagName)) {if (tagName == "cells") {while (is.openChild(tagName)) {@@ -72,26 +78,29 @@ void TXshSoundTextColumn::loadData(TIStream &is) {std::string rowRangeStr = "1";int fidNumber = 1;TFilePath path;+is >> rowRangeStr >> fidNumber >> p;+TXshLevel *xshLevel = dynamic_cast<TXshLevel *>(p);TXshCell cell(xshLevel, TFrameId(fidNumber));- QString _rowRangeStr = QString::fromStdString(rowRangeStr);- QStringList rows = _rowRangeStr.split('-');- if (rows.size() == 1)+ QString qs = QString::fromStdString(rowRangeStr);+ QStringList rows = qs.split('-');++ if (rows.size() == 1) {setCell(rows[0].toInt(), cell);- else if (rows.size() == 2) {+ } else if (rows.size() == 2) {for (int r = rows[0].toInt(); r <= rows[1].toInt(); r++)setCell(r, cell);}- } else+ } else {throw TException("TXshLevelColumn, unknown tag(2): " + tagName);+ }is.closeChild();}- } else if (loadCellMarks(tagName, is)) {- // do nothing- } else+ } else if (!loadCellMarks(tagName, is)) {throw TException("TXshLevelColumn, unknown tag: " + tagName);+ }is.closeChild();}}@@ -100,49 +109,55 @@ void TXshSoundTextColumn::loadData(TIStream &is) {void TXshSoundTextColumn::saveData(TOStream &os) {int r0, r1;+if (getRange(r0, r1)) {os.openChild("cells");+TXshCell prevCell;int fromR = r0;+for (int r = r0; r <= r1; r++) {TXshCell cell = getCell(r);+ // New run of identical cellsif (cell != prevCell) {if (!prevCell.isEmpty()) {int toR = r - 1;TFrameId fid = prevCell.m_frameId;- if (fromR == toR)++ if (fromR == toR) {os.child("cell")<< toR << fid.getNumber() << prevCell.m_level.getPointer();- else {+ } else {QString rangeStr = QString("%1-%2").arg(fromR).arg(toR);os.child("cell") << rangeStr.toStdString() << fid.getNumber()<< prevCell.m_level.getPointer();}}+prevCell = cell;fromR = r;}- assert(cell == prevCell);- if (r == r1) {- if (!cell.isEmpty()) {- int toR = r;- TFrameId fid = cell.m_frameId;- if (fromR == toR)- os.child("cell")- << toR << fid.getNumber() << cell.m_level.getPointer();- else {- QString rangeStr = QString("%1-%2").arg(fromR).arg(toR);- os.child("cell") << rangeStr.toStdString() << fid.getNumber()- << cell.m_level.getPointer();- }++ if (r == r1 && !cell.isEmpty()) {+ int toR = r;+ TFrameId fid = cell.m_frameId;++ if (fromR == toR) {+ os.child("cell") << toR << fid.getNumber()+ << cell.m_level.getPointer();+ } else {+ QString rangeStr = QString("%1-%2").arg(fromR).arg(toR);+ os.child("cell") << rangeStr.toStdString() << fid.getNumber()+ << cell.m_level.getPointer();}}}+os.closeChild();}- // cell marks+saveCellMarks(os);}-PERSIST_IDENTIFIER(TXshSoundTextColumn, "soundTextColumn")+PERSIST_IDENTIFIER(TXshSoundTextColumn, "soundTextColumn")\ No newline at end of filediff --git a/toonz/sources/toonzqt/styleselection.cpp b/toonz/sources/toonzqt/styleselection.cppindex fa6ed8f07..997ccab5e 100644--- a/toonz/sources/toonzqt/styleselection.cpp+++ b/toonz/sources/toonzqt/styleselection.cpp@@ -32,6 +32,7 @@#include <QClipboard>#include <QByteArray>#include <QBuffer>+#include <memory>using namespace DVGui;@@ -48,7 +49,7 @@ void copyStylesWithoutUndo(TPalette *palette, TPaletteHandle *pltHandle,if (n == 0) return;TPalette::Page *page = palette->getPage(pageIndex);assert(page);- StyleData *data = new StyleData();+ auto data = std::make_unique<StyleData>();std::set<int>::iterator it;for (it = styleIndicesInPage->begin(); it != styleIndicesInPage->end();++it) {@@ -59,12 +60,12 @@ void copyStylesWithoutUndo(TPalette *palette, TPaletteHandle *pltHandle,TColorStyle *newStyle = style->clone();data->addStyle(styleId, newStyle);}- QApplication::clipboard()->setMimeData(data);+ QApplication::clipboard()->setMimeData(data.release());}//------------------------------------------------------------------------------/*! Paste styles contained in \b data in the end of current palette page.- Add to styleIndicesInPage pasted styles index.+/*! Paste styles contained in \b data at the end of the current palette page.+ Add pasted styles indices to styleIndicesInPage.*/bool pasteStylesDataWithoutUndo(TPalette *palette, TPaletteHandle *pltHandle,const StyleData *data, int indexInPage,@@ -72,33 +73,33 @@ bool pasteStylesDataWithoutUndo(TPalette *palette, TPaletteHandle *pltHandle,std::set<int> *styleIndicesInPage) {if (!palette) palette = pltHandle->getPalette();if (!palette) return false;- // page = pagina corrente+ // page = current pageTPalette::Page *page = palette->getPage(pageIndex);if (!data) return false;- // comincio a fare paste+ // start pastingint i;int styleId = 0;for (i = 0; i < data->getStyleCount(); i++) {styleId = data->getStyleIndex(i);TColorStyle *style = data->getStyle(i)->clone();- // Se la palette e' di cleanup gli stili devono essere 8.+ // If palette is cleanup palette, styles must be 8.if (palette->isCleanupPalette() && palette->getStyleInPagesCount() >= 8) {delete style;break;}- // For now styles will be inserted regardless the styleId of copied styles- // are already used in the target palette or not.+ // For now styles will be inserted regardless of whether the styleId of+ // copied styles are already used in the target palette or not.styleId = palette->getFirstUnpagedStyle();if (styleId >= 0)palette->setStyle(styleId, style);elsestyleId = palette->addStyle(style);- // check the type of the original(copied) style+ // check the type of the original (copied) style// If the original is NormalStyleif (style->getGlobalName() == L"") {// 1. If pasting normal style to level palette, do nothing@@ -124,11 +125,11 @@ bool pasteStylesDataWithoutUndo(TPalette *palette, TPaletteHandle *pltHandle,else {}- // move in the page- // inserisco lo stile nella pagina+ // move to the page+ // insert style into pageint index = indexInPage + i;page->insertStyle(index, styleId);- // e lo seleziono+ // and select itif (styleIndicesInPage) styleIndicesInPage->insert(index);}if (palette == pltHandle->getPalette()) pltHandle->setStyleIndex(styleId);@@ -139,24 +140,23 @@ bool pasteStylesDataWithoutUndo(TPalette *palette, TPaletteHandle *pltHandle,//-----------------------------------------------------------------------------/*! Paste styles contained in application data after current style. Clear- styleIndicesInPage- and add to it pasted styles. If currentStyleIndex == -1 take- paletteHandle current style.+ styleIndicesInPage and add pasted styles to it. If currentStyleIndex == -1+ use paletteHandle current style.*/bool pasteStylesWithoutUndo(TPalette *palette, TPaletteHandle *pltHandle,int pageIndex, std::set<int> *styleIndicesInPage) {if (!palette) palette = pltHandle->getPalette();- // page = pagina corrente+ // page = current pageTPalette::Page *page = palette->getPage(pageIndex);assert(page);- // cerco il punto di inserimento (dopo lo stile corrente)+ // find insertion point (after current style)int currentStyleIndex = pltHandle->getStyleIndex();int indexInPage = page->search(currentStyleIndex) + 1;const StyleData *data =dynamic_cast<const StyleData *>(QApplication::clipboard()->mimeData());if (!data) return false;- // cancello la selezione+ // clear selectionif (styleIndicesInPage) styleIndicesInPage->clear();return pasteStylesDataWithoutUndo(palette, pltHandle, data, indexInPage,pageIndex, styleIndicesInPage);@@ -182,7 +182,7 @@ void deleteStylesWithoutUndo(TPalette *palette, TPaletteHandle *pltHandle,int j = *it;int styleId = page->getStyleId(j);if (styleId < 2) {- error(QObject::tr("It is not possible to delete the style #") ++ error(QObject::tr("It is not possible to delete style #") +QString::number(styleId));} else {if (styleId == pltHandle->getStyleIndex()) pltHandle->setStyleIndex(1);@@ -192,17 +192,16 @@ void deleteStylesWithoutUndo(TPalette *palette, TPaletteHandle *pltHandle,}styleIndicesInPage->clear();if (mustChangeCurrentStyle) {- // ho cancellato lo stile corrente+ // deleted current styleif (currentStyleIndexInPage < page->getStyleCount()) {- // posso fare in modo che lo stile selezionato sia nella stessa posizione+ // can keep selected style at same positionpltHandle->setStyleIndex(page->getStyleId(currentStyleIndexInPage));} else if (page->getStyleCount() > 0) {- // almeno faccio in modo che sia nella stessa pagina+ // at least keep it in the same pageint styleId = page->getStyleId(page->getStyleCount() - 1);pltHandle->setStyleIndex(styleId);} else {- // seleziono lo stile #1 (che c'e' sempre). n.b. questo puo' comportare un- // cambio pagina+ // select style #1 (always exists). Note: this may cause page changepltHandle->setStyleIndex(1);}}@@ -233,7 +232,7 @@ void insertStylesWithoutUndo(TPalette *palette, TPaletteHandle *pltHandle,if (!data) return;int styleId = 0;- // comincio a fare paste+ // start pastingstd::set<int>::iterator it = styleIndicesInPage->begin();int i;for (i = 0; i < data->getStyleCount(); i++, it++) {@@ -241,7 +240,7 @@ void insertStylesWithoutUndo(TPalette *palette, TPaletteHandle *pltHandle,TColorStyle *style = data->getStyle(i)->clone();palette->setStyle(styleId, style);- // inserisco lo stile nella pagina+ // insert style into pageint index = *it;page->insertStyle(index, styleId);}@@ -283,13 +282,13 @@ public:m_selection->selectNone();m_selection->makeCurrent();- // Setto l'indice corrente.+ // Set current index.if (m_palette.getPointer() == paletteHandle->getPalette())paletteHandle->setStyleIndex(m_oldStyleIndex);}void redo() const override {- // Se e' la paletta corrente setto l'indice corrente.+ // If it's the current palette, set current index.TPaletteHandle *paletteHandle = m_selection->getPaletteHandle();if (m_palette.getPointer() == paletteHandle->getPalette())paletteHandle->setStyleIndex(m_oldStyleIndex);@@ -303,7 +302,7 @@ public:pasteStylesDataWithoutUndo(m_palette.getPointer(), paletteHandle, data,indexInPage, m_pageIndex, &styleIndicesInPage);- // Se e' la paletta corrente aggiorno la selezione+ // If it's the current palette, update selectionif (m_selection && m_palette.getPointer() == paletteHandle->getPalette()) {m_selection->selectNone();m_selection->select(m_pageIndex);@@ -317,7 +316,7 @@ public:int getSize() const override { return sizeof(*this); }QString getHistoryString() override {- return QObject::tr("Paste Style in Palette : %1")+ return QObject::tr("Paste Style to Palette: %1").arg(QString::fromStdWString(m_palette->getPaletteName()));}int getHistoryType() override { return HistoryType::Palette; }@@ -352,10 +351,10 @@ public:void undo() const override {TPaletteHandle *paletteHandle = m_selection->getPaletteHandle();- // Prendo il data corrente+ // Get current dataQClipboard *clipboard = QApplication::clipboard();QMimeData *currentData = cloneData(clipboard->mimeData());- // Setto il vecchio data+ // Set old dataclipboard->setMimeData(cloneData(m_data), QClipboard::Clipboard);std::set<int> styleIndicesInPage = m_styleIndicesInPage;@@ -372,7 +371,7 @@ public:m_selection->makeCurrent();}- // Rimetto il data corrente.+ // Restore current data.clipboard->setMimeData(currentData, QClipboard::Clipboard);// do not activate dirty flag here in case that the m_palette is not current// when undo@@ -393,7 +392,7 @@ public:int getSize() const override { return sizeof(*this); }QString getHistoryString() override {- return QObject::tr("Delete Style from Palette : %1")+ return QObject::tr("Delete Style from Palette: %1").arg(QString::fromStdWString(m_palette->getPaletteName()));}int getHistoryType() override { return HistoryType::Palette; }@@ -427,7 +426,7 @@ public:void undo() const override {TPaletteHandle *paletteHandle = m_selection->getPaletteHandle();- // Setto il data del cut+ // Set cut dataQClipboard *clipboard = QApplication::clipboard();clipboard->setMimeData(cloneData(m_data), QClipboard::Clipboard);@@ -445,7 +444,7 @@ public:m_selection->makeCurrent();}- // Setto il che c'era prima del cut+ // Set data that was there before cutclipboard->setMimeData(cloneData(m_oldData), QClipboard::Clipboard);}@@ -462,7 +461,7 @@ public:int getSize() const override { return sizeof(*this); }QString getHistoryString() override {- return QObject::tr("Cut Style from Palette : %1")+ return QObject::tr("Cut Style from Palette: %1").arg(QString::fromStdWString(m_palette->getPaletteName()));}int getHistoryType() override { return HistoryType::Palette; }@@ -590,7 +589,7 @@ void TStyleSelection::cutStyles() {if (!palette) return;if (palette->isLocked()) return;- StyleData *data = new StyleData();+ auto data = std::make_unique<StyleData>();std::set<int>::iterator it;TPalette::Page *page = palette->getPage(m_pageIndex);std::vector<int> styleIds;@@ -604,7 +603,7 @@ void TStyleSelection::cutStyles() {styleIds.push_back(page->getStyleId(*it));}- std::unique_ptr<TUndo> undo(new CutStylesUndo(this, data, oldData));+ std::unique_ptr<TUndo> undo(new CutStylesUndo(this, data.release(), oldData));if (m_xsheetHandle) {if (eraseStylesInDemand(palette, styleIds, m_xsheetHandle) == 0) return;@@ -627,7 +626,7 @@ void TStyleSelection::copyStyles() {void TStyleSelection::pasteStyles() {TPalette *palette = getPalette();- // se non c'e' palette o pagina corrente esco+ // if no palette or current page, exitif (!palette || m_pageIndex < 0) return;if (palette->isLocked()) return;@@ -660,7 +659,7 @@ void TStyleSelection::deleteStyles() {}if (getStyleCount() == 0) return;- StyleData *data = new StyleData();+ auto data = std::make_unique<StyleData>();std::set<int>::iterator it;TPalette::Page *page = palette->getPage(m_pageIndex);std::vector<int> styleIds;@@ -678,11 +677,12 @@ void TStyleSelection::deleteStyles() {if (m_xsheetHandle) {if (eraseStylesInDemand(palette, styleIds, m_xsheetHandle) ==- 0) // Could add an undo+ 0) { // Could add an undoreturn;+ }}- std::unique_ptr<TUndo> undo(new DeleteStylesUndo(this, data));+ std::unique_ptr<TUndo> undo(new DeleteStylesUndo(this, data.release()));deleteStylesWithoutUndo(m_paletteHandle->getPalette(), m_paletteHandle,m_pageIndex, &m_styleIndicesInPage);@@ -699,13 +699,13 @@ void TStyleSelection::eraseUnusedStyle() {TPalette *palette = m_paletteHandle->getPalette();findPaletteLevels(levels, row, column, palette, m_xsheetHandle->getXsheet());- // Verifico quali stili sono usati e quali no+ // Check which styles are used and which are notstd::map<int, bool> usedStyleIds;int pageCount = palette->getPageCount();for (auto const level : levels) {std::vector<TFrameId> fids;level->getFids(fids);- int m, i, j;+ int m;for (m = 0; m < (int)fids.size(); m++) {TImageP image = level->getFrame(fids[m], false);if (!image) continue;@@ -716,9 +716,8 @@ void TStyleSelection::eraseUnusedStyle() {int styleId = page->getStyleId(j);if (m != 0 && usedStyleIds[styleId]) continue;if (i == 0 &&- (j == 0 || j == 1)) // Il primo stile della prima pagina non deve- // essere mai cancellato- {+ (j == 0 ||+ j == 1)) { // First style of first page should never be deletedusedStyleIds[styleId] = true;continue;}@@ -732,9 +731,9 @@ void TStyleSelection::eraseUnusedStyle() {QMap<int, std::set<int>> styleIndicesInPageMap;QString indicesStr;int count = 0;- // Butto gli stili non usati+ // Remove unused stylesfor (i = 0; i < pageCount; i++) {- // Variabili usate per l'undo+ // Variables used for undostd::set<int> styleIndicesInPage;TPalette::Page *page = palette->getPage(i);assert(page);@@ -774,20 +773,20 @@ void TStyleSelection::eraseUnusedStyle() {while (styleMapItr != styleIndicesInPageMap.constEnd()) {int pageIndex = styleMapItr.key();std::set<int> styleIndicesInPage = styleMapItr.value();- StyleData *data = new StyleData();- TPalette::Page *page = palette->getPage(pageIndex);- for (auto indexInPage : styleIndicesInPage) {++ auto data = std::make_unique<StyleData>();+ TPalette::Page *page = palette->getPage(pageIndex);+ for (int indexInPage : styleIndicesInPage) {int styleId = page->getStyleId(indexInPage);data->addStyle(styleId, page->getStyle(indexInPage)->clone());}- // Cancello gli stili- std::set<int>::reverse_iterator it;- for (it = styleIndicesInPage.rbegin(); it != styleIndicesInPage.rend();+ // Delete styles+ for (auto it = styleIndicesInPage.rbegin(); it != styleIndicesInPage.rend();++it)page->removeStyle(*it);- // Undo- DeleteStylesUndo *undo = new DeleteStylesUndo(this, data);++ DeleteStylesUndo *undo = new DeleteStylesUndo(this, data.release());undo->setPageIndex(pageIndex);undo->setStyleIndicesInPage(styleIndicesInPage);TUndoManager::manager()->add(undo);@@ -866,7 +865,7 @@ public:}void pasteValue(int styleId, const TColorStyle *newStyle) const {- // preserva il vecchio nome se m_pasteOnlyColor e' falso+ // preserve old name if m_pasteOnlyColor is falsestd::wstring str = newStyle->getName();if (m_pasteColor) {getPalette()->setStyle(styleId, newStyle->clone());@@ -887,7 +886,7 @@ public:m_selection->select(m_pageIndex, indexInPage, true);}- // Se avevo aggiunto degli stili devo rimuoverli.+ // If I added styles, I need to remove them.int j;for (j = (int)m_itemsInserted.size() - 1; j >= 0; j--) {int indexInPage = m_itemsInserted[j]->m_index;@@ -975,22 +974,21 @@ public:{if (dstType == NORMALSTYLE) {} // 7. From linked to normal. Do nothing.- else if (dstType == STUDIOSTYLE) // 8. From linked to studio. Restore- // the global name. Delete the- // original name. Set the edited flag- // to off.+ else if (dstType ==+ STUDIOSTYLE) // 8. From linked to studio. Restore the global+ // name. Delete the original name. Set the edited+ // flag to off.{pastedStyle->setGlobalName(dstGlobalName);pastedStyle->setOriginalName(L"");pastedStyle->setIsEditedFlag(false);} else // dstStyle == LINKEDSTYLE //9. From linked to- // linked.- // Do nothing (bring all information from the original).+ // linked. Do nothing (bring all information from the original).{}}- if (!m_pasteName) // devo settare al nuovo stile il vecchio nome+ if (!m_pasteName) // need to set old name to new stylegetPalette()->getStyle(styleId)->setName(oldName);m_selection->select(m_pageIndex, indexInPage, true);}@@ -1023,12 +1021,12 @@ public:}int getSize() const override {- return sizeof(*this) + (int)m_items.size() * 100; // forfait+ return sizeof(*this) + (int)m_items.size() * 100; // approximate}QString getHistoryString() override {QString palNameStr =- QObject::tr(" to Palette : %1")+ QObject::tr(" to Palette: %1").arg(QString::fromStdWString(m_palette->getPaletteName()));if (m_pasteName && m_pasteColor)return QObject::tr("Paste Color && Name%1").arg(palNameStr);@@ -1136,8 +1134,8 @@ void TStyleSelection::pasteStylesValues(bool pasteName, bool pasteColor) {}} else if (srcType == STUDIOSTYLE) {if (dstType ==- NORMALSTYLE) // 4. From studio to normal. Set the studio- // style's name to the original name.+ NORMALSTYLE) // 4. From studio to normal. Set the studio style's+ // name to the original name.pastedStyle->setOriginalName(data->getStyle(i)->getName());else if (dstType == STUDIOSTYLE) // 5. From studio to studio. Restore// the global name.@@ -1153,17 +1151,17 @@ void TStyleSelection::pasteStylesValues(bool pasteName, bool pasteColor) {{if (dstType == NORMALSTYLE) {} // 7. From linked to normal. Do nothing.- else if (dstType == STUDIOSTYLE) // 8. From linked to studio. Restore- // the global name. Delete the- // original name. Set the edited- // flag to off.+ else if (dstType ==+ STUDIOSTYLE) // 8. From linked to studio. Restore the global+ // name. Delete the original name. Set the+ // edited flag to off.{pastedStyle->setGlobalName(dstGlobalName);pastedStyle->setOriginalName(L"");pastedStyle->setIsEditedFlag(false);} else // dstType == LINKEDSTYLE //9. From linked to- // linked.- // Do nothing (bring all information from the original).+ // linked. Do nothing (bring all information from the+ // original).{}}@@ -1188,23 +1186,17 @@ void TStyleSelection::pasteStylesValues(bool pasteName, bool pasteColor) {// If the styles of the data are more than those selected, make a paste of the// styles that remain, inserting the new styles after indexInPageif (i < dataStyleCount) {- StyleData *newData = new StyleData();- int j;- for (j = i; j < dataStyleCount; j++)+ auto newData = std::make_unique<StyleData>();+ for (int j = i; j < dataStyleCount; j++)newData->addStyle(data->getStyleIndex(j), data->getStyle(j)->clone());std::set<int> styleIndicesInPage;pasteStylesDataWithoutUndo(m_paletteHandle->getPalette(), m_paletteHandle,- newData, indexInPage + 1, m_pageIndex,+ newData.get(), indexInPage + 1, m_pageIndex,&styleIndicesInPage);undo->addItemToInsert(styleIndicesInPage);- std::set<int>::iterator styleIt;- for (styleIt = styleIndicesInPage.begin();- styleIt != styleIndicesInPage.end(); ++styleIt)- m_styleIndicesInPage.insert(*styleIt);-- delete newData;+ for (int idx : styleIndicesInPage) m_styleIndicesInPage.insert(idx);}TUndoManager::manager()->add(undo);@@ -1304,11 +1296,11 @@ public:int getSize() const override {return sizeof(- *this); //+500*m_oldStyles.size(); //dipende da che stile ha salvato+ *this); //+500*m_oldStyles.size(); //depends on what style was saved}QString getHistoryString() override {- return QObject::tr("Blend Colors in Palette : %1")+ return QObject::tr("Blend Colors in Palette: %1").arg(QString::fromStdWString(m_palette->getPaletteName()));}int getHistoryType() override { return HistoryType::Palette; }@@ -1438,7 +1430,7 @@ public:int getSize() const override { return sizeof(*this); }QString getHistoryString() override {- return QObject::tr("Toggle Link in Palette : %1")+ return QObject::tr("Toggle Link in Palette: %1").arg(QString::fromStdWString(m_palette->getPaletteName()));}int getHistoryType() override { return HistoryType::Palette; }@@ -1451,7 +1443,7 @@ public:void TStyleSelection::toggleLink() {TPalette *palette = getPalette();if (!palette || m_pageIndex < 0) return;- if (isEmpty() || palette->isLocked()) return;+ if (isEmpty() || palette->isLocked()) return; // 110804 iwasawaint n = m_styleIndicesInPage.size();if (n <= 0) return;@@ -1636,7 +1628,7 @@ public:int getSize() const override { return sizeof(*this); }QString getHistoryString() override {- return QObject::tr("Remove Reference in Palette : %1")+ return QObject::tr("Remove Reference in Palette: %1").arg(QString::fromStdWString(m_palette->getPaletteName()));}int getHistoryType() override { return HistoryType::Palette; }@@ -1718,7 +1710,7 @@ public:TPalette::Page *page = palette->getPage(pageIndex);if (!page) return;std::set<int> indices = selection.getIndicesInPage();- // non si puo' modificare il BG+ // cannot modify BGif (pageIndex == 0) indices.erase(0);styles.reserve(indices.size());for (std::set<int>::iterator it = indices.begin(); it != indices.end();@@ -1813,7 +1805,7 @@ void TStyleSelection::getBackOriginalStyle() {std::map<std::wstring, TPaletteP>::iterator palIt;palIt = table.find(paletteId);- TPalette *spPalette = 0;+ TPaletteP spPalette;// If not found in the table, then search for a new studio palette.if (palIt == table.end()) {@@ -1821,14 +1813,17 @@ void TStyleSelection::getBackOriginalStyle() {if (!spPalette) continue;table[paletteId] = spPalette;assert(spPalette->getRefCount() == 1);- } else- spPalette = palIt->second.getPointer();+ } else {+ spPalette = palIt->second;+ }// j is StyleIDint j = std::stoi(gname.substr(k + 1));- if (spPalette && 0 <= j && j < spPalette->getStyleCount()) {- TColorStyle *spStyle = spPalette->getStyle(j);+ // Use the palette from the table to ensure we have a valid reference+ TPalette *currentPalette = table[paletteId].getPointer();+ if (currentPalette && 0 <= j && j < currentPalette->getStyleCount()) {+ TColorStyle *spStyle = currentPalette->getStyle(j);assert(spStyle);// edit flag is also copied here@@ -1883,4 +1878,4 @@ bool TStyleSelection::hasLinkedStyle() {}}return false;-}+}\ No newline at end of file