OpenToonz - An open-source full-featured 2D animation creation software
C
Memory Leaks Fixes, C++ Refactoring
andeon50430c1f8fe6
diff --git a/toonz/sources/tconverter/tconverter.cpp b/toonz/sources/tconverter/tconverter.cppindex 56d3e869a..696d113df 100644--- a/toonz/sources/tconverter/tconverter.cpp+++ b/toonz/sources/tconverter/tconverter.cpp@@ -33,11 +33,11 @@#include <QGuiApplication>#endif-using namespace std;-using namespace TCli;+// Add memory header for smart pointers+#include <memory>-typedef ArgumentT<TFilePath> FilePathArgument;-typedef QualifierT<TFilePath> FilePathQualifier;+using TCli::ArgumentT;+using TCli::QualifierT;#define RENDER_LICENSE_NOT_FOUND 888@@ -48,22 +48,29 @@ namespace {//--------------------------------------------------------------------+/**+ * Check if file already exists and prompt user for replacement+ * @param fp File path to check+ */void doesExist(const TFilePath &fp) {- string msg;+ std::string msg;TFilePath path =fp.getParentDir() + (fp.getName() + "." + fp.getDottedType());+if (TSystem::doesExistFileOrLevel(fp) ||TSystem::doesExistFileOrLevel(path)) {msg = "File " + fp.getLevelName() + " already exists:";- cout << endl << msg << endl;+ std::cout << std::endl << msg << std::endl;+char answer = ' ';while (answer != 'Y' && answer != 'N' && answer != 'y' && answer != 'n') {msg = "do you want to replace it? [Y/N] ";- cout << msg;- cin >> answer;+ std::cout << msg;+ std::cin >> answer;+if (answer == 'N' || answer == 'n') {msg = "Conversion aborted.";- cout << endl << msg << endl;+ std::cout << std::endl << msg << std::endl;exit(1);}}@@ -72,286 +79,375 @@ void doesExist(const TFilePath &fp) {//---------------------------------------------------------------------// Ritorna un vettore contenete i soli TFrameId corrispondenti al range inserito-// dall'utente-vector<TFrameId> getFrameIds(const RangeQualifier &range,- const TLevelP &level) {- string msg;+/**+ * Get frame IDs based on user specified range+ * @param range Range qualifier from user input+ * @param level Input level+ * @return Vector of frame IDs to process+ */+std::vector<TFrameId> getFrameIds(const TCli::RangeQualifier &range,+ const TLevelP &level) {+ std::string msg;TFrameId r0, r1, lastFrame;TLevel::Iterator begin = level->begin();TLevel::Iterator end = level->end();end--;lastFrame = end->first;- vector<TFrameId> frames;++ std::vector<TFrameId> frames;+if (range.isSelected()) {r0 = TFrameId(range.getFrom());r1 = TFrameId(range.getTo());if (r0 > r1) {- TFrameId app = r0;- r0 = r1;- r1 = app;+ std::swap(r0, r1);}} else {r0 = begin->first;r1 = end->first;}- // cerco il primo TFrameId++ // Find first TFrameIdTLevel::Iterator it = begin;- if (r0 <= end->first)+ if (r0 <= end->first) {while (it->first < r0) ++it;+ }++ // Fill vector up to last needed TFrameIdwhile (it != level->end() && r1 >= it->first) {- // Riempio il vettore fino all'ultimo TFrameId che mi serveframes.push_back(it->first);++it;}+return frames;}//--------------------------------------------------------------------+/**+ * Convert from colored-mask (CM) format+ * @param lr Level reader+ * @param plt Palette+ * @param lw Level writer+ * @param frames Frame IDs to convert+ * @param aff Affine transformation+ * @param resType Resample filter type+ */void convertFromCM(const TLevelReaderP &lr, const TPaletteP &plt,- const TLevelWriterP &lw, const vector<TFrameId> &frames,+ const TLevelWriterP &lw, const std::vector<TFrameId> &frames,const TAffine &aff,const TRop::ResampleFilterType &resType) {- TDimension dim(- 0,- 0); // Serve per controllare che non ci siano frame di diverse dimensioni- for (int i = 0; i < (int)frames.size(); i++) {+ TDimension dim(0, 0); // Track dimensions to ensure consistent frame sizes++ for (size_t i = 0; i < frames.size(); i++) {try {TImageReaderP ir = lr->getFrameReader(frames[i]);TImageP img = ir->load();TToonzImageP toonzImage(img);++ if (!toonzImage) continue;+double xdpi, ydpi;toonzImage->getDpi(xdpi, ydpi);- assert(toonzImage);- if (toonzImage) {- TRasterCM32P rasCMImage = toonzImage->getRaster();- if (i == 0)- dim = rasCMImage->getSize();- else if (dim != rasCMImage->getSize()) {- // dimensioni diverse dei frame- string msg = "Cannot continue to convert: not valid level!";- cout << msg << endl;- exit(1);- }- TRaster32P ras(- convert(aff * convert(rasCMImage->getBounds())).getSize());- if (!aff.isIdentity())- TRop::resample(ras, rasCMImage, plt, aff, resType);- else- TRop::convert(ras, rasCMImage, plt);- TRasterImageP rasImage(ras);- rasImage->setDpi(xdpi, ydpi);- TImageWriterP iw = lw->getFrameWriter(frames[i]);- iw->save(rasImage);+ TRasterCM32P rasCMImage = toonzImage->getRaster();++ // Check frame dimensions consistency+ if (i == 0) {+ dim = rasCMImage->getSize();+ } else if (dim != rasCMImage->getSize()) {+ std::string msg = "Cannot continue to convert: not valid level!";+ std::cout << msg << std::endl;+ exit(1);+ }++ TRaster32P ras(convert(aff * convert(rasCMImage->getBounds())).getSize());++ if (!aff.isIdentity()) {+ TRop::resample(ras, rasCMImage, plt, aff, resType);+ } else {+ TRop::convert(ras, rasCMImage, plt);}++ TRasterImageP rasImage(ras);+ rasImage->setDpi(xdpi, ydpi);+ TImageWriterP iw = lw->getFrameWriter(frames[i]);+ iw->save(rasImage);+} catch (...) {- string msg = "Frame " + std::to_string(frames[i].getNumber()) +- ": conversion failed!";- cout << msg << endl;+ std::string msg = "Frame " + std::to_string(frames[i].getNumber()) ++ ": conversion failed!";+ std::cout << msg << std::endl;}}}//--------------------------------------------------------------------+/**+ * Convert from vector image (VI) format+ * @param lr Level reader+ * @param plt Palette+ * @param lw Level writer+ * @param frames Frame IDs to convert+ * @param resType Resample filter type+ * @param width Output width+ */void convertFromVI(const TLevelReaderP &lr, const TPaletteP &plt,- const TLevelWriterP &lw, const vector<TFrameId> &frames,+ const TLevelWriterP &lw, const std::vector<TFrameId> &frames,const TRop::ResampleFilterType &resType, int width) {- int i;- vector<TVectorImageP> images;+ std::vector<TVectorImageP> images;TRectD maxBbox;TAffine aff;- for (i = 0; i < (int)frames.size();- i++) { // trovo la bbox che possa contenere tutte le immagini++ // Find bounding box that contains all images+ for (size_t i = 0; i < frames.size(); i++) {try {TImageReaderP ir = lr->getFrameReader(frames[i]);TVectorImageP img = ir->load();images.push_back(img);maxBbox += img->getBBox();} catch (...) {- string msg = "Frame " + std::to_string(frames[i].getNumber()) +- ": conversion failed!";- cout << msg << endl;+ std::string msg = "Frame " + std::to_string(frames[i].getNumber()) ++ ": conversion failed!";+ std::cout << msg << std::endl;}}+maxBbox = maxBbox.enlarge(2);- if (width) // calcolo l'affine- aff = TScale((double)width / maxBbox.getLx());++ // Calculate affine transformation for width+ if (width) {+ aff = TScale(static_cast<double>(width) / maxBbox.getLx());+ }+maxBbox = aff * maxBbox;- for (i = 0; i < (int)images.size(); i++) {+ for (size_t i = 0; i < images.size(); i++) {try {TVectorImageP vectorImage = images[i];- assert(vectorImage);- if (vectorImage) {- // faccio il render dell'immagine- vectorImage->transform(aff, true);- const TVectorRenderData rd(TTranslation(-maxBbox.getP00()), TRect(),- plt.getPointer(), 0, true, true);- TOfflineGL *glContext = new TOfflineGL(convert(maxBbox).getSize());- glContext->clear(TPixel32::Transparent);- glContext->draw(vectorImage, rd);- TRaster32P rasImage = (glContext->getRaster());- TImageWriterP iw = lw->getFrameWriter(frames[i]);- iw->save(TRasterImageP(rasImage));- }+ if (!vectorImage) continue;++ // Apply transformation and render image+ vectorImage->transform(aff, true);+ const TVectorRenderData rd(TTranslation(-maxBbox.getP00()), TRect(),+ plt.getPointer(), 0, true, true);++ std::unique_ptr<TOfflineGL> glContext(+ new TOfflineGL(convert(maxBbox).getSize()));+ glContext->clear(TPixel32::Transparent);+ glContext->draw(vectorImage, rd);++ TRaster32P rasImage = glContext->getRaster();+ TImageWriterP iw = lw->getFrameWriter(frames[i]);+ iw->save(TRasterImageP(rasImage));+} catch (...) {- string msg = "Frame " + frames[i].expand() + ": conversion failed!";- cout << msg << endl;+ std::string msg = "Frame " + frames[i].expand() + ": conversion failed!";+ std::cout << msg << std::endl;}}}//-----------------------------------------------------------------------+/**+ * Convert from full raster format+ * @param lr Level reader+ * @param lw Level writer+ * @param frames Frame IDs to convert+ * @param aff Affine transformation+ * @param resType Resample filter type+ */void convertFromFullRaster(const TLevelReaderP &lr, const TLevelWriterP &lw,- const vector<TFrameId> &frames, const TAffine &aff,+ const std::vector<TFrameId> &frames,+ const TAffine &aff,const TRop::ResampleFilterType &resType) {- for (int i = 0; i < (int)frames.size(); i++) {+ for (size_t i = 0; i < frames.size(); i++) {try {TImageReaderP ir = lr->getFrameReader(frames[i]);TRasterImageP img = ir->load();+TRaster32P raster(convert(aff * img->getBBox()).getSize());- if (!aff.isIdentity())++ if (!aff.isIdentity()) {TRop::resample(raster, img->getRaster(), aff, resType);- else {- if ((TRaster32P)img->getRaster())- raster = img->getRaster();- else+ } else {+ if (TRaster32P ras32 = img->getRaster()) {+ raster = ras32;+ } else {TRop::convert(raster, img->getRaster());+ }}+TImageWriterP iw = lw->getFrameWriter(frames[i]);iw->save(TRasterImageP(raster));+} catch (...) {- string msg = "Frame " + frames[i].expand() + ": conversion failed!";- cout << msg << endl;+ std::string msg = "Frame " + frames[i].expand() + ": conversion failed!";+ std::cout << msg << std::endl;}}}//-----------------------------------------------------------------------+/**+ * Convert from full raster to colored-mask format+ * @param lr Level reader+ * @param lw Level writer+ * @param frames Frame IDs to convert+ * @param aff Affine transformation+ * @param resType Resample filter type+ */void convertFromFullRasterToCm(const TLevelReaderP &lr, const TLevelWriterP &lw,- const vector<TFrameId> &frames,+ const std::vector<TFrameId> &frames,const TAffine &aff,const TRop::ResampleFilterType &resType) {- TPalette *plt = new TPalette();+ std::unique_ptr<TPalette> plt(new TPalette());- for (int i = 0; i < (int)frames.size(); i++) {+ for (size_t i = 0; i < frames.size(); i++) {try {TImageReaderP ir = lr->getFrameReader(frames[i]);TRasterImageP img = ir->load();+double dpix, dpiy;img->getDpi(dpix, dpiy);- if (dpix == 0 && dpiy == 0)+ if (dpix == 0 && dpiy == 0) {dpix = dpiy = Preferences::instance()->getDefLevelDpi();+ }+TRasterCM32P raster(convert(aff * img->getBBox()).getSize());if (!aff.isIdentity()) {TRaster32P raux(raster->getSize());TRop::resample(raux, img->getRaster(), aff, resType);TRop::convert(raster, raux);- } else+ } else {TRop::convert(raster, img->getRaster());+ }TImageWriterP iw = lw->getFrameWriter(frames[i]);TToonzImageP outimg(raster, raster->getBounds());outimg->setDpi(dpix, dpiy);- outimg->setPalette(plt);+ outimg->setPalette(plt.get());iw->save(outimg);} catch (...) {- string msg = "Frame " + frames[i].expand() + ": conversion failed!";- cout << msg << endl;+ std::string msg = "Frame " + frames[i].expand() + ": conversion failed!";+ std::cout << msg << std::endl;}}+ // Save palette to fileTFilePath pltPath = lw->getFilePath().withNoFrame().withType("tpl");if (TSystem::touchParentDir(pltPath)) {- if (TSystem::doesExistFileOrLevel(pltPath))+ if (TSystem::doesExistFileOrLevel(pltPath)) {TSystem::removeFileOrLevel(pltPath);- TOStream os(pltPath);- os << plt;+ }++ try {+ TOStream os(pltPath);+ os << plt.get();+ } catch (...) {+ std::cout << "Warning: Could not save palette file" << std::endl;+ }}}+//-----------------------------------------------------------------------+/**+ * Main conversion function+ * @param source Source file path+ * @param dest Destination file path+ * @param range Frame range qualifier+ * @param width Width qualifier+ * @param prop Output properties+ * @param resQuality Resample quality+ */void convert(const TFilePath &source, const TFilePath &dest,- const RangeQualifier &range, const IntQualifier &width,+ const TCli::RangeQualifier &range, const TCli::IntQualifier &width,TPropertyGroup *prop,const TRenderSettings::ResampleQuality &resQuality) {- string msg;- // Carico le informazione del livello+ std::string msg;++ // Load level informationTLevelReaderP lr(source);TLevelP level = lr->loadInfo();- // Trovo i TFrameId corrispondenti al range- vector<TFrameId> frames = getFrameIds(range, level);+ // Get frame IDs based on range+ std::vector<TFrameId> frames = getFrameIds(range, level);doesExist(dest);msg = "Level loaded";- cout << msg << endl;+ std::cout << msg << std::endl;msg = "Conversion in progress: wait please...";- cout << msg << endl;+ std::cout << msg << std::endl;TAffine aff;if (width.isSelected()) {- // calcolo un affine per fare la resample+ // Calculate affine for resamplingint imgLx = lr->getImageInfo()->m_lx;- aff = TScale((double)width / (double)imgLx);+ aff = TScale(static_cast<double>(width.getValue()) /+ static_cast<double>(imgLx));}- // setto il FilterResempleType giusto- TRop::ResampleFilterType resType;- if (resQuality == TRenderSettings::StandardResampleQuality)+ // Set resample filter type based on quality+ TRop::ResampleFilterType resType = TRop::Triangle; // Default++ if (resQuality == TRenderSettings::StandardResampleQuality) {resType = TRop::Triangle;- else if (resQuality == TRenderSettings::ImprovedResampleQuality)+ } else if (resQuality == TRenderSettings::ImprovedResampleQuality) {resType = TRop::Hann2;- else if (resQuality == TRenderSettings::HighResampleQuality)+ } else if (resQuality == TRenderSettings::HighResampleQuality) {resType = TRop::Hamming3;- else if (resQuality == TRenderSettings::Triangle_FilterResampleQuality)+ } else if (resQuality == TRenderSettings::Triangle_FilterResampleQuality) {resType = TRop::Triangle;- else if (resQuality == TRenderSettings::Mitchell_FilterResampleQuality)+ } else if (resQuality == TRenderSettings::Mitchell_FilterResampleQuality) {resType = TRop::Mitchell;- else if (resQuality == TRenderSettings::Cubic5_FilterResampleQuality)+ } else if (resQuality == TRenderSettings::Cubic5_FilterResampleQuality) {resType = TRop::Cubic5;- else if (resQuality == TRenderSettings::Cubic75_FilterResampleQuality)+ } else if (resQuality == TRenderSettings::Cubic75_FilterResampleQuality) {resType = TRop::Cubic75;- else if (resQuality == TRenderSettings::Cubic1_FilterResampleQuality)+ } else if (resQuality == TRenderSettings::Cubic1_FilterResampleQuality) {resType = TRop::Cubic1;- else if (resQuality == TRenderSettings::Hann2_FilterResampleQuality)+ } else if (resQuality == TRenderSettings::Hann2_FilterResampleQuality) {resType = TRop::Hann2;- else if (resQuality == TRenderSettings::Hann3_FilterResampleQuality)+ } else if (resQuality == TRenderSettings::Hann3_FilterResampleQuality) {resType = TRop::Hann3;- else if (resQuality == TRenderSettings::Hamming2_FilterResampleQuality)+ } else if (resQuality == TRenderSettings::Hamming2_FilterResampleQuality) {resType = TRop::Hamming2;- else if (resQuality == TRenderSettings::Hamming3_FilterResampleQuality)+ } else if (resQuality == TRenderSettings::Hamming3_FilterResampleQuality) {resType = TRop::Hamming3;- else if (resQuality == TRenderSettings::Lanczos2_FilterResampleQuality)+ } else if (resQuality == TRenderSettings::Lanczos2_FilterResampleQuality) {resType = TRop::Lanczos2;- else if (resQuality == TRenderSettings::Lanczos3_FilterResampleQuality)+ } else if (resQuality == TRenderSettings::Lanczos3_FilterResampleQuality) {resType = TRop::Lanczos3;- else if (resQuality == TRenderSettings::Gauss_FilterResampleQuality)+ } else if (resQuality == TRenderSettings::Gauss_FilterResampleQuality) {resType = TRop::Gauss;- else if (resQuality == TRenderSettings::ClosestPixel_FilterResampleQuality)+ } else if (resQuality ==+ TRenderSettings::ClosestPixel_FilterResampleQuality) {resType = TRop::ClosestPixel;- else if (resQuality == TRenderSettings::Bilinear_FilterResampleQuality)+ } else if (resQuality == TRenderSettings::Bilinear_FilterResampleQuality) {resType = TRop::Bilinear;+ }- string ext = source.getType();+ std::string ext = source.getType();TLevelWriterP lw(dest, prop);+if (ext != "tlv" && ext != "pli") {- if (dest.getType() == "tlv")+ if (dest.getType() == "tlv") {convertFromFullRasterToCm(lr, lw, frames, aff, resType);- else+ } else {convertFromFullRaster(lr, lw, frames, aff, resType);- } else if (ext == "tlv") // ToonzImage+ }+ } else if (ext == "tlv") { // ToonzImageconvertFromCM(lr, level->getPalette(), lw, frames, aff, resType);- else if (ext == "pli") // VectorImage+ } else if (ext == "pli") { // VectorImageconvertFromVI(lr, level->getPalette(), lw, frames, resType,width.getValue());+ }}} // namespace@@ -366,103 +462,125 @@ int main(int argc, char *argv[]) {TEnv::setRootVarName(rootVarName);TEnv::setSystemVarPrefix(systemVarPrefix);TEnv::setApplicationFileName(argv[0]);- TFilePath fp = TEnv::getStuffDir();- string msg;- // Inizializzo i qualificatori+ std::string msg;++ // Initialize qualifiersTCli::FilePathArgument srcName("srcName", "Source file");TCli::FilePathArgument dstName("dstName", "Target file");- FilePathQualifier tnzName("-s sceneName", "Scene file");- RangeQualifier range;- IntQualifier width("-w width", "Image width");+ TCli::QualifierT<TFilePath> tnzName("-s sceneName", "Scene file");+ TCli::RangeQualifier range;+ TCli::IntQualifier width("-w width", "Image width");- Usage usage(argv[0]);+ TCli::Usage usage(argv[0]);usage.add(srcName + dstName + width + tnzName + range);- if (!usage.parse(argc, argv)) exit(1);++ if (!usage.parse(argc, argv)) {+ exit(1);+ }try {Tiio::defineStd();- // TPluginManager::instance()->loadStandardPlugins();-TSystem::hasMainLoop(false);- TPropertyGroup *prop = 0;++ TPropertyGroup *prop = nullptr;initImageIo();+TRenderSettings::ResampleQuality resQuality =TRenderSettings::StandardResampleQuality;TFilePath dstFilePath = dstName.getValue();TFilePath srcFilePath = srcName.getValue();+if (!TSystem::doesExistFileOrLevel(srcFilePath)) {msg = srcFilePath.getLevelName() + " level doesn't exist.";- cout << endl << msg << endl;+ std::cout << std::endl << msg << std::endl;exit(1);}+msg = "Loading " + srcFilePath.getLevelName();- cout << endl << msg << endl;+ std::cout << std::endl << msg << std::endl;- string ext = dstFilePath.getType();- // controllo che ci sia un'estensione- if (ext == "") {- ext = ::to_string(dstFilePath);- if (ext == "") {+ std::string ext = dstFilePath.getType();++ // Check for valid extension+ if (ext.empty()) {+ ext = dstFilePath.getName();+ if (ext.empty()) {msg = "Invalid extension!";- cout << msg << endl;+ std::cout << msg << std::endl;exit(1);}}- if (dstFilePath.getParentDir()- .isEmpty()) // ho specificato solo l'estensione++ // Handle destination path+ if (dstFilePath.getParentDir().isEmpty()) {dstFilePath =srcFilePath.getParentDir() + (srcFilePath.getName() + "." + ext);+ }++ // Scene-based conversion+ std::unique_ptr<ToonzScene> scenePtr;if (tnzName.isSelected()) {- // Devo prendermi i settaggi degli "output setting" dalla scena!TFilePath tnzFilePath = tnzName.getValue();if (tnzFilePath.getType() != "tnz") {msg = "Invalid scene file: conversion terminated!";- cout << msg << endl;+ std::cout << msg << std::endl;exit(1);}- if (!TSystem::doesExistFileOrLevel(tnzFilePath)) return -1;- ToonzScene *scene = new ToonzScene();+ if (!TSystem::doesExistFileOrLevel(tnzFilePath)) {+ return -1;+ }++ scenePtr = std::make_unique<ToonzScene>();try {- scene->loadTnzFile(tnzFilePath);+ scenePtr->loadTnzFile(tnzFilePath);} catch (...) {- string msg;- msg = "There were problems loading the scene " +- ::to_string(srcFilePath) + ".\n Some files may be missing.";- cout << msg << endl;- // return false;+ msg = "There were problems loading the scene " + srcFilePath.getName() ++ ".\n Some files may be missing.";+ std::cout << msg << std::endl;}- if (scene) {- resQuality = scene->getProperties()+ if (scenePtr) {+ resQuality = scenePtr->getProperties()->getOutputProperties()->getRenderSettings().m_quality;- prop = scene->getProperties()+ prop = scenePtr->getProperties()->getOutputProperties()->getFileFormatProperties(ext);} else {msg = "Invalid scene file: conversion terminated!";- cout << msg << endl;+ std::cout << msg << std::endl;exit(1);}}++ // Perform conversion based on formatif (ext != "3gp" && ext != "pli") {- // assert(ext!="3gp" && ext!="pli" && ext!="tlv");convert(srcFilePath, dstFilePath, range, width, prop, resQuality);} else {msg = "Cannot convert to ." + ext + " format.";- cout << msg << endl;+ std::cout << msg << std::endl;exit(1);}+} catch (TException &e) {msg = "Untrapped exception: " + ::to_string(e.getMessage());- cout << msg << endl;+ std::cout << msg << std::endl;+ return -1;+ } catch (std::exception &e) {+ msg = "Standard exception: " + std::string(e.what());+ std::cout << msg << std::endl;+ return -1;+ } catch (...) {+ msg = "Unknown exception occurred!";+ std::cout << msg << std::endl;return -1;}+msg = "Conversion terminated!";- cout << endl << msg << endl;+ std::cout << std::endl << msg << std::endl;return 0;}diff --git a/toonz/sources/tnzext/StrokeDeformationImpl.cpp b/toonz/sources/tnzext/StrokeDeformationImpl.cppindex 65ac5ee8c..8de8a9c4d 100644--- a/toonz/sources/tnzext/StrokeDeformationImpl.cpp+++ b/toonz/sources/tnzext/StrokeDeformationImpl.cpp@@ -3,46 +3,55 @@/*** @author Fabrizio Morciano <[email protected]>*/-#ifdef _DEBUG-#define _STLP_DEBUG 1-#endif#include "ext/StrokeDeformationImpl.h"#include "ext/StrokeDeformation.h"#include "ext/SquarePotential.h"#include "ext/StrokeParametricDeformer.h"-//#include "ext/NotSymmetricBezierPotential.h"+// #include "ext/NotSymmetricBezierPotential.h"#include "ext/ContextStatus.h"#include "ext/Designer.h"-//#include "ext/TriParam.h"+// #include "ext/TriParam.h"#include <tcurves.h>#include <tstrokeutil.h>-//#include <tvectorimage.h>+// #include <tvectorimage.h>#include <tmathutil.h>#include <algorithm>#include <iterator>#include <vector>+#include <memory> // Added for smart pointers#include "DeformationSelector.h"-using namespace ToonzExt;+namespace ToonzExt {namespace {-/*- * Avoid to reduce curves with great zoom out.- * assert that pixelSize and factor > 0.0- */+/**+ * Compute reduction factor based on pixel size to avoid reducing curves with+ * great zoom out+ * @param pixelSize Pixel size+ * @param factor Base factor+ * @return Computed reduction factor+ */double computeReductionFactor(double pixelSize, double factor) {assert(pixelSize > 0.0 && factor > 0.0);- if (factor <= 0.0) factor = 1.0;+ if (factor <= 0.0) factor = 1.0;if (pixelSize <= 0.0 || pixelSize > 1.0) pixelSize = 1.0;return pixelSize * factor;}//---------------------------------------------------------------------------++/**+ * Retrieve parameter at length with offset+ * @param stroke2change Stroke to process+ * @param length Target length+ * @param offset Offset parameter+ * @return Parameter at computed length+ */double retrieveParamAtLengthWithOffset(const TStroke *stroke2change,double length, // = 0.5 * strokeLength,double offset) {@@ -74,14 +83,22 @@ double retrieveParamAtLengthWithOffset(const TStroke *stroke2change,//---------------------------------------------------------------------------+/**+ * Rotate stroke to bring a specific parameter to position 0+ * @param stroke2change Original stroke+ * @param rotated Output rotated stroke+ * @param from From parameter (input/output)+ * @param to To parameter (input/output)+ * @param old_w0_pos Original position of w=0+ * @return true if rotation successful+ */bool rotateStroke(const TStroke *stroke2change, TStroke *&rotated, double &from,double &to, TPointD &old_w0_pos) {if (!stroke2change || !isValid(from) || !isValid(to)) return false;rotated = 0;- // save position of w=0 (useful to retrieve this- // position after changes)+ // save position of w=0 (useful to retrieve this position after changes)old_w0_pos = convert(stroke2change->getControlPoint(0));double rotateAtLength = stroke2change->getLength(to);@@ -99,23 +116,37 @@ bool rotateStroke(const TStroke *stroke2change, TStroke *&rotated, double &from,// save some other information (style, etc..)ToonzExt::cloneStrokeStatus(stroke2change, rotated);- return true; // rotated;+ return true;}//---------------------------------------------------------------------------+/**+ * Rotate control point to bring a specific point to position 0+ * @param stroke Stroke to rotate+ * @param pnt Point to bring to position 0+ * @return Rotated stroke or nullptr+ */TStroke *rotateControlPointAtPoint(const TStroke *stroke, const TPointD &pnt) {if (!stroke || tdistance2(stroke->getPoint(0.0), pnt) < sq(TConsts::epsilon))return 0;- double w = stroke->getW(pnt);- TPointD theSamePnt = stroke->getPoint(w);- double length = stroke->getLength(w);+ double w = stroke->getW(pnt);+ // Removed unused variable: TPointD theSamePnt = stroke->getPoint(w);+ double length = stroke->getLength(w);return ToonzExt::rotateControlPoint(stroke, ToonzExt::EvenInt(0), length);}//---------------------------------------------------------------------------+/**+ * Find extremes based on tool action length+ * @param toolActionLength Length of tool action+ * @param stroke Stroke to process+ * @param w Parameter position+ * @param out Output interval+ * @return true if successful+ */bool findExtremesFromActionLength(double toolActionLength,const TStroke *stroke, double w,ToonzExt::Interval &out) {@@ -179,6 +210,12 @@ bool findExtremesFromActionLength(double toolActionLength,//---------------------------------------------------------------------------+/**+ * Check if two strokes are different+ * @param ref1 First stroke+ * @param ref2 Second stroke+ * @return true if strokes are different+ */bool areDifferent(const TStroke *ref1, const TStroke *ref2) {if (!isValid(ref1) || !isValid(ref2)) return true;@@ -195,26 +232,26 @@ bool areDifferent(const TStroke *ref1, const TStroke *ref2) {}//----------------------------------------------------------------------------}+} // namespace//-----------------------------------------------------------------------------TStroke *StrokeDeformationImpl::copyOfLastSelectedStroke_ =- 0; // deep copy stroke selected previously+ nullptr; // deep copy stroke selected previously//-----------------------------------------------------------------------------const ContextStatus *&StrokeDeformationImpl::getImplStatus() {// if multi threading this datas need to be serialized// a ref to status- static const ContextStatus *contextStatus_instance;+ static const ContextStatus *contextStatus_instance = nullptr;return contextStatus_instance;}//-----------------------------------------------------------------------------TStroke *&StrokeDeformationImpl::getLastSelectedStroke() {- static TStroke *lastSelectedStroke_instance;+ static TStroke *lastSelectedStroke_instance = nullptr;return lastSelectedStroke_instance;}@@ -232,7 +269,7 @@ void StrokeDeformationImpl::setLastSelectedStroke(TStroke *stroke) {//-----------------------------------------------------------------------------int &StrokeDeformationImpl::getLastSelectedDegree() {- static int lastSelectedDegree_instance;+ static int lastSelectedDegree_instance = -1;return lastSelectedDegree_instance;}@@ -258,10 +295,19 @@ ToonzExt::Intervals &StrokeDeformationImpl::getStraightsList() {//------------------------------------------------------------------------------StrokeDeformationImpl::StrokeDeformationImpl() {- shortcutKey_ = ContextStatus::NONE;- cursorId_ = -1;- this->reset();+StrokeDeformationImpl::StrokeDeformationImpl()+ : potential_(nullptr)+ , deformer_(nullptr)+ , stroke2manipulate_(nullptr)+ , old_w0_(-1)+ , old_w0_pos_(TConsts::napd)+ , shortcutKey_(ContextStatus::NONE)+ , cursorId_(-1) {+ // Direct initialization without virtual call+ old_w0_ = -1;+ old_w0_pos_ = TConsts::napd;+ deformer_ = nullptr;+ stroke2manipulate_ = nullptr;}//-----------------------------------------------------------------------------@@ -269,11 +315,11 @@ StrokeDeformationImpl::StrokeDeformationImpl() {StrokeDeformationImpl::~StrokeDeformationImpl() {clearPointerContainer(strokes_);delete potential_;- potential_ = 0;+ potential_ = nullptr;delete deformer_;- deformer_ = 0;+ deformer_ = nullptr;delete copyOfLastSelectedStroke_;- copyOfLastSelectedStroke_ = 0;+ copyOfLastSelectedStroke_ = nullptr;}//-----------------------------------------------------------------------------@@ -287,10 +333,17 @@ bool StrokeDeformationImpl::activate_impl(const ContextStatus *status) {ToonzExt::Interval extremes = this->getExtremes();- TStroke *stroke2transform;+ // Use unique_ptr for automatic cleanup+ std::unique_ptr<TStroke> stroke2transformPtr;+ TStroke *stroke2transform = nullptr;- if (!this->computeStroke2Transform(status, stroke2transform, w, extremes))+ if (!this->computeStroke2Transform(status, stroke2transform, w, extremes)) {+ delete stroke2transform; // Clean up if function failedreturn false;+ }++ // Wrap in unique_ptr for automatic cleanup+ stroke2transformPtr.reset(stroke2transform);// to avoid strange behaviour in limit's valueif (areAlmostEqual(extremes.first, w)) w = extremes.first;@@ -400,14 +453,15 @@ bool StrokeDeformationImpl::activate_impl(const ContextStatus *status) {assert(deformer_ && "Deformer is not available");if (exception) {- deformer_ = 0;+ deformer_ = nullptr;return false;}- assert(getImplStatus() != 0 && "ContextStatus is null???");+ assert(getImplStatus() != nullptr && "ContextStatus is null???");if (!getImplStatus()) {delete deformer_;+ deformer_ = nullptr;this->reset();return false;}@@ -470,7 +524,7 @@ void StrokeDeformationImpl::update_impl(const TPointD &delta) {TStroke *StrokeDeformationImpl::deactivate_impl() {if (!stroke2manipulate_ || !getImplStatus()) {this->reset();- return 0;+ return nullptr;}// retrieve the point@@ -484,18 +538,18 @@ TStroke *StrokeDeformationImpl::deactivate_impl() {const int size = stroke2manipulate_->getControlPointCount();std::vector<TThickPoint> pnt(size);for (int i = 0; i < size; ++i)- pnt[i] = stroke2manipulate_->getControlPoint(i);+ pnt[i] = stroke2manipulate_->getControlPoint(i);std::vector<TStroke *>::iterator it =std::find(strokes_.begin(), strokes_.end(), stroke2manipulate_);assert(it != strokes_.end());int pos = std::distance(strokes_.begin(), it);- stroke2manipulate_ = 0;+ stroke2manipulate_ = nullptr;delete strokes_[pos];TStroke *tmpStroke = new TStroke(pnt);- assert((tmpStroke != 0) && "Not valid stroke!");+ assert((tmpStroke != nullptr) && "Not valid stroke!");strokes_[pos] = tmpStroke;strokes_[pos]->reduceControlPoints(reductionFactor);@@ -518,7 +572,7 @@ TStroke *StrokeDeformationImpl::deactivate_impl() {ToonzExt::cloneStrokeStatus(getImplStatus()->stroke2change_, ref);else {delete ref;- ref = 0;+ ref = nullptr;}}}@@ -533,16 +587,16 @@ void StrokeDeformationImpl::reset() {old_w0_ = -1;old_w0_pos_ = TConsts::napd;- deformer_ = 0;- getImplStatus() = 0;+ deformer_ = nullptr;+ getImplStatus() = nullptr;this->setLastSelectedDegree(-1);- this->setLastSelectedStroke(0);+ this->setLastSelectedStroke(nullptr);this->getSpiresList().clear();this->getStraightsList().clear();- stroke2manipulate_ = 0;- clearPointerContainer(strokes_); // stroke2move is deleted here (it- // is in vector)+ stroke2manipulate_ = nullptr;+ clearPointerContainer(+ strokes_); // stroke2move is deleted here (it is in vector)}//-----------------------------------------------------------------------------@@ -632,23 +686,48 @@ bool StrokeDeformationImpl::init(const ContextStatus *status) {bool StrokeDeformationImpl::computeStroke2Transform(const ContextStatus *status, TStroke *&stroke2transform, double &w,ToonzExt::Interval &extremes) {- if (!status || !isValid(w)) return false;+ // Use unique_ptr for local cleanup+ std::unique_ptr<TStroke> localStrokePtr;- stroke2transform = 0;+ if (!status || !isValid(w)) {+ // Clean up if stroke2transform was allocated before failure+ delete stroke2transform;+ stroke2transform = nullptr;+ return false;+ }++ // Set to null initially+ stroke2transform = nullptr;if (status->stroke2change_->isSelfLoop()) {if (extremes.first > extremes.second) {double new_w = (extremes.first + extremes.second) * 0.5;if (!rotateStroke(status->stroke2change_, stroke2transform, w, new_w,- old_w0_pos_))+ old_w0_pos_)) {+ // Clean up on failure+ delete stroke2transform;+ stroke2transform = nullptr;return false;+ }++ // Save current status+ const ContextStatus *oldStatus = getImplStatus();+ // Create temporary status on stack but don't store pointer in static+ // variableContextStatus tmpStatus = *status;tmpStatus.stroke2change_ = stroke2transform;tmpStatus.w_ = w;++ // Temporarily set the status for check() function+ getImplStatus() = &tmpStatus;this->check(&tmpStatus);extremes = this->getExtremes();++ // Restore original status+ getImplStatus() = oldStatus;+this->init(status);return true;} else if (extremes.first == extremes.second) {@@ -676,35 +755,45 @@ bool StrokeDeformationImpl::computeStroke2Transform(// also forced modedefault:assert(extremes.first != -1);- // if( extremes.first == -1 )- // positionOfFixPoint=retrieveParamAtLengthWithOffset(status->stroke2change_,- // status->stroke2change_->getLength()*0.5,- // w);- // elsepositionOfFixPoint = extremes.first;break;}if (!rotateStroke(status->stroke2change_, stroke2transform, w,- positionOfFixPoint, old_w0_pos_))+ positionOfFixPoint, old_w0_pos_)) {+ // Clean up on failure+ delete stroke2transform;+ stroke2transform = nullptr;return false;+ }extremes = ToonzExt::Interval(0.0, 1.0);return true;}}- if (!isValid(extremes.first) || !isValid(extremes.second)) return false;+ if (!isValid(extremes.first) || !isValid(extremes.second)) {+ // Clean up on failure+ delete stroke2transform;+ stroke2transform = nullptr;+ return false;+ }try {- if (!stroke2transform)+ if (!stroke2transform) {stroke2transform = new TStroke(*status->stroke2change_);+ }} catch (...) {+ // Clean up on exception+ delete stroke2transform;+ stroke2transform = nullptr;return false;}return true;}+//-----------------------------------------------------------------------------// End Of File//-----------------------------------------------------------------------------+} // namespace ToonzExtdiff --git a/toonz/sources/tnztools/controlpointselection.cpp b/toonz/sources/tnztools/controlpointselection.cppindex 20195614c..177a9bdac 100644--- a/toonz/sources/tnztools/controlpointselection.cpp+++ b/toonz/sources/tnztools/controlpointselection.cpp@@ -12,37 +12,44 @@#include "toonz/txshlevelhandle.h"#include "toonz/tstageobject.h"+#include <memory>+using namespace ToolUtils;+//-----------------------------------------------------------------------------+namespace {//-----------------------------------------------------------------------------+constexpr double MIN_DISTANCE = 0.02;+constexpr double MIN_CROSS_VALUE = 0.09; // more than 5°+constexpr double LINEAR_FACTOR = 0.01;++//-----------------------------------------------------------------------------+inline bool isLinearPoint(const TPointD &p0, const TPointD &p1,const TPointD &p2) {- return (tdistance(p0, p1) < 0.02) && (tdistance(p1, p2) < 0.02);+ return (tdistance(p0, p1) < MIN_DISTANCE) &&+ (tdistance(p1, p2) < MIN_DISTANCE);}//------------------------------------------------------------------------------//! Ritorna \b true se il punto \b p1 e' una cuspide.+//! Returns \b true if point \b p1 is a cusp.bool isCuspPoint(const TPointD &p0, const TPointD &p1, const TPointD &p2) {TPointD p0_p1(p0 - p1), 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;+ if ((n1 < MIN_DISTANCE) || (n2 < MIN_DISTANCE)) 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);+ (std::fabs(cross(p0_p1, p2_p1)) > MIN_CROSS_VALUE);}//-----------------------------------------------------------------------------@@ -56,31 +63,34 @@ TThickPoint computeLinearPoint(const TThickPoint &p1, const TThickPoint &p2,}//------------------------------------------------------------------------------/*! Insert a point in the most long chunk between chunk \b indexA and chunk \b+/*! Insert a point in the longest chunk between chunk \b indexA and chunk \b* indexB. */void insertPoint(TStroke *stroke, int indexA, int indexB) {assert(stroke);- int j = 0;int chunkCount = indexB - indexA;if (chunkCount % 2 == 0) return;- double length = 0;- double firstW, lastW;- for (j = indexA; j < indexB; j++) {- // cerco il chunk piu' lungo++ double maxLength = 0;+ double firstW = 0.0, lastW = 1.0;++ for (int j = indexA; j < indexB; ++j) {+ // find the longest chunkdouble 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 length0 = stroke->getLength(w0);+ double length1 = stroke->getLength(w1);+ double chunkLength = length1 - length0;++ if (chunkLength > maxLength) {+ firstW = w0;+ lastW = w1;+ maxLength = chunkLength;}}+stroke->insertControlPoints((firstW + lastW) * 0.5);}@@ -90,17 +100,30 @@ void insertPoint(TStroke *stroke, int indexA, int indexB) {// ControlPointEditorStroke//-----------------------------------------------------------------------------+ControlPointEditorStroke::ControlPointEditorStroke(+ const ControlPointEditorStroke &other)+ : m_controlPoints(other.m_controlPoints)+ , m_vi(other.m_vi)+ , m_strokeIndex(other.m_strokeIndex) {}++ControlPointEditorStroke &ControlPointEditorStroke::operator=(+ const ControlPointEditorStroke &other) {+ if (this != &other) {+ m_controlPoints = other.m_controlPoints;+ m_vi = other.m_vi;+ m_strokeIndex = other.m_strokeIndex;+ }+ return *this;+}+ControlPointEditorStroke *ControlPointEditorStroke::clone() const {- ControlPointEditorStroke *controlPointEditorStroke =- new ControlPointEditorStroke();- controlPointEditorStroke->setStroke(m_vi->clone(), m_strokeIndex);- return controlPointEditorStroke;+ return new ControlPointEditorStroke(*this);}//-----------------------------------------------------------------------------int ControlPointEditorStroke::nextIndex(int index) const {- int cpCount = m_controlPoints.size();+ int cpCount = static_cast<int>(m_controlPoints.size());if (++index < cpCount) return index;if (isSelfLoop()) {@@ -114,7 +137,7 @@ int ControlPointEditorStroke::nextIndex(int index) const {//-----------------------------------------------------------------------------int ControlPointEditorStroke::prevIndex(int index) const {- int cpCount = m_controlPoints.size();+ int cpCount = static_cast<int>(m_controlPoints.size());if (--index >= 0) return index;if (isSelfLoop()) {@@ -130,22 +153,26 @@ int ControlPointEditorStroke::prevIndex(int index) const {void ControlPointEditorStroke::adjustChunkParity() {TStroke *stroke = getStroke();if (!stroke) return;+int firstChunk;int secondChunk = stroke->getChunkCount();- int i;- for (i = stroke->getChunkCount() - 1; i > 0; i--) {++ for (int i = stroke->getChunkCount() - 1; i > 0; --i) {if (tdistance(stroke->getChunk(i - 1)->getP0(),stroke->getChunk(i)->getP2()) < 0.5)continue;+TPointD p0 = stroke->getChunk(i - 1)->getP1();TPointD p1 = stroke->getChunk(i - 1)->getP2();TPointD p2 = stroke->getChunk(i)->getP1();+if (isCuspPoint(p0, p1, p2) || isLinearPoint(p0, p1, p2)) {firstChunk = i;insertPoint(stroke, firstChunk, secondChunk);secondChunk = firstChunk;}}+insertPoint(stroke, 0, secondChunk);}@@ -154,48 +181,56 @@ void ControlPointEditorStroke::adjustChunkParity() {void ControlPointEditorStroke::resetControlPoints() {TStroke *stroke = getStroke();if (!stroke) return;+m_controlPoints.clear();- int i;int cpCount = stroke->getControlPointCount();+if (cpCount == 3) {const TThickQuadratic *chunk = stroke->getChunk(0);- if (chunk->getP0() == chunk->getP1() &&- chunk->getP0() == chunk->getP2()) // E' un punto- {- m_controlPoints.push_back(+ if (chunk->getP0() == chunk->getP1() && chunk->getP0() == chunk->getP2()) {+ // It's a single point+ m_controlPoints.append(ControlPoint(0, TPointD(0.0, 0.0), TPointD(0.0, 0.0), true));return;}}- for (i = 0; i < cpCount; i = i + 4) {++ for (int i = 0; i < cpCount; i += 4) {TThickPoint speedIn, speedOut;- bool isPickOut = false;TThickPoint p = stroke->getControlPoint(i);TThickPoint precP = stroke->getControlPoint(i - 1);TThickPoint nextP = stroke->getControlPoint(i + 1);- if (0 < i && i < cpCount - 1) // calcola speedIn e speedOut- {++ if (0 < i && i < cpCount - 1) {+ // calculate speedIn and speedOutspeedIn = p - precP;speedOut = nextP - p;}- if (i == 0) // calcola solo lo speedOut- {++ if (i == 0) {+ // calculate only speedOutspeedOut = nextP - p;if (isSelfLoop()) {precP = stroke->getControlPoint(cpCount - 2);speedIn = p - precP;}}- if (i == cpCount - 1) // calcola solo lo speedIn++ if (i == cpCount - 1) {+ // calculate only speedInspeedIn = p - precP;- if (i == cpCount - 1 && isSelfLoop())- break; // Se lo stroke e' selfLoop inserisco solo il primo dei due punti- // coincidenti+ }++ if (i == cpCount - 1 && isSelfLoop()) {+ // If stroke is selfLoop, insert only the first of two coincident points+ break;+ }bool isCusp = ((i != 0 && i != cpCount - 1) || (isSelfLoop() && i == 0))? isCuspPoint(precP, p, nextP): true;- m_controlPoints.push_back(ControlPoint(i, speedIn, speedOut, isCusp));++ m_controlPoints.append(ControlPoint(i, speedIn, speedOut, isCusp));}}@@ -203,9 +238,11 @@ void ControlPointEditorStroke::resetControlPoints() {TThickPoint ControlPointEditorStroke::getPureDependentPoint(int index) const {TStroke *stroke = getStroke();- if (!stroke) return TThickPoint();- bool selfLoop = isSelfLoop();- int cpCount = selfLoop ? m_controlPoints.size() + 1 : m_controlPoints.size();+ if (!stroke) return {};++ bool selfLoop = isSelfLoop();+ int cpCount = selfLoop ? static_cast<int>(m_controlPoints.size()) + 1+ : static_cast<int>(m_controlPoints.size());int nextIndex = (selfLoop && index == cpCount - 2) ? 0 : index + 1;int pointIndex = m_controlPoints[index].m_pointIndex;@@ -219,10 +256,7 @@ TThickPoint ControlPointEditorStroke::getPureDependentPoint(int index) const {TPointD speedOutPoint(getSpeedOutPoint(index));TPointD nextSpeedInPoint(getSpeedInPoint(nextIndex));- return TThickPoint((1 - t) * nextSpeedInPoint + t * speedOutPoint,- oldP.thick);-- // return TThickPoint(0.5 * (speedOutPoint + nextSpeedInPoint), oldThick);+ return {(1 - t) * nextSpeedInPoint + t * speedOutPoint, oldP.thick};}//-----------------------------------------------------------------------------@@ -232,17 +266,19 @@ void ControlPointEditorStroke::getDependentPoints(TStroke *stroke = getStroke();if (!stroke) return;- int cpCount = m_controlPoints.size();- if (index == cpCount && isSelfLoop()) // strange, but was treated...+ int cpCount = static_cast<int>(m_controlPoints.size());+ if (index == cpCount && isSelfLoop()) {+ // strange, but was treated...index = 0;+ }if (index == 0 && cpCount == 1) {// Single point caseTStroke *stroke = getStroke();TThickPoint pos(stroke->getControlPoint(m_controlPoints[0].m_pointIndex));- points.push_back(std::make_pair(1, pos));- points.push_back(std::make_pair(2, pos));+ points.emplace_back(1, pos);+ points.emplace_back(2, pos);return;}@@ -251,23 +287,19 @@ void ControlPointEditorStroke::getDependentPoints(int prevPointIndex = m_controlPoints[prev].m_pointIndex;if (isSpeedOutLinear(prev))- points.push_back(- std::make_pair(prevPointIndex + 1, getSpeedOutPoint(prev)));- points.push_back(- std::make_pair(prevPointIndex + 2, getPureDependentPoint(prev)));- points.push_back(- std::make_pair(prevPointIndex + 3, getSpeedInPoint(index)));+ points.emplace_back(prevPointIndex + 1, getSpeedOutPoint(prev));+ points.emplace_back(prevPointIndex + 2, getPureDependentPoint(prev));+ points.emplace_back(prevPointIndex + 3, getSpeedInPoint(index));}int next = nextIndex(index);if (next >= 0) {int pointIndex = m_controlPoints[index].m_pointIndex;- points.push_back(std::make_pair(pointIndex + 1, getSpeedOutPoint(index)));- points.push_back(- std::make_pair(pointIndex + 2, getPureDependentPoint(index)));+ points.emplace_back(pointIndex + 1, getSpeedOutPoint(index));+ points.emplace_back(pointIndex + 2, getPureDependentPoint(index));if (isSpeedInLinear(next))- points.push_back(std::make_pair(pointIndex + 3, getSpeedInPoint(next)));+ points.emplace_back(pointIndex + 3, getSpeedInPoint(next));}}@@ -276,42 +308,45 @@ void ControlPointEditorStroke::getDependentPoints(void ControlPointEditorStroke::updatePoints() {TStroke *stroke = getStroke();if (!stroke) return;+bool selfLoop = isSelfLoop();- // Se e' rimasto un unico punto non ha senso che la stroke sia selfloop+ // If only one point remains, stroke cannot be self-loopif (selfLoop && m_controlPoints.size() == 1) {stroke->setSelfLoop(false);selfLoop = false;}- // Se e' self loop devo aggiungere un punto in piu' al cpCount+ // If self loop, add one more point to cpCountstd::vector<TThickPoint> points;- int cpCount = selfLoop ? m_controlPoints.size() + 1 : m_controlPoints.size();- if (cpCount == 1)+ int cpCount = selfLoop ? static_cast<int>(m_controlPoints.size()) + 1+ : static_cast<int>(m_controlPoints.size());+ if (cpCount == 1) {// Single point casepoints.resize(3, getControlPoint(0));- else {+ } else {std::vector<std::pair<int, TThickPoint>> dependentPoints;points.push_back(getControlPoint(0));points.push_back(getSpeedOutPoint(0));- int i, pointIndex, currPointIndex = m_controlPoints[0].m_pointIndex + 1;- for (i = 1; i < cpCount; ++i) {+ int currPointIndex = m_controlPoints[0].m_pointIndex + 1;+ for (int i = 1; i < cpCount; ++i) {bool isLastSelfLoopPoint = (selfLoop && i == cpCount - 1);int index = isLastSelfLoopPoint ? 0 : i;- TThickPoint p = getControlPoint(index);- pointIndex = isLastSelfLoopPoint ? getStroke()->getControlPointCount()- : m_controlPoints[index].m_pointIndex;+ TThickPoint p = getControlPoint(index);+ int pointIndex = isLastSelfLoopPoint+ ? getStroke()->getControlPointCount()+ : m_controlPoints[index].m_pointIndex;dependentPoints.clear();getDependentPoints(index, dependentPoints);- int j;- for (j = 0; j < (int)dependentPoints.size() &&- dependentPoints[j].first < pointIndex;- j++) {+ size_t j;+ for (j = 0;+ j < dependentPoints.size() && dependentPoints[j].first < pointIndex;+ ++j) {if (currPointIndex < dependentPoints[j].first) {currPointIndex = dependentPoints[j].first;points.push_back(dependentPoints[j].second);@@ -320,7 +355,7 @@ void ControlPointEditorStroke::updatePoints() {points.push_back(p);- for (; j < (int)dependentPoints.size(); j++) {+ for (; j < dependentPoints.size(); ++j) {if (currPointIndex < dependentPoints[j].first) {currPointIndex = dependentPoints[j].first;points.push_back(dependentPoints[j].second);@@ -329,7 +364,7 @@ void ControlPointEditorStroke::updatePoints() {}}- stroke->reshape(&points[0], points.size());+ stroke->reshape(points.data(), points.size());m_vi->notifyChangedStrokes(m_strokeIndex);}@@ -342,9 +377,8 @@ void ControlPointEditorStroke::updateDependentPoint(int index) {std::vector<std::pair<int, TThickPoint>> points;getDependentPoints(index, points);- int i;- for (i = 0; i < (int)points.size(); i++)- stroke->setControlPoint(points[i].first, points[i].second);+ for (const auto &[pointIdx, point] : points)+ stroke->setControlPoint(pointIdx, point);m_vi->notifyChangedStrokes(m_strokeIndex);}@@ -358,22 +392,25 @@ void ControlPointEditorStroke::moveSpeedOut(int index, const TPointD &delta,// If the next cp has linear speed in, it must be recomputedbool selfLoop = isSelfLoop();- int cpCount = selfLoop ? m_controlPoints.size() + 1 : m_controlPoints.size();+ int cpCount = selfLoop ? static_cast<int>(m_controlPoints.size()) + 1+ : static_cast<int>(m_controlPoints.size());int nextIndex = (selfLoop && index == cpCount - 2) ? 0 : index + 1;if (m_controlPoints[nextIndex].m_isCusp && isSpeedInLinear(nextIndex))setLinearSpeedIn(nextIndex, true, false);// Update the speedOutm_controlPoints[index].m_speedOut += delta;- TPointD newP = m_controlPoints[index].m_speedOut;+ const TPointD &newP = m_controlPoints[index].m_speedOut;+if (areAlmostEqual(newP.x, 0, minDistance) &&- areAlmostEqual(newP.y, 0, minDistance)) // Setto a linear- {+ areAlmostEqual(newP.y, 0, minDistance)) {+ // Set to linearsetLinearSpeedOut(index);return;}+if (!m_controlPoints[index].m_isCusp && !isSpeedInLinear(index)) {- // Devo ricalcolare lo SpeedIn+ // Recalculate SpeedInTPointD v(m_controlPoints[index].m_speedOut *(1.0 / norm(m_controlPoints[index].m_speedOut)));m_controlPoints[index].m_speedIn =@@ -391,22 +428,25 @@ void ControlPointEditorStroke::moveSpeedIn(int index, const TPointD &delta,// If the prev cp has linear speed out, it must be recomputedbool selfLoop = isSelfLoop();- int cpCount = selfLoop ? m_controlPoints.size() + 1 : m_controlPoints.size();+ int cpCount = selfLoop ? static_cast<int>(m_controlPoints.size()) + 1+ : static_cast<int>(m_controlPoints.size());int prevIndex = (selfLoop && index == 0) ? cpCount - 2 : index - 1;if (m_controlPoints[prevIndex].m_isCusp && isSpeedOutLinear(prevIndex))setLinearSpeedOut(prevIndex, true, false);- // Update the speedOut+ // Update the speedInm_controlPoints[index].m_speedIn -= delta;- TPointD newP = m_controlPoints[index].m_speedIn;+ const TPointD &newP = m_controlPoints[index].m_speedIn;+if (areAlmostEqual(newP.x, 0, minDistance) &&- areAlmostEqual(newP.y, 0, minDistance)) // Setto a linear- {+ areAlmostEqual(newP.y, 0, minDistance)) {+ // Set to linearsetLinearSpeedIn(index);return;}+if (!m_controlPoints[index].m_isCusp && !isSpeedOutLinear(index)) {- // Devo ricalcolare lo SpeedOut+ // Recalculate SpeedOutTPointD v(m_controlPoints[index].m_speedIn *(1.0 / norm(m_controlPoints[index].m_speedIn)));m_controlPoints[index].m_speedOut =@@ -427,7 +467,8 @@ void ControlPointEditorStroke::moveSingleControlPoint(int index,pointIndex < stroke->getControlPointCount());bool selfLoop = isSelfLoop();- int cpCount = selfLoop ? m_controlPoints.size() + 1 : m_controlPoints.size();+ int cpCount = selfLoop ? static_cast<int>(m_controlPoints.size()) + 1+ : static_cast<int>(m_controlPoints.size());TThickPoint p = stroke->getControlPoint(pointIndex);p = TThickPoint(p + delta, p.thick);@@ -438,19 +479,10 @@ void ControlPointEditorStroke::moveSingleControlPoint(int index,// Directions must be recalculated in the linear casesif ((selfLoop || index > 0) && isSpeedInLinear(index)) {setLinearSpeedIn(index, true, false);-- // Furthermore, if the NEIGHBOUR point is linear, it has to be- // recalculated too- int prevIndex = (selfLoop && index == 0) ? cpCount - 2 : index - 1;- if (m_controlPoints[prevIndex].m_isCusp && isSpeedOutLinear(prevIndex))- setLinearSpeedOut(prevIndex, true, false);}+if ((selfLoop || index < cpCount - 1) && isSpeedOutLinear(index)) {setLinearSpeedOut(index, true, false);-- int nextIndex = (selfLoop && index == cpCount - 2) ? 0 : index + 1;- if (m_controlPoints[nextIndex].m_isCusp && isSpeedInLinear(nextIndex))- setLinearSpeedIn(nextIndex, true, false);}}@@ -460,19 +492,24 @@ bool ControlPointEditorStroke::setStroke(const TVectorImageP &vi,int strokeIndex) {bool ret = true;if (m_strokeIndex == strokeIndex && m_vi == vi) ret = false;+m_strokeIndex = strokeIndex;m_vi = vi;+if (!vi || strokeIndex == -1) {m_controlPoints.clear();return true;}+TStroke *stroke = getStroke();const TThickQuadratic *chunk = stroke->getChunk(0);+if (stroke->getControlPointCount() == 3 && chunk->getP0() == chunk->getP1() &&chunk->getP0() == chunk->getP2()) {resetControlPoints();return ret;}+adjustChunkParity();resetControlPoints();return ret;@@ -482,7 +519,8 @@ bool ControlPointEditorStroke::setStroke(const TVectorImageP &vi,TThickPoint ControlPointEditorStroke::getControlPoint(int index) const {TStroke *stroke = getStroke();- assert(stroke && 0 <= index && index < (int)m_controlPoints.size());+ assert(stroke && 0 <= index &&+ index < static_cast<int>(m_controlPoints.size()));return stroke->getControlPoint(m_controlPoints[index].m_pointIndex);}@@ -496,9 +534,10 @@ int ControlPointEditorStroke::getIndexPointInStroke(int index) const {TThickPoint ControlPointEditorStroke::getSpeedInPoint(int index) const {TStroke *stroke = getStroke();- assert(stroke && 0 <= index && index < (int)m_controlPoints.size());+ assert(stroke && 0 <= index &&+ index < static_cast<int>(m_controlPoints.size()));- ControlPoint cp = m_controlPoints[index];+ const ControlPoint &cp = m_controlPoints[index];return stroke->getControlPoint(cp.m_pointIndex) - cp.m_speedIn;}@@ -506,17 +545,17 @@ TThickPoint ControlPointEditorStroke::getSpeedInPoint(int index) const {TThickPoint ControlPointEditorStroke::getSpeedOutPoint(int index) const {TStroke *stroke = getStroke();- assert(stroke && 0 <= index && index < (int)m_controlPoints.size());+ assert(stroke && 0 <= index &&+ index < static_cast<int>(m_controlPoints.size()));- ControlPoint cp = m_controlPoints[index];+ const ControlPoint &cp = m_controlPoints[index];return stroke->getControlPoint(cp.m_pointIndex) + cp.m_speedOut;}//-----------------------------------------------------------------------------bool ControlPointEditorStroke::isCusp(int index) const {- TStroke *stroke = getStroke();- assert(stroke && 0 <= index && index < (int)getControlPointCount());+ assert(0 <= index && index < static_cast<int>(getControlPointCount()));return m_controlPoints[index].m_isCusp;}@@ -532,17 +571,17 @@ void ControlPointEditorStroke::setCusp(int index, bool isCusp,//-----------------------------------------------------------------------------bool ControlPointEditorStroke::isSpeedInLinear(int index) const {- assert(index < (int)m_controlPoints.size());- return (fabs(m_controlPoints[index].m_speedIn.x) <= 0.02) &&- (fabs(m_controlPoints[index].m_speedIn.y) <= 0.02);+ assert(index < static_cast<int>(m_controlPoints.size()));+ return (std::fabs(m_controlPoints[index].m_speedIn.x) <= MIN_DISTANCE) &&+ (std::fabs(m_controlPoints[index].m_speedIn.y) <= MIN_DISTANCE);}//-----------------------------------------------------------------------------bool ControlPointEditorStroke::isSpeedOutLinear(int index) const {- assert(index < (int)m_controlPoints.size());- return (fabs(m_controlPoints[index].m_speedOut.x) <= 0.02) &&- (fabs(m_controlPoints[index].m_speedOut.y) <= 0.02);+ assert(index < static_cast<int>(m_controlPoints.size()));+ return (std::fabs(m_controlPoints[index].m_speedOut.x) <= MIN_DISTANCE) &&+ (std::fabs(m_controlPoints[index].m_speedOut.y) <= MIN_DISTANCE);}//-----------------------------------------------------------------------------@@ -551,6 +590,7 @@ void ControlPointEditorStroke::setLinearSpeedIn(int index, bool linear,bool updatePoints) {TStroke *stroke = getStroke();if (!stroke || m_controlPoints.size() == 1) return;+int pointIndex = m_controlPoints[index].m_pointIndex;if (pointIndex == 0) {if (isSelfLoop())@@ -558,8 +598,6 @@ void ControlPointEditorStroke::setLinearSpeedIn(int index, bool linear,elsereturn;}- int precIndex =- (index == 0 && isSelfLoop()) ? m_controlPoints.size() - 1 : index - 1;TThickPoint point = stroke->getControlPoint(pointIndex);TThickPoint precPoint = (pointIndex > 2)@@ -568,15 +606,17 @@ void ControlPointEditorStroke::setLinearSpeedIn(int index, bool linear,if (linear) {TThickPoint p(point - precPoint);- double n = norm(p);- TThickPoint speedIn =- (n != 0.0) ? (0.01 / n) * p : TThickPoint(0.001, 0.001, 0.0);+ double n = norm(p);+ TThickPoint speedIn = (n != 0.0)+ ? (LINEAR_FACTOR / n) * p+ : TThickPoint(LINEAR_FACTOR, LINEAR_FACTOR, 0.0);m_controlPoints[index].m_speedIn = speedIn;} else {TThickPoint newPrec2 = (precPoint + point) * 0.5;TThickPoint speedIn = (point - newPrec2) * 0.5;m_controlPoints[index].m_speedIn = speedIn;}+if (updatePoints) updateDependentPoint(index);}@@ -586,16 +626,16 @@ void ControlPointEditorStroke::setLinearSpeedOut(int index, bool linear,bool updatePoints) {TStroke *stroke = getStroke();if (!stroke || m_controlPoints.size() == 1) return;+int cpCount = stroke->getControlPointCount();int pointIndex = m_controlPoints[index].m_pointIndex;+if (pointIndex == cpCount - 1) {if (isSelfLoop())pointIndex = 0;elsereturn;}- int nextIndex =- (index == m_controlPoints.size() - 1 && isSelfLoop()) ? 0 : index + 1;TThickPoint point = stroke->getControlPoint(pointIndex);TThickPoint nextPoint = (pointIndex < cpCount - 3)@@ -604,15 +644,17 @@ void ControlPointEditorStroke::setLinearSpeedOut(int index, bool linear,if (linear) {TThickPoint p(nextPoint - point);- double n = norm(p);- TThickPoint speedOut =- (n != 0.0) ? (0.01 / n) * p : TThickPoint(0.001, 0.001, 0.0);+ double n = norm(p);+ TThickPoint speedOut = (n != 0.0)+ ? (LINEAR_FACTOR / n) * p+ : TThickPoint(LINEAR_FACTOR, LINEAR_FACTOR, 0.0);m_controlPoints[index].m_speedOut = speedOut;} else {TThickPoint newNext2 = (nextPoint + point) * 0.5;TThickPoint speedOut = (newNext2 - point) * 0.5;m_controlPoints[index].m_speedOut = speedOut;}+if (updatePoints) updateDependentPoint(index);}@@ -622,28 +664,35 @@ bool ControlPointEditorStroke::setLinear(int index, bool isLinear,bool updatePoints) {bool movePrec = (!isSelfLoop()) ? index > 0 : true;bool moveNext = (!isSelfLoop()) ? (index < getControlPointCount() - 1) : true;- if (isLinear != isSpeedInLinear(index))++ bool precChanged = false;+ bool nextChanged = false;++ if (isLinear != isSpeedInLinear(index)) {setLinearSpeedIn(index, isLinear, updatePoints);- else- movePrec = false;- if (isLinear != isSpeedOutLinear(index))+ precChanged = true;+ }++ if (isLinear != isSpeedOutLinear(index)) {setLinearSpeedOut(index, isLinear, updatePoints);- else- moveNext = false;- bool ret = moveNext || movePrec;+ nextChanged = true;+ }++ bool ret = nextChanged || precChanged;if (ret) m_controlPoints[index].m_isCusp = true;return ret;}//------------------------------------------------------------------------------bool ControlPointEditorStroke::setControlPointsLinear(std::set<int> points,- bool isLinear) {- std::set<int>::iterator it;+bool ControlPointEditorStroke::setControlPointsLinear(+ const std::set<int> &points, bool isLinear) {bool isChanged = false;- for (it = points.begin(); it != points.end(); it++)- isChanged = setLinear(*it, isLinear, false) || isChanged;- for (it = points.begin(); it != points.end(); it++) updateDependentPoint(*it);+ for (int point : points)+ isChanged = setLinear(point, isLinear, false) || isChanged;++ for (int point : points) updateDependentPoint(point);+return isChanged;}@@ -653,7 +702,8 @@ void ControlPointEditorStroke::moveControlPoint(int index,const TPointD &delta) {TStroke *stroke = getStroke();if (!stroke) return;- assert(stroke && 0 <= index && index < (int)getControlPointCount());+ assert(stroke && 0 <= index &&+ index < static_cast<int>(getControlPointCount()));moveSingleControlPoint(index, delta);updateDependentPoint(index);@@ -664,11 +714,13 @@ void ControlPointEditorStroke::moveControlPoint(int index,int ControlPointEditorStroke::addControlPoint(const TPointD &pos) {TStroke *stroke = getStroke();if (!stroke) return -1;- double d = 0.01;- int indexAtPos;- int cpCount = stroke->getControlPointCount();- if (cpCount <= 3) // e' un unico chunk e in questo caso rappresenta un punto- {++ double d = 0.01;+ int indexAtPos = -1;+ int cpCount = stroke->getControlPointCount();++ if (cpCount <= 3) {+ // it's a single chunk representing a pointgetPointTypeAt(pos, d, indexAtPos);return indexAtPos;}@@ -676,33 +728,36 @@ int ControlPointEditorStroke::addControlPoint(const TPointD &pos) {double w = stroke->getW(pos);int pointIndex = stroke->getControlPointIndexAfterParameter(w);- int i, index;- for (i = 0; i < getControlPointCount(); i++) {- // Cerco il ControlPoint corrispondente all'indice pointIndex. OSS.:- // Effettuo il- // controllo da zero a getControlPointCount()-1 per gestire il caso del- // selfLoop+ int index = 0; // Initialize index+ for (int i = 0; i < getControlPointCount(); ++i) {+ // Find ControlPoint corresponding to pointIndexif (pointIndex == m_controlPoints[i].m_pointIndex + 1 ||pointIndex == m_controlPoints[i].m_pointIndex + 2 ||pointIndex == m_controlPoints[i].m_pointIndex + 3 ||- pointIndex == m_controlPoints[i].m_pointIndex + 4)+ pointIndex == m_controlPoints[i].m_pointIndex + 4) {index = i;+ break; // Found+ }}ControlPoint precCp = m_controlPoints[index];assert(precCp.m_pointIndex >= 0);std::vector<TThickPoint> points;- for (i = 0; i < cpCount; i++) {+ for (int i = 0; i < cpCount; ++i) {if (i != precCp.m_pointIndex + 1 && i != precCp.m_pointIndex + 2 &&i != precCp.m_pointIndex + 3)points.push_back(stroke->getControlPoint(i));+if (i == precCp.m_pointIndex + 2) {bool isBeforePointLinear = isSpeedOutLinear(index);- int nextIndex =- (isSelfLoop() && index == m_controlPoints.size() - 1) ? 0 : index + 1;+ int nextIndex = (isSelfLoop() &&+ index == static_cast<int>(m_controlPoints.size()) - 1)+ ? 0+ : index + 1;bool isNextPointLinear =- nextIndex < (int)m_controlPoints.size() && isSpeedInLinear(nextIndex);+ nextIndex < static_cast<int>(m_controlPoints.size()) &&+ isSpeedInLinear(nextIndex);TThickPoint a0 = stroke->getControlPoint(precCp.m_pointIndex);TThickPoint a1 = stroke->getControlPoint(precCp.m_pointIndex + 1);@@ -713,16 +768,16 @@ int ControlPointEditorStroke::addControlPoint(const TPointD &pos) {TThickPoint d0, d1, d2, d3, d4, d5, d6;if (isBeforePointLinear && isNextPointLinear) {- // Se sono entrambi i punti lineari inserisco un punto lineare+ // If both points are linear, insert a linear pointd0 = a1;d3 = stroke->getThickPoint(w);d6 = a3;- d2 = computeLinearPoint(d0, d3, 0.01, true); // SpeedIn- d4 = computeLinearPoint(d3, d6, 0.01, false); // SpeedOut+ d2 = computeLinearPoint(d0, d3, LINEAR_FACTOR, true); // SpeedIn+ d4 = computeLinearPoint(d3, d6, LINEAR_FACTOR, false); // SpeedOutd1 = 0.5 * (d0 + d2);d5 = 0.5 * (d4 + d6);} else if (dist2 < 32) {- // Sono molto vicino al punto che non viene visualizzato+ // Very close to the point that is not displayedTThickPoint b0 = 0.5 * (a0 + a1);TThickPoint b1 = 0.5 * (a2 + a1);TThickPoint c0 = 0.5 * (b0 + b1);@@ -741,7 +796,7 @@ int ControlPointEditorStroke::addControlPoint(const TPointD &pos) {} else {bool isInFirstChunk = true;if (pointIndex > precCp.m_pointIndex + 2) {- // nel caso in cui sono nel secondo chunk scambio i punti+ // if in the second chunk, swap pointsa0 = a4;std::swap(a1, a3);isInFirstChunk = false;@@ -774,10 +829,12 @@ int ControlPointEditorStroke::addControlPoint(const TPointD &pos) {d5 = (isInFirstChunk) ? a2 : c2;d6 = (isInFirstChunk) ? a3 : c0;}+if (isBeforePointLinear && !isNextPointLinear)- d1 = computeLinearPoint(d0, d2, 0.01, false);+ d1 = computeLinearPoint(d0, d2, LINEAR_FACTOR, false);else if (isNextPointLinear && !isBeforePointLinear)- d5 = computeLinearPoint(d4, d6, 0.01, true);+ d5 = computeLinearPoint(d4, d6, LINEAR_FACTOR, true);+points.push_back(d0);points.push_back(d1);points.push_back(d2);@@ -788,7 +845,7 @@ int ControlPointEditorStroke::addControlPoint(const TPointD &pos) {}}- stroke->reshape(&points[0], points.size());+ stroke->reshape(points.data(), points.size());resetControlPoints();getPointTypeAt(pos, d, indexAtPos);@@ -801,8 +858,10 @@ void ControlPointEditorStroke::deleteControlPoint(int index) {TStroke *stroke = getStroke();if (!stroke) return;- assert(stroke && 0 <= index && index < (int)getControlPointCount());- // E' un unico chunk e in questo caso rappresenta un punto+ assert(stroke && 0 <= index &&+ index < static_cast<int>(getControlPointCount()));++ // It's a single chunk representing a pointif (stroke->getControlPointCount() <= 3 ||(isSelfLoop() && stroke->getControlPointCount() <= 5)) {m_controlPoints.clear();@@ -811,16 +870,16 @@ void ControlPointEditorStroke::deleteControlPoint(int index) {}QList<int> newPointsIndex;- int i;- for (i = 0; i < (int)getControlPointCount() - 1; i++)+ for (int i = 0; i < static_cast<int>(getControlPointCount()) - 1; ++i)newPointsIndex.push_back(m_controlPoints[i].m_pointIndex);m_controlPoints.removeAt(index);updatePoints();- // Aggiorno gli indici dei punti nella stroke- assert((int)newPointsIndex.size() == (int)getControlPointCount());- for (i = 0; i < (int)getControlPointCount(); i++)+ // Update point indices in stroke+ assert(static_cast<int>(newPointsIndex.size()) ==+ static_cast<int>(getControlPointCount()));+ for (int i = 0; i < static_cast<int>(getControlPointCount()); ++i)m_controlPoints[i].m_pointIndex = newPointsIndex.at(i);int prev = prevIndex(index);@@ -828,7 +887,9 @@ void ControlPointEditorStroke::deleteControlPoint(int index) {setLinearSpeedOut(prev);updateDependentPoint(prev);}- if (index < (int)m_controlPoints.size() && isSpeedInLinear(index)) {++ if (index < static_cast<int>(m_controlPoints.size()) &&+ isSpeedInLinear(index)) {setLinearSpeedIn(index);updateDependentPoint(index);}@@ -855,17 +916,17 @@ void ControlPointEditorStroke::moveSegment(int beforeIndex, int nextIndex,if (!stroke) return;int cpCount = getControlPointCount();- // Verifiche per il caso in cui lo stroke e' selfLoop+ // Checks for self-loop stroke caseif (isSelfLoop() && beforeIndex == 0 && nextIndex == cpCount - 1)std::swap(beforeIndex, nextIndex);int beforePointIndex = m_controlPoints[beforeIndex].m_pointIndex;int nextPointIndex = (isSelfLoop() && nextIndex == 0)- ? stroke->getControlPointCount() - 1- : m_controlPoints[nextIndex].m_pointIndex;- double w = stroke->getW(pos);- double w0 = stroke->getParameterAtControlPoint(beforePointIndex);- double w4 = stroke->getParameterAtControlPoint(nextPointIndex);+ ? stroke->getControlPointCount() - 1+ : m_controlPoints[nextIndex].m_pointIndex;+ double w = stroke->getW(pos);+ double w0 = stroke->getParameterAtControlPoint(beforePointIndex);+ double w4 = stroke->getParameterAtControlPoint(nextPointIndex);if (w0 > w) return;assert(w0 <= w && w <= w4);@@ -881,7 +942,7 @@ void ControlPointEditorStroke::moveSegment(int beforeIndex, int nextIndex,m_controlPoints[beforeIndex].m_isCusp = true;} else if (!isSpeedOutLinear(beforeIndex) && !isSpeedInLinear(beforeIndex) &&!isCusp(beforeIndex)) {- t = 1 - fabs(w - w0) / fabs(w4 - w0);+ t = 1 - std::fabs(w - w0) / std::fabs(w4 - w0);moveSingleControlPoint(beforeIndex, t * delta);t = 1 - t;}@@ -895,16 +956,13 @@ void ControlPointEditorStroke::moveSegment(int beforeIndex, int nextIndex,m_controlPoints[nextIndex].m_isCusp = true;} else if (!isSpeedInLinear(nextIndex) && !isSpeedOutLinear(nextIndex) &&!isCusp(nextIndex)) {- s = 1 - fabs(w4 - w) / fabs(w4 - w0);+ s = 1 - std::fabs(w4 - w) / std::fabs(w4 - w0);moveSingleControlPoint(nextIndex, s * delta);s = 1 - s;}moveSpeedOut(beforeIndex, delta * s, 0);- // updateDependentPoint(beforeIndex);moveSpeedIn(nextIndex, delta * t, 0);- // updateDependentPoint(nextIndex);-updatePoints();}@@ -913,7 +971,11 @@ void ControlPointEditorStroke::moveSegment(int beforeIndex, int nextIndex,ControlPointEditorStroke::PointType ControlPointEditorStroke::getPointTypeAt(const TPointD &pos, double &distance2, int &index) const {TStroke *stroke = getStroke();- if (!stroke) return NONE;+ if (!stroke) {+ index = -1;+ return NONE;+ }+double w = stroke->getW(pos);TPointD p = stroke->getPoint(w);double strokeDistance = tdistance2(p, pos);@@ -923,18 +985,19 @@ ControlPointEditorStroke::PointType ControlPointEditorStroke::getPointTypeAt(double minDistance2 = distance2;index = -1;PointType type = NONE;- int cpCount = m_controlPoints.size();- int i;- for (i = 0; i < cpCount; i++) {+ int cpCount = static_cast<int>(m_controlPoints.size());++ for (int i = 0; i < cpCount; ++i) {ControlPoint cPoint = m_controlPoints[i];TPointD point = stroke->getControlPoint(cPoint.m_pointIndex);double cpDistance2 = tdistance2(pos, point);double distanceIn2 = !isSpeedInLinear(i)- ? tdistance2(pos, point - cPoint.m_speedIn)- : cpDistance2 + 1;+ ? tdistance2(pos, point - cPoint.m_speedIn)+ : cpDistance2 + 1;double distanceOut2 = !isSpeedOutLinear(i)? tdistance2(pos, point + cPoint.m_speedOut): cpDistance2 + 1;+if (i == 0 && !isSelfLoop())distanceIn2 = std::max(cpDistance2, distanceOut2) + 1;if (i == cpCount - 1 && !isSelfLoop())@@ -967,9 +1030,9 @@ ControlPointEditorStroke::PointType ControlPointEditorStroke::getPointTypeAt(}}- if (minDistance2 < distance2)+ if (minDistance2 < distance2) {distance2 = minDistance2;- else if (strokeDistance > distance2) {+ } else if (strokeDistance > distance2) {distance2 = strokeDistance;index = -1;type = NONE;@@ -1010,73 +1073,101 @@ void ControlPointSelection::addMenuItems(QMenu *menu) {(m_controlPointEditorStroke &&m_controlPointEditorStroke->getControlPointCount() <= 1))return;+QAction *linear = menu->addAction(tr("Set Linear Control Point"));QAction *unlinear = menu->addAction(tr("Set Nonlinear Control Point"));menu->addSeparator();- bool ret = connect(linear, SIGNAL(triggered()), this, SLOT(setLinear()));- ret =- ret && connect(unlinear, SIGNAL(triggered()), this, SLOT(setUnlinear()));- assert(ret);++ connect(linear, &QAction::triggered, this, &ControlPointSelection::setLinear);+ connect(unlinear, &QAction::triggered, this,+ &ControlPointSelection::setUnlinear);}//-----------------------------------------------------------------------------void ControlPointSelection::setLinear() {- TTool *tool = TTool::getApplication()->getCurrentTool()->getTool();+ TTool *tool = TTool::getApplication()->getCurrentTool()->getTool();+ if (!tool) return;+int currentStrokeIndex = m_controlPointEditorStroke->getStrokeIndex();TVectorImageP vi(tool->getImage(false));if (!vi || isEmpty() || currentStrokeIndex == -1) return;- TUndo *undo;- if (tool->getApplication()->getCurrentObject()->isSpline())- undo = new UndoPath(- tool->getXsheet()->getStageObject(tool->getObjectId())->getSpline());- else {++ // Use unique_ptr for automatic cleanup+ std::unique_ptr<TUndo> undoPtr;++ if (tool->getApplication()->getCurrentObject()->isSpline()) {+ if (tool->getXsheet() &&+ tool->getXsheet()->getStageObject(tool->getObjectId())) {+ undoPtr = std::make_unique<UndoPath>(+ tool->getXsheet()->getStageObject(tool->getObjectId())->getSpline());+ }+ } else {TXshSimpleLevel *level =tool->getApplication()->getCurrentLevel()->getSimpleLevel();- UndoControlPointEditor *cpEditorUndo =- new UndoControlPointEditor(level, tool->getCurrentFid());- cpEditorUndo->addOldStroke(currentStrokeIndex,- vi->getVIStroke(currentStrokeIndex));- undo = cpEditorUndo;+ if (level) {+ auto cpEditorUndo = std::make_unique<UndoControlPointEditor>(+ level, tool->getCurrentFid());+ cpEditorUndo->addOldStroke(currentStrokeIndex,+ vi->getVIStroke(currentStrokeIndex));+ undoPtr = std::move(cpEditorUndo);+ }+ }++ if (m_controlPointEditorStroke->getControlPointCount() == 0 || !undoPtr) {+ return;}- if (m_controlPointEditorStroke->getControlPointCount() == 0) return;bool isChanged = m_controlPointEditorStroke->setControlPointsLinear(m_selectedPoints, true);if (!isChanged) return;- TUndoManager::manager()->add(undo);++ TUndoManager::manager()->add(undoPtr.release());tool->notifyImageChanged();}//-----------------------------------------------------------------------------void ControlPointSelection::setUnlinear() {- TTool *tool = TTool::getApplication()->getCurrentTool()->getTool();+ TTool *tool = TTool::getApplication()->getCurrentTool()->getTool();+ if (!tool) return;+int currentStrokeIndex = m_controlPointEditorStroke->getStrokeIndex();TVectorImageP vi(tool->getImage(false));if (!vi || isEmpty() || currentStrokeIndex == -1) return;- TUndo *undo;- if (tool->getApplication()->getCurrentObject()->isSpline())- undo = new UndoPath(- tool->getXsheet()->getStageObject(tool->getObjectId())->getSpline());- else {+ // Use unique_ptr for automatic cleanup+ std::unique_ptr<TUndo> undoPtr;++ if (tool->getApplication()->getCurrentObject()->isSpline()) {+ if (tool->getXsheet() &&+ tool->getXsheet()->getStageObject(tool->getObjectId())) {+ undoPtr = std::make_unique<UndoPath>(+ tool->getXsheet()->getStageObject(tool->getObjectId())->getSpline());+ }+ } else {TXshSimpleLevel *level =tool->getApplication()->getCurrentLevel()->getSimpleLevel();- UndoControlPointEditor *cpEditorUndo =- new UndoControlPointEditor(level, tool->getCurrentFid());- cpEditorUndo->addOldStroke(currentStrokeIndex,- vi->getVIStroke(currentStrokeIndex));- undo = cpEditorUndo;+ if (level) {+ auto cpEditorUndo = std::make_unique<UndoControlPointEditor>(+ level, tool->getCurrentFid());+ cpEditorUndo->addOldStroke(currentStrokeIndex,+ vi->getVIStroke(currentStrokeIndex));+ undoPtr = std::move(cpEditorUndo);+ }+ }++ if (m_controlPointEditorStroke->getControlPointCount() == 0 || !undoPtr) {+ return;}- if (m_controlPointEditorStroke->getControlPointCount() == 0) return;bool isChanged = m_controlPointEditorStroke->setControlPointsLinear(m_selectedPoints, false);if (!isChanged) return;- TUndoManager::manager()->add(undo);++ TUndoManager::manager()->add(undoPtr.release());tool->notifyImageChanged();}@@ -1084,6 +1175,7 @@ void ControlPointSelection::setUnlinear() {void ControlPointSelection::deleteControlPoints() {TTool *tool = TTool::getApplication()->getCurrentTool()->getTool();+ if (!tool) return;// cancel deleting while dragging pointsControlPointEditorTool *cpTool = dynamic_cast<ControlPointEditorTool *>(tool);@@ -1093,41 +1185,49 @@ void ControlPointSelection::deleteControlPoints() {int currentStrokeIndex = m_controlPointEditorStroke->getStrokeIndex();if (!vi || isEmpty() || currentStrokeIndex == -1) return;- // Inizializzo l'UNDO- TUndo *undo;+ // Initialize UNDO+ std::unique_ptr<TUndo> undoPtr;bool isCurrentObjectSpline =tool->getApplication()->getCurrentObject()->isSpline();- if (isCurrentObjectSpline)- undo = new UndoPath(- tool->getXsheet()->getStageObject(tool->getObjectId())->getSpline());- else {++ if (isCurrentObjectSpline) {+ if (tool->getXsheet() &&+ tool->getXsheet()->getStageObject(tool->getObjectId())) {+ undoPtr = std::make_unique<UndoPath>(+ tool->getXsheet()->getStageObject(tool->getObjectId())->getSpline());+ }+ } else {TXshSimpleLevel *level =tool->getApplication()->getCurrentLevel()->getSimpleLevel();- UndoControlPointEditor *cpEditorUndo =- new UndoControlPointEditor(level, tool->getCurrentFid());- cpEditorUndo->addOldStroke(currentStrokeIndex,- vi->getVIStroke(currentStrokeIndex));- undo = cpEditorUndo;+ if (level) {+ auto cpEditorUndo = std::make_unique<UndoControlPointEditor>(+ level, tool->getCurrentFid());+ cpEditorUndo->addOldStroke(currentStrokeIndex,+ vi->getVIStroke(currentStrokeIndex));+ undoPtr = std::move(cpEditorUndo);+ }}- int i;- for (i = m_controlPointEditorStroke->getControlPointCount() - 1; i >= 0; i--)+ if (!undoPtr) return;++ for (int i = m_controlPointEditorStroke->getControlPointCount() - 1; i >= 0;+ --i)if (isSelected(i)) m_controlPointEditorStroke->deleteControlPoint(i);if (m_controlPointEditorStroke->getControlPointCount() == 0) {- m_controlPointEditorStroke->setStroke((TVectorImage *)0, -1);+ m_controlPointEditorStroke->setStroke(TVectorImageP(), -1);if (!isCurrentObjectSpline) {UndoControlPointEditor *cpEditorUndo =- dynamic_cast<UndoControlPointEditor *>(undo);+ dynamic_cast<UndoControlPointEditor *>(undoPtr.get());if (cpEditorUndo) cpEditorUndo->isStrokeDelete(true);}}- // La spline non puo' essere cancellata completamente!!!+ // Spline cannot be completely deleted!!!if (vi->getStrokeCount() == 0) {if (TTool::getApplication()->getCurrentObject()->isSpline()) {std::vector<TPointD> points;- double d = 10;+ constexpr double d = 10;points.push_back(TPointD(-d, 0));points.push_back(TPointD(0, 0));points.push_back(TPointD(d, 0));@@ -1136,10 +1236,12 @@ void ControlPointSelection::deleteControlPoints() {m_controlPointEditorStroke->setStrokeIndex(0);}}+tool->notifyImageChanged();selectNone();- // Registro l'UNDO- TUndoManager::manager()->add(undo);++ // Register UNDO+ TUndoManager::manager()->add(undoPtr.release());}//-----------------------------------------------------------------------------diff --git a/toonz/sources/tnztools/controlpointselection.h b/toonz/sources/tnztools/controlpointselection.hindex b4682be33..14bad2eef 100644--- a/toonz/sources/tnztools/controlpointselection.h+++ b/toonz/sources/tnztools/controlpointselection.h@@ -9,6 +9,9 @@#include "tvectorimage.h"#include "tcurves.h"+#include <memory>+#include <set>+//=============================================================================// ControlPointEditorStroke//-----------------------------------------------------------------------------@@ -22,73 +25,99 @@ private:TThickPoint m_speedOut;bool m_isCusp;- ControlPoint(int i, TThickPoint speedIn, TThickPoint speedOut,+ ControlPoint(int i, const TThickPoint& speedIn, const TThickPoint& speedOut,bool isCusp = true): m_pointIndex(i), m_speedIn(speedIn), m_speedOut(speedOut), m_isCusp(isCusp) {}- ControlPoint() {}++ ControlPoint() = default;};QList<ControlPoint> m_controlPoints;TVectorImageP m_vi;- int m_strokeIndex;+ int m_strokeIndex = -1;+ // Adjust chunk parity in the strokevoid adjustChunkParity();- /*! Reset m_controlPoints. */+ // Reset m_controlPoints based on current strokevoid resetControlPoints();+ // Get dependent point between two control pointsTThickPoint getPureDependentPoint(int index) const;++ // Get all points that depend on the control point at indexvoid getDependentPoints(- int index, std::vector<std::pair<int, TThickPoint>> &points) const;+ int index, std::vector<std::pair<int, TThickPoint>>& points) const;++ // Update all points in the strokevoid updatePoints();++ // Update points dependent on the specified control pointvoid updateDependentPoint(int index);- inline int nextIndex(int index) const;- inline int prevIndex(int index) const;+ // Get next control point index (with wrap-around for self-loop strokes)+ int nextIndex(int index) const;++ // Get previous control point index (with wrap-around for self-loop strokes)+ int prevIndex(int index) const;- void moveSpeedIn(int index, const TPointD &delta, double minDistance);- void moveSpeedOut(int index, const TPointD &delta, double minDistance);+ // Move speed-in point+ void moveSpeedIn(int index, const TPointD& delta, double minDistance);- void moveSingleControlPoint(int index, const TPointD &delta);+ // Move speed-out point+ void moveSpeedOut(int index, const TPointD& delta, double minDistance);++ // Move a single control point without updating dependents+ void moveSingleControlPoint(int index, const TPointD& delta);public:enum PointType { CONTROL_POINT, SPEED_IN, SPEED_OUT, SEGMENT, NONE };- ControlPointEditorStroke() : m_vi() {}+ ControlPointEditorStroke() = default;++ // Allow copy constructor and assignment operator for compatibility+ ControlPointEditorStroke(const ControlPointEditorStroke& other);+ ControlPointEditorStroke& operator=(const ControlPointEditorStroke& other);- ~ControlPointEditorStroke() { m_controlPoints.clear(); }+ // Create a deep copy of this stroke editor+ ControlPointEditorStroke* clone() const;- ControlPointEditorStroke *clone() const;+ /*! Modify stroke: between two linear or cusp points there must be an even+ number of chunks. WARNING: This function may add control points to the+ stroke. */+ bool setStroke(const TVectorImageP& vi, int strokeIndex);- /*! Modify stroke: between two linear or cusp point must be a pair chunk-number.-PAY ATTENTION: Can add control point in the stroke. */- bool setStroke(const TVectorImageP &vi, int strokeIndex);- TStroke *getStroke() const {- return m_vi ? m_vi->getStroke(m_strokeIndex) : 0;+ // Get the underlying TStroke+ TStroke* getStroke() const {+ return m_vi ? m_vi->getStroke(m_strokeIndex) : nullptr;}+ // Stroke index accessorsvoid setStrokeIndex(int strokeIndex) { m_strokeIndex = strokeIndex; }int getStrokeIndex() const { return m_strokeIndex; }+ // Control point countint getControlPointCount() const { return m_controlPoints.size(); }+ // Get control point dataTThickPoint getControlPoint(int index) const;- /*! From index point in \b ControlPointEditorStroke to index point in \b++ /*! Convert from index point in ControlPointEditorStroke to index point in* TStroke. */int getIndexPointInStroke(int index) const;++ // Get speed pointsTThickPoint getSpeedInPoint(int index) const;TThickPoint getSpeedOutPoint(int index) const;- //! Return true if index point is a cusp.+ // Cusp point managementbool isCusp(int index) const;- //! Set \b m_isCusp of \b index point to \b isCusp.- /*! If isCusp == false check \b setSpeedIn and modify speed. */void setCusp(int index, bool isCusp, bool setSpeedIn);+ // Linear speed point managementbool isSpeedInLinear(int index) const;bool isSpeedOutLinear(int index) const;void setLinearSpeedIn(int index, bool linear = true,@@ -96,35 +125,34 @@ PAY ATTENTION: Can add control point in the stroke. */void setLinearSpeedOut(int index, bool linear = true,bool updatePoints = true);- /*! If isLinear==true set to "0" the speedIn and speedOut value of index-point; otherwise set to default value.-Return true if speedIn or speedOut is modified.-If updatePoints is true update dependent point after.*/+ /*! If isLinear==true, set the speedIn and speedOut values of the index point+ to "0"; otherwise, set them to default values. Returns true if speedIn or+ speedOut is modified. If updatePoints is true, update dependent points+ afterwards. */bool setLinear(int index, bool isLinear, bool updatePoints = true);- bool setControlPointsLinear(std::set<int> points, bool isLinear);-- /*! Move \b index ControlPoint of \b delta. */- void moveControlPoint(int index, const TPointD &delta);-- /*! Add a ControlPoint in \b point. Return added ControlPoint index. */- int addControlPoint(const TPointD &pos);+ bool setControlPointsLinear(const std::set<int>& points, bool isLinear);+ // Control point manipulation+ void moveControlPoint(int index, const TPointD& delta);+ int addControlPoint(const TPointD& pos);void deleteControlPoint(int index);- /*! Move speed in \b index of \b delta. */- void moveSpeed(int index, const TPointD &delta, bool isIn,+ // Speed point manipulation+ void moveSpeed(int index, const TPointD& delta, bool isIn,double minDistance);- /*! Move segment between \b beforeIndex and \b nextIndex of \b delta. */- void moveSegment(int beforeIndex, int nextIndex, const TPointD &delta,- const TPointD &pos);+ // Segment manipulation+ void moveSegment(int beforeIndex, int nextIndex, const TPointD& delta,+ const TPointD& pos);- /*!Return NONE if \b pos is far from stroke.*/- PointType getPointTypeAt(const TPointD &pos, double &distance2,- int &index) const;+ /*! Returns NONE if pos is far from the stroke.+ Otherwise returns the type of point at the given position. */+ PointType getPointTypeAt(const TPointD& pos, double& distance2,+ int& index) const;+ // Check if stroke is self-loopingbool isSelfLoop() const {- TStroke *stroke = getStroke();+ TStroke* stroke = getStroke();return stroke && stroke->isSelfLoop();}};@@ -138,30 +166,41 @@ class ControlPointSelection final : public QObject, public TSelection {private:std::set<int> m_selectedPoints;- int m_strokeIndex;- ControlPointEditorStroke *m_controlPointEditorStroke;+ int m_strokeIndex = -1;+ ControlPointEditorStroke* m_controlPointEditorStroke = nullptr;public:- ControlPointSelection() : m_controlPointEditorStroke(0), m_strokeIndex(-1) {}+ ControlPointSelection() = default;+ // QObject doesn't allow copying, so we delete copy operations+ ControlPointSelection(const ControlPointSelection&) = delete;+ ControlPointSelection& operator=(const ControlPointSelection&) = delete;++ // Set the control point editor stroke to work withvoid setControlPointEditorStroke(- ControlPointEditorStroke *controlPointEditorStroke) {+ ControlPointEditorStroke* controlPointEditorStroke) {m_controlPointEditorStroke = controlPointEditorStroke;}+ // Selection interface implementationbool isEmpty() const override { return m_selectedPoints.empty(); }-void selectNone() override { m_selectedPoints.clear(); }++ // Selection managementbool isSelected(int index) const;void select(int index);void unselect(int index);+ // Delete selected control pointsvoid deleteControlPoints();- void addMenuItems(QMenu *menu);+ // Context menu management+ void addMenuItems(QMenu* menu);+ // Command enablingvoid enableCommands() override;-protected slots:++private slots:void setLinear();void setUnlinear();};diff --git a/toonz/sources/tnztools/filltool.cpp b/toonz/sources/tnztools/filltool.cppindex 21575a1aa..ba484bdbe 100644--- a/toonz/sources/tnztools/filltool.cpp+++ b/toonz/sources/tnztools/filltool.cpp@@ -1,4 +1,5 @@+#include "filltool.h"#include "toonz/tframehandle.h"@@ -198,7 +199,7 @@ public:if (!app) return;TVectorImageP img = m_level->getFrame(m_frameId, true);- assert(!!img);+ assert(img);if (!img) return;if (m_regionFillInformation) {for (UINT i = 0; i < m_regionFillInformation->size(); i++) {@@ -350,17 +351,8 @@ class RasterFillUndo final : public TRasterUndo {int m_column, m_row;public:- /*RasterFillUndo(TTileSetCM32 *tileSet, TPoint fillPoint,- int paintId, int- fillDepth,- std::wstring- fillType, bool isSegment,- bool selective, bool- isShiftFill,- TXshSimpleLevel* sl,- const TFrameId& fid)*/~RasterFillUndo() {- if (m_tileSet) delete m_tileSet;+ // if (m_tileSet) delete m_tileSet;}RasterFillUndo(TTileSetCM32 *tileSet, const FillParameters ¶ms,TXshSimpleLevel *sl, const TFrameId &fid, bool saveboxOnly,@@ -643,7 +635,7 @@ public:if (!app) return;TVectorImageP img = m_level->getFrame(m_frameId, true);;- assert(!!img);+ assert(img);if (!img) return;if (m_regionFillInformation) {for (UINT i = 0; i < m_regionFillInformation->size(); i++) {@@ -853,8 +845,7 @@ void fillAreaWithUndo(const TImageP &img, const TRaster32P &ref,bool fillAllautoPaintLines) {TRectD selArea = stroke ? stroke->getBBox().enlarge(1) : area;if (TToonzImageP ti = img) {- // allargo di 1 la savebox, perche cosi' il rectfill di tutta l'immagine fa- // una sola fillata+ // Expand savebox by 1 so rectfill of entire image does a single fillTRasterCM32P ras;ras = ti->getRaster();@@ -863,14 +854,14 @@ void fillAreaWithUndo(const TImageP &img, const TRaster32P &ref,TRect rasFillArea = rasStrokeBox * rasBounds;if (rasFillArea.isEmpty()) return;- /*-- tileSetでFill範囲のRectをUndoに格納しておく --*/+ /*-- Store fill area Rect in undo using tileSet --*/TTileSetCM32 *rasTileSet = new TTileSetCM32(ras->getSize());rasTileSet->add(ras, rasFillArea);// Don't use ti to get paletteTPalette *plt = sl->getPalette();- // !autopaintLines will temporary disable autopaint line feature+ // !autopaintLines temporarily disables autopaint line featureif ((plt && !hasAutoInks(plt)) || !autopaintLines) plt = 0;TPoint offs(0, 0);@@ -913,8 +904,7 @@ void fillAreaWithUndo(const TImageP &img, const TRaster32P &ref,rasTileSet, stroke, rasSaveBox, auxFillArea, cs, sl, colorType,onlyUnfilled, fid, ref.getPointer(), plt, fillAllautoPaintLines));- // Restore original position because the stroke might be used- // for calculating inbetween frames+ // Restore original position for inbetween frame calculationsstroke->transform(TTranslation(-total));}@@ -987,8 +977,7 @@ void drawReferImage(TRaster32P &ras, TXsheet *xsh, int col, int row,xsh->getStageObject(TStageObjectId::ColumnId(colIndex));TAffine aff = pegbar->getPlacement(row);- // The dpi might not be stored in vector level- // And the dpi of vector level should always be standardDpi+ // Vector level dpi should always be standardDpiTPointD dpi = sl->getType() == PLI_XSHLEVEL? TPointD(Stage::standardDpi, Stage::standardDpi): sl->getDpi();@@ -1095,7 +1084,7 @@ void doRefFill(const TImageP &img, const TRaster32P &refImg, const TPointD &pos,TDimension imageSize = ti->getSize();TPointD p(imageSize.lx % 2 ? 0.0 : 0.5, imageSize.ly % 2 ? 0.0 : 0.5);- /*-- params.m_p = convert(pos-p)では、マイナス座標でずれが生じる --*/+ /*-- Fix for negative coordinate offset --*/TPointD tmp_p = pos - p;params.m_p = TPoint((int)floor(tmp_p.x + 0.5), (int)floor(tmp_p.y + 0.5));@@ -1109,7 +1098,7 @@ void doRefFill(const TImageP &img, const TRaster32P &refImg, const TPointD &pos,return;}- // !autoPaintLines will temporary disable autopaint line feature+ // !autoPaintLines temporarily disables autopaint line featureif (plt && hasAutoInks(plt) && autopaintLines) params.m_palette = plt;if (params.m_fillType == ALL || params.m_fillType == AREAS) {fill(ras, params, &tileSaver, refImg);@@ -1137,7 +1126,7 @@ void doRefFill(const TImageP &img, const TRaster32P &refImg, const TPointD &pos,Preferences::instance()->getFillOnlySavebox(), refImg.getPointer()));}- // al posto di updateFrame:+ // Instead of updateFrame:TXshLevel *xl = app->getCurrentLevel()->getLevel();if (!xl) return;@@ -1150,8 +1139,6 @@ void doRefFill(const TImageP &img, const TRaster32P &refImg, const TPointD &pos,} else if (TVectorImageP vi = TImageP(img)) {int oldStyleId;QMutexLocker lock(vi->getMutex());- /*if(params.m_fillType==ALL || params.m_fillType==AREAS)-vi->computeRegion(pos, params.m_styleId);*/if ((oldStyleId = vectorFill(vi, params.m_fillType, pos, params.m_styleId,params.m_emptyOnly)) != -1)@@ -1205,7 +1192,7 @@ public://=============================================================================// SequencePainter-// da spostare in toolutils?+// To be moved to toolutils?//-----------------------------------------------------------------------------class SequencePainter {@@ -1424,7 +1411,8 @@ AreaFillTool::AreaFillTool(TTool *parent), m_mousePosition(), m_onion(false), m_isLeftButtonPressed(false)- , m_autopaintLines(true) {}+ , m_autopaintLines(true)+ , m_bckStyleId(0) {}void AreaFillTool::draw() {m_thick = m_parent->getPixelSize() / 2.0;@@ -1475,7 +1463,7 @@ int AreaFillTool::pick(const TImageP &image, const TPointD &pos,scale2 = aff.det();}TPointD pickPos = pos;- // in case that the column is animated in scene-editing mode+ // Adjust for animated columns in scene-editing modeif (frame > 0) {TPointD dpiScale = viewer->getDpiScale();pickPos.x *= dpiScale.x;@@ -1485,7 +1473,7 @@ int AreaFillTool::pick(const TImageP &image, const TPointD &pos,pickPos.x /= dpiScale.x;pickPos.y /= dpiScale.y;}- // thin stroke can be picked with 10 pixel range+ // Thin stroke pick with 10 pixel rangereturn picker.pickStyleId(pickPos, 10.0, scale2, mode);}@@ -1531,10 +1519,8 @@ void AreaFillTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e,m_selectingRect.x1 = pos.x + 1;m_selectingRect.y1 = pos.y + 1;} else if (m_type == FREEHAND || m_type == POLYLINE || m_type == FREEPICK) {- int col = TTool::getApplication()->getCurrentColumn()->getColumnIndex();- m_isPath = TTool::getApplication()- ->getCurrentObject()- ->isSpline(); // getApplication()->isEditingSpline();+ int col = TTool::getApplication()->getCurrentColumn()->getColumnIndex();+ m_isPath = TTool::getApplication()->getCurrentObject()->isSpline();m_enabled = col >= 0 || m_isPath;if (!m_enabled) return;@@ -1559,10 +1545,10 @@ void AreaFillTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e,m_isLeftButtonPressed = true;}-/*-- PolyLineFillを閉じる時に呼ばれる --*/+/*-- Called when closing PolyLineFill --*/void AreaFillTool::leftButtonDoubleClick(const TPointD &pos,const TMouseEvent &e) {- TStroke *stroke;+ TStroke *stroke = nullptr; // Initialized as nullptrFillTool *fillTool = (FillTool *)m_parent;auto refImgTable = fillTool->getRefImgTable();auto slFidsPairs = fillTool->getSlFidsPairs();@@ -1578,6 +1564,7 @@ void AreaFillTool::leftButtonDoubleClick(const TPointD &pos,if (m_polyline.back() != pos) m_polyline.push_back(pos);if (m_polyline.back() != m_polyline.front())m_polyline.push_back(m_polyline.front());+std::vector<TThickPoint> strokePoints;for (UINT i = 0; i < m_polyline.size() - 1; i++) {strokePoints.push_back(TThickPoint(m_polyline[i], 1));@@ -1589,12 +1576,8 @@ void AreaFillTool::leftButtonDoubleClick(const TPointD &pos,stroke = new TStroke(strokePoints);assert(stroke->getPoint(0) == stroke->getPoint(1));- // if (m_type==POLYLINE)- // m_polyline.push_back(pos);- // drawPolyline(m_polyline);int styleIndex = app->getCurrentLevelStyleIndex();- if (m_frameRange) // stroke multi- {+ if (m_frameRange) { // stroke multiif (m_firstFrameSelected && !slFidsPairs.empty()) {MultiAreaFiller filler(refImgTable, m_firstStroke, stroke, m_onlyUnfilled,m_colorType, styleIndex, m_autopaintLines,@@ -1616,11 +1599,9 @@ void AreaFillTool::leftButtonDoubleClick(const TPointD &pos,app->getCurrentFrame()->setFid(m_veryFirstFrameId);resetMulti();}- } else // primo frame- {+ } else { // first framem_firstFrameSelected = true;m_firstStroke = stroke;- // if (app->getCurrentFrame()->isEditingScene())m_currCell =std::pair<int, int>(app->getCurrentColumn()->getColumnIndex(),app->getCurrentFrame()->getFrame());@@ -1631,11 +1612,14 @@ void AreaFillTool::leftButtonDoubleClick(const TPointD &pos,OnionSkinMask osMask = app->getCurrentOnionSkin()->getOnionSkinMask();doStrokeAutofill(m_parent->getImage(true), stroke, m_onlyUnfilled, osMask,m_level.getPointer(), m_parent->getCurrentFid());- } else+ delete stroke; // Delete the stroke when using onion skin+ } else {fillAreaWithUndo(m_parent->getImage(true), refImgTable[imgId], TRectD(),stroke, m_onlyUnfilled, m_colorType,m_level.getPointer(), m_parent->getCurrentFid(),styleIndex, m_autopaintLines, m_paintAllAPs);+ // fillAreaWithUndo should take on the stroke property+ }TTool *t = app->getCurrentTool()->getTool();if (t) t->notifyImageChanged();}@@ -1719,7 +1703,7 @@ void AreaFillTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {OnionSkinMask osMask = app->getCurrentOnionSkin()->getOnionSkinMask();doRectAutofill(m_parent->getImage(true), m_selectingRect,m_onlyUnfilled, osMask, m_level.getPointer(),- m_parent->getCurrentFid()); // Do not support ReferImg+ m_parent->getCurrentFid()); // ReferImg not supported} elsefillAreaWithUndo(m_parent->getImage(true), refImgTable[imgId],m_selectingRect, 0, m_onlyUnfilled, m_colorType,@@ -1771,7 +1755,7 @@ void AreaFillTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {}resetMulti();}- } else // primo frame+ } else // first frame{m_firstFrameSelected = true;m_firstRect = m_selectingRect;@@ -1818,7 +1802,7 @@ void AreaFillTool::onImageChanged() {resetMulti();}-/*--Normal以外のTypeが選択された場合に呼ばれる--*/+/*-- Called when Type other than Normal is selected --*/bool AreaFillTool::onPropertyChanged(bool multi, bool onlyUnfilled, bool onion,Type type, std::wstring colorType,bool autopaintLines) {@@ -1831,7 +1815,7 @@ bool AreaFillTool::onPropertyChanged(bool multi, bool onlyUnfilled, bool onion,if (m_frameRange) resetMulti();- /*--動作中にプロパティが変わったら、現在の動作を無効にする--*/+ /*-- Cancel current operation if property changes during action --*/if (m_isLeftButtonPressed) m_isLeftButtonPressed = false;if (m_type == POLYLINE && !m_polyline.empty()) m_polyline.clear();@@ -1857,8 +1841,8 @@ bool descending(int i, int j) { return (i > j); }//=============================================================================/*! NormalLineFillTool- マウスドラッグで直線を延ばし、その直線がまたいだ点をFillLineするツール。- Raster - Normal - Line Fillツール(FrameRangeなし)のとき使用可能にする+ Extend line with mouse drag and FillLine at points the line crosses.+ Available for Raster - Normal - Line Fill tool (without FrameRange)*/class NormalLineFillTool {TTool *m_parent;@@ -1869,7 +1853,7 @@ public:NormalLineFillTool(TTool *parent): m_parent(parent), m_isEditing(false), m_mousePosition() {}- /*-- FillLineツールに戻ってきたときに前の位置情報をリセットする --*/+ /*-- Reset previous position info when returning to FillLine tool --*/void init() {m_startPosition = TPointD();m_mousePosition = TPointD();@@ -1877,8 +1861,8 @@ public:}void leftButtonDown(const TPointD &pos, const TMouseEvent &e) {- m_startPosition = pos; /*-始点-*/- m_mousePosition = pos; /*-終点-*/+ m_startPosition = pos; /*-- Start point --*/+ m_mousePosition = pos; /*-- End point --*/m_isEditing = true;}@@ -1908,13 +1892,13 @@ public:if (!ras) return;int styleId = params.m_styleId;- /*--- 線分上にある全ての点でdoFillを行う ---*/+ /*-- Perform doFill at every point on the line segment --*/double dx = m_mousePosition.x - m_startPosition.x;double dy = m_mousePosition.y - m_startPosition.y;- if (std::abs(dx) > std::abs(dy)) /*-- 横長の線分の場合 --*/+ if (std::abs(dx) > std::abs(dy)) /*-- Horizontally oriented line --*/{- double k = dy / dx; /*-- 直線の傾き --*/- /*--- roundでは負値のときにうまく繋がらない ---*/+ double k = dy / dx; /*-- Slope of the line --*/+ /*-- round doesn't connect properly with negative values --*/int start = std::min((int)floor(m_startPosition.x + 0.5),(int)floor(m_mousePosition.x + 0.5));int end = std::max((int)floor(m_startPosition.x + 0.5),@@ -1936,10 +1920,10 @@ public:doFill(img, tmpPos, params, e.isShiftPressed(), sl,m_parent->getCurrentFid(), true);}- } else /*-- 縦長の線分の場合 --*/+ } else /*-- Vertically oriented line --*/{- double k = dx / dy; /*-- 直線の傾き --*/- /*--- roundでは負値のときにうまく繋がらない ---*/+ double k = dx / dy; /*-- Slope of the line --*/+ /*-- round doesn't connect properly with negative values --*/int start = std::min((int)floor(m_startPosition.y + 0.5),(int)floor(m_mousePosition.y + 0.5));int end = std::max((int)floor(m_startPosition.y + 0.5),@@ -2002,7 +1986,7 @@ FillTool::FillTool(int targetType), m_autopaintLines("Autopaint Lines", true), m_referFill("Refer Fill", false), m_extendFill("Extend Fill", true) {- m_areaFillTool = new AreaFillTool(this);+ m_areaFillTool = new AreaFillTool(this);m_normalLineFillTool = new NormalLineFillTool(this);bind(targetType);@@ -2155,8 +2139,8 @@ void FillTool::computeRefImgsIfNeeded(const FillParameters ¶ms) {// Calculate every refImgbool fillOnlySavebox = Preferences::instance()->getFillOnlySavebox();- TPointD cameraDpi =- app->getCurrentScene()->getScene()->getCurrentCamera()->getDpi();+ // TPointD cameraDpi =+ // app->getCurrentScene()->getScene()->getCurrentCamera()->getDpi();for (auto [sl, fid] : m_slFidsPairs) {if (sl->getType() != TXshLevelType::TZP_XSHLEVEL) continue;@@ -2226,14 +2210,14 @@ FillParameters FillTool::getFillParameters() const {FillParameters params;int styleId = TTool::getApplication()->getCurrentLevelStyleIndex();params.m_styleId = styleId;- /*---紛らわしいことに、colorTypeをfillTypeに名前を変えて保存している。間違いではない。---*/+ /*-- Note: colorType is saved as fillType. This is not an error. --*/params.m_fillType = m_colorType.getValue();params.m_emptyOnly = m_emptyOnly.getValue();params.m_segment = m_segment.getValue();// RefFill is not controlled paramsparams.m_minFillDepth = (int)m_fillDepth.getValue().first;params.m_maxFillDepth = (int)m_fillDepth.getValue().second;- params.m_extendFill = m_extendFill.getValue();+ params.m_extendFill = m_extendFill.getValue();return params;}@@ -2246,8 +2230,8 @@ void FillTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {!DEF_REGION_WITH_PAINT);m_restoreEmptyOnly = e.isShiftPressed() && m_emptyOnly.getValue();if (m_restoreEmptyOnly) {- m_emptyOnly.setValue(false);- onPropertyChanged(m_emptyOnly.getName(), false);+ m_emptyOnly.setValue(false);+ onPropertyChanged(m_emptyOnly.getName(), false);}m_clickPoint = pos;@@ -2262,7 +2246,7 @@ void FillTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {return;}- /*--以下、NormalFillの場合--*/+ /*-- Below, for NormalFill --*/TTool::Application *app = TTool::getApplication();if (!app) return;FillParameters params = getFillParameters();@@ -2289,7 +2273,7 @@ void FillTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {// frame-range-filling. Calling processEvents() here to make sure to// consume the mouse press event in advance.qApp->processEvents();- // SECONDO CLICK+ // SECOND CLICKMultiFiller filler(m_refImgTable, m_firstPoint, pos, params,m_autopaintLines.getValue());filler.setSelectionUndo(new FillToolSelectionUndo(@@ -2405,8 +2389,8 @@ void FillTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {Preferences::instance()->setValue(PreferencesItemId::DefRegionWithPaint,(!DEF_REGION_WITH_PAINT));if (m_restoreEmptyOnly) {- m_emptyOnly.setValue(true);- onPropertyChanged(m_emptyOnly.getName(), false);+ m_emptyOnly.setValue(true);+ onPropertyChanged(m_emptyOnly.getName(), false);}}@@ -2437,9 +2421,8 @@ void FillTool::resetMulti(bool resetAreaFiller) {//-----------------------------------------------------------------------------bool FillTool::onPropertyChanged(std::string propertyName, bool addToUndo) {- /*--- m_areaFillTool->onPropertyChangedを呼ぶかどうかのフラグ- fillType, frameRange, selective,- colorTypeが変わったときに呼ぶ---*/+ /*-- Flag to call m_areaFillTool->onPropertyChanged+ Called when fillType, frameRange, selective, colorType changes --*/bool rectPropChangedflag = false;// Areas, Lines etc.@@ -2447,9 +2430,9 @@ bool FillTool::onPropertyChanged(std::string propertyName, bool addToUndo) {FillColorType = ::to_string(m_colorType.getValue());rectPropChangedflag = true;- /*--- ColorModelのCursor更新のためにSIGNALを出す ---*/+ /*-- Emit SIGNAL to update ColorModel Cursor --*/TTool::getApplication()->getCurrentTool()->notifyToolChanged();- /*--- FillLineツールに戻ってきたときに前回の位置情報をリセットする ---*/+ /*-- Reset previous position info when returning to FillLine tool --*/if (FillColorType.getValue() == "Lines") m_normalLineFillTool->init();}// Rect, Polyline etc.@@ -2464,7 +2447,7 @@ bool FillTool::onPropertyChanged(std::string propertyName, bool addToUndo) {// Onion Skinelse if (propertyName == m_onion.getName()) {if (m_onion.getValue()) FillType = ::to_string(m_fillType.getValue());- FillOnion = (int)(m_onion.getValue());+ FillOnion = (int)(m_onion.getValue());rectPropChangedflag = true;}// Frame Range@@ -2503,7 +2486,7 @@ bool FillTool::onPropertyChanged(std::string propertyName, bool addToUndo) {// Gap Close Distanceelse if (propertyName == m_gapCloseDistance.getName()) {AutocloseDistance = m_gapCloseDistance.getValue();- auto st = ToonzCheck::instance()->getAutocloseSettings();+ // auto st = ToonzCheck::instance()->getAutocloseSettings();ToonzCheck::instance()->setAutocloseSettings(AutocloseDistance, AutocloseAngle, AutocloseOpacity,AutocloseIgnoreAutoPaint);@@ -2515,8 +2498,7 @@ bool FillTool::onPropertyChanged(std::string propertyName, bool addToUndo) {FillExtend = (int)(m_extendFill.getValue());}- else if (!m_frameSwitched &&- (propertyName == m_maxGapDistance.getName())) {+ else if (!m_frameSwitched && (propertyName == m_maxGapDistance.getName())) {TXshLevel *xl = TTool::getApplication()->getCurrentLevel()->getLevel();m_level = xl ? xl->getSimpleLevel() : 0;if (TVectorImageP vi = getImage(true)) {@@ -2550,7 +2532,7 @@ bool FillTool::onPropertyChanged(std::string propertyName, bool addToUndo) {}}- /*--- fillType, frameRange, selective, onionSkin, colorTypeが変わったとき ---*/+ /*-- When fillType, frameRange, selective, onionSkin, colorType change --*/if (rectPropChangedflag && m_fillType.getValue() != NORMALFILL) {AreaFillTool::Type type;if (m_fillType.getValue() == RECTFILL)@@ -2651,7 +2633,7 @@ int FillTool::pick(const TImageP &image, const TPointD &pos, const int frame) {scale2 = aff.det();}TPointD pickPos = pos;- // in case that the column is animated in scene-editing mode+ // Adjust for animated columns in scene-editing modeif (frame > 0) {TPointD dpiScale = getViewer()->getDpiScale();pickPos.x *= dpiScale.x;@@ -2661,7 +2643,7 @@ int FillTool::pick(const TImageP &image, const TPointD &pos, const int frame) {pickPos.x /= dpiScale.x;pickPos.y /= dpiScale.y;}- // thin stroke can be picked with 10 pixel range+ // Thin stroke pick with 10 pixel rangereturn picker.pickStyleId(pickPos, 10.0, scale2);}@@ -2670,8 +2652,8 @@ int FillTool::pick(const TImageP &image, const TPointD &pos, const int frame) {int FillTool::pickOnionColor(const TPointD &pos) {TTool::Application *app = TTool::getApplication();if (!app) return 0;- bool filmStripEditing = !app->getCurrentObject()->isSpline();- OnionSkinMask osMask = app->getCurrentOnionSkin()->getOnionSkinMask();+ // bool filmStripEditing = !app->getCurrentObject()->isSpline();+ OnionSkinMask osMask = app->getCurrentOnionSkin()->getOnionSkinMask();TFrameId fid = getCurrentFid();@@ -2680,7 +2662,7 @@ int FillTool::pickOnionColor(const TPointD &pos) {std::vector<int> rows;- // level editing case+ // For level editingif (app->getCurrentFrame()->isEditingLevel()) {osMask.getAll(sl->guessIndex(fid), rows);int i, j;@@ -2693,7 +2675,7 @@ int FillTool::pickOnionColor(const TPointD &pos) {if (onionFid != fid &&((onionStyleId =pick(m_level->getFrame(onionFid, ImageManager::none, 1), pos)) >- 0)) // subsampling must be 1, otherwise onionfill does not work+ 0)) // subsampling must be 1 for onionfill to workbreak;}if (onionStyleId == 0)@@ -2702,11 +2684,11 @@ int FillTool::pickOnionColor(const TPointD &pos) {if (onionFid != fid &&((onionStyleId = pick(m_level->getFrame(onionFid, ImageManager::none, 1), pos)) >- 0)) // subsampling must be 1, otherwise onionfill does not work+ 0)) // subsampling must be 1 for onionfill to workbreak;}return onionStyleId;- } else { // scene editing case+ } else { // For scene editingTXsheet *xsh = app->getCurrentXsheet()->getXsheet();int colId = app->getCurrentColumn()->getColumnIndex();int row = app->getCurrentFrame()->getFrame();@@ -2809,26 +2791,26 @@ void FillTool::onActivate() {}}}- bool ret = true;- ret = ret && connect(TTool::m_application->getCurrentFrame(),- SIGNAL(frameSwitched()), this, SLOT(onFrameSwitched()));- ret = ret && connect(TTool::m_application->getCurrentScene(),- SIGNAL(sceneSwitched()), this, SLOT(onFrameSwitched()));- ret = ret &&- connect(TTool::m_application->getCurrentColumn(),- SIGNAL(columnIndexSwitched()), this, SLOT(onFrameSwitched()));- assert(ret);++ connect(TTool::m_application->getCurrentFrame(), &TFrameHandle::frameSwitched,+ this, &FillTool::onFrameSwitched);+ connect(TTool::m_application->getCurrentScene(), &TSceneHandle::sceneSwitched,+ this, &FillTool::onFrameSwitched);+ connect(TTool::m_application->getCurrentColumn(),+ &TColumnHandle::columnIndexSwitched, this,+ &FillTool::onFrameSwitched);}//-----------------------------------------------------------------------------void FillTool::onDeactivate() {- disconnect(TTool::m_application->getCurrentFrame(), SIGNAL(frameSwitched()),- this, SLOT(onFrameSwitched()));- disconnect(TTool::m_application->getCurrentScene(), SIGNAL(sceneSwitched()),- this, SLOT(onFrameSwitched()));+ disconnect(TTool::m_application->getCurrentFrame(),+ &TFrameHandle::frameSwitched, this, &FillTool::onFrameSwitched);+ disconnect(TTool::m_application->getCurrentScene(),+ &TSceneHandle::sceneSwitched, this, &FillTool::onFrameSwitched);disconnect(TTool::m_application->getCurrentColumn(),- SIGNAL(columnIndexSwitched()), this, SLOT(onFrameSwitched()));+ &TColumnHandle::columnIndexSwitched, this,+ &FillTool::onFrameSwitched);}//-----------------------------------------------------------------------------diff --git a/toonz/sources/tnztools/fullcolorerasertool.cpp b/toonz/sources/tnztools/fullcolorerasertool.cppindex 46b63614a..133b26148 100644--- a/toonz/sources/tnztools/fullcolorerasertool.cpp+++ b/toonz/sources/tnztools/fullcolorerasertool.cpp@@ -150,9 +150,9 @@ public:TRasterImageP ri = getImage();if (!ri) return;- if (m_eraseType == RECTERASE)- TRect rect = TRasterImageUtils::eraseRect(ri, m_modifyArea);- else if (m_eraseType == FREEHANDERASE || m_eraseType == POLYLINEERASE) {+ if (m_eraseType == RECTERASE) {+ TRasterImageUtils::eraseRect(ri, m_modifyArea);+ } else if (m_eraseType == FREEHANDERASE || m_eraseType == POLYLINEERASE) {TPoint pos;TRaster32P image =@@ -298,7 +298,12 @@ public:, m_eraseStroke(nullptr), m_strokeTemp(nullptr), m_clickNumber(0)- , m_isSingleArc(false) {}+ , m_isSingleArc(false)+ , m_smooth(false)+ , m_size(0)+ , m_isEditing(false)+ , m_color(TPixel32::Red) {}+MultiArcPrimitive(TTool *tool, bool smooth = false): m_tool(tool), m_stroke(0)@@ -306,7 +311,10 @@ public:, m_strokeTemp(0), m_clickNumber(0), m_isSingleArc(false)- , m_smooth(smooth) {}+ , m_smooth(smooth)+ , m_size(0)+ , m_isEditing(false)+ , m_color(TPixel32::Red) {}~MultiArcPrimitive() { delete m_stroke; }@@ -339,9 +347,6 @@ public:m_centralPoint = centralPoint;m_clickNumber = clickNumber;}-- // Only execute touchImage when clicking the first point of the multi arc- // bool canTouchImageOnPreLeftClick() override { return m_clickNumber == 0; }};//=============================================================================@@ -767,10 +772,9 @@ void FullColorEraserTool::leftButtonDown(const TPointD &pos,TRectD invalidateRect;TRasterP ras = ri->getRaster();if (m_eraseType.getValue() == NORMALERASE) {- TDimension dim = ras->getSize();- double opacity = m_opacity.getValue() * 0.01;- double hardness = m_hardness.getValue() * 0.01;- m_workRaster = TRaster32P(dim);+ TDimension dim = ras->getSize();+ double opacity = m_opacity.getValue() * 0.01;+ m_workRaster = TRaster32P(dim);m_workRaster->clear();m_backUpRas = ras->clone();@@ -846,7 +850,6 @@ void FullColorEraserTool::leftButtonDrag(const TPointD &pos,if (!ri) return;if (m_eraseType.getValue() == NORMALERASE) {double thickness = m_size.getValue();- TDimension size = m_workRaster->getSize();TPointD rasCenter = ri->getRaster()->getCenterD();TThickPoint point(pos + rasCenter, thickness);@@ -941,11 +944,9 @@ void FullColorEraserTool::leftButtonUp(const TPointD &pos,}m_workRaster->unlock();- double opacity = m_opacity.getValue() * 0.01;- double hardness = m_hardness.getValue() * 0.01;-- m_workRaster = TRaster32P();- m_backUpRas = TRaster32P();+ double opacity = m_opacity.getValue() * 0.01;+ m_workRaster = TRaster32P();+ m_backUpRas = TRaster32P();delete m_tileSaver;TTool::Application *app = TTool::getApplication();@@ -1068,7 +1069,7 @@ void FullColorEraserTool::leftButtonUp(const TPointD &pos,resetMulti();delete stroke;}- } else // primo frame+ } else // first frame{m_firstStroke = stroke;m_isXsheetCell = app->getCurrentFrame()->isEditingScene();@@ -1090,7 +1091,8 @@ void FullColorEraserTool::leftButtonUp(const TPointD &pos,} else if (m_eraseType.getValue() == MULTIARCERASE) {TStroke *stroke;m_multiArcPrimitive.leftButtonUp(pos, e);- if (stroke = m_multiArcPrimitive.getEraseStroke()) {+ stroke = m_multiArcPrimitive.getEraseStroke();+ if (stroke) {TTool::Application *app = TTool::getApplication();if (m_multi.getValue()) // stroke multi{@@ -1114,9 +1116,10 @@ void FullColorEraserTool::leftButtonUp(const TPointD &pos,} elseapp->getCurrentFrame()->setFid(m_veryFirstFrameId);resetMulti();- delete stroke;+ // Don't delete stroke here because it belongs to+ // m_multiArcPrimitive}- } else // primo frame+ } else // first frame{m_firstStroke = stroke;m_isXsheetCell = app->getCurrentFrame()->isEditingScene();@@ -1151,7 +1154,7 @@ void FullColorEraserTool::leftButtonDoubleClick(const TPointD &pos,TRasterImageP ri(getImage(true));if (!ri) return;- TStroke *stroke;+ TStroke *stroke = nullptr;TTool::Application *app = TTool::getApplication();if (m_eraseType.getValue() == POLYLINEERASE) {if (m_polyline.size() <= 1) {@@ -1173,11 +1176,16 @@ void FullColorEraserTool::leftButtonDoubleClick(const TPointD &pos,assert(stroke->getPoint(0) == stroke->getPoint(1));} else if (m_eraseType.getValue() == MULTIARCERASE) {m_multiArcPrimitive.leftButtonDoubleClick(pos, e);- if (stroke = m_multiArcPrimitive.getEraseStroke())- ;- else- return;+ stroke = m_multiArcPrimitive.getEraseStroke();+ if (!stroke) return;}++ std::unique_ptr<TStroke> strokePtr;+ if (m_eraseType.getValue() == POLYLINEERASE) {+ strokePtr.reset(stroke);+ stroke = strokePtr.get();+ }+if (m_multi.getValue()) // stroke multi{if (m_firstFrameSelected) {@@ -1189,7 +1197,11 @@ void FullColorEraserTool::leftButtonDoubleClick(const TPointD &pos,delete m_firstStroke;m_firstStroke = 0;invalidate(invalidateRect.enlarge(2));- m_firstStroke = stroke;+ if (m_eraseType.getValue() == POLYLINEERASE) {+ m_firstStroke = strokePtr.release();+ } else {+ m_firstStroke = stroke;+ }invalidateRect = m_firstStroke->getBBox();invalidate(invalidateRect.enlarge(2));m_firstFrameId = getFrameId();@@ -1200,11 +1212,14 @@ void FullColorEraserTool::leftButtonDoubleClick(const TPointD &pos,} elseapp->getCurrentFrame()->setFid(m_veryFirstFrameId);resetMulti();- delete stroke;}- } else // primo frame+ } else // first frame{- m_firstStroke = stroke;+ if (m_eraseType.getValue() == POLYLINEERASE) {+ m_firstStroke = strokePtr.release();+ } else {+ m_firstStroke = stroke;+ }m_isXsheetCell = app->getCurrentFrame()->isEditingScene();m_currCell = std::pair<int, int>(getColumnIndex(), getFrame());invalidate(m_firstStroke->getBBox().enlarge(2));@@ -1361,10 +1376,11 @@ void FullColorEraserTool::update(const TRasterImageP &ri, TRectD selArea,tileSet->add(raster, TRasterImageUtils::convertWorldToRaster(selArea, ri));TUndo *undo;- undo = new RectFullColorUndo(tileSet, selArea, TStroke(),- m_eraseType.getValue(), level.getPointer(),- m_invertOption.getValue(), frameId);- TRect rect = TRasterImageUtils::eraseRect(ri, selArea);+ undo = new RectFullColorUndo(tileSet, selArea, TStroke(),+ m_eraseType.getValue(), level.getPointer(),+ m_invertOption.getValue(), frameId);++ TRasterImageUtils::eraseRect(ri, selArea);TUndoManager::manager()->add(undo);}@@ -1400,10 +1416,10 @@ void FullColorEraserTool::onImageChanged() {(m_selectingRect.isEmpty() && !m_firstStroke))resetMulti();else if (m_firstFrameId == getCurrentFid())- m_firstFrameSelected = false; // nel caso sono passato allo stato 1 e torno- // all'immagine iniziale, torno allo stato- // iniziale- else { // cambio stato.+ m_firstFrameSelected =+ false; // if I passed to state 1 and return to the+ // initial image, I return to the initial state+ else { // state change.m_firstFrameSelected = true;if (m_eraseType.getValue() != FREEHANDERASE &&m_eraseType.getValue() != POLYLINEERASE &&@@ -1529,7 +1545,6 @@ void FullColorEraserTool::doMultiEraser(const TImageP &img, double t,const TFrameId &fid,const TVectorImageP &firstImage,const TVectorImageP &lastImage) {- int styleId = TTool::getApplication()->getCurrentLevelStyleIndex();if (t == 0)eraseStroke(img, firstImage->getStroke(0), m_eraseType.getValue(),m_invertOption.getValue(), /*m_multi.getValue(),*/ m_level,@@ -1547,4 +1562,4 @@ void FullColorEraserTool::doMultiEraser(const TImageP &img, double t,m_invertOption.getValue(), /*m_multi.getValue(),*/ m_level,fid);}-}\ No newline at end of file+}diff --git a/toonz/sources/tnztools/geometrictool.cpp b/toonz/sources/tnztools/geometrictool.cppindex b6ad17c96..17a5192b9 100644--- a/toonz/sources/tnztools/geometrictool.cpp+++ b/toonz/sources/tnztools/geometrictool.cpp@@ -1250,8 +1250,7 @@ void GeometricTool::mouseMove(const TPointD &p, const TMouseEvent &e) {m_rotateCenter = 0.5 * (bbox.getP11() + bbox.getP00());}- // rotate- // first, rotate the stroke back to original+ // rotate first, rotate the stroke back to originalm_rotatedStroke->transform(TRotation(m_rotateCenter, -m_lastRotateAngle));// then, rotate it according to mouse position@@ -1670,7 +1669,8 @@ void GeometricTool::addStroke() {options.m_joinStyle = m_param.m_joinStyle.getIndex();options.m_miterUpper = m_param.m_miterJoinLimit.getValue();- TImage *image = getImage(true);+ // Use TImageP to maintain the reference+ TImageP image = getImage(true);TToonzImageP ti(image);TVectorImageP vi(image);TRasterImageP ri(image);@@ -1866,8 +1866,6 @@ GeometricTool GeometricRasterFullColorTool(TTool::RasterImage |TTool::EmptyTarget);//====================================================================================================-//-//-------------------------------------------------------------------------------------------------------------void Primitive::drawSnap() {// snapping@@ -1890,17 +1888,22 @@ TPointD Primitive::checkGuideSnapping(TPointD pos) {elsereturn pos;}+if ((m_param->m_targetType & TTool::Vectors) && m_param->m_snap.getValue()) {int vGuideCount = 0, hGuideCount = 0;double guideDistance = sqrt(m_param->m_minDistance2);TToolViewer *viewer = m_tool->getViewer();++ // Initialize variables+ double vGuide = 0.0, hGuide = 0.0;+ double distanceToVGuide = -1.0, distanceToHGuide = -1.0;+ bool useGuides = false;+if (viewer) {vGuideCount = viewer->getVGuideCount();hGuideCount = viewer->getHGuideCount();}- double distanceToVGuide = -1.0, distanceToHGuide = -1.0;- double vGuide, hGuide;- bool useGuides = false;+if (vGuideCount) {for (int j = 0; j < vGuideCount; j++) {double guide = viewer->getVGuide(j);@@ -1913,6 +1916,7 @@ TPointD Primitive::checkGuideSnapping(TPointD pos) {}}}+if (hGuideCount) {for (int j = 0; j < hGuideCount; j++) {double guide = viewer->getHGuide(j);@@ -1925,36 +1929,40 @@ TPointD Primitive::checkGuideSnapping(TPointD pos) {}}}+if (useGuides && m_param->m_foundSnap) {double currYDistance = std::abs(m_param->m_snapPoint.y - pos.y);double currXDistance = std::abs(m_param->m_snapPoint.x - pos.x);double hypotenuse =sqrt(pow(currYDistance, 2.0) + pow(currXDistance, 2.0));+if ((distanceToVGuide >= 0 && distanceToVGuide < hypotenuse) ||(distanceToHGuide >= 0 && distanceToHGuide < hypotenuse))useGuides = true;elseuseGuides = false;}+if (useGuides) {assert(distanceToHGuide >= 0 || distanceToVGuide >= 0);if (distanceToHGuide < 0 ||(distanceToVGuide <= distanceToHGuide && distanceToVGuide >= 0)) {m_param->m_snapPoint.y = vGuide;m_param->m_snapPoint.x = pos.x;-} else {m_param->m_snapPoint.y = pos.y;m_param->m_snapPoint.x = hGuide;}m_param->m_foundSnap = true;}+if (m_param->m_foundSnap)return m_param->m_snapPoint;elsereturn pos;- } else+ } else {return pos;+ }}//=============================================================================@@ -2106,7 +2114,11 @@ TStroke *RectanglePrimitive::makeStroke() const {points[8] = points[0];stroke = new TStroke(points);}- stroke->setSelfLoop();++ // Check if stroke is not null+ if (stroke) {+ stroke->setSelfLoop();+ }return stroke;}@@ -2318,11 +2330,10 @@ void MultiLinePrimitive::moveSpeed(const TPointD &delta) {//-----------------------------------------------------------------------------void MultiLinePrimitive::draw() {- UINT size = m_vertex.size();-+ // remove unused variable 'size' // UINT size = m_vertex.size();drawSnap();- if ((m_isEditing || m_isPrompting) && size > 0) {+ if ((m_isEditing || m_isPrompting) && !m_vertex.empty()) {tglColor(m_isEditing ? m_color : TPixel32::Green);std::vector<TPointD> points;points.assign(m_vertex.begin(), m_vertex.end());@@ -2579,8 +2590,7 @@ void MultiLinePrimitive::onImageChanged() { onActivate(); }//-----------------------------------------------------------------------------void LinePrimitive::draw() {- UINT size = m_vertex.size();-+ // remove unused variable 'size' // UINT size = m_vertex.size();drawSnap();tglColor(TPixel32::Red);@@ -2871,7 +2881,10 @@ void MultiArcPrimitive::draw() {//-----------------------------------------------------------------------------TStroke *MultiArcPrimitive::makeStroke() const {- return new TStroke(*m_stroke);+ if (m_stroke) {+ return new TStroke(*m_stroke);+ }+ return 0;}//-----------------------------------------------------------------------------@@ -2908,10 +2921,10 @@ void MultiArcPrimitive::leftButtonDrag(const TPointD &pos,!Preferences::instance()->isClickTwiceToCreateArcs())return;- TPointD newPos = calculateSnap(pos);- newPos = checkGuideSnapping(pos);- double dist = joinDistance * joinDistance;- static MultiArcPrimitiveUndo *undo;+ TPointD newPos = calculateSnap(pos);+ newPos = checkGuideSnapping(pos);+ double dist = joinDistance * joinDistance;+ static MultiArcPrimitiveUndo *undo = nullptr;if (m_clickNumber == 0) {undo = new MultiArcPrimitiveUndo(this, m_stroke, m_strokeTemp, m_startPoint,@@ -2985,11 +2998,12 @@ void MultiArcPrimitive::leftButtonDrag(const TPointD &pos,break;}- if (m_undoCount == 0) {+ if (m_undoCount == 0 && undo) {undo->setRedoData(m_stroke, m_strokeTemp, m_startPoint, m_endPoint,m_centralPoint, m_clickNumber);TUndoManager::manager()->add(undo);++m_undoCount;+ undo = nullptr; // Transfer ownership to undo manager}}@@ -3157,13 +3171,15 @@ void MultiArcPrimitive::mouseMove(const TPointD &pos, const TMouseEvent &e) {assert(q01.getP2() == q10.getP0());assert(q10.getP2() == q11.getP0());- m_strokeTemp->setControlPoint(1, q00.getP1());- m_strokeTemp->setControlPoint(2, q00.getP2());- m_strokeTemp->setControlPoint(3, q01.getP1());- m_strokeTemp->setControlPoint(4, q01.getP2());- m_strokeTemp->setControlPoint(5, q10.getP1());- m_strokeTemp->setControlPoint(6, q10.getP2());- m_strokeTemp->setControlPoint(7, q11.getP1());+ if (m_strokeTemp) {+ m_strokeTemp->setControlPoint(1, q00.getP1());+ m_strokeTemp->setControlPoint(2, q00.getP2());+ m_strokeTemp->setControlPoint(3, q01.getP1());+ m_strokeTemp->setControlPoint(4, q01.getP2());+ m_strokeTemp->setControlPoint(5, q10.getP1());+ m_strokeTemp->setControlPoint(6, q10.getP2());+ m_strokeTemp->setControlPoint(7, q11.getP1());+ }break;}m_tool->invalidate();@@ -3292,7 +3308,11 @@ TStroke *PolygonPrimitive::makeStroke() const {}stroke = new TStroke(points);}- stroke->setSelfLoop();++ // check if stroke is not null+ if (stroke) {+ stroke->setSelfLoop();+ }return stroke;}@@ -3320,13 +3340,11 @@ FullColorGeometricToolNotifier::FullColorGeometricToolNotifier(: m_tool(tool) {if (TTool::Application *app = m_tool->getApplication()) {if (TPaletteHandle *paletteHandle = app->getCurrentPalette()) {- bool ret;- ret = connect(paletteHandle, SIGNAL(colorStyleChanged(bool)), this,- SLOT(onColorStyleChanged()));- assert(ret);- ret = connect(paletteHandle, SIGNAL(colorStyleSwitched()), this,- SLOT(onColorStyleChanged()));- assert(ret);+ connect(paletteHandle, &TPaletteHandle::colorStyleChanged, this,+ [this](bool) { onColorStyleChanged(); });++ connect(paletteHandle, &TPaletteHandle::colorStyleSwitched, this,+ &FullColorGeometricToolNotifier::onColorStyleChanged);}}}diff --git a/toonz/sources/tnztools/geometrictool.h b/toonz/sources/tnztools/geometrictool.hindex c39c7d22d..135f22fbc 100644--- a/toonz/sources/tnztools/geometrictool.h+++ b/toonz/sources/tnztools/geometrictool.h@@ -9,15 +9,22 @@#include "tools/cursors.h"#include "mypainttoonzbrush.h"#include "trasterimage.h"-#include <QObject>+#include "trastercm.h"// For Qt translation support#include <QCoreApplication>+#include <map>+#include <memory>class Primitive;class FullColorGeometricToolNotifier;class TTileSaverFullColor;class TTileSaverCM32;+class TStroke;+class TVectorImage;+class TToonzImage;+class TXshSimpleLevel;+class TFrameId;//-----------------------------------------------------------------------------@@ -60,6 +67,7 @@ public:void updateTranslation();};+//=============================================================================// Geometric Tool//-----------------------------------------------------------------------------@@ -146,4 +154,4 @@ protected slots:void onColorStyleChanged() { m_tool->onColorStyleChanged(); }};-#endif\ No newline at end of file+#endifdiff --git a/toonz/sources/tnztools/hookselection.cpp b/toonz/sources/tnztools/hookselection.cppindex 8c9e2781d..1b4619c7a 100644--- a/toonz/sources/tnztools/hookselection.cpp+++ b/toonz/sources/tnztools/hookselection.cpp@@ -221,12 +221,13 @@ void HookSelection::deleteSelectedHooks() {TTool::Application *app = TTool::getApplication();TTool *tool = app->getCurrentTool()->getTool();if (!app) return;- TXshLevel *xl = app->getCurrentLevel()->getLevel();- HookSet *hookSet = xl->getHookSet();- if (!xl || !xl->getSimpleLevel() || !hookSet ||- xl->getSimpleLevel()->isReadOnly())+ TXshLevel *xl = app->getCurrentLevel()->getLevel();+ if (!xl || !xl->getSimpleLevel() || xl->getSimpleLevel()->isReadOnly())return;+ HookSet *hookSet = xl->getHookSet();+ if (!hookSet) return;+HookUndo *undo = new HookUndo(xl->getSimpleLevel());TFrameId fid = tool->getCurrentFid();@@ -266,20 +267,30 @@ void HookSelection::copySelectedHooks() {void HookSelection::cutSelectedHooks() {copySelectedHooks();- TXshLevel *xl = TTool::getApplication()->getCurrentLevel()->getLevel();- TUndo *undo = new HookUndo(xl);+ TTool::Application *app = TTool::getApplication();+ if (!app) return;++ TXshLevel *xl = app->getCurrentLevel()->getLevel();+ if (!xl) return;+HookSet *hookSet = xl->getHookSet();+ if (!hookSet) return;++ TUndo *undo = new HookUndo(xl);std::set<std::pair<int, int>>::iterator it;- for (it = m_hooks.begin(); it != m_hooks.end(); it++) {++ for (it = m_hooks.begin(); it != m_hooks.end(); ++it) {Hook *hook = hookSet->getHook(it->first);- assert(hook);- if (!hook) return;- TFrameId fid =- TTool::getApplication()->getCurrentTool()->getTool()->getCurrentFid();+ if (!hook) {+ // Delete the undo object if a hook is null to prevent memory leak+ delete undo;+ return;+ }+ TFrameId fid = app->getCurrentTool()->getTool()->getCurrentFid();hook->eraseFrame(fid);}TUndoManager::manager()->add(undo);- TTool::getApplication()->getCurrentTool()->getTool()->invalidate();+ app->getCurrentTool()->getTool()->invalidate();}//---------------------------------------------------------------------------@@ -288,9 +299,28 @@ void HookSelection::pasteSelectedHooks() {const QMimeData *data = QApplication::clipboard()->mimeData();const HooksData *hooksData = dynamic_cast<const HooksData *>(data);if (!hooksData) return;- TXshLevel *xl = TTool::getApplication()->getCurrentLevel()->getLevel();- TUndo *undo = new HookUndo(xl);++ TTool::Application *app = TTool::getApplication();+ if (!app) return;++ TXshLevel *xl = app->getCurrentLevel()->getLevel();+ if (!xl) return;++ // Check if hooks can be restored before creating undo+ TXshLevelP level = app->getCurrentLevel()->getLevel();+ if (!level || level->getSimpleLevel()->isReadOnly()) return;++ HookSet *hookSet = level->getHookSet();+ if (!hookSet) return;++ // Check if there are hooks to restore using the public method+ if (!hooksData->hasStoredHooks()) {+ return; // Nothing to restore+ }++ TUndo *undo = new HookUndo(xl);+hooksData->restoreHookPositions();TUndoManager::manager()->add(undo);- TTool::getApplication()->getCurrentTool()->getTool()->invalidate();+ app->getCurrentTool()->getTool()->invalidate();}diff --git a/toonz/sources/tnztools/hookselection.h b/toonz/sources/tnztools/hookselection.hindex beb0ee54d..d077635b7 100644--- a/toonz/sources/tnztools/hookselection.h+++ b/toonz/sources/tnztools/hookselection.h@@ -55,6 +55,9 @@ public:HooksData *clone() const override;void storeHookPositions(const std::vector<int> &ids);void restoreHookPositions() const;++ // Public method to check if there are stored hook positions+ bool hasStoredHooks() const { return !m_hookPositions.empty(); }};//=============================================================================diff --git a/toonz/sources/tnztools/rastererasertool.cpp b/toonz/sources/tnztools/rastererasertool.cppindex 8ffaec4b6..d778ba7c0 100644--- a/toonz/sources/tnztools/rastererasertool.cpp+++ b/toonz/sources/tnztools/rastererasertool.cpp@@ -75,12 +75,11 @@ TEnv::IntVar ErasePencil("InknpaintErasePencil", 0);namespace {//==============================================================================-// Undo dei Tools+// Tools Undo Classes//==============================================================================/*!- Viene realizzata la funzione di "UNDO" per il cancellino nell'opzione- RECTERASE+ "UNDO" function for the eraser in RECTERASE option*/class RectRasterUndo final : public TRasterUndo {@@ -149,8 +148,7 @@ public://=====================================================================/*!- Viene realizzata la funzione di "UNDO" per il cancellino nell'opzione- NORMALERAS+ "UNDO" function for the eraser in NORMALERASE option*/class RasterEraserUndo final : public TRasterUndo {std::vector<TThickPoint> m_points;@@ -284,7 +282,7 @@ void eraseStroke(const TToonzImageP &ti, TStroke *stroke,if (!invert)area = rasterErasedArea.enlarge(2);else- area = ras->getBounds();+ area = ras->getBounds();TTileSetCM32 *tileSet = new TTileSetCM32(ras->getSize());tileSet->add(ras, area);TUndoManager::manager()->add(new RectRasterUndo(@@ -418,7 +416,7 @@ void drawEmptyCircle(int thick, const TPointD &mousePos, bool isPencil,if (isLxEven) pos.x += 0.5;if (isLyEven) pos.y += 0.5;if (!isPencil)- tglDrawCircle(pos, (thick)*0.5);+ tglDrawCircle(pos, (thick) * 0.5);else {int x = 0, y = tround((thick * 0.5) - 0.5);int d = 3 - 2 * (int)(thick * 0.5);@@ -493,15 +491,15 @@ public:int getCursorId() const override;void resetMulti();- /*-- ドラッグ中にツールが切り替わった場合、処理を終了させる--*/+ /*-- If the tool is switched while dragging, finish the operation --*/void onDeactivate() override;- /*-- Brush、PaintBrush、EraserToolがPencilModeのときにTrueを返す --*/+ /*-- Returns True when Brush, PaintBrush, or EraserTool is in PencilMode --*/bool isPencilModeActive() override;TPointD getCenteredCursorPos(const TPointD &originalCursorPos);TPointD fixMousePos(TPointD pos, bool precise = false);private:- /*-- 終了処理 --*/+ /*-- Finalization process --*/void storeUndoAndRefresh();enum Type { NONE = 0, BRUSH, INKCHANGE, ERASER };@@ -542,7 +540,7 @@ private:std::vector<TPointD> m_polyline;- // gestione cancellino blurato+ // Blurred eraser managementTRasterCM32P m_backupRas;TRaster32P m_workRas;QRadialGradient m_brushPad;@@ -554,13 +552,11 @@ private:bool m_isXsheetCell, m_active, m_enabled, m_selecting, m_firstFrameSelected,m_firstTime;- /*--- 消しゴム開始時のFrameIdを保存し、マウスリリース時(Undoの登録時)に- 別のフレームに移動していた場合に備える- ---*/+ /*--- Store the FrameId when erasing starts, and use it for Undo registration+ in case the frame has moved during mouse release ---*/TFrameId m_workingFrameId;- /*--- マウスボタンDown→プロパティ変更→マウスボタンUpのように、- ボタンDownからUpまでストレートに来なかった場合は処理を行わないようにする。- ---*/+ /*--- If mouse button Down → property change → mouse button Up occurs,+ do not process since the Down to Up sequence wasn't straight ---*/bool m_isLeftButtonPressed;};@@ -583,8 +579,10 @@ EraserTool::EraserTool(std::string name), m_multi("Frame Range", false) // W_ToolOptions_FrameRange, m_pencil("Pencil Mode", false), m_currCell(-1, -1)- , m_tileSaver(0)- , m_bluredBrush(0)+ , m_tileSaver(nullptr)+ , m_bluredBrush(nullptr)+ , m_normalEraser(nullptr)+ , m_firstStroke(nullptr), m_pointSize(-1), m_thick(0.5), m_firstFrameSelected(false)@@ -681,7 +679,7 @@ TPointD EraserTool::fixMousePos(TPointD pos, bool precise) {//------------------------------------------------------------------------void EraserTool::draw() {- /*-- MouseLeave時に赤点が描かれるのを防ぐ --*/+ /*-- Prevent red dot from being drawn during MouseLeave --*/if (m_pointSize == -1 && m_cleanerSize == 0) return;double pixelSize2 = getPixelSize() * getPixelSize();@@ -707,8 +705,8 @@ void EraserTool::draw() {int lx = ras->getLx();int ly = ras->getLy();- /*-- InkCheck, PaintCheck, Ink#1CheckがONのときは、BrushTipの描画色を変える- * --*/+ /*-- Change brush tip drawing color when InkCheck, PaintCheck, or Ink#1Check+ * is ON --*/if ((ToonzCheck::instance()->getChecks() & ToonzCheck::eInk) ||(ToonzCheck::instance()->getChecks() & ToonzCheck::ePaint) ||(ToonzCheck::instance()->getChecks() & ToonzCheck::eInk1))@@ -781,12 +779,12 @@ void EraserTool::resetMulti() {m_selectingRect.empty();TTool::Application *app = TTool::getApplication();m_level = app->getCurrentLevel()->getLevel()- ? app->getCurrentLevel()->getSimpleLevel()- : 0;+ ? app->getCurrentLevel()->getSimpleLevel()+ : 0;m_firstFrameId = m_veryFirstFrameId = getFrameId();if (m_firstStroke) {delete m_firstStroke;- m_firstStroke = 0;+ m_firstStroke = nullptr;}}@@ -804,7 +802,7 @@ void EraserTool::multiUpdate(const TXshSimpleLevelP &level, TFrameId firstFid,std::vector<TFrameId> allFids;level->getFids(allFids);- /*-- フレーム範囲に対応するFIdを取得 --*/+ /*-- Get FIds corresponding to the frame range --*/std::vector<TFrameId>::iterator i0 = allFids.begin();while (i0 != allFids.end() && *i0 < firstFid) i0++;if (i0 == allFids.end()) return;@@ -817,16 +815,16 @@ void EraserTool::multiUpdate(const TXshSimpleLevelP &level, TFrameId firstFid,std::wstring levelName = level->getName();- /*-- FrameRangeの各フレームについて --*/+ /*-- For each frame in the FrameRange --*/TUndoManager::manager()->beginBlock();for (int i = 0; i < m; ++i) {TFrameId fid = fids[i];assert(firstFid <= fid && fid <= lastFid);TToonzImageP ti = level->getFrame(fid, true);if (!ti) continue;- /*--補間の係数を取得 --*/+ /*-- Get interpolation coefficient --*/double t = m > 1 ? (double)i / (double)(m - 1) : 0.5;- /*--invertがONのとき、外側領域を4つのRectに分けてupdate--*/+ /*-- When invert is ON, divide the outer area into 4 Rects and update --*/if (m_invertOption.getValue()) {TRect rect =convert(interpolateRect(firstRect, lastRect, backward ? 1 - t : t));@@ -915,7 +913,8 @@ void EraserTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {TRasterCM32P raster = ti->getRaster();TPointD fixedPos = fixMousePos(pos);TThickPoint intPos;- /*--Areasタイプの時は常にPencilと同じ消し方にする--*/+ /*-- When Areas type is selected, always use the same erasing method as+ * Pencil --*/if (m_pencil.getValue() || m_colorType.getValue() == AREAS)intPos = TThickPoint(fixedPos + convert(raster->getCenter()),m_toolSize.getValue());@@ -925,8 +924,8 @@ void EraserTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {int currentStyle = 0;if (m_currentStyle.getValue())currentStyle = TTool::getApplication()->getCurrentLevelStyleIndex();- m_tileSet = new TTileSetCM32(raster->getSize());- m_tileSaver = new TTileSaverCM32(raster, m_tileSet);+ m_tileSet = new TTileSetCM32(raster->getSize());+ m_tileSaver = new TTileSaverCM32(raster, m_tileSet);TPointD halfThick(m_toolSize.getValue() * 0.5,m_toolSize.getValue() * 0.5);invalidateRect = TRectD(fixedPos - halfThick, fixedPos + halfThick);@@ -936,7 +935,7 @@ void EraserTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {m_colorTypeEraser = INK;}if (m_colorType.getValue() == AREAS) m_colorTypeEraser = PAINT;- if (m_colorType.getValue() == ALL) m_colorTypeEraser = INKNPAINT;+ if (m_colorType.getValue() == ALL) m_colorTypeEraser = INKNPAINT;m_normalEraser = new RasterStrokeGenerator(raster, ERASE, m_colorTypeEraser, 0, intPos,m_currentStyle.getValue(), currentStyle, false,@@ -962,7 +961,7 @@ void EraserTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {m_currentStyle.getValue(), currentStyle,m_colorType.getValue());}- /*--- 現在のFidを記憶する ---*/+ /*--- Store the current Fid ---*/m_workingFrameId = getFrameId();}if (m_eraseType.getValue() == FREEHANDERASE ||@@ -975,7 +974,7 @@ void EraserTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {if (m_multi.getValue() && m_firstStroke && !m_firstFrameSelected) {invalidateRect = m_firstStroke->getBBox();delete m_firstStroke;- m_firstStroke = 0;+ m_firstStroke = nullptr;invalidate(invalidateRect.enlarge(2));}@@ -1002,7 +1001,7 @@ void EraserTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {//----------------------------------------------------------------------void EraserTool::leftButtonDrag(const TPointD &pos, const TMouseEvent &e) {- /*-- 先にLeftButtonDownに入っていなければreturn --*/+ /*-- Return if LeftButtonDown wasn't entered first --*/if (!m_isLeftButtonPressed) return;double pixelSize2 = getPixelSize() * getPixelSize();@@ -1082,7 +1081,7 @@ void EraserTool::leftButtonDrag(const TPointD &pos, const TMouseEvent &e) {TRect bbox;int m = (int)m_points.size();if (m == 3) {- // ho appena cominciato. devo disegnare un segmento+ // Just started. Need to draw a segmentTThickPoint pa = m_points.front();std::vector<TThickPoint> points;points.push_back(pa);@@ -1127,10 +1126,9 @@ void EraserTool::onImageChanged() {(m_selectingRect.isEmpty() && !m_firstStroke))resetMulti();else if (m_firstFrameId == getFrameId())- m_firstFrameSelected = false; // nel caso sono passato allo stato 1 e torno- // all'immagine iniziale, torno allo stato- // iniziale- else { // cambio stato.+ m_firstFrameSelected = false; // If we move to state 1 and return to the+ // initial image, return to initial state+ else { // Change state.m_firstFrameSelected = true;if (m_eraseType.getValue() != FREEHANDERASE &&m_eraseType.getValue() != POLYLINEERASE) {@@ -1143,7 +1141,7 @@ void EraserTool::onImageChanged() {//----------------------------------------------------------------------void EraserTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {- /*--先にLeftButtonDownに入っていなければ処理をしない--*/+ /*-- Do not process if LeftButtonDown wasn't entered first --*/if (!m_isLeftButtonPressed) return;m_isLeftButtonPressed = false;@@ -1225,7 +1223,8 @@ void EraserTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {TXshLevel *level = app->getCurrentLevel()->getLevel();TXshSimpleLevelP simLevel = level->getSimpleLevel();- /*--Erase中にフレームが動いても、クリック時のFidに対してUndoを記録する--*/+ /*-- Record Undo for the Fid at click time, even if the frame moved during+ * erasing --*/TFrameId frameId =m_workingFrameId.isEmptyFrame() ? getCurrentFid() : m_workingFrameId;@@ -1240,7 +1239,7 @@ void EraserTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {app->getCurrentTool()->getTool()->notifyImageChanged(frameId);app->getCurrentXsheet()->notifyXsheetChanged();delete m_normalEraser;- m_normalEraser = 0;+ m_normalEraser = nullptr;} else {if (m_points.size() != 1) {TPointD rasCenter = ti->getRaster()->getCenterD();@@ -1265,17 +1264,17 @@ void EraserTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {m_backupRas = TRasterCM32P();m_workRas = TRaster32P();delete m_bluredBrush;- m_bluredBrush = 0;+ m_bluredBrush = nullptr;TUndoManager::manager()->add(new RasterBluredEraserUndo(m_tileSet, m_points, currentStyle, m_currentStyle.getValue(),simLevel.getPointer(), frameId, m_toolSize.getValue(),m_hardness.getValue() * 0.01, m_colorType.getValue()));}delete m_tileSaver;- m_tileSaver = 0;- /*-- 作業したフレームをシグナルで知らせる --*/+ m_tileSaver = nullptr;+ /*-- Signal the processed frame --*/notifyImageChanged(frameId);- /*-- 作業フレームをリセット --*/+ /*-- Reset working frame --*/m_workingFrameId = TFrameId();}if (m_eraseType.getValue() == FREEHANDERASE) {@@ -1303,10 +1302,13 @@ void EraserTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {stroke);notifyImageChanged();if (e.isShiftPressed()) {- TRectD invalidateRect = m_firstStroke->getBBox();- delete m_firstStroke;- m_firstStroke = 0;- invalidate(invalidateRect.enlarge(2));+ TRectD invalidateRect;+ if (m_firstStroke) {+ invalidateRect = m_firstStroke->getBBox();+ delete m_firstStroke;+ m_firstStroke = nullptr;+ invalidate(invalidateRect.enlarge(2));+ }m_firstStroke = stroke;invalidateRect = m_firstStroke->getBBox();invalidate(invalidateRect.enlarge(2));@@ -1320,7 +1322,7 @@ void EraserTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {resetMulti();delete stroke;}- } else // primo frame+ } else // first frame{m_firstStroke = stroke;m_isXsheetCell = app->getCurrentFrame()->isEditingScene();@@ -1329,7 +1331,11 @@ void EraserTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {}} else // stroke non multi{- if (!getImage(true)) return;+ // Check image before processing to avoid memory leak+ if (!getImage(true)) {+ delete stroke;+ return;+ }TXshLevel *level = app->getCurrentLevel()->getLevel();TXshSimpleLevelP simLevel = level->getSimpleLevel();TFrameId frameId = getFrameId();@@ -1383,10 +1389,13 @@ void EraserTool::leftButtonDoubleClick(const TPointD &pos,if (m_firstStroke && stroke)multiAreaEraser(m_level, m_firstFrameId, tmp, m_firstStroke, stroke);if (e.isShiftPressed()) {- TRectD invalidateRect = m_firstStroke->getBBox();- delete m_firstStroke;- m_firstStroke = 0;- invalidate(invalidateRect.enlarge(2));+ TRectD invalidateRect;+ if (m_firstStroke) {+ invalidateRect = m_firstStroke->getBBox();+ delete m_firstStroke;+ m_firstStroke = nullptr;+ invalidate(invalidateRect.enlarge(2));+ }m_firstStroke = stroke;invalidateRect = m_firstStroke->getBBox();invalidate(invalidateRect.enlarge(2));@@ -1400,7 +1409,7 @@ void EraserTool::leftButtonDoubleClick(const TPointD &pos,resetMulti();delete stroke;}- } else // primo frame+ } else // first frame{m_firstStroke = stroke;m_isXsheetCell = app->getCurrentFrame()->isEditingScene();@@ -1408,7 +1417,11 @@ void EraserTool::leftButtonDoubleClick(const TPointD &pos,invalidate(m_firstStroke->getBBox().enlarge(2));}} else {- if (!getImage(true)) return;+ // Check image before processing to avoid memory leak+ if (!getImage(true)) {+ delete stroke;+ return;+ }TXshLevel *level = app->getCurrentLevel()->getLevel();TXshSimpleLevelP simLevel = level->getSimpleLevel();TFrameId frameId = getFrameId();@@ -1427,9 +1440,9 @@ void EraserTool::leftButtonDoubleClick(const TPointD &pos,//----------------------------------------------------------------------bool EraserTool::onPropertyChanged(std::string propertyName) {- /*--- 変更されたPropertyに合わせて処理を分ける ---*/+ /*--- Process according to the changed Property ---*/if (propertyName == m_eraseType.getName()) {- /*--- polylineにした時、前回のpolyline選択をクリアする ---*/+ /*--- When switched to polyline, clear previous polyline selection ---*/if (m_eraseType.getValue() == POLYLINEERASE && !m_polyline.empty())m_polyline.clear();EraseType = ::to_string(m_eraseType.getValue());@@ -1460,14 +1473,14 @@ bool EraserTool::onPropertyChanged(std::string propertyName) {else if (propertyName == m_colorType.getName()) {EraseColorType = ::to_string(m_colorType.getValue());- /*-- ColorModelのCursor更新のためにSIGNALを出す --*/+ /*-- Emit SIGNAL for Cursor update in ColorModel --*/TTool::getApplication()->getCurrentTool()->notifyToolChanged();}else if (propertyName == m_hardness.getName()) {EraseHardness = m_hardness.getValue();m_brushPad = ToolUtils::getBrushPad(m_toolSize.getValue(),- m_hardness.getValue() * 0.01);+ m_hardness.getValue() * 0.01);}if (propertyName == m_hardness.getName() ||@@ -1479,7 +1492,7 @@ bool EraserTool::onPropertyChanged(std::string propertyName) {invalidate(rect);}- /*--- Erase動作中にプロパティが変わったら、終了処理を行う ---*/+ /*--- If property changes during erasing, perform finalization ---*/if (m_isLeftButtonPressed) {storeUndoAndRefresh();}@@ -1560,8 +1573,8 @@ void EraserTool::onEnter() {m_cleanerSize = m_toolSize.getValue();TTool::Application *app = TTool::getApplication();m_level = app->getCurrentLevel()->getLevel()- ? app->getCurrentLevel()->getSimpleLevel()- : 0;+ ? app->getCurrentLevel()->getSimpleLevel()+ : 0;}//----------------------------------------------------------------------@@ -1576,7 +1589,8 @@ void EraserTool::onLeave() {void EraserTool::onActivate() {if (m_multi.getValue()) resetMulti();- /*-- 他のツールからpolylineに入った時、前回のpolyline選択をクリアする --*/+ /*-- When entering polyline from another tool, clear previous polyline+ * selection --*/if (m_eraseType.getValue() == POLYLINEERASE && !m_polyline.empty())m_polyline.clear();@@ -1661,7 +1675,7 @@ void EraserTool::doMultiEraser(const TImageP &img, double t,}//---------------------------------------------------------------------------------------------------/*!ドラッグ中にツールが切り替わった時、終了処理を行う+/*! When the tool is switched while dragging, finish the operation*/void EraserTool::onDeactivate() {@@ -1671,14 +1685,14 @@ void EraserTool::onDeactivate() {}//---------------------------------------------------------------------------------------------------/*-- Erase終了処理 --*/+/*-- Erase finalization --*/void EraserTool::storeUndoAndRefresh() {m_isLeftButtonPressed = false;- /*-- 各データのリフレッシュ --*/+ /*-- Refresh each data --*/if (m_firstStroke) {delete m_firstStroke;- m_firstStroke = 0;+ m_firstStroke = nullptr;}if (m_normalEraser) {TUndoManager::manager()->add(new RasterEraserUndo(@@ -1692,27 +1706,28 @@ void EraserTool::storeUndoAndRefresh() {m_workingFrameId.isEmptyFrame() ? getCurrentFid() : m_workingFrameId,(m_pencil.getValue() || m_colorType.getValue() == AREAS)));delete m_normalEraser;- m_normalEraser = 0;+ m_normalEraser = nullptr;}if (m_bluredBrush) {m_backupRas = TRasterCM32P();m_workRas = TRaster32P();delete m_bluredBrush;- m_bluredBrush = 0;+ m_bluredBrush = nullptr;TUndoManager::manager()->add(new RasterBluredEraserUndo(m_tileSet, m_points,TTool::getApplication()->getCurrentLevelStyleIndex(),- m_currentStyle.getValue(), TTool::getApplication()- ->getCurrentLevel()- ->getLevel()- ->getSimpleLevel(),+ m_currentStyle.getValue(),+ TTool::getApplication()+ ->getCurrentLevel()+ ->getLevel()+ ->getSimpleLevel(),m_workingFrameId.isEmptyFrame() ? getCurrentFid() : m_workingFrameId,m_toolSize.getValue(), m_hardness.getValue() * 0.01,m_colorType.getValue()));}if (m_tileSaver) {delete m_tileSaver;- m_tileSaver = 0;+ m_tileSaver = nullptr;}TRectD invalidateRect;@@ -1730,7 +1745,7 @@ void EraserTool::storeUndoAndRefresh() {}//---------------------------------------------------------------------------------------------------/*! Brush、PaintBrush、EraserToolがPencilModeのときにTrueを返す+/*! Returns True when Brush, PaintBrush, or EraserTool is in PencilMode*/bool EraserTool::isPencilModeActive() {return m_eraseType.getValue() == NORMALERASE && m_pencil.getValue();diff --git a/toonz/sources/tnztools/trackertool.cpp b/toonz/sources/tnztools/trackertool.cppindex 8a379354b..5ff8f882e 100644--- a/toonz/sources/tnztools/trackertool.cpp+++ b/toonz/sources/tnztools/trackertool.cpp@@ -45,7 +45,7 @@ namespace {//=============================================================================// TrackerRegionSelection//------------------------------------------------------------------------------// Ancora da definire.+// Still to be defined.// under constructionclass TrackerRegionSelection final : public TSelection {TXshLevelP m_level;@@ -54,7 +54,7 @@ class TrackerRegionSelection final : public TSelection {TrackerTool *m_tool;public:- TrackerRegionSelection() : m_tool(0) {}+ TrackerRegionSelection() : m_tool(nullptr) {}void setTool(TrackerTool *tool) { m_tool = tool; }@@ -85,7 +85,7 @@ public:HookSet *getHookSet() const {TXshLevel *xl = TTool::getApplication()->getCurrentLevel()->getLevel();// TXshLevel *xl = m_level.getPointer();- if (!xl) return 0;+ if (!xl) return nullptr;return xl->getHookSet();}@@ -112,7 +112,7 @@ hook->setAPos(fid, hook->getBPos(fid));}makeCurrent();return TDataP(); */- return (NULL);+ return TDataP();}TDataP pasteData(const TDataP &data) { return TDataP(); }@@ -148,9 +148,8 @@ class TrackerTool final : public TTool {int m_hookSelectedIndex;int m_lastHookSelectedIndex;bool m_deselectArmed;- bool m_newObjectAdded; // serve al buttonUp per sapere se l'ultima tracker- // region- // aggiunta è un oggetto nuovo oppure no+ bool m_newObjectAdded; // used in buttonUp to know if the last tracker region+ // added is a new object or notTPropertyGroup m_prop;TDoubleProperty m_toolSizeWidth;@@ -162,7 +161,7 @@ class TrackerTool final : public TTool {bool m_buttonDown;bool m_dragged;bool m_picked;- TPointD m_pos; // posizione del mouse+ TPointD m_pos; // mouse positionTPointD m_oldPos;int m_what;@@ -262,12 +261,13 @@ void TrackerTool::updateTranslation() {TrackerObjectsSet *TrackerTool::getTrackerObjectsSet() const {HookSet *hookSet = getHookSet();- if (!hookSet) return 0;+ if (!hookSet) return nullptr;return hookSet->getTrackerObjectsSet();}+HookSet *TrackerTool::getHookSet() const {TXshLevel *xl = TTool::getApplication()->getCurrentLevel()->getLevel();- if (!xl) return 0;+ if (!xl) return nullptr;return xl->getHookSet();}@@ -285,8 +285,8 @@ void TrackerTool::draw() {hookSet->getHook(m_hookSelectedIndex)->getTrackerObjectId();elseselectedObjectId = -1;- int i = 0;- double pixelSize = getPixelSize();+ int i = 0;+ double pixelSize = getPixelSize();std::vector<TRectD> balloons; // this is used to avoid balloons overlapping// draw hooks@@ -294,7 +294,7 @@ void TrackerTool::draw() {Hook *hook = hookSet->getHook(i);if (!hook || hook->isEmpty()) continue;assert(hook);- // Se l'Hook ha una TrackerRegion allora la disegno+ // If the Hook has a TrackerRegion then draw itif (hook->getTrackerObjectId() >= 0) {TRectD rect;rect = hook->getTrackerRegion(fid);@@ -305,11 +305,11 @@ void TrackerTool::draw() {if (m_hookSelectedIndex == i) {TPixel32 frameColor(127, 127, 127);drawSquare(0.5 * (rect.getP01() + rect.getP11()), pixelSize * 4,- frameColor); // scalaY+ frameColor); // scaleYdrawSquare(0.5 * (rect.getP11() + rect.getP10()), pixelSize * 4,- frameColor); // scalaX- drawSquare(rect.getP00(), pixelSize * 4, frameColor); // scala- drawSquare(rect.getP10(), pixelSize * 4, frameColor); // ridimensiona+ frameColor); // scaleX+ drawSquare(rect.getP00(), pixelSize * 4, frameColor); // scale+ drawSquare(rect.getP10(), pixelSize * 4, frameColor); // resizetrackerObjectColor = TPixel32(183, 227, 0);textColor = TPixel32(155, 213, 219);} else {@@ -365,14 +365,14 @@ bool TrackerTool::pick(int &hookIndex, const TPointD &pos) {Hook *hook = hookSet->getHook(i);if (!hook || hook->isEmpty()) continue;int trackerObjectId = hook->getTrackerObjectId();- if (trackerObjectId < 0) // se non è una trackeRregion+ if (trackerObjectId < 0) // if it's not a tracker region{TPointD hookPos = hook->getPos(fid);TRectD overArea =TRectD(hookPos.x - 20 * pixelSize, hookPos.y - 20 * pixelSize,hookPos.x + 20 * pixelSize, hookPos.y + 20 * pixelSize);if (overArea.contains(pos)) {- hookIndex = i; // setto l'indice dell'hook+ hookIndex = i; // set the hook indexm_what = NormalHook;return true;}@@ -393,7 +393,7 @@ bool TrackerTool::pick(int &hookIndex, const TPointD &pos) {TRectD overArea = TRectD(rect.getP00().x - 4 * pixelSize, rect.getP00().y - 4 * pixelSize,rect.getP11().x + 4 * pixelSize, rect.getP11().y + 4 * pixelSize);- // se pos è all'interno del'area sensibile del rettangolo+ // if pos is inside the sensitive area of the rectangleif (overArea.contains(pos)) {if (distance < minDistance || minDistance == -1) {minDistance = distance;@@ -403,15 +403,15 @@ bool TrackerTool::pick(int &hookIndex, const TPointD &pos) {// scale Y Areadouble x =- 0.5 * (rect.getP01().x + rect.getP11().x); // ascissa punto medio+ 0.5 * (rect.getP01().x + rect.getP11().x); // midpoint abscissaTPointD my = TPointD(x, rect.getP11().y);TRectD scaleYArea =TRectD(my.x - 4 * pixelSize, my.y - 4 * pixelSize,my.x + 4 * pixelSize, my.y + 4 * pixelSize);if (scaleYArea.contains(pos)) m_what = PM1;// scale X Area- double y = 0.5 * (rect.getP11().y +- rect.getP10().y); // ordinata punto medio+ double y =+ 0.5 * (rect.getP11().y + rect.getP10().y); // midpoint ordinateTPointD mx = TPointD(rect.getP10().x, y);TRectD scaleXArea =TRectD(mx.x - 4 * pixelSize, mx.y - 4 * pixelSize,@@ -439,11 +439,19 @@ bool TrackerTool::pick(int &hookIndex, const TPointD &pos) {//-----------------------------------------------------------------------------void TrackerTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {- m_buttonDown = true;- m_picked = true;- TXshLevel *xl = TTool::getApplication()->getCurrentLevel()->getLevel();- if (!xl) return;- m_selection.setLevel(xl);+ m_buttonDown = true;+ m_picked = true;+ // Get level as smart pointer to prevent use-after-free+ TXshLevelP level = TTool::getApplication()->getCurrentLevel()->getLevel();+ if (!level) return;++ // Store the level in selection - this keeps a reference+ m_selection.setLevel(level);++ // Get raw pointer for local use (safe because level is kept alive by the+ // smart pointer)+ TXshLevel *xl = level.getPointer();+m_firstPos = m_lastPos = pos;m_deselectArmed = false;@@ -451,6 +459,7 @@ void TrackerTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {m_oldPos = pos;double pixelSize = getPixelSize();+ // Now get hookSet using the level (safe because level is alive)HookSet *hookSet = xl->getHookSet();if (!hookSet) return;TrackerObjectsSet *trackerObjectsSet = getTrackerObjectsSet();@@ -480,36 +489,35 @@ void TrackerTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {TFrameId fid = getCurrentFid();m_what = P10;- // Se non è selezionato alcun oggetto allora aggiungo un nuovo oggetto e a- // questo- // aggiungo una trackerRegion+ // If no object is selected then add a new object and+ // add a trackerRegion to itint trackerObjectId;if (m_hookSelectedIndex == -1 ||- hookSet->getHook(m_hookSelectedIndex) == 0) {+ hookSet->getHook(m_hookSelectedIndex) == nullptr) {trackerObjectId = trackerObjectsSet->addObject();m_newObjectAdded = true;} elsetrackerObjectId =hookSet->getHook(m_hookSelectedIndex)->getTrackerObjectId();- // se l'oggetto selezionato è un semplice Hook (senza region)- // allora creo un nuovo hook con region+ // if the selected object is a simple Hook (without region)+ // then create a new hook with regionif (trackerObjectId == -1) {trackerObjectId = trackerObjectsSet->addObject();m_newObjectAdded = true;}- // aggiungo un Hook all'oggetto selezionato+ // add a Hook to the selected objectHook *newHook = hookSet->addHook();if (newHook) {newHook->setTrackerObjectId(trackerObjectId);newHook->setAPos(fid, pos);newHook->setTrackerRegionHeight(pixelSize * 10);newHook->setTrackerRegionWidth(pixelSize * 10);- // setto l'indice della trackerRegion corrente+ // set the current trackerRegion indexm_hookSelectedIndex = newHook->getId(); // hookSet->getHookCount()-1;} else {if (hookSet->getHookCount() >= 20)- QMessageBox::warning(0, "TrackerTool Error",+ QMessageBox::warning(nullptr, "TrackerTool Error","Hooks number must be at most 20");m_hookSelectedIndex = -1;}@@ -527,24 +535,25 @@ void TrackerTool::leftButtonDrag(const TPointD &pp, const TMouseEvent &e) {if (m_hookSelectedIndex < 0 && m_what != NormalHook) return;HookSet *hookSet = getHookSet();if (!hookSet) return;- assert(hookSet->getHook(m_hookSelectedIndex) != 0);+ assert(hookSet->getHook(m_hookSelectedIndex) != nullptr);TrackerObjectsSet *trackerObjectsSet = getTrackerObjectsSet();TFrameId fid = getCurrentFid();if (!trackerObjectsSet) return;- if (m_dragged == false) {+ if (!m_dragged) {m_dragged = true;}TXshLevel *xl = TTool::getApplication()->getCurrentLevel()->getLevel();- if (xl->getSimpleLevel() && xl->getSimpleLevel()->isReadOnly() &&+ if (xl && xl->getSimpleLevel() && xl->getSimpleLevel()->isReadOnly() &&m_what != Inside && m_what != NormalHook)return;- if (m_dragged == true) {- Hook *hook = new Hook();- hook = getHookSet()->getHook(m_hookSelectedIndex);+ if (m_dragged) {+ // Get existing hook - don't create a new one!+ Hook *hook = hookSet->getHook(m_hookSelectedIndex);if (!hook || hook->isEmpty()) return;+TPointD deltaPos = pp - m_oldPos;m_oldPos = pp;double newWidth = hook->getTrackerRegionWidth();@@ -555,16 +564,16 @@ void TrackerTool::leftButtonDrag(const TPointD &pp, const TMouseEvent &e) {double a = norm2(pp - posCenter);double b = norm2(pp - deltaPos - posCenter);switch (m_what) {- case Inside: // Traslazione+ case Inside: // Translationhook->setAPos(fid, hook->getPos(fid) + deltaPos);break;- case NormalHook: // Traslazione Hook+ case NormalHook: // Hook Translation{hook->setAPos(fid, hook->getPos(fid) + deltaPos);invalidate();return;}- case P00: // Scalatura+ case P00: // Scaling{if (a <= epsilon || b <= epsilon) return;aff = TScale(posCenter, sqrt(a / b));@@ -578,12 +587,12 @@ void TrackerTool::leftButtonDrag(const TPointD &pp, const TMouseEvent &e) {newHeight = rect.getLy();break;}- case P10: // Scalatura X e Y+ case P10: // Scaling X and Y{- TPointD pos = hook->getPos(fid);- TPointD diffPos = pp - pos;- int signumx = 1;- int signumy = 1;+ TPointD pos = hook->getPos(fid);+ TPointD diffPos = pp - pos;+ int signumx = 1;+ int signumy = 1;if (diffPos.x < 0) signumx = -1;if (diffPos.y < 0) signumy = -1;newWidth = fabs(hook->getTrackerRegionWidth() + 2 * signumx * deltaPos.x);@@ -593,14 +602,14 @@ void TrackerTool::leftButtonDrag(const TPointD &pp, const TMouseEvent &e) {// double newHeight = fabs(2*diffPos.y-fabs(2*signumy*deltaPos.y));break;}- case P1M: // Ridimensiono X+ case P1M: // Resize X{TRectD rect = hook->getTrackerRegion(fid);rect = rect.enlarge(deltaPos.x, 0);newWidth = rect.getLx();break;}- case PM1: // Ridimensiono Y+ case PM1: // Resize Y{TRectD rect = hook->getTrackerRegion(fid);rect = rect.enlarge(0, deltaPos.y);@@ -635,10 +644,9 @@ void TrackerTool::leftButtonUp(const TPointD &pos, const TMouseEvent &) {// note: apparently sometimes (when the user triple-clicks) we receive this// event twiceif (!m_buttonDown) return;- // se clicco su una TrackerRegion già selezionato lo deseleziono (per- // permettere- // poi l'aggiunta di un nuovo TrackerObject- if (m_dragged == false && m_hookSelectedIndex == m_lastHookSelectedIndex) {+ // if I click on an already selected TrackerRegion, deselect it (to allow+ // then the addition of a new TrackerObject+ if (!m_dragged && m_hookSelectedIndex == m_lastHookSelectedIndex) {m_hookSelectedIndex = -1;}if (m_newObjectAdded) {@@ -665,7 +673,7 @@ void TrackerTool::leftButtonUp(const TPointD &pos, const TMouseEvent &) {void TrackerTool::deleteSelectedTrackerRegion() {TTool::Application *app = TTool::getApplication();TXshLevel *xl = app->getCurrentLevel()->getLevel();- HookSet *hookSet = xl->getHookSet();+ HookSet *hookSet = xl ? xl->getHookSet() : nullptr;if (!xl || !xl->getSimpleLevel() || !hookSet ||xl->getSimpleLevel()->isReadOnly())return;@@ -716,8 +724,8 @@ invalidate(); */void TrackerTool::mouseMove(const TPointD &pos, const TMouseEvent &e) {m_picked = true;- if (m_dragged == false) {- int hookSelectedIndex;+ if (!m_dragged) {+ int hookSelectedIndex = -1; // Initialize to prevent garbage valuepick(hookSelectedIndex, pos);if (hookSelectedIndex < 0) {m_pos = pos;@@ -728,6 +736,7 @@ void TrackerTool::mouseMove(const TPointD &pos, const TMouseEvent &e) {}//-----------------------------------------------------------------------------+bool TrackerTool::onPropertyChanged(std::string propertyName) {HookSet *hookSet = getHookSet();if (!hookSet || m_hookSelectedIndex < 0) return false;@@ -757,7 +766,9 @@ bool TrackerTool::onPropertyChanged(std::string propertyName) {invalidate();return true;}+void TrackerTool::reset() { m_hookSelectedIndex = -1; }+int TrackerTool::getCursorId() const {switch (m_what) {case Outside:@@ -783,6 +794,7 @@ int TrackerTool::getCursorId() const {}return ToolCursor::TrackerCursor;}+bool TrackerTool::keyDown(QKeyEvent *event) {TXshLevel *xl = TTool::getApplication()->getCurrentLevel()->getLevel();if (!xl) return false;@@ -808,10 +820,10 @@ bool TrackerTool::keyDown(QKeyEvent *event) {case Qt::Key_0:delta.x = 1;break;- case Qt::Key_PageUp: // converto in Hook+ case Qt::Key_PageUp: // convert to Hookhook->setTrackerObjectId(-1);break;- case Qt::Key_PageDown: // converto in trackerRegion+ case Qt::Key_PageDown: // convert to trackerRegion{TrackerObjectsSet *trackerObjectsSet = getTrackerObjectsSet();if (!trackerObjectsSet) return false;@@ -834,6 +846,7 @@ bool TrackerTool::keyDown(QKeyEvent *event) {return true;}+// bool moveCursor(const TPointD &pos){}void TrackerTool::onEnter() {HookSet *hookSet = getHookSet();diff --git a/toonz/sources/tnztools/vectorerasertool.cpp b/toonz/sources/tnztools/vectorerasertool.cppindex 7b8e0a984..e7dfca596 100644--- a/toonz/sources/tnztools/vectorerasertool.cpp+++ b/toonz/sources/tnztools/vectorerasertool.cpp@@ -65,7 +65,7 @@ namespace {//------------------------------------------------------------------------------const double minDistance2 = 16.0; // 4 pixel+const double minDistance2 = 16.0; // 4 pixels//-----------------------------------------------------------------------------@@ -162,9 +162,9 @@ public:}if (image->isComputedRegionAlmostOnce())- image->findRegions(); // in futuro togliere. Serve perche' la- // removeStrokes, se gli si dice- // di non calcolare le regioni, e' piu' veloce ma poi chrash tutto+ image->findRegions(); // TODO: Remove in the future. Needed because+ // removeStrokes is faster when not calculating+ // regions, but then everything crashesUINT size = m_oldFillInformation.size();if (!size) {@@ -216,9 +216,9 @@ public:}if (image->isComputedRegionAlmostOnce())- image->findRegions(); // in futuro togliere. Serve perche' la- // removeStrokes, se gli si dice- // di non calcolare le regioni, e' piu' veloce ma poi chrash tutto+ image->findRegions(); // TODO: Remove in the future. Needed because+ // removeStrokes is faster when not calculating+ // regions, but then everything crashesUINT size = m_newFillInformation.size();if (!size) {@@ -267,12 +267,9 @@ public:void draw() override;- void startErase(- TVectorImageP vi,- const TPointD &pos); //, const TImageLocation &imageLocation);+ void startErase(TVectorImageP vi, const TPointD &pos);void erase(TVectorImageP vi, const TPointD &pos);- void erase(TVectorImageP vi,- TRectD &rect); //, const TImageLocation &imageLocation);+ void erase(TVectorImageP vi, TRectD &rect);void stopErase(TVectorImageP vi);@@ -291,7 +288,7 @@ public:int getCursorId() const override { return ToolCursor::EraserCursor; }void onImageChanged() override;- /*-- ドラッグ中にツールが切り替わった場合、Eraseの終了処理を行う --*/+ /*-- When the tool is switched during dragging, perform erase termination --*/void onDeactivate() override;private:@@ -311,10 +308,9 @@ private:TPointD m_mousePos, //!< Current mouse position.m_oldMousePos, //!< Previous mouse position.- m_brushPos, //!< Position the brush will be painted at.- m_firstPos; //!< Either The first point inserted either in m_track or- //! m_polyline- //! (depending on selected erase mode).+ m_brushPos, //!< Position where the brush will be painted.+ m_firstPos; //!< First point inserted either in m_track or m_polyline+ //! (depending on selected erase mode).UndoEraser *m_undo;std::vector<int> m_indexes;@@ -325,14 +321,14 @@ private:TXshSimpleLevelP m_level;std::pair<int, int> m_currCell;- StrokeGenerator m_track; //!< Lazo selection generator.+ StrokeGenerator m_track; //!< Freehand selection generator.std::vector<TPointD> m_polyline; //!< Polyline points.TStroke *m_stroke; //!< Stores the stroke generated by m_track.TStroke*m_firstStroke; //!< Stores the first stroke in the "frame range" case.- TImageP m_activeImage = NULL; // needed if an frame is changed mid-erase+ TImageP m_activeImage = nullptr; // needed if a frame is changed mid-erasedouble m_thick;bool m_firstTime, m_active, m_firstFrameSelected;@@ -342,12 +338,12 @@ private:void updateTranslation() override;- // Metodi per disegnare la linea della modalita' Freehand+ // Methods to draw the line in Freehand modevoid startFreehand(const TPointD &pos);void freehandDrag(const TPointD &pos);void closeFreehand(const TPointD &pos);- // Metodi per disegnare la linea della modalita' Polyline+ // Methods to draw the line in Polyline modevoid addPointPolyline(const TPointD &pos);void closePolyline(const TPointD &pos);@@ -381,9 +377,10 @@ EraserTool::EraserTool(), m_invertOption("Invert", false) // "W_ToolOptions_Invert", m_multi("Frame Range", false) // "W_ToolOptions_FrameRange", m_pointSize(-1)- , m_undo(0)+ , m_undo(nullptr), m_currCell(-1, -1)- , m_stroke(0)+ , m_stroke(nullptr)+ , m_firstStroke(nullptr), m_thick(5), m_active(false), m_firstTime(true) {@@ -417,9 +414,21 @@ EraserTool::EraserTool()//-----------------------------------------------------------------------------EraserTool::~EraserTool() {- if (m_stroke) delete m_stroke;+ // Release allocated memory+ if (m_stroke) {+ delete m_stroke;+ m_stroke = nullptr;+ }++ if (m_firstStroke) {+ delete m_firstStroke;+ m_firstStroke = nullptr;+ }- if (m_firstStroke) delete m_firstStroke;+ if (m_undo) {+ delete m_undo;+ m_undo = nullptr;+ }}//-----------------------------------------------------------------------------@@ -519,25 +528,25 @@ void EraserTool::resetMulti() {m_firstFrameId = m_veryFirstFrameId = getCurrentFid();m_level = application->getCurrentLevel()->getLevel()? application->getCurrentLevel()->getLevel()->getSimpleLevel()- : 0;+ : nullptr;if (m_firstStroke) {delete m_firstStroke;- m_firstStroke = 0;+ m_firstStroke = nullptr;}}//------------------------------------------------------------------------------void EraserTool::startErase(- TVectorImageP vi,- const TPointD &pos) //, const TImageLocation &imageLocation)-{+void EraserTool::startErase(TVectorImageP vi, const TPointD &pos) {UINT size = vi->getStrokeCount();m_indexes.resize(size);for (UINT i = 0; i < size; i++) m_indexes[i] = i;- if (m_undo) delete m_undo;+ if (m_undo) {+ delete m_undo;+ m_undo = nullptr;+ }TXshSimpleLevel *level =TTool::getApplication()->getCurrentLevel()->getSimpleLevel();m_undo = new UndoEraser(level, getCurrentFid());@@ -557,7 +566,7 @@ void EraserTool::erase(TVectorImageP vi, const TPointD &pos) {m_distance2 = 0;m_oldMousePos = pos;- // quadrato circoscritto alla circonferenza+ // Square circumscribing the circleTRectD circumscribedSquare(pos.x - m_pointSize, pos.y - m_pointSize,pos.x + m_pointSize, pos.y + m_pointSize);if (!circumscribedSquare.overlaps(vi->getBBox())) {@@ -571,9 +580,9 @@ void EraserTool::erase(TVectorImageP vi, const TPointD &pos) {std::vector<TStroke *> splitStrokes;double rectEdge_2 = m_pointSize * M_SQRT1_2;- // quadrato iscritto nella circonferenza- TRectD enrolledSquare(pos.x - rectEdge_2, pos.y - rectEdge_2,- pos.x + rectEdge_2, pos.y + rectEdge_2);+ // Square inscribed in the circle+ TRectD inscribedSquare(pos.x - rectEdge_2, pos.y - rectEdge_2,+ pos.x + rectEdge_2, pos.y + rectEdge_2);UINT i = 0;double pointSize2 = sq(m_pointSize);@@ -594,17 +603,17 @@ void EraserTool::erase(TVectorImageP vi, const TPointD &pos) {TRectD strokeBBox = oldStroke->getBBox();- if (!circumscribedSquare.overlaps(strokeBBox)) { // stroke all'esterno del- // quadrato circoscritto- // alla circonferenxa+ if (!circumscribedSquare.overlaps(+ strokeBBox)) { // Stroke outside the square circumscribing the+ // circlei++;it++;continue;}- if (enrolledSquare.contains(strokeBBox)) { // stroke tutta contenuta nel- // quadrato iscritto nella- // circonferenza+ if (inscribedSquare.contains(+ strokeBBox)) { // Stroke entirely contained within the square+ // inscribed in the circleif (*it != -1) m_undo->addOldStroke(*it, vi->getVIStroke(i));oneStrokeIndex[0] = i;vi->removeStrokes(oneStrokeIndex, true, true);@@ -628,33 +637,31 @@ intersect( *oldStroke, pos, m_pointSize, intersections );*/if (intersections.empty()) {- // BASTEREBBE CONTROLLARE UN SOLO PUNTO PERCHE' SE LA- // STROKE NON INTERSECA IL CERCHIO E CONTENTIENE ALMENO- // UN PUNTO, LA CONTIENE TUTTA. MA SICCOME NON MI FIDO- // DELLA INTERSECT, NE CONTROLLO UN PAIO E AVVANTAGGIO (CON L' AND)- // IL NON CONTENIMENTO, DATO CHE E' MEGLIO CANCELLARE UNA COSA IN- // MENO, CHE UNA IN PIU'+ // WE SHOULD ONLY CHECK ONE POINT BECAUSE IF THE STROKE DOES NOT+ // INTERSECT THE CIRCLE AND CONTAINS AT LEAST ONE POINT, IT CONTAINS ALL.+ // BUT SINCE I DON'T TRUST THE INTERSECT, I CHECK A COUPLE AND FAVOR (WITH+ // AND) NON-CONTAINMENT, AS IT'S BETTER TO DELETE ONE LESS THING THAN ONE+ // MOREif (tdistance2(oldStroke->getPoint(0), pos) < pointSize2 &&tdistance2(oldStroke->getPoint(1), pos) <- pointSize2) { // stroke tutta contenuta nella circonferenxa+ pointSize2) { // Stroke entirely contained within the circleif (*it != -1) m_undo->addOldStroke(*it, vi->getVIStroke(i));oneStrokeIndex[0] = i;vi->removeStrokes(oneStrokeIndex, true, true);it = m_indexes.erase(it);- } else { // non colpita+ } else { // Not hiti++;it++;}continue;}- //------------------------ almeno un'intersezione- //---------------------------------------------------------+ // At least one intersectionif (intersections.size() == 1) {- if (oldStroke->isSelfLoop()) { // una sola intersezione di una stroke- // chiusa con un cerchio dovrebbe accadere- // solo in caso di sfioramento, quindi faccio finta di nulla+ if (oldStroke->isSelfLoop()) { // Only one intersection of a closed+ // stroke with a circle should only happen+ // in case of grazing, so pretend nothing happenedi++;it++;continue;@@ -706,7 +713,7 @@ intersect( *oldStroke, pos, m_pointSize, intersections );oldStroke->reshape(&(points[0]), points.size());- vi->notifyChangedStrokes(i); // per adesso cosi', pero' e' lento+ vi->notifyChangedStrokes(i); // For now like this, but it's slow*it = -1;i++;@@ -714,11 +721,10 @@ intersect( *oldStroke, pos, m_pointSize, intersections );continue;}- //---------- piu'- // intersezioni--------------------------------------------------------+ // Multiple intersectionsif (intersections.size() & 1 &&- oldStroke->isSelfLoop()) { // non dovrebbe mai accadere+ oldStroke->isSelfLoop()) { // Should never happenassert(0);i++;it++;@@ -726,7 +732,7 @@ intersect( *oldStroke, pos, m_pointSize, intersections );}if (intersections.size() == 2 &&- intersections[0] == intersections[1]) { // solo sfiorata+ intersections[0] == intersections[1]) { // Only grazedi++;it++;continue;@@ -765,8 +771,8 @@ intersect( *oldStroke, pos, m_pointSize, intersections );vi->splitStroke(i, sortedWRanges);- UINT addedStroke = vi->getStrokeCount() -- (oldStrokeSize - 1); //-1 perche' e' quella tolta+ UINT addedStroke =+ vi->getStrokeCount() - (oldStrokeSize - 1); // -1 for the removed onei += addedStroke;@@ -789,6 +795,11 @@ void EraserTool::erase(TVectorImageP vi, TRectD &rect) {TXshSimpleLevel *level =TTool::getApplication()->getCurrentLevel()->getSimpleLevel();+ // Release the previous undo if it exists+ if (m_undo) {+ delete m_undo;+ m_undo = nullptr;+ }m_undo = new UndoEraser(level, getCurrentFid());for (i = 0; i < (int)vi->getStrokeCount(); i++) {if (!vi->inCurrentGroup(i)) continue;@@ -810,14 +821,14 @@ void EraserTool::erase(TVectorImageP vi, TRectD &rect) {for (i = (int)eraseStrokes.size() - 1; i >= 0; i--)vi->deleteStroke(eraseStrokes[i]);TUndoManager::manager()->add(m_undo);- m_undo = 0;+ m_undo = nullptr;invalidate();}//-----------------------------------------------------------------------------void EraserTool::stopErase(TVectorImageP vi) {- assert(m_undo != 0);+ assert(m_undo != nullptr);UINT size = m_indexes.size();@@ -827,7 +838,7 @@ void EraserTool::stopErase(TVectorImageP vi) {if (m_indexes[i] == -1) m_undo->addNewStroke(i, vi->getVIStroke(i));}TUndoManager::manager()->add(m_undo);- m_undo = 0;+ m_undo = nullptr;m_active = false;invalidate();notifyImageChanged();@@ -843,7 +854,7 @@ void EraserTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {TImageP image(getImage(true));m_activeImage = image;if (m_eraseType.getValue() == NORMAL_ERASE) {- if (TVectorImageP vi = image) startErase(vi, pos /*,imageLocation*/);+ if (TVectorImageP vi = image) startErase(vi, pos);} else if (m_eraseType.getValue() == RECT_ERASE) {m_selectingRect.x0 = pos.x;m_selectingRect.y0 = pos.y;@@ -925,11 +936,11 @@ void EraserTool::multiEraseRect(TFrameId firstFrameId, TFrameId lastFrameId,double t = m > 1 ? (double)i / (double)(m - 1) : 0.5;t = TInbetween::interpolation(t, algorithm);TRectD rect = interpolateRect(firstRect, lastRect, t);- // m_level->setFrame(fid, img); //necessario: se la getFrame ha scompattato- // una img compressa, senza setFrame le modifiche sulla img fatte qui- // andrebbero perse.+ // m_level->setFrame(fid, img); // Necessary: if getFrame uncompressed a+ // compressed image, without setFrame the modifications made here would be+ // lost.- // Setto fid come corrente per notificare il cambiamento dell'immagine+ // Set fid as current to notify the image changeTTool::Application *app = TTool::getApplication();if (app) {if (app->getCurrentFrame()->isEditingScene())@@ -954,7 +965,7 @@ void EraserTool::onImageChanged() {if (!m_multi.getValue()) return;TTool::Application *application = TTool::getApplication();if (!application) return;- TXshSimpleLevel *xshl = 0;+ TXshSimpleLevel *xshl = nullptr;if (application->getCurrentLevel()->getLevel())xshl = application->getCurrentLevel()->getLevel()->getSimpleLevel();@@ -966,10 +977,9 @@ void EraserTool::onImageChanged() {!m_firstStroke))resetMulti();else if (m_firstFrameId == getCurrentFid())- m_firstFrameSelected = false; // nel caso sono passato allo stato 1 e torno- // all'immagine iniziale, torno allo stato- // iniziale- else { // cambio stato.+ m_firstFrameSelected = false; // If I passed to state 1 and return to the+ // initial image, return to initial state+ else { // Change state.m_firstFrameSelected = true;if (m_eraseType.getValue() == RECT_ERASE) {assert(!m_selectingRect.isEmpty());@@ -1012,7 +1022,7 @@ void EraserTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {application->getCurrentFrame()->setFid(m_veryFirstFrameId);resetMulti();}- invalidate(); // invalidate(m_selectingRect.enlarge(2));+ invalidate();} else {if (application->getCurrentFrame()->isEditingScene())m_currCell = std::pair<int, int>(@@ -1054,11 +1064,10 @@ void EraserTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {//------------------------------------------------------------------------------//! Viene chiusa la polyline e si da il via alla cancellazione.-/*!Viene creato lo \b stroke rappresentante la polyline disegnata.- Se e' selzionato il metodo di cancellazione "frame range" viene richiamato il- metodo \b multiEreserRegion, altrimenti- viene richiamato il metodo \b eraseRegion*/+//! The polyline is closed and erasing begins.+/*! A stroke representing the drawn polyline is created.+ If "frame range" erase method is selected, \b multiEraserRegion is called,+ otherwise \b eraseRegion is called*/void EraserTool::leftButtonDoubleClick(const TPointD &pos,const TMouseEvent &e) {TVectorImageP vi = getImage(true);@@ -1073,15 +1082,18 @@ void EraserTool::leftButtonDoubleClick(const TPointD &pos,}strokePoints.push_back(TThickPoint(m_polyline.back(), 1));m_polyline.clear();- TStroke *stroke = new TStroke(strokePoints);++ std::unique_ptr<TStroke> stroke(new TStroke(strokePoints));assert(stroke->getPoint(0) == stroke->getPoint(1));- if (m_multi.getValue())- multiErase(stroke, e, &EraserTool::eraseRegion);- else {- eraseRegion(vi, stroke);++ if (m_multi.getValue()) {+ multiErase(stroke.get(), e, &EraserTool::eraseRegion);+ } else {+ eraseRegion(vi, stroke.get());m_active = false;notifyImageChanged();}+ // The unique_ptr will be automatically released when it goes out of scopeinvalidate();}}@@ -1196,8 +1208,8 @@ void EraserTool::onActivate() {//------------------------------------------------------------------------------//! Viene aggiunto \b pos a \b m_track e disegnato il primo pezzetto del lazzo.-//! Viene inizializzato \b m_firstPos+//! \b pos is added to \b m_track and the first piece of the freehand is drawn.+//! \b m_firstPos is initializedvoid EraserTool::startFreehand(const TPointD &pos) {m_track.clear();m_firstPos = pos;@@ -1206,10 +1218,10 @@ void EraserTool::startFreehand(const TPointD &pos) {//------------------------------------------------------------------------------//! Viene aggiunto \b pos a \b m_track e disegnato un altro pezzetto del lazzo.+//! \b pos is added to \b m_track and another piece of the freehand is drawn.void EraserTool::freehandDrag(const TPointD &pos) {#if defined(MACOSX)-// m_viewer->enableRedraw(false);+// m_viewer->enableRedraw(false);#endifm_track.add(TThickPoint(pos, m_thick), getPixelSize() * getPixelSize());invalidate(m_track.getModifiedRegion());@@ -1217,24 +1229,29 @@ void EraserTool::freehandDrag(const TPointD &pos) {//------------------------------------------------------------------------------//! Viene chiuso il lazzo (si aggiunge l'ultimo punto ad m_track) e viene creato-//! lo stroke rappresentante il lazzo.+//! The freehand is closed (last point added to m_track) and a stroke+//! representing the freehand is created.void EraserTool::closeFreehand(const TPointD &pos) {#if defined(MACOSX)-// m_viewer->enableRedraw(true);+// m_viewer->enableRedraw(true);#endifif (m_track.isEmpty()) return;m_track.add(TThickPoint(m_firstPos, m_thick),getPixelSize() * getPixelSize());m_track.filterPoints();double error = (30.0 / 11) * sqrt(getPixelSize() * getPixelSize());- m_stroke = m_track.makeStroke(error);++ // Release the previous stroke if it exists+ if (m_stroke) {+ delete m_stroke;+ }+ m_stroke = m_track.makeStroke(error);m_stroke->setStyle(1);}//------------------------------------------------------------------------------//! Viene aggiunto un punto al vettore m_polyline.+//! A point is added to the m_polyline vector.void EraserTool::addPointPolyline(const TPointD &pos) {m_firstPos = pos;m_polyline.push_back(pos);@@ -1242,8 +1259,8 @@ void EraserTool::addPointPolyline(const TPointD &pos) {//------------------------------------------------------------------------------//! Agginge l'ultimo pos a \b m_polyline e chiude la spezzata (aggiunge \b-//! m_polyline.front() alla fine del vettore)+//! Adds the last pos to \b m_polyline and closes the polyline (adds+//! \b m_polyline.front() to the end of the vector)void EraserTool::closePolyline(const TPointD &pos) {if (m_polyline.size() <= 1) return;if (m_polyline.back() != pos) m_polyline.push_back(pos);@@ -1423,6 +1440,11 @@ void EraserTool::eraseSegments(const TVectorImageP vi, TStroke *eraseStroke) {// do the erasing and construct the undo actionTXshSimpleLevel *level =TTool::getApplication()->getCurrentLevel()->getSimpleLevel();+ // Release the previous stroke if it exists+ if (m_undo) {+ delete m_undo;+ m_undo = nullptr;+ }UndoEraser *undo = new UndoEraser(level, getCurrentFid());for (int i = touchedStrokeIndex.size() - 1; i >= 0; --i) {undo->addOldStroke(touchedStrokeIndex[i],@@ -1451,21 +1473,19 @@ void EraserTool::eraseSegments(const TVectorImageP vi, TStroke *eraseStroke) {}TUndoManager::manager()->add(undo);+ m_undo = nullptr;return;}//------------------------------------------------------------------------------//! Cancella stroke presenti in \b vi e contenuti nella regione delimitata da \b+//! Erases strokes present in \b vi and contained in the region delimited by \b//! stroke.-/*!Vengono cercati gli stroke da cancellare facendo i dovuti controlli sui- parametri \b m_invertOption e \b m_selective.- Se uno stroke deve essere cancellato viene inserito in \b eraseStrokes.- Gli stroke vengono cancellati tutti alla fine.*/-void EraserTool::eraseRegion(- const TVectorImageP vi,- TStroke *stroke) //, const TImageLocation &imageLocation)-{+/*!Strokes to be erased are searched with the necessary checks on parameters \b+ m_invertOption and \b m_selective.+ If a stroke should be erased, it is inserted in \b eraseStrokes.+ All strokes are erased at the end.*/+void EraserTool::eraseRegion(const TVectorImageP vi, TStroke *stroke) {if (!vi || !stroke) return;TVectorImage eraseImg;TStroke *eraseStroke = new TStroke(*stroke);@@ -1477,6 +1497,11 @@ void EraserTool::eraseRegion(TXshSimpleLevel *level =TTool::getApplication()->getCurrentLevel()->getSimpleLevel();+ // Release the previous stroke if it exists+ if (m_undo) {+ delete m_undo;+ m_undo = nullptr;+ }m_undo = new UndoEraser(level, getCurrentFid());if (!m_invertOption.getValue()) {@@ -1522,29 +1547,30 @@ void EraserTool::eraseRegion(for (i = (int)eraseStrokes.size() - 1; i >= 0; i--)vi->deleteStroke(eraseStrokes[i]);TUndoManager::manager()->add(m_undo);- m_undo = 0;+ m_undo = nullptr;}//------------------------------------------------------------------------------//! Viene richiamata la doErase sui frame compresi tra \b firstFrameId e \b-//! lastFrameId.-/*!Viene caricato il vettore \b fids con i TFrameId delle immagini sulle quali- * si deve effettuare una cancellazione.*/+//! doErase is called on frames between \b firstFrameId and \b lastFrameId.+/*!Vector \b fids is loaded with TFrameIds of images on which to perform+ * erasure.*/void EraserTool::doMultiErase(TFrameId &firstFrameId, TFrameId &lastFrameId,const TStroke *firstStroke,const TStroke *lastStroke,EraserTool::EraseFunction eraseFunction) {- TXshSimpleLevel *sl =+ TXshSimpleLevelP sl =TTool::getApplication()->getCurrentLevel()->getLevel()->getSimpleLevel();- TStroke *first = new TStroke();- TStroke *last = new TStroke();- *first = *firstStroke;- *last = *lastStroke;++ std::unique_ptr<TStroke> first(new TStroke());+ std::unique_ptr<TStroke> last(new TStroke());+ *first = *firstStroke;+ *last = *lastStroke;+TVectorImageP firstImage = new TVectorImage();TVectorImageP lastImage = new TVectorImage();- firstImage->addStroke(first);- lastImage->addStroke(last);+ firstImage->addStroke(first.release()); // Transfere posse para a imagem+ lastImage->addStroke(last.release()); // Transfere posse para a imagembool backward = false;if (firstFrameId > lastFrameId) {@@ -1590,7 +1616,7 @@ void EraserTool::doMultiErase(TFrameId &firstFrameId, TFrameId &lastFrameId,assert(firstFrameId <= fid && fid <= lastFrameId);double t = m > 1 ? (double)i / (double)(m - 1) : 0.5;t = TInbetween::interpolation(t, algorithm);- // Setto il fid come corrente per notificare il cambiamento dell'immagine+ // Set the fid as current to notify the image changeif (app) {if (app->getCurrentFrame()->isEditingScene())app->getCurrentFrame()->setFrame(startRowInXSheet + fid.getNumber() -@@ -1607,38 +1633,35 @@ void EraserTool::doMultiErase(TFrameId &firstFrameId, TFrameId &lastFrameId,//------------------------------------------------------------------------------//! Viene richiamata la \b eraseRegion per il frame giusto nel caso della-//! modalita' "Frame Range".-/*!Nei casi in cui \b t e' diverso da zero e uno, viene generata una nuova \b- TVectorImageP richiamando la \b TInbetween.- La nuova immagine contiene lo stroke da dare alla eraseRegion. \b fid e'- il TFrameId dell'immagine sulla quale- bisogna effettuare la cancellazione.*/+//! \b eraseRegion is called for the correct frame in "Frame Range" mode.+/*!In cases where \b t is different from zero and one, a new \b TVectorImageP is+ generated by calling \b TInbetween.+ The new image contains the stroke to give to eraseRegion. \b fid is the+ TFrameId of the image on which+ erasure should be performed.*/void EraserTool::doErase(double t, const TXshSimpleLevelP &sl,const TFrameId &fid, const TVectorImageP &firstImage,const TVectorImageP &lastImage,EraserTool::EraseFunction eraseFunction) {- // TImageLocation imageLocation(m_level->getName(),fid);TVectorImageP img = sl->getFrame(fid, true);if (t == 0)- (this->*eraseFunction)(img, firstImage->getStroke(0)); //,imageLocation);+ (this->*eraseFunction)(img, firstImage->getStroke(0));else if (t == 1)- (this->*eraseFunction)(img, lastImage->getStroke(0)); //,imageLocation);+ (this->*eraseFunction)(img, lastImage->getStroke(0));else {assert(firstImage->getStrokeCount() == 1);assert(lastImage->getStrokeCount() == 1);TVectorImageP vi = TInbetween(firstImage, lastImage).tween(t);assert(vi->getStrokeCount() == 1);- (this->*eraseFunction)(img, vi->getStroke(0)); //,imageLocation);+ (this->*eraseFunction)(img, vi->getStroke(0));}}//------------------------------------------------------------------------------//! Effettua la cancellazione nella modalita' "Frame range".-/*! Se il primo frame e' gia stato selezionato richiama la \b doMultiErase;- altrimenti viene inizializzato- \b m_firstStroke.*/+//! Performs erasure in "Frame range" mode.+/*! If the first frame has already been selected, call \b doMultiErase;+ otherwise \b m_firstStroke is initialized.*/void EraserTool::multiErase(TStroke *stroke, const TMouseEvent &e,EraserTool::EraseFunction eraseFunction) {TTool::Application *application = TTool::getApplication();@@ -1651,6 +1674,10 @@ void EraserTool::multiErase(TStroke *stroke, const TMouseEvent &e,eraseFunction);}if (e.isShiftPressed()) {+ // Release the previous stroke if it exists+ if (m_firstStroke) {+ delete m_firstStroke;+ }m_firstStroke = new TStroke(*stroke);m_firstFrameId = getCurrentFid();} else {@@ -1662,6 +1689,10 @@ void EraserTool::multiErase(TStroke *stroke, const TMouseEvent &e,resetMulti();}} else {+ // Release the previous stroke if it exists+ if (m_firstStroke) {+ delete m_firstStroke;+ }m_firstStroke = new TStroke(*stroke);if (application->getCurrentFrame()->isEditingScene())m_currCell =@@ -1678,7 +1709,7 @@ void EraserTool::onDeactivate() {m_active = false;- // TODO : finishing erase procedure is only available for normal type.+ // TODO: Finishing erase procedure is only available for normal type.// Supporting other types is needed. 2016/1/22 shun_iwasawaif (m_eraseType.getValue() != NORMAL_ERASE) return;