OpenToonz - An open-source full-featured 2D animation creation software
C
Migrate regex to QRegularExpression, clean up code and headers
andeon8dc1475f4385
diff --git a/toonz/sources/include/toonz/txshsimplelevel.h b/toonz/sources/include/toonz/txshsimplelevel.hindex 6e417df6c..bdccc74d8 100644--- a/toonz/sources/include/toonz/txshsimplelevel.h+++ b/toonz/sources/include/toonz/txshsimplelevel.h@@ -4,6 +4,10 @@#define TXSHSIMPLELEVEL_INCLUDED#include <memory>+#include <set>+#include <string>+#include <vector>+#include <map>// TnzLib includes#include "toonz/txshlevel.h"@@ -22,9 +26,6 @@#include <boost/container/flat_set.hpp>#include <boost/container/flat_map.hpp>-// STD includes-#include <set>-#undef DVAPI#undef DVVAR#ifdef TOONZLIB_EXPORTS@@ -37,24 +38,24 @@//===================================================================-// Forward declarations-+// Forward declarationsclass ImageBuilder;class LevelProperties;class TPalette;class TContentHistory;--//===================================================================+class TFrameId;+class TFilePath;+class TImageInfo;+class TRasterImageP;//*************************************************************************************************-// TXshSimpleLevel declaration+// TXshSimpleLevel declaration//*************************************************************************************************/*!- \brief The \p TXshLevel specialization for image levels.+ \brief The \p TXshLevel specialization for image levels.- \todo Substitute m_frames with a sorted vector or- a boost flat_set.+ \todo Substitute m_frames with a sorted vector or a boost flat_set.*/class DVAPI TXshSimpleLevel final : public TXshLevel {@@ -64,44 +65,52 @@ class DVAPI TXshSimpleLevel final : public TXshLevel {DECLARE_CLASS_CODEpublic:- /*! \details Level frames may have special properties depending on+ /*! \details Level frames may have special properties depending onthe level type they are part of.-\sa \p TXshSimpleLevel::getFrameStatus() and- \p setFrameStatus() for further details. */+ \sa \p TXshSimpleLevel::getFrameStatus() and \p setFrameStatus() for further+ details. */- enum FrameStatusBit //! Describes a level's frame status.- {+ //! Describes a level's frame status.+ enum FrameStatusBit {Normal = 0x0, //!< Frame has no special status.Scanned = 0x1, //!< A fullcolor frame (only tlv levels).Cleanupped = 0x2, //!< A cleanupped frame (only tlv levels).CleanupPreview = 0x4 //!< A cleanup preview (only fullcolor levels).};-public:+ // Static members+ static bool+ m_rasterizePli; //!< \internal Not the proper place for this data.static bool- m_rasterizePli; //!< \internal Not the proper place for this data.- static bool m_fillFullColorRaster; //!< \internal Not the proper place for- //! this data.+ m_fillFullColorRaster; //!< \internal Not the proper place for this data.public:- TXshSimpleLevel(- const std::wstring &name =- std::wstring()); //!< Constructs a TXshSimpleLevel with a name- ~TXshSimpleLevel();+ // Construction/Destruction+ explicit TXshSimpleLevel(const std::wstring &name = std::wstring());+ ~TXshSimpleLevel() override;++ // Disable copying and moving+ TXshSimpleLevel(const TXshSimpleLevel &) = delete;+ TXshSimpleLevel &operator=(const TXshSimpleLevel &) = delete;++ TXshSimpleLevel(TXshSimpleLevel &&) = delete;+ TXshSimpleLevel &operator=(TXshSimpleLevel &&) = delete;- TXshSimpleLevel *getSimpleLevel() override {- return this;- } //!< Reimplemented for TXshLevel.+ // Type casting+ TXshSimpleLevel *getSimpleLevel() override { return this; }+ // Subsequence statusbool isSubsequence() const { return m_isSubsequence; }+ // Channel level type queriesbool is16BitChannelLevel() const {return getType() == OVL_XSHLEVEL && m_16BitChannelLevel;}void set16BitChannelLevel(bool value) {m_16BitChannelLevel = (value && getType() == OVL_XSHLEVEL);}+bool isFloatChannelLevel() const {return getType() == OVL_XSHLEVEL && m_floatChannelLevel;}@@ -109,90 +118,60 @@ public:m_floatChannelLevel = (value && getType() == OVL_XSHLEVEL);}+ // Read-only statusbool isReadOnly() const { return m_isReadOnly; }void setIsReadOnly(bool value) { m_isReadOnly = value; }void updateReadOnly();- LevelProperties *getProperties()- const //!< Returns a pointer to the \a owned level properties.- {- return m_properties.get();- }+ // Properties management+ LevelProperties *getProperties() const { return m_properties.get(); }void clonePropertiesFrom(const TXshSimpleLevel *oldSl);- TPalette *getPalette()- const; //!< Returns a pointer to the \a shared level palette.- void setPalette(TPalette *palette); //!< Assigns a palette to the level.+ // Palette management+ TPalette *getPalette() const;+ void setPalette(TPalette *palette);+ // Path managementTFilePath getPath() const override { return m_path; }void setPath(const TFilePath &path, bool retainCachedImages = false);TFilePath getScannedPath() const { return m_scannedPath; }void setScannedPath(const TFilePath &path);- /*! \details Each level frame have a corresponding image retrievable- with the getFrame() method and similar.--\remark Consider using functions getFrameCount() and getFrameId()- to avoid a container copy. */-- std::vector<TFrameId> getFids()- const; //!< Returns a copy of the level's frame ids.- void getFids(- std::vector<TFrameId> &fids) const override; //!< Copies fids() into- //! fids. \deprecated Use- //! the return valued- //! variation instead.-- TFrameId getFirstFid()- const; //!< Returns the first level frame's id; roughly equivalent to- //! <TT>index2fid(0)</TT>.- TFrameId getLastFid()- const; //!< Returns the last level frame's id; roughly equivalent to- //! <TT>index2fid(getFrameCount()-1)</TT>.-- bool isEmpty() const override {- return m_frames.empty();- } //!< Returns whether the level is empty.- bool isFid(const TFrameId &fid)- const; //!< Returns whether a given frameId is in the level.-- /*! \details Unlike function index2fid(), getFrameId() \a asserts- beyond current frames count. */-- const TFrameId &getFrameId(- int index) const; //!< Returns the frame id at specified index.+ // Frame ID management+ std::vector<TFrameId> getFids() const;+ void getFids(std::vector<TFrameId> &fids) const override;++ TFrameId getFirstFid() const;+ TFrameId getLastFid() const;++ bool isEmpty() const override { return m_frames.empty(); }+ bool isFid(const TFrameId &fid) const;++ const TFrameId &getFrameId(int index) const;int getFrameCount() const override {- return m_frames.size();- } //!< Returns the level's frames count.-- /*! \details Function index2fid() attempts guessing frame ids for- frame indexes beyond current frames count. See function- guessStep() for further details. */-- TFrameId index2fid(int index) const; //!< Returns a frame id corresponding to- //! the specified frame index, or- //! an invalid frame otherwise.- int fid2index(const TFrameId &fid) const; //!< Returns the frame \a index- //! corresponding to the specified- //! frame id,- //! or \p -1 if not found.-- /*-if the table contains 'fid' it returns fid2index(fid).-if fid is greater than the last fid in the table, it returns a "guessed" index.-e.g. if fids = [1,3,5,7] then fid2index(11) == 5-if fid is smaller than the last fid in the table (and is not contained in the-table) it returns the proper insertion index-*/+ return static_cast<int>(m_frames.size());+ }++ TFrameId index2fid(int index) const;+ int fid2index(const TFrameId &fid) const;++ /*!+ if the table contains 'fid' it returns fid2index(fid).+ if fid is greater than the last fid in the table, it returns a "guessed"+ index. e.g. if fids = [1,3,5,7] then fid2index(11) == 5 if fid is smaller+ than the last fid in the table (and is not contained in the table) it+ returns the proper insertion index+ */int guessIndex(const TFrameId &fid) const;//! Analyzes the level's frames table and returns the alleged entries \a step- //! - ie the distance- //! from each entry to the next.+ //! - ie the distance from each entry to the next.int guessStep() const;void formatFId(TFrameId &fid, TFrameId tmplFId);++ // Frame image operationsvoid setFrame(const TFrameId &fid, const TImageP &img);TImageP getFrame(const TFrameId &fid, UCHAR imgManagerParamsMask,@@ -201,18 +180,18 @@ table) it returns the proper insertion indexreturn getFrame(fid, toBeModified ? ImageManager::toBeModified : ImageManager::none, 0);}+TImageP getFullsampledFrame(const TFrameId &fid,UCHAR imgManagerParamsMask) const;-TImageInfo *getFrameInfo(const TFrameId &fid, bool toBeModified);TImageP getFrameIcon(const TFrameId &fid) const;- // load icon (and image) data of all frames into cache+ // Load icon (and image) data of all frames into cachevoid loadAllIconsAndPutInCache(bool cacheImagesAsWell);TRasterImageP getFrameToCleanup(const TFrameId &fid,bool toBeLineProcessed) const;- TRasterImageP getFrameRasterized(const TFrameId& fid, TPointD dpi) const;+ TRasterImageP getFrameRasterized(const TFrameId &fid, TPointD dpi) const;std::string getImageId(const TFrameId &fid, int frameStatus = -1) const;std::string getIconId(const TFrameId &fid, int frameStatus = -1) const;@@ -221,54 +200,44 @@ table) it returns the proper insertion indexvoid eraseFrame(const TFrameId &fid);void clearFrames();void invalidateFrames();-void invalidateFrame(const TFrameId &fid);- /*!-Set the range of frame that can be edited and saved.-Editable range is contained in \b m_editableRange.-*/+ // Editable range managementvoid setEditableRange(unsigned int from, unsigned int to,const std::wstring &userName);void mergeTemporaryHookFile(unsigned int from, unsigned int to,const TFilePath &hookFile);void clearEditableRange();std::wstring getEditableFileName();+ std::set<TFrameId> getEditableRange();- std::set<TFrameId>- getEditableRange(); //!< Returns the set of editable frames.-+ // Frame status managementint getFrameStatus(const TFrameId &fid) const;void setFrameStatus(const TFrameId &fid, int status);- /*! \details This function will implicitly convert the input path+ /*! \details This function will implicitly convert the input pathextension to a correctly formatted \a tlv. Behavioris undefined in case the level is not of fullcolor type.-\deprecated Function is obviously an implementation detail of the- cleanup process. Should be moved there. */+ \deprecated Function is obviously an implementation detail of the+ cleanup process. Should be moved there. */+ void makeTlv(const TFilePath &tlvPath);- void makeTlv(const TFilePath &tlvPath); //!< Transforms the level from \a- //! fullcolor to tlv (colormap),- //! and assigns the specified level path.TImageP createEmptyFrame();-void initializePalette();void initializeResolutionAndDpi(const TDimension &dim = TDimension(),- double dpi = 0);+ double dpi = 0.0);TDimension getResolution();-TPointD getImageDpi(const TFrameId &fid = TFrameId::NO_FRAME,int frameStatus = -1);int getImageSubsampling(const TFrameId &fid) const;TPointD getDpi(const TFrameId &fid = TFrameId::NO_FRAME,int frameStatus = -1);- /*! \brief Returns the bbox for the level's fid, specified in standard+ /*! \brief Returns the bbox for the level's fid, specified in standard\a inch coordinates (which are \a different from Toonz's- standard world coordinates, by a \p Stage::inch factor). */-+ standard world coordinates, by a \p Stage::inch factor). */TRectD getBBox(const TFrameId &fid) const;void setDirtyFlag(bool on) override;@@ -278,6 +247,7 @@ Editable range is contained in \b m_editableRange.//! \warning Not what users may expect!void touchFrame(const TFrameId &fid);+ // Serializationvoid loadData(TIStream &is) override;void saveData(TOStream &os) override;@@ -290,13 +260,13 @@ Editable range is contained in \b m_editableRange.void save() override;/*!-Save the level in the specified fp.-The oldFp is used when the current scene path change...-*/+ Save the level in the specified fp.+ The oldFp is used when the current scene path change...+ */void save(const TFilePath &fp, const TFilePath &oldFp = TFilePath(),bool overwritePalette = true);- //! note gets the contentHistory. can be 0+ // Content history managementconst TContentHistory *getContentHistory() const {return m_contentHistory.get();}@@ -306,7 +276,7 @@ The oldFp is used when the current scene path change...//! ownershipvoid setContentHistory(TContentHistory *contentHistory);- //! Set elements of m_renumberTable with m_frames.+ // Frame renumberingvoid setRenumberTable();const std::map<TFrameId, TFrameId> &renumberTable() const {return m_renumberTable;@@ -319,55 +289,57 @@ The oldFp is used when the current scene path change...bool isFrameReadOnly(TFrameId fid);public:- // Auxiliary files management: hooks, tpl, etc.+ // Static methods for auxiliary files management: hooks, tpl, etc.// May throw; copy and rename perform touchparentdir- static void copyFiles(const TFilePath &dst,- const TFilePath &src); //!< Copy files from src to dst.- static void renameFiles(- const TFilePath &dst,- const TFilePath &src); //!< Rename files from src to dst.- static void removeFiles(const TFilePath &fp); //!< Remove files at fp.+ //! Copy files from src to dst.+ static void copyFiles(const TFilePath &dst, const TFilePath &src);++ //! Rename files from src to dst.+ static void renameFiles(const TFilePath &dst, const TFilePath &src);++ //! Remove files at fp.+ static void removeFiles(const TFilePath &fp);//! Get the auxiliary files list: hooks, tpl, etc.static void getFiles(const TFilePath &fp, TFilePathSet &fpset);/*!-Translates a level path into the corresponding hook path (no check for-the existence of said hook file).-*/+ Translates a level path into the corresponding hook path (no check for+ the existence of said hook file).+ */static TFilePath getHookPath(const TFilePath &levelPath);/*!-\brief Returns the list of \a existing hook files associated to the- specified level, sorted by modification date (last modified at front).- The list stores <I>local paths<\I> relative to- decodedLevelPath.getParentDir().--\note A level may have multiple hook files if the hook set was edited- with older Toonz versions. Use this function if you need to access all- of them. Only the latest file format is considered when loading a level.-*/+ \brief Returns the list of \a existing hook files associated to the+ specified level, sorted by modification date (last modified at+ front). The list stores <I>local paths<\I> relative to+ decodedLevelPath.getParentDir().++ \note A level may have multiple hook files if the hook set was edited+ with older Toonz versions. Use this function if you need to access all+ of them. Only the latest file format is considered when loading a+ level.+ */static QStringList getHookFiles(const TFilePath &decodedLevelPath);/*!-\brief Returns the path of the newest \a existing hook file associated to the- specified \b decoded level path - or an empty path if none was found.+ \brief Returns the path of the newest \a existing hook file associated to+ the specified \b decoded level path - or an empty path if none was found.-\note In case there are more than one hook file (ie files from older- Toonz version), the latest file version is used.-*/+ \note In case there are more than one hook file (ie files from older+ Toonz version), the latest file version is used.+ */static TFilePath getExistingHookFile(const TFilePath &decodedLevelPath);static void setCompatibilityMasks(int writeMask, int neededMask,int forbiddenMask);public Q_SLOTS:-void onPaletteChanged(); //!< Invoked when some colorstyle has been changedprivate:- typedef boost::container::flat_set<TFrameId> FramesSet;+ using FramesSet = boost::container::flat_set<TFrameId>;private:std::unique_ptr<LevelProperties> m_properties;@@ -388,25 +360,23 @@ private:std::set<TFrameId> m_editableRange;- TFilePath m_path, m_scannedPath;+ TFilePath m_path;+ TFilePath m_scannedPath;std::string m_idBase;std::wstring m_editableRangeUserInfo;- bool m_isSubsequence, m_16BitChannelLevel, m_floatChannelLevel, m_isReadOnly,- m_temporaryHookMerged; //!< Used only during hook merge (and hence during- //! saving)+ bool m_isSubsequence;+ bool m_16BitChannelLevel;+ bool m_floatChannelLevel;+ bool m_isReadOnly;+ bool m_temporaryHookMerged; //!< Used only during hook merge (and hence+ //!< during saving)private://! Save simple level in scene-decoded path \p decodedFp.- void saveSimpleLevel(- const TFilePath &decodedFp,- bool overwritePalette = true); // Difference from save(..)?--private:- // Not copyable- TXshSimpleLevel(const TXshSimpleLevel &);- TXshSimpleLevel &operator=(const TXshSimpleLevel &);+ void saveSimpleLevel(const TFilePath &decodedFp,+ bool overwritePalette = true);};//=====================================================================================@@ -414,11 +384,12 @@ private:#ifdef _WIN32template class DV_EXPORT_API TSmartPointerT<TXshSimpleLevel>;#endif+typedef TSmartPointerT<TXshSimpleLevel> TXshSimpleLevelP;//=====================================================================================-void DVAPI setLoadingLevelRange(const TFrameId &fromFid, const TFrameId &toFid);-void DVAPI getLoadingLevelRange(TFrameId &fromFid, TFrameId &toFid);+DVAPI void setLoadingLevelRange(const TFrameId &fromFid, const TFrameId &toFid);+DVAPI void getLoadingLevelRange(TFrameId &fromFid, TFrameId &toFid);#endif // TXSHSIMPLELEVEL_INCLUDEDdiff --git a/toonz/sources/toonzlib/txshsimplelevel.cpp b/toonz/sources/toonzlib/txshsimplelevel.cppindex b1ff7bd59..0f4a01364 100644--- a/toonz/sources/toonzlib/txshsimplelevel.cpp+++ b/toonz/sources/toonzlib/txshsimplelevel.cpp@@ -1,3 +1,5 @@++#include "toonz/txshsimplelevel.h"#include "imagebuilders.h"@@ -39,7 +41,7 @@// Qt includes#include <QDir>-#include <QRegExp>+#include <QRegularExpression>#include <QMessageBox>#include <QtCore>@@ -68,23 +70,20 @@ struct CompatibilityStruct {};CompatibilityStruct compatibility = {- 0x00F1, // mask written. Note: Student main must be 0x00F2- // Note: the 0x00F0 part is currently not used.- 0x0000, // mandatory mask: loaded levels MUST have a mask with these bits- // set- // Note: if mandatory mask != 0 then no old level (without- // mask)- // can be loaded- // Note: this mask is currently not used.- 0x000E // forbidden mask: loaded levels MUST NOT have a mask with these- // bits set- //+ 0x00F1, // Mask written. NOTE: Student main must be 0x00F2+ // NOTE: The 0x00F0 range is currently unused+ 0x0000, // Mandatory mask: Loaded levels MUST have all these bits set+ // NOTE: If != 0 old levels (without a mask) cannot be loaded+ // NOTE: This mask is currently not used.+ 0x000E // Forbidden mask:Loaded levels MUST NOT have any of these bits set};//------------------------------------------------------------------------------inline std::string rasterized(std::string id) { return id + "_rasterized"; }-inline std::string filled(std::string id) { return id + "_filled"; }+inline std::string rasterized(const std::string& id) {+ return id + "_rasterized";+}+inline std::string filled(const std::string& id) { return id + "_filled"; }//-----------------------------------------------------------------------------@@ -99,15 +98,16 @@ QString getCreatorString() {bool checkCreatorString(const QString& creator) {int mask = 0;- if (creator != "") {- QRegExp rx("CM\\([0-9A-Fa-f]*\\)");- int pos = rx.indexIn(creator);- int len = rx.matchedLength();- if (pos >= 0 && len >= 4) {- QString v;- if (len > 4) v = creator.mid(pos + 3, len - 4);- bool ok = true;- mask = v.toInt(&ok, 16);+ if (!creator.isEmpty()) {+ QRegularExpression rx(R"(CM\([0-9A-Fa-f]*\))");+ QRegularExpressionMatch match = rx.match(creator);+ if (match.hasMatch()) {+ QString v = match.captured(0);+ if (v.length() > 4) {+ v = v.mid(3, v.length() - 4);+ bool ok = true;+ mask = v.toInt(&ok, 16);+ }}}return (mask & compatibility.neededMask) == compatibility.neededMask &&@@ -118,6 +118,7 @@ bool checkCreatorString(const QString& creator) {bool isAreadOnlyLevel(const TFilePath& path) {if (path.isEmpty() || !path.isAbsolute()) return false;+if (path.getDots() == "." ||(path.getDots() == ".." &&(path.getType() == "tlv" || path.getType() == "tpl"))) {@@ -126,34 +127,8 @@ bool isAreadOnlyLevel(const TFilePath& path) {TFileStatus fs(path);return !fs.isWritable();}- /*- Since processing is heavy, all sequential files return false -*/- /*-else if(path.getDots() == "..")-{-TFilePath dir = path.getParentDir();-QDir qDir(QString::fromStdWString(dir.getWideString()));-QString levelName =-QRegExp::escape(QString::fromStdWString(path.getWideName()));-QString levelType = QString::fromStdString(path.getType());-QString exp(levelName+".[0-9]{1,4}."+levelType);-QRegExp regExp(exp);-QStringList list = qDir.entryList(QDir::Files);-QStringList livelFrames = list.filter(regExp);--bool isReadOnly=false;-int i;-for(i=0; i<livelFrames.size() && !isReadOnly; i++)-{-TFilePath frame = dir+TFilePath(livelFrames[i].toStdWString());-if(frame.isEmpty() || !frame.isAbsolute()) continue;-TFileStatus fs(frame);-isReadOnly = !fs.isWritable();-}-return isReadOnly;-}-*/- else- return false;++ return false;}//-----------------------------------------------------------------------------@@ -169,9 +144,8 @@ void getIndexesRangefromFids(TXshSimpleLevel* level,toIndex = 0;fromIndex = level->getFrameCount() - 1;- std::set<TFrameId>::const_iterator it;- for (it = fids.begin(); it != fids.end(); ++it) {- int index = level->guessIndex(*it);+ for (const auto& fid : fids) {+ int index = level->guessIndex(fid);if (index > toIndex) toIndex = index;if (index < fromIndex) fromIndex = index;}@@ -180,7 +154,7 @@ void getIndexesRangefromFids(TXshSimpleLevel* level,} // namespace//******************************************************************************************-// TXshSimpleLevel implementation+// TXshSimpleLevel implementation//******************************************************************************************bool TXshSimpleLevel::m_rasterizePli = false;@@ -191,7 +165,7 @@ bool TXshSimpleLevel::m_fillFullColorRaster = false;TXshSimpleLevel::TXshSimpleLevel(const std::wstring& name): TXshLevel(m_classCode, name), m_properties(new LevelProperties)- , m_palette(0)+ , m_palette(nullptr), m_idBase(std::to_string(idBaseCode++)), m_editableRangeUserInfo(L""), m_isSubsequence(false)@@ -205,16 +179,21 @@ TXshSimpleLevel::TXshSimpleLevel(const std::wstring& name)TXshSimpleLevel::~TXshSimpleLevel() {clearFrames();- if (m_palette) m_palette->release();+ if (m_palette) {+ m_palette->release();+ m_palette = nullptr;+ }}//-----------------------------------------------------------------------------void TXshSimpleLevel::setEditableRange(unsigned int from, unsigned int to,const std::wstring& userName) {- assert(from <= to && to < (unsigned int)getFrameCount());- unsigned int i;- for (i = from; i <= to; i++) m_editableRange.insert(index2fid(i));+ assert(from <= to && to < static_cast<unsigned int>(getFrameCount()));++ for (unsigned int i = from; i <= to; i++) {+ m_editableRange.insert(index2fid(i));+ }QString hostName = TSystem::getHostName();m_editableRangeUserInfo = userName + L"_" + hostName.toStdWString();@@ -228,7 +207,7 @@ void TXshSimpleLevel::setEditableRange(unsigned int from, unsigned int to,TLevelReaderP lr(dstPath);TLevelP level = lr->loadInfo();setPalette(level->getPalette());- for (TLevel::Iterator it = level->begin(); it != level->end(); it++) {+ for (TLevel::Iterator it = level->begin(); it != level->end(); ++it) {TImageP img = lr->getFrameReader(it->first)->load();setFrame(it->first, img);}@@ -245,12 +224,15 @@ void TXshSimpleLevel::mergeTemporaryHookFile(unsigned int from, unsigned int to,const TFilePath& hookFile) {if (!TFileStatus(hookFile).doesExist()) return;- HookSet* tempHookSet = new HookSet;+ std::unique_ptr<HookSet> tempHookSet(new HookSet);TIStream is(hookFile);std::string tagName;try {- if (is.matchTag(tagName) && tagName == "hooks") tempHookSet->loadData(is);+ if (is.matchTag(tagName) && tagName == "hooks") {+ tempHookSet->loadData(is);+ }} catch (...) {+ return;}HookSet* hookSet = getHookSet();@@ -283,7 +265,7 @@ void TXshSimpleLevel::mergeTemporaryHookFile(unsigned int from, unsigned int to,void TXshSimpleLevel::clearEditableRange() {m_editableRange.clear();- m_editableRangeUserInfo = L"";+ m_editableRangeUserInfo.clear();}//-----------------------------------------------------------------------------@@ -295,7 +277,7 @@ std::wstring TXshSimpleLevel::getEditableFileName() {std::wstring fileName = m_path.getWideName();#endiffileName += L"_" + m_editableRangeUserInfo;- int from, to;+ int from = 0, to = 0;getIndexesRangefromFids(this, m_editableRange, from, to);if (from == -1 && to == -1) return L"";fileName += L"_" + std::to_wstring(from + 1) + L"-" + std::to_wstring(to + 1);@@ -313,8 +295,9 @@ std::set<TFrameId> TXshSimpleLevel::getEditableRange() {void TXshSimpleLevel::setRenumberTable() {m_renumberTable.clear();- FramesSet::iterator ft, fEnd = m_frames.end();- for (ft = m_frames.begin(); ft != fEnd; ++ft) m_renumberTable[*ft] = *ft;+ for (const auto& fid : m_frames) {+ m_renumberTable[fid] = fid;+ }}//-----------------------------------------------------------------------------@@ -351,10 +334,7 @@ void TXshSimpleLevel::touchFrame(const TFrameId& fid) {//-----------------------------------------------------------------------------void TXshSimpleLevel::onPaletteChanged() {- FramesSet::iterator ft, fEnd = m_frames.end();- for (ft = m_frames.begin(); ft != fEnd; ++ft) {- const TFrameId& fid = *ft;-+ for (const auto& fid : m_frames) {if (getType() == PLI_XSHLEVEL) {std::string id = rasterized(getImageId(fid));ImageManager::instance()->invalidate(id);@@ -387,23 +367,21 @@ void TXshSimpleLevel::setPath(const TFilePath& fp, bool keepFrames) {}}- if (getType() != PLI_XSHLEVEL) {- if (!m_frames.empty()) {- std::string imageId = getImageId(getFirstFid());- const TImageInfo* imageInfo =- ImageManager::instance()->getInfo(imageId, ImageManager::none, 0);- if (imageInfo) {- TDimension imageRes(0, 0);- TPointD imageDpi;- imageRes.lx = imageInfo->m_lx;- imageRes.ly = imageInfo->m_ly;- imageDpi.x = imageInfo->m_dpix;- imageDpi.y = imageInfo->m_dpiy;- m_properties->setImageDpi(imageDpi);- m_properties->setImageRes(imageRes);- m_properties->setBpp(imageInfo->m_bitsPerSample *- imageInfo->m_samplePerPixel);- }+ if (getType() != PLI_XSHLEVEL && !m_frames.empty()) {+ std::string imageId = getImageId(getFirstFid());+ const TImageInfo* imageInfo =+ ImageManager::instance()->getInfo(imageId, ImageManager::none, 0);+ if (imageInfo) {+ TDimension imageRes(0, 0);+ TPointD imageDpi;+ imageRes.lx = imageInfo->m_lx;+ imageRes.ly = imageInfo->m_ly;+ imageDpi.x = imageInfo->m_dpix;+ imageDpi.y = imageInfo->m_dpiy;+ m_properties->setImageDpi(imageDpi);+ m_properties->setImageRes(imageRes);+ m_properties->setBpp(imageInfo->m_bitsPerSample *+ imageInfo->m_samplePerPixel);}}}@@ -429,12 +407,16 @@ TPalette* TXshSimpleLevel::getPalette() const { return m_palette; }void TXshSimpleLevel::setPalette(TPalette* palette) {if (m_palette != palette) {- if (m_palette) m_palette->release();+ if (m_palette) {+ m_palette->release();+ }m_palette = palette;if (m_palette) {m_palette->addRef();- if (!(getType() & FULLCOLOR_TYPE)) m_palette->setPaletteName(getName());+ if (!(getType() & FULLCOLOR_TYPE)) {+ m_palette->setPaletteName(getName());+ }}}}@@ -454,13 +436,19 @@ std::vector<TFrameId> TXshSimpleLevel::getFids() const {//-----------------------------------------------------------------------------bool TXshSimpleLevel::isFid(const TFrameId& fid) const {- return m_frames.count(fid);+ return m_frames.count(fid) > 0;}//-----------------------------------------------------------------------------const TFrameId& TXshSimpleLevel::getFrameId(int index) const {- return *(m_frames.begin() += index);+ static const TFrameId emptyFrameId(TFrameId::NO_FRAME);+ if (index < 0 || index >= static_cast<int>(m_frames.size())) {+ return emptyFrameId;+ }+ auto it = m_frames.begin();+ std::advance(it, index);+ return *it;}//-----------------------------------------------------------------------------@@ -478,33 +466,33 @@ TFrameId TXshSimpleLevel::getLastFid() const {//-----------------------------------------------------------------------------int TXshSimpleLevel::guessStep() const {- int frameCount = m_frames.size();- if (frameCount < 2)+ int frameCount = static_cast<int>(m_frames.size());+ if (frameCount < 2) {return 1; // a level with zero or one frame has step=1 by definition+ }- FramesSet::const_iterator ft = m_frames.begin();-- TFrameId firstFid = *ft++, secondFid = *ft++;+ auto ft = m_frames.begin();+ TFrameId firstFid = *ft++;+ TFrameId secondFid = *ft++;- if (!firstFid.getLetter().isEmpty() || !secondFid.getLetter().isEmpty())+ if (!firstFid.getLetter().isEmpty() || !secondFid.getLetter().isEmpty()) {return 1;+ }int step = secondFid.getNumber() - firstFid.getNumber();if (step == 1) return 1;// check immediately if the step applies to the last frame- // (try to limit the number of times I have to check the entire list)TFrameId lastFid = *m_frames.rbegin();if (!lastFid.getLetter().isEmpty()) return 1;- if (lastFid.getNumber() != firstFid.getNumber() + step * (frameCount - 1))+ if (lastFid.getNumber() != firstFid.getNumber() + step * (frameCount - 1)) {return 1;+ }for (int i = 2; ft != m_frames.end(); ++ft, ++i) {const TFrameId& fid = *ft;-if (!fid.getLetter().isEmpty()) return 1;-if (fid.getNumber() != firstFid.getNumber() + step * i) return 1;}@@ -514,10 +502,10 @@ int TXshSimpleLevel::guessStep() const {//-----------------------------------------------------------------------------int TXshSimpleLevel::fid2index(const TFrameId& fid) const {- FramesSet::const_iterator ft = m_frames.find(fid);- return (ft != m_frames.end()) ? std::distance(m_frames.begin(), ft)- : // Note: flat_set has random access- -1; // iterators, so this is FAST+ auto ft = m_frames.find(fid);+ return (ft != m_frames.end())+ ? static_cast<int>(std::distance(m_frames.begin(), ft))+ : -1;}//-----------------------------------------------------------------------------@@ -525,19 +513,18 @@ int TXshSimpleLevel::fid2index(const TFrameId& fid) const {int TXshSimpleLevel::guessIndex(const TFrameId& fid) const {if (m_frames.empty()) return 0; // no frames, return 0 (by definition)- FramesSet::const_iterator ft = m_frames.lower_bound(fid);+ auto ft = m_frames.lower_bound(fid);if (ft == m_frames.end()) {const TFrameId& maxFid = *m_frames.rbegin();assert(fid > maxFid);// fid not in the table, but greater than the last one.- // return a suitable index. (e.g. frames are 1,3,5,7; fid2index(11) should- // return index=5)int step = guessStep();int i = (fid.getNumber() - maxFid.getNumber()) / step;- return m_frames.size() - 1 + i;- } else- return std::distance(m_frames.begin(), ft);+ return static_cast<int>(m_frames.size()) - 1 + i;+ } else {+ return static_cast<int>(std::distance(m_frames.begin(), ft));+ }}//-----------------------------------------------------------------------------@@ -545,11 +532,11 @@ int TXshSimpleLevel::guessIndex(const TFrameId& fid) const {TFrameId TXshSimpleLevel::index2fid(int index) const {if (index < 0) return TFrameId(-2);- int frameCount = m_frames.size();+ int frameCount = static_cast<int>(m_frames.size());if (frameCount == 0) return TFrameId(1); // o_o?if (index < frameCount) {- FramesSet::const_iterator ft = m_frames.begin();+ auto ft = m_frames.begin();std::advance(ft, index);return *ft;} else {@@ -575,9 +562,7 @@ TImageP TXshSimpleLevel::getFrame(const TFrameId& fid, UCHAR imFlags,TImageP img = ImageManager::instance()->getImage(imgId, imFlags, &extData);if (imFlags & ImageManager::toBeModified) {- // The image will be modified. Perform any related invalidation.- texture_utils::invalidateTexture(- this, fid); // We must rebuild associated textures+ texture_utils::invalidateTexture(this, fid);}return img;@@ -590,7 +575,7 @@ TImageInfo* TXshSimpleLevel::getFrameInfo(const TFrameId& fid,assert(m_type != UNKNOWN_XSHLEVEL);// If the required frame is not in range, quit- if (m_frames.count(fid) == 0) return 0;+ if (m_frames.count(fid) == 0) return nullptr;const std::string& imgId = getImageId(fid);@@ -607,24 +592,23 @@ TImageP TXshSimpleLevel::getFrameIcon(const TFrameId& fid) const {if (m_frames.count(fid) == 0) return TImageP();- // NOTE: Icons caching is DISABLED at this stage. It is now responsibility of- // ToonzQt's IconGenerator class.-ImageLoader::BuildExtData extData(this, fid);- extData.m_subs = 1, extData.m_icon = true;+ extData.m_subs = 1;+ extData.m_icon = true;const std::string& imgId = getImageId(fid);TImageP img = ImageManager::instance()->getImage(imgId, ImageManager::dontPutInCache, &extData);- TToonzImageP timg = (TToonzImageP)img;- if (timg && m_palette) timg->setPalette(m_palette);+ if (TToonzImageP timg = img) {+ if (m_palette) timg->setPalette(m_palette);+ }return img;}//------------------------------------------------------------------------------// load icon (and image) data of all frames into cache+void TXshSimpleLevel::loadAllIconsAndPutInCache(bool cacheImagesAsWell) {if (m_type != TZP_XSHLEVEL && m_type != OVL_XSHLEVEL) return;@@ -632,9 +616,10 @@ void TXshSimpleLevel::loadAllIconsAndPutInCache(bool cacheImagesAsWell) {getFids(fids);std::vector<std::string> iconIds;+ iconIds.reserve(fids.size());- for (int i = 0; i < (int)fids.size(); i++) {- iconIds.push_back(getIconId(fids[i]));+ for (const auto& fid : fids) {+ iconIds.push_back(getIconId(fid));}ImageManager::instance()->loadAllTlvIconsAndPutInCache(this, fids, iconIds,@@ -647,8 +632,8 @@ TRasterImageP TXshSimpleLevel::getFrameToCleanup(const TFrameId& fid,bool toBeLineProcessed) const {assert(m_type != UNKNOWN_XSHLEVEL);- FramesSet::const_iterator ft = m_frames.find(fid);- if (ft == m_frames.end()) return TImageP();+ auto ft = m_frames.find(fid);+ if (ft == m_frames.end()) return TRasterImageP();bool flag = (m_scannedPath != TFilePath());std::string imageId = getImageId(fid, flag ? Scanned : 0);@@ -656,15 +641,15 @@ TRasterImageP TXshSimpleLevel::getFrameToCleanup(const TFrameId& fid,ImageLoader::BuildExtData extData(this, fid, 1);UCHAR imFlags = ImageManager::dontPutInCache;- // if lines are not processed, obtain the original sampled imageif (!toBeLineProcessed) imFlags |= ImageManager::is64bitEnabled;+TRasterImageP img =ImageManager::instance()->getImage(imageId, imFlags, &extData);if (!img) return img;- double x_dpi, y_dpi;+ double x_dpi = 0, y_dpi = 0;img->getDpi(x_dpi, y_dpi);- if (!x_dpi && !y_dpi) {+ if (x_dpi == 0.0 && y_dpi == 0.0) {TPointD dpi = m_properties->getDpi();img->setDpi(dpi.x, dpi.y);}@@ -678,8 +663,8 @@ TImageP TXshSimpleLevel::getFullsampledFrame(const TFrameId& fid,UCHAR imFlags) const {assert(m_type != UNKNOWN_XSHLEVEL);- FramesSet::const_iterator it = m_frames.find(fid);- if (it == m_frames.end()) return TRasterImageP();+ auto it = m_frames.find(fid);+ if (it == m_frames.end()) return TImageP();std::string imageId = getImageId(fid);@@ -687,9 +672,7 @@ TImageP TXshSimpleLevel::getFullsampledFrame(const TFrameId& fid,TImageP img = ImageManager::instance()->getImage(imageId, imFlags, &extData);if (imFlags & ImageManager::toBeModified) {- // The image will be modified. Perform any related invalidation.- texture_utils::invalidateTexture(- this, fid); // We must rebuild associated textures+ texture_utils::invalidateTexture(this, fid);}return img;@@ -701,16 +684,15 @@ TRasterImageP TXshSimpleLevel::getFrameRasterized(const TFrameId& fid,TPointD dpi) const {assert(m_type == PLI_XSHLEVEL);- FramesSet::const_iterator it = m_frames.find(fid);+ auto it = m_frames.find(fid);if (it == m_frames.end()) return TRasterImageP();- std::string imageId = getImageId(fid);- imageId = rasterized(imageId);+ std::string imageId = rasterized(getImageId(fid));ImageLoader::BuildExtData extData(this, fid, 1);extData.m_cameraDPI = dpi;TImageP img =ImageManager::instance()->getImage(imageId, ImageManager::none, &extData);- return img;+ return TRasterImageP(img);}//-----------------------------------------------------------------------------@@ -733,8 +715,8 @@ std::string TXshSimpleLevel::getIconId(const TFrameId& fid,namespace {TAffine getAffine(const TDimension& srcSize, const TDimension& dstSize) {- double scx = 1 * dstSize.lx / (double)srcSize.lx;- double scy = 1 * dstSize.ly / (double)srcSize.ly;+ double scx = 1.0 * dstSize.lx / static_cast<double>(srcSize.lx);+ double scy = 1.0 * dstSize.ly / static_cast<double>(srcSize.ly);double sc = std::min(scx, scy);double dx = (dstSize.lx - srcSize.lx * sc) * 0.5;double dy = (dstSize.ly - srcSize.ly * sc) * 0.5;@@ -744,12 +726,10 @@ TAffine getAffine(const TDimension& srcSize, const TDimension& dstSize) {//------------------------------------------------------------------------------/*!Builds the icon of dimension \b size of the image \b img.*/TImageP buildIcon(const TImageP& img, const TDimension& size) {TRaster32P raster(size);if (TVectorImageP vi = img) {- TOfflineGL* glContext = new TOfflineGL(size);- // TDimension cameraSize(768, 576);+ std::unique_ptr<TOfflineGL> glContext(new TOfflineGL(size));TDimension cameraSize(1920, 1080);TPalette* vPalette = img->getPalette();assert(vPalette);@@ -758,38 +738,35 @@ TImageP buildIcon(const TImageP& img, const TDimension& size) {glContext->clear(TPixel32::White);glContext->draw(vi, rd);raster->copy(glContext->getRaster());- delete glContext;} else if (TToonzImageP ti = img) {raster->fill(TPixel32(255, 255, 255, 255));TRasterCM32P rasCM32 = ti->getRaster();- TRect bbox;- bbox = ti->getSavebox();+ TRect bbox = ti->getSavebox();if (!bbox.isEmpty()) {- rasCM32 = rasCM32->extractT(bbox);- double sx = raster->getLx() / (double)rasCM32->getLx();- double sy = raster->getLy() / (double)rasCM32->getLy();+ rasCM32 = rasCM32->extract(bbox);+ double sx = static_cast<double>(raster->getLx()) / rasCM32->getLx();+ double sy = static_cast<double>(raster->getLy()) / rasCM32->getLy();double sc = std::min(sx, sy);TAffine aff =TScale(sc).place(rasCM32->getCenterD(), raster->getCenterD());TRop::resample(raster, rasCM32, ti->getPalette(), aff);+raster->lock();for (int y = 0; y < raster->getLy(); y++) {TPixel32* pix = raster->pixels(y);TPixel32* endPix = pix + raster->getLx();while (pix < endPix) {*pix = overPix(TPixel32::White, *pix);- pix++;+ ++pix;}}raster->unlock();}+ } else if (TRasterImageP ri = img) {+ ri->makeIcon(raster);+ TRop::addBackground(raster, TPixel32::White);} else {- TRasterImageP ri = img;- if (ri) {- ri->makeIcon(raster);- TRop::addBackground(raster, TPixel32::White);- } else- raster->fill(TPixel32(127, 50, 20));+ raster->fill(TPixel32(127, 50, 20));}return TRasterImageP(raster);@@ -799,7 +776,6 @@ TImageP buildIcon(const TImageP& img, const TDimension& size) {//------------------------------------------------------------------------------// modify frameId to be with the same frame format as existing framesvoid TXshSimpleLevel::formatFId(TFrameId& fid, TFrameId _tmplFId) {if (m_type != OVL_XSHLEVEL && m_type != TZI_XSHLEVEL) return;@@ -807,10 +783,7 @@ void TXshSimpleLevel::formatFId(TFrameId& fid, TFrameId _tmplFId) {TFrameId tmplFId = *m_frames.begin();fid.setZeroPadding(tmplFId.getZeroPadding());fid.setStartSeqInd(tmplFId.getStartSeqInd());- }- // since there is no reference frame, take sepChar from the path- else {- // override sepchar by the path+ } else {QChar sepChar = m_path.getSepChar();if (!sepChar.isNull()) _tmplFId.setStartSeqInd(sepChar.toLatin1());fid.setZeroPadding(_tmplFId.getZeroPadding());@@ -823,19 +796,20 @@ void TXshSimpleLevel::formatFId(TFrameId& fid, TFrameId _tmplFId) {void TXshSimpleLevel::setFrame(const TFrameId& fid, const TImageP& img) {assert(m_type != UNKNOWN_XSHLEVEL);- if (img) img->setPalette(getPalette());+ if (img) {+ img->setPalette(getPalette());+ }m_frames.insert(fid);- TFilePath path = m_path;-+ TFilePath path = m_path;int frameStatus = getFrameStatus(fid);static const int SCANNED_OR_CLEANUPPED = (Scanned | Cleanupped);- if ((frameStatus & SCANNED_OR_CLEANUPPED) == Scanned) path = m_scannedPath;+ if ((frameStatus & SCANNED_OR_CLEANUPPED) == Scanned) {+ path = m_scannedPath;+ }- // Deal with the ImageManger: ensure the identifiers are bound, and the- // associated image is either modified to img or (if !img) invalidated.const std::string& imageId = getImageId(fid);if (!ImageManager::instance()->isBound(imageId)) {@@ -843,26 +817,25 @@ void TXshSimpleLevel::setFrame(const TFrameId& fid, const TImageP& img) {ImageManager::instance()->bind(imageId, new ImageLoader(decodedPath, fid));}- ImageManager::instance()->setImage(imageId, img); // Invalidates if !img+ ImageManager::instance()->setImage(imageId, img);if (frameStatus == Normal) {- // Only a normal frame can have these. Justified since:- // PLIs have nothing to share with cleanup stuff-if (m_type == PLI_XSHLEVEL) {const std::string& imageId2 = rasterized(imageId);- if (!ImageManager::instance()->isBound(imageId2))+ if (!ImageManager::instance()->isBound(imageId2)) {ImageManager::instance()->bind(imageId2, new ImageRasterizer);- else+ } else {ImageManager::instance()->invalidate(imageId2);+ }}if (m_type == OVL_XSHLEVEL || m_type == TZI_XSHLEVEL) {const std::string& imageId2 = filled(imageId);- if (!ImageManager::instance()->isBound(imageId2))+ if (!ImageManager::instance()->isBound(imageId2)) {ImageManager::instance()->bind(imageId2, new ImageFiller);- else+ } else {ImageManager::instance()->invalidate(imageId2);+ }}}}@@ -870,14 +843,13 @@ void TXshSimpleLevel::setFrame(const TFrameId& fid, const TImageP& img) {//-----------------------------------------------------------------------------void TXshSimpleLevel::eraseFrame(const TFrameId& fid) {- FramesSet::iterator ft = m_frames.find(fid);+ auto ft = m_frames.find(fid);if (ft == m_frames.end()) return;// Erase the corresponding entry in the renumber table- std::map<TFrameId, TFrameId>::iterator rt, rEnd(m_renumberTable.end());- for (rt = m_renumberTable.begin(); rt != rEnd; ++rt) {- if (rt->second == fid) {- m_renumberTable.erase(rt->first);+ for (auto it = m_renumberTable.begin(); it != m_renumberTable.end(); ++it) {+ if (it->second == fid) {+ m_renumberTable.erase(it);break;}}@@ -887,22 +859,24 @@ void TXshSimpleLevel::eraseFrame(const TFrameId& fid) {ImageManager* im = ImageManager::instance();TImageCache* ic = TImageCache::instance();- {- im->unbind(getImageId(fid, Normal));- im->unbind(getImageId(fid, Scanned));- im->unbind(getImageId(fid, CleanupPreview));- // remove icon cache as well- ic->remove(getIconId(fid, Normal));- ic->remove(getIconId(fid, Scanned));- ic->remove(getIconId(fid, CleanupPreview));- if (m_type == PLI_XSHLEVEL) im->unbind(rasterized(getImageId(fid)));+ im->unbind(getImageId(fid, Normal));+ im->unbind(getImageId(fid, Scanned));+ im->unbind(getImageId(fid, CleanupPreview));- if (m_type == OVL_XSHLEVEL || m_type == TZI_XSHLEVEL)- im->unbind(filled(getImageId(fid)));+ ic->remove(getIconId(fid, Normal));+ ic->remove(getIconId(fid, Scanned));+ ic->remove(getIconId(fid, CleanupPreview));- texture_utils::invalidateTexture(this, fid);+ if (m_type == PLI_XSHLEVEL) {+ im->unbind(rasterized(getImageId(fid)));+ }++ if (m_type == OVL_XSHLEVEL || m_type == TZI_XSHLEVEL) {+ im->unbind(filled(getImageId(fid)));}++ texture_utils::invalidateTexture(this, fid);}//-----------------------------------------------------------------------------@@ -910,26 +884,27 @@ void TXshSimpleLevel::eraseFrame(const TFrameId& fid) {void TXshSimpleLevel::clearFrames() {ImageManager* im = ImageManager::instance();TImageCache* ic = TImageCache::instance();- // Unbind frames- FramesSet::iterator ft, fEnd = m_frames.end();- for (ft = m_frames.begin(); ft != fEnd; ++ft) {- im->unbind(getImageId(*ft, Scanned));- im->unbind(getImageId(*ft, Cleanupped));- im->unbind(getImageId(*ft, CleanupPreview));- // remove icon cache as well- ic->remove(getIconId(*ft, Normal));- ic->remove(getIconId(*ft, Scanned));- ic->remove(getIconId(*ft, CleanupPreview));- if (m_type == PLI_XSHLEVEL) im->unbind(rasterized(getImageId(*ft)));+ for (const auto& fid : m_frames) {+ im->unbind(getImageId(fid, Scanned));+ im->unbind(getImageId(fid, Cleanupped));+ im->unbind(getImageId(fid, CleanupPreview));- if (m_type == OVL_XSHLEVEL || m_type == TZI_XSHLEVEL)- im->unbind(filled(getImageId(*ft)));+ ic->remove(getIconId(fid, Normal));+ ic->remove(getIconId(fid, Scanned));+ ic->remove(getIconId(fid, CleanupPreview));- texture_utils::invalidateTexture(this, *ft);+ if (m_type == PLI_XSHLEVEL) {+ im->unbind(rasterized(getImageId(fid)));+ }++ if (m_type == OVL_XSHLEVEL || m_type == TZI_XSHLEVEL) {+ im->unbind(filled(getImageId(fid)));+ }++ texture_utils::invalidateTexture(this, fid);}- // Clear levelm_frames.clear();m_editableRange.clear();m_editableRangeUserInfo.clear();@@ -963,11 +938,14 @@ void TXshSimpleLevel::loadData(TIStream& is) {int isStopMotionLevel = 0;double colorSpaceGamma = LevelOptions::DefaultColorSpaceGamma;LevelProperties::DpiPolicy dpiPolicy = LevelProperties::DP_ImageDpi;+if (is.getTagParam("dpix", v)) xdpi = std::stod(v);if (is.getTagParam("dpiy", v)) ydpi = std::stod(v);if (xdpi != 0 && ydpi != 0) dpiPolicy = LevelProperties::DP_CustomDpi;+std::string dpiType = is.getTagAttribute("dpiType");if (dpiType == "image") dpiPolicy = LevelProperties::DP_ImageDpi;+if (is.getTagParam("type", v) && v == "s") type = TZI_XSHLEVEL;if (is.getTagParam("subsampling", v)) subsampling = std::stoi(v);if (is.getTagParam("premultiply", v)) doPremultiply = std::stoi(v);@@ -986,21 +964,21 @@ void TXshSimpleLevel::loadData(TIStream& is) {m_properties->setWhiteTransp(whiteTransp);m_properties->setIsStopMotion(isStopMotionLevel);m_properties->setColorSpaceGamma(colorSpaceGamma);+if (isStopMotionLevel == 1) setIsReadOnly(true);- } else+ } else {throw TException("unexpected tag " + tagName);+ }} else {- if (flag) break; // there can be only one name+ if (flag) break;flag = true;std::wstring token;is >> token;if (token == L"__empty") {- // empty = true;is >> token;}- if (token == L"_raster") // obsolete (Tab2.2)- {+ if (token == L"_raster") {double xdpi = 1, ydpi = 1;is >> xdpi >> ydpi >> m_name;setName(m_name);@@ -1010,8 +988,7 @@ void TXshSimpleLevel::loadData(TIStream& is) {setPath(TFilePath("+drawings/") + (getName() + L"." + ::to_wstring("bmp")),true);- } else if (token == L"__raster") // obsolete (Tab2.2)- {+ } else if (token == L"__raster") {double xdpi = 1, ydpi = 1;std::string extension;is >> xdpi >> ydpi >> m_name >> extension;@@ -1028,6 +1005,7 @@ void TXshSimpleLevel::loadData(TIStream& is) {}}}+if (type == UNKNOWN_XSHLEVEL) {std::string ext = m_path.getType();if (ext == "pli" || ext == "svg")@@ -1055,7 +1033,6 @@ public:LoadingLevelRange() : m_fromFid(1), m_toFid(0) {}bool match(const TFrameId& fid) const {- /*-- ↓Condition for being within SubSequence range ↓When loading all --*/return ((m_fromFid <= fid && fid <= m_toFid) || m_fromFid > m_toFid);}bool isEnabled() const { return m_fromFid <= m_toFid; }@@ -1063,11 +1040,10 @@ public:m_fromFid = TFrameId(1);m_toFid = TFrameId(0);}-} loadingLevelRange;-//-----------------------------------------------------------------------------} // namespace+//-----------------------------------------------------------------------------void setLoadingLevelRange(const TFrameId& fromFid, const TFrameId& toFid) {@@ -1080,6 +1056,8 @@ void getLoadingLevelRange(TFrameId& fromFid, TFrameId& toFid) {toFid = loadingLevelRange.m_toFid;}+//-----------------------------------------------------------------------------+static TFilePath getLevelPathAndSetNameWithPsdLevelName(TXshSimpleLevel* xshLevel) {TFilePath retfp = xshLevel->getPath();@@ -1099,11 +1077,8 @@ static TFilePath getLevelPathAndSetNameWithPsdLevelName(Preferences::instance()->getLayerNameEncoding().c_str());if (hasLayerId) {- // An explicit photoshop layer id must be converted to the associated- // level nameTPSDParser psdparser(xshLevel->getScene()->decodeFilePath(retfp));- std::string levelName = psdparser.getLevelNameWithCounter(- layid); // o_o what about UNICODE names??+ std::string levelName = psdparser.getLevelNameWithCounter(layid);list[1] = layerNameCodec->toUnicode(levelName.c_str());std::wstring wLevelName = list.join("#").toStdWString();@@ -1112,9 +1087,9 @@ static TFilePath getLevelPathAndSetNameWithPsdLevelName(if (removeFileName) wLevelName = list[1].toStdWString();TLevelSet* levelSet = xshLevel->getScene()->getLevelSet();- if (levelSet && levelSet->hasLevel(- wLevelName)) // levelSet should be asserted instead+ if (levelSet && levelSet->hasLevel(wLevelName)) {levelSet->renameLevel(xshLevel, wLevelName);+ }xshLevel->setName(wLevelName);}@@ -1122,10 +1097,9 @@ static TFilePath getLevelPathAndSetNameWithPsdLevelName(return retfp;}+//------------------------------------------------------------------------------// Note: load() does NOT clearFrames(). It only adds the information-// relative to the frames on diskvoid TXshSimpleLevel::load() {getProperties()->setCreator("");QString creator;@@ -1139,8 +1113,7 @@ void TXshSimpleLevel::load() {std::string type = checkpath.getType();if (m_scannedPath != TFilePath()) {- getProperties()->setDirtyFlag(- false); // Level is now supposedly loaded from disk+ getProperties()->setDirtyFlag(false);static const int ScannedCleanuppedMask = Scanned | Cleanupped;TFilePath path = getScene()->decodeFilePath(m_scannedPath);@@ -1148,16 +1121,17 @@ void TXshSimpleLevel::load() {TLevelReaderP lr(path);assert(lr);TLevelP level = lr->loadInfo();- if (!checkCreatorString(creator = lr->getCreator()))+ if (!checkCreatorString(creator = lr->getCreator())) {getProperties()->setIsForbidden(true);- else- for (TLevel::Iterator it = level->begin(); it != level->end(); it++) {+ } else {+ for (TLevel::Iterator it = level->begin(); it != level->end(); ++it) {TFrameId fid = it->first;if (!loadingLevelRange.match(fid)) continue;setFrameStatus(fid, (getFrameStatus(fid) & ~ScannedCleanuppedMask) | Scanned);setFrame(fid, TImageP());}+ }}path = getScene()->decodeFilePath(m_path);@@ -1165,60 +1139,55 @@ void TXshSimpleLevel::load() {TLevelReaderP lr(path);assert(lr);TLevelP level = lr->loadInfo();- if (getType() & FULLCOLOR_TYPE)+ if (getType() & FULLCOLOR_TYPE) {setPalette(FullColorPalette::instance()->getPalette(getScene()));- else+ } else {setPalette(level->getPalette());- if (!checkCreatorString(creator = lr->getCreator()))+ }+ if (!checkCreatorString(creator = lr->getCreator())) {getProperties()->setIsForbidden(true);- else- for (TLevel::Iterator it = level->begin(); it != level->end(); it++) {+ } else {+ for (TLevel::Iterator it = level->begin(); it != level->end(); ++it) {TFrameId fid = it->first;if (!loadingLevelRange.match(fid)) continue;setFrameStatus(fid, getFrameStatus(fid) | Cleanupped);setFrame(fid, TImageP());}+ }setContentHistory(- lr->getContentHistory() ? lr->getContentHistory()->clone() : 0);+ lr->getContentHistory() ? lr->getContentHistory()->clone() : nullptr);}-} else {- // Not a scan + cleanup level-- // Loading PSD files via load level command needs to convert layerID in the- // file path to layer name here. The conversion is not needed on loading- // scene as the file path loaded from the scene file is already converted.- if (m_path.getType() == "psd" && !this->getScene()->isLoading())+ if (m_path.getType() == "psd" && !this->getScene()->isLoading()) {m_path = getLevelPathAndSetNameWithPsdLevelName(this);+ }TFilePath path = getScene()->decodeFilePath(m_path);+ getProperties()->setDirtyFlag(false);- getProperties()->setDirtyFlag(- false); // Level is now supposedly loaded from disk-- TLevelReaderP lr(path); // May throw+ TLevelReaderP lr(path);assert(lr);TLevelP level = lr->loadInfo();if (level->isPartialLoad()) {QString msg =QString(- "File '%1' partially loaded. Not all frames were found. Possible "- "file corruption. Loaded what could be found.\nRecommend "- "replacing any bad frames in Level Strip and saving.")+ "File '%1' partially loaded. Not all frames were found. "+ "Possible file corruption. Loaded what could be found.\n"+ "Recommend replacing any bad frames in Level Strip and saving.").arg(QString::fromStdWString(m_path.getWideString()));- QMessageBox::warning(0, "File load warning", msg);+ QMessageBox::warning(nullptr, "File load warning", msg);setDirtyFlag(true);}+if (level->getFrameCount() > 0) {const TImageInfo* info = lr->getImageInfo(level->begin()->first);-if (info && info->m_samplePerPixel >= 5) {QString msg = QString("Failed to open %1.\nSamples per pixel is more than ""4. It may contain more than one alpha channel.").arg(QString::fromStdWString(m_path.getWideString()));- QMessageBox::warning(0, "Image format not supported", msg);+ QMessageBox::warning(nullptr, "Image format not supported", msg);return;}@@ -1227,28 +1196,30 @@ void TXshSimpleLevel::load() {setFloatChannelLevel(info->m_bitsPerSample == 32);}}- if ((getType() & FULLCOLOR_TYPE) && !is16BitChannelLevel())++ if ((getType() & FULLCOLOR_TYPE) && !is16BitChannelLevel()) {setPalette(FullColorPalette::instance()->getPalette(getScene()));- else+ } else {setPalette(level->getPalette());+ }- if (!checkCreatorString(creator = lr->getCreator()))+ if (!checkCreatorString(creator = lr->getCreator())) {getProperties()->setIsForbidden(true);- else- for (TLevel::Iterator it = level->begin(); it != level->end(); it++) {- m_renumberTable[it->first] = it->first; // I want the table to- // also contain the frames that- // are not loaded+ } else {+ for (TLevel::Iterator it = level->begin(); it != level->end(); ++it) {+ m_renumberTable[it->first] = it->first;if (!loadingLevelRange.match(it->first)) continue;setFrame(it->first, TImageP());}+ }setContentHistory(lr->getContentHistory() ? lr->getContentHistory()->clone()- : 0);+ : nullptr);}- getProperties()->setCreator(creator.toStdString());+ getProperties()->setCreator(creator.toStdString());loadingLevelRange.reset();+if (getType() != PLI_XSHLEVEL) {if (m_properties->getImageDpi() == TPointD() && !m_frames.empty()) {TDimension imageRes(0, 0);@@ -1273,8 +1244,9 @@ void TXshSimpleLevel::load() {setRenumberTable();}- if (getPalette() && StudioPalette::isEnabled())+ if (getPalette() && StudioPalette::isEnabled()) {StudioPalette::instance()->updateLinkedColors(getPalette());+ }TFilePath refImgName;if (m_palette) {@@ -1287,44 +1259,22 @@ void TXshSimpleLevel::load() {if (level->getFrameCount() > 0) {TImageP img = lr->getFrameReader(level->begin()->first)->load();if (img && getPalette()) {- img->setPalette(0);+ img->setPalette(nullptr);getPalette()->setRefImg(img);std::vector<TFrameId> fids = getPalette()->getRefLevelFids();- // in case the fids are specified by user- if (fids.size() > 0) {- // check existence of each fid- auto itr = fids.begin();- while (itr != fids.end()) {- bool found = false;- for (TLevel::Iterator it = level->begin(); it != level->end();- ++it) {- if (itr->getNumber() == it->first.getNumber()) {- found = true;- break;- }- }- if (!found) // remove the fid if it does not exist in the level- itr = fids.erase(itr);- else- itr++;- }- }- // in case the fids are not specified, or all specified fids are- // absent- if (fids.size() == 0) {+ if (fids.empty()) {for (TLevel::Iterator it = level->begin(); it != level->end();- ++it)+ ++it) {fids.push_back(it->first);+ }getPalette()->setRefLevelFids(fids, false);- } else if (fids.size() != getPalette()->getRefLevelFids().size())- getPalette()->setRefLevelFids(fids, true);+ }}}}}}- // Load hooksHookSet* hookSet = getHookSet();hookSet->clearHooks();@@ -1352,20 +1302,18 @@ void TXshSimpleLevel::load(const std::vector<TFrameId>& fIds) {m_isSubsequence = loadingLevelRange.isEnabled();- // it is not a scan+cleanup levelTFilePath path = getScene()->decodeFilePath(m_path);-TLevelReaderP lr(path);assert(lr);- if (!checkCreatorString(creator = lr->getCreator()))+ if (!checkCreatorString(creator = lr->getCreator())) {getProperties()->setIsForbidden(true);- else {- if (fIds.size() != 0) {- for (int i = 0; i < (int)fIds.size(); i++) {- m_renumberTable[fIds[i]] = fIds[i];- if (!loadingLevelRange.match(fIds[i])) continue;- setFrame(fIds[i], TImageP());+ } else {+ if (!fIds.empty()) {+ for (const auto& fid : fIds) {+ m_renumberTable[fid] = fid;+ if (!loadingLevelRange.match(fid)) continue;+ setFrame(fid, TImageP());}const TImageInfo* info = lr->getImageInfo(fIds[0]);if (info) {@@ -1374,7 +1322,7 @@ void TXshSimpleLevel::load(const std::vector<TFrameId>& fIds) {}} else {TLevelP level = lr->loadInfo();- for (TLevel::Iterator it = level->begin(); it != level->end(); it++) {+ for (TLevel::Iterator it = level->begin(); it != level->end(); ++it) {m_renumberTable[it->first] = it->first;if (!loadingLevelRange.match(it->first)) continue;setFrame(it->first, TImageP());@@ -1386,15 +1334,15 @@ void TXshSimpleLevel::load(const std::vector<TFrameId>& fIds) {}}- if ((getType() & FULLCOLOR_TYPE) && !is16BitChannelLevel())+ if ((getType() & FULLCOLOR_TYPE) && !is16BitChannelLevel()) {setPalette(FullColorPalette::instance()->getPalette(getScene()));+ }}setContentHistory(lr->getContentHistory() ? lr->getContentHistory()->clone()- : 0);+ : nullptr);getProperties()->setCreator(creator.toStdString());-loadingLevelRange.reset();if (getType() != PLI_XSHLEVEL) {@@ -1464,9 +1412,8 @@ void TXshSimpleLevel::saveData(TOStream& os) {os.openCloseChild("info", attr);- os.child("path") << m_path; // fp;- if (m_scannedPath != TFilePath())- os.child("scannedPath") << m_scannedPath; // fp;+ os.child("path") << m_path;+ if (m_scannedPath != TFilePath()) os.child("scannedPath") << m_scannedPath;}//-----------------------------------------------------------------------------@@ -1494,14 +1441,11 @@ void TXshSimpleLevel::save() {//-----------------------------------------------------------------------------static void saveBackup(TFilePath path) {- // The additional .bak extension keeps it from being detected as a sequence.- // If the original path is a sequence, find the individual files and back it- // up individuallyif (path.isLevelName()) {TFilePathSet files =TSystem::readDirectory(path.getParentDir(), false, true);for (TFilePathSet::iterator file = files.begin(); file != files.end();- file++) {+ ++file) {if (file->getLevelName() == path.getLevelName()) saveBackup(*file);}return;@@ -1546,78 +1490,60 @@ void TXshSimpleLevel::save(const TFilePath& fp, const TFilePath& oldFp,dDstPath,"The level cannot be saved: failed to access the target folder.");- // backupif (Preferences::instance()->isBackupEnabled() && dOldPath == dDstPath &&TSystem::doesExistFileOrLevel(dDstPath) &&- !getProperties()->isStopMotionLevel())+ !getProperties()->isStopMotionLevel()) {saveBackup(dDstPath);+ }if (isAreadOnlyLevel(dDstPath)) {- if (m_editableRange.empty() &&- !m_temporaryHookMerged) // file internally locked+ if (m_editableRange.empty() && !m_temporaryHookMerged) {throw TSystemException(dDstPath, "The level cannot be saved: it is a read only level.");- else if (getType() != OVL_XSHLEVEL) {- // file partially unlocked+ } else if (getType() != OVL_XSHLEVEL) {std::wstring fileName = getEditableFileName();assert(!fileName.empty());TFilePath app = dDstPath.withName(fileName).withType(dDstPath.getType());- // removes old filesif (TSystem::doesExistFileOrLevel(app)) TSystem::removeFileOrLevel(app);TFilePathSet oldFilePaths;getFiles(app, oldFilePaths);- TFilePathSet::iterator it;- for (it = oldFilePaths.begin(); it != oldFilePaths.end(); ++it) {+ for (auto it = oldFilePaths.begin(); it != oldFilePaths.end(); ++it) {if (TSystem::doesExistFileOrLevel(*it)) TSystem::removeFileOrLevel(*it);}- // save new filesTXshSimpleLevel* sl = new TXshSimpleLevel;sl->setScene(getScene());sl->setPalette(getPalette());sl->setPath(getScene()->codeFilePath(app));sl->setType(getType());sl->setDirtyFlag(getDirtyFlag());- sl->addRef(); // Needed so levelUpdater doesn't destroy it right away- // when its done writing+ sl->addRef();- std::set<TFrameId>::iterator eft, efEnd = m_editableRange.end();- for (eft = m_editableRange.begin(); eft != efEnd; ++eft) {- const TFrameId& fid = *eft;+ for (const auto& fid : m_editableRange) {sl->setFrame(fid, getFrame(fid, false));}- // Copy hooksHookSet* hookSet = sl->getHookSet();*hookSet = *getHookSet();- FramesSet::iterator ft, fEnd = m_frames.end();- for (ft = m_frames.begin(); ft != fEnd; ++ft) {- const TFrameId& fid = *ft;-- if (m_editableRange.find(fid) == m_editableRange.end())+ for (const auto& fid : m_frames) {+ if (m_editableRange.find(fid) == m_editableRange.end()) {hookSet->eraseFrame(fid);+ }}sl->setRenumberTable();-- // Copy mesh levelsl->save(app);#ifdef _WIN32-- // hides files- oldFilePaths.clear();-if (TSystem::doesExistFileOrLevel(app)) TSystem::hideFileOrLevel(app);-+ oldFilePaths.clear();getFiles(app, oldFilePaths);-- for (it = oldFilePaths.begin(); it != oldFilePaths.end(); ++it) {+ for (auto it = oldFilePaths.begin(); it != oldFilePaths.end(); ++it) {if (TSystem::doesExistFileOrLevel(*it)) TSystem::hideFileOrLevel(*it);}#endif@@ -1627,18 +1553,16 @@ void TXshSimpleLevel::save(const TFilePath& fp, const TFilePath& oldFp,if (dOldPath != dDstPath && m_path != TFilePath()) {const TFilePath& dSrcPath = dOldPath;-try {if (TSystem::doesExistFileOrLevel(dSrcPath)) {if (TSystem::doesExistFileOrLevel(dDstPath))TSystem::removeFileOrLevel(dDstPath);-copyFiles(dDstPath, dSrcPath);}} catch (...) {}}- // when saving the level palette with global name+if (overwritePalette && getType() == TZP_XSHLEVEL && getPalette() &&getPalette()->getGlobalName() != L"") {overwritePalette = false;@@ -1654,19 +1578,13 @@ void TXshSimpleLevel::save(const TFilePath& fp, const TFilePath& oldFp,void TXshSimpleLevel::saveSimpleLevel(const TFilePath& decodedFp,bool overwritePalette) {- /* Precondition: Destination level with path decodedFp is supposed to already- store those image frames not tagged as 'modified' in this level- instance. */-TFilePath oldPath = m_path;TFilePath dOldPath = getScene()->decodeFilePath(oldPath);- // Substitute m_path with decodedFp until the function quits.struct CopyOnExit {TFilePath &m_dstPath, &m_srcPath;~CopyOnExit() { m_dstPath = m_srcPath; }- } copyOnExit = {m_path = decodedFp,- oldPath}; // m_path substituted here until function quits+ } copyOnExit = {m_path = decodedFp, oldPath};bool savingOriginal = (decodedFp == dOldPath), paletteNotSaved = false;@@ -1682,10 +1600,6 @@ void TXshSimpleLevel::saveSimpleLevel(const TFilePath& decodedFp,if (getPalette()) isPaletteModified = getPalette()->getDirtyFlag();if (isLevelModified || isPaletteModified) {- // gmt (8/8/08. trying to solve the mess of tlv writing.- // We need- // to rethink it more calmly. For now, trying to do as little damage as- // possible).TDimension oldRes(0, 0);bool fileOrLevelRemoved = false;if (TSystem::doesExistFileOrLevel(decodedFp)) {@@ -1700,9 +1614,6 @@ void TXshSimpleLevel::saveSimpleLevel(const TFilePath& decodedFp,oldRes.ly = imageInfo->m_ly;lr = TLevelReaderP();if (getProperties()->getImageRes() != oldRes) {- // The canvas size command changes the level dimensions!!!- // If the file already exists, in the level writer the dimensions of- // the existing file are reset and it saves badlyTSystem::removeFileOrLevel(decodedFp);fileOrLevelRemoved = true;}@@ -1710,21 +1621,15 @@ void TXshSimpleLevel::saveSimpleLevel(const TFilePath& decodedFp,} catch (...) {}}- // overwrite tlv+if (decodedFp.getType() == "tlv" &&TSystem::doesExistFileOrLevel(decodedFp)) {if (isLevelModified) {- // in this case I should only write the modified frames.- // certainly I MUST NOT write those that I don't have (and that I- // should reread from the same file that I'm writing-int oldSubs = getProperties()->getSubsampling();-TLevelWriterP lw;try {lw = TLevelWriterP(decodedFp);} catch (...) {- // revert subsamplingm_properties->setSubsampling(oldSubs);m_path = oldPath;throw TSystemException(decodedFp,@@ -1734,15 +1639,10 @@ void TXshSimpleLevel::saveSimpleLevel(const TFilePath& decodedFp,}lw->setOverwritePaletteFlag(overwritePalette);-lw->setCreator(getCreatorString());lw->setPalette(getPalette());- // Filter out of the renumber table all non-tlv frames (could happen- // if the level is a scan-cleanup mix). This is fine even on the- // temporarily substituted m_path.std::map<TFrameId, TFrameId> renumberTable;-for (auto it = m_renumberTable.rbegin(); it != m_renumberTable.rend();++it) {TFrameId id = (*it).first;@@ -1764,9 +1664,7 @@ void TXshSimpleLevel::saveSimpleLevel(const TFilePath& decodedFp,ImageLoader::BuildExtData extData(this, TFrameId());for (auto const& fid : fids) {- std::string imageId = getImageId(- fid,- Normal); // Retrieve the actual level frames ("L_whatever")+ std::string imageId = getImageId(fid, Normal);if (!fileOrLevelRemoved &&!ImageManager::instance()->isModified(imageId))continue;@@ -1788,9 +1686,6 @@ void TXshSimpleLevel::saveSimpleLevel(const TFilePath& decodedFp,if (subs != 1) continue;if (TToonzImageP ti = img) {- /*-- * When using SaveBox to prevent paint leakage, the actual image- * range and SaveBox size differ, so update it here-*/TRect saveBox;TRop::computeBBox(ti->getRaster(), saveBox);ti->setSavebox(saveBox);@@ -1799,7 +1694,7 @@ void TXshSimpleLevel::saveSimpleLevel(const TFilePath& decodedFp,lw->getFrameWriter(fid)->save(img);}- lw = TLevelWriterP(); // TLevelWriterP's destructor saves the palette+ lw = TLevelWriterP();} else if (isPaletteModified && overwritePalette) {TFilePath palettePath = decodedFp.withNoFrame().withType("tpl");if (Preferences::instance()->isBackupEnabled() &&@@ -1812,8 +1707,6 @@ void TXshSimpleLevel::saveSimpleLevel(const TFilePath& decodedFp,paletteNotSaved = true;}} else {- // for now I'm doing what I did before, but we need to review the whole- // strategyLevelUpdater updater(this);updater.getLevelWriter()->setCreator(getCreatorString());if (updater.getImageInfo())@@ -1821,11 +1714,6 @@ void TXshSimpleLevel::saveSimpleLevel(const TFilePath& decodedFp,updater.getImageInfo()->m_frameRate);if (isLevelModified) {- // Apply the level's renumber table, before saving other files.- // NOTE: This is currently NOT under LevelUpdater's responsibility, as- // renumber tables- // are set/manipulated heavily here. The approach should be- // re-designed, though...updater.getLevelWriter()->renumberFids(m_renumberTable);if (!m_editableRange.empty())@@ -1835,9 +1723,7 @@ void TXshSimpleLevel::saveSimpleLevel(const TFilePath& decodedFp,ImageLoader::BuildExtData extData(this, TFrameId());for (auto const& fid : fids) {- std::string imageId = getImageId(- fid,- Normal); // Retrieve the actual level frames ("L_whatever")+ std::string imageId = getImageId(fid, Normal);if (!fileOrLevelRemoved &&!ImageManager::instance()->isModified(imageId))continue;@@ -1861,29 +1747,24 @@ void TXshSimpleLevel::saveSimpleLevel(const TFilePath& decodedFp,updater.update(fid, img);}}- updater.close(); // Needs the original level subs+ updater.close();if ((getType() & FULLCOLOR_TYPE) && isPaletteModified)FullColorPalette::instance()->savePalette(getScene());}}- // Save hooks-TFilePath hookFile;- HookSet* hookSet = 0;+ HookSet* hookSet = nullptr;- // Save the hookSet in a temporary hook fileif (getType() == OVL_XSHLEVEL && !m_editableRange.empty()) {hookSet = new HookSet(*getHookSet());- FramesSet::const_iterator it;- for (it = m_frames.begin(); it != m_frames.end(); ++it) {- TFrameId fid = *it;- if (m_editableRange.find(fid) == m_editableRange.end())+ for (const auto& fid : m_frames) {+ if (m_editableRange.find(fid) == m_editableRange.end()) {hookSet->eraseFrame(fid);+ }}- // file partially unlockedstd::wstring fileName = getEditableFileName();assert(!fileName.empty());TFilePath app = decodedFp.withName(fileName).withType(decodedFp.getType());@@ -1894,8 +1775,6 @@ void TXshSimpleLevel::saveSimpleLevel(const TFilePath& decodedFp,}#ifdef _WIN32- // Remove the hidden attribute (since TOStream's fopen fails on hidden- // files)if (getType() == OVL_XSHLEVEL && !m_editableRange.empty())SetFileAttributesW(hookFile.getWideString().c_str(), FILE_ATTRIBUTE_NORMAL);#endif@@ -1918,16 +1797,15 @@ void TXshSimpleLevel::saveSimpleLevel(const TFilePath& decodedFp,#endifif (savingOriginal) {- setRenumberTable(); // Since the renumber table refers to the- // 'original' frames saved on disk+ setRenumberTable();if (m_properties) m_properties->setDirtyFlag(false);-if (getPalette() && overwritePalette) getPalette()->setDirtyFlag(false);}- if (paletteNotSaved)+ if (paletteNotSaved) {throw TSystemException(m_path,"The palette of the level could not be saved.");+ }}//-----------------------------------------------------------------------------@@ -1947,7 +1825,7 @@ std::string TXshSimpleLevel::getImageId(const TFrameId& fid,//-----------------------------------------------------------------------------int TXshSimpleLevel::getFrameStatus(const TFrameId& fid) const {- std::map<TFrameId, int>::const_iterator it = m_framesStatus.find(fid);+ auto it = m_framesStatus.find(fid);return (it != m_framesStatus.end()) ? it->second : Normal;}@@ -1957,9 +1835,9 @@ void TXshSimpleLevel::setFrameStatus(const TFrameId& fid, int status) {assert((status & ~(Scanned | Cleanupped | CleanupPreview)) == 0);m_framesStatus[fid] = status;}+//------------------------------------------------------------------------------/*- Used in CleanupPopup::setCurrentLevel / TCleanupper -*/void TXshSimpleLevel::makeTlv(const TFilePath& tlvPath) {int ltype = getType();@@ -1969,15 +1847,11 @@ void TXshSimpleLevel::makeTlv(const TFilePath& tlvPath) {}setType(TZP_XSHLEVEL);-m_scannedPath = m_path;-assert(tlvPath.getType() == "tlv");m_path = tlvPath;- FramesSet::const_iterator it;- for (it = m_frames.begin(); it != m_frames.end(); ++it) {- TFrameId fid = *it;+ for (const auto& fid : m_frames) {setFrameStatus(fid, Scanned);ImageManager::instance()->rebind(getImageId(fid, Scanned),getImageId(fid, 0));@@ -1989,20 +1863,20 @@ void TXshSimpleLevel::makeTlv(const TFilePath& tlvPath) {//-----------------------------------------------------------------------------void TXshSimpleLevel::invalidateFrames() {- FramesSet::iterator ft, fEnd = m_frames.end();- for (ft = m_frames.begin(); ft != fEnd; ++ft)- ImageManager::instance()->invalidate(getImageId(*ft));+ for (const auto& fid : m_frames) {+ ImageManager::instance()->invalidate(getImageId(fid));+ }}+//------------------------------------------------------------------------------/*- Invalidate only the specified FId -*/void TXshSimpleLevel::invalidateFrame(const TFrameId& fid) {std::string id = getImageId(fid);ImageManager::instance()->invalidate(id);}//------------------------------------------------------------------------------// note that the palette will always be replaced by the new one.+void TXshSimpleLevel::initializePalette() {ToonzScene* scene = getScene();assert(scene);@@ -2073,7 +1947,7 @@ void TXshSimpleLevel::initializeResolutionAndDpi(const TDimension& dim,double dpiY = dpi;getProperties()->setDpiPolicy(LevelProperties::DP_ImageDpi);if (dim == TDimension()) {- double w, h;+ double w = 0, h = 0;Preferences* pref = Preferences::instance();if (pref->isNewLevelSizeToCameraSizeEnabled()) {TDimensionD camSize = getScene()->getCurrentCamera()->getSize();@@ -2090,8 +1964,9 @@ void TXshSimpleLevel::initializeResolutionAndDpi(const TDimension& dim,}getProperties()->setImageRes(TDimension(tround(w * dpi), tround(h * dpiY)));- } else+ } else {getProperties()->setImageRes(dim);+ }getProperties()->setImageDpi(TPointD(dpi, dpiY));getProperties()->setDpi(dpi);@@ -2099,13 +1974,7 @@ void TXshSimpleLevel::initializeResolutionAndDpi(const TDimension& dim,//------------------------------------------------------------------------------// creates a frame with type, dimensions, dpi, etc. compatible with the levelTImageP TXshSimpleLevel::createEmptyFrame() {- // In case this is the first frame to be created in this level (i.e. the- // level file was missing when loading resources) initialize the level in- // the same manner as createNewLevel() in order to avoid crash. This can be- // happened if the level was not saved after creating and being placed in- // the xsheet.if (isEmpty()) {if (!getPalette()) initializePalette();initializeResolutionAndDpi();@@ -2123,23 +1992,11 @@ TImageP TXshSimpleLevel::createEmptyFrame() {break;case MESH_XSHLEVEL:- assert(false); // Not implemented yet+ assert(false);break;default: {- // normally the image must have the level->getProperties()->getImageDpi().- // if this value is missing (for some reason - can this happen, ever?)- // then we use the getDpi() (that is the current dpi, e.g. cameraDpi or- // customDpi).-- TPointD dpi = getProperties()->getImageDpi();- /*--- When inserting and pasting something converted from tga to tlv,- only the pasted frame gets DPI, so skip this processing- --*/- // if(dpi.x==0.0 || dpi.y==0.0)- // dpi = getProperties()->getDpi();-+ TPointD dpi = getProperties()->getImageDpi();TDimension res = getProperties()->getImageRes();if (m_type == TZP_XSHLEVEL) {@@ -2148,17 +2005,14 @@ TImageP TXshSimpleLevel::createEmptyFrame() {TToonzImageP ti(raster, TRect());ti->setDpi(dpi.x, dpi.y);ti->setSavebox(TRect(0, 0, res.lx - 1, res.ly - 1));-result = ti;} else {TRaster32P raster(res);raster->fill(TPixel32(0, 0, 0, 0));TRasterImageP ri(raster);ri->setDpi(dpi.x, dpi.y);-result = ri;}-break;}}@@ -2168,8 +2022,6 @@ TImageP TXshSimpleLevel::createEmptyFrame() {//------------------------------------------------------------------------------// returns the resolution of the level frames (if the level is not-// vector)TDimension TXshSimpleLevel::getResolution() {if (isEmpty() || getType() == PLI_XSHLEVEL) return TDimension();return m_properties->getImageRes();@@ -2177,7 +2029,6 @@ TDimension TXshSimpleLevel::getResolution() {//------------------------------------------------------------------------------// returns the dpi read from fileTPointD TXshSimpleLevel::getImageDpi(const TFrameId& fid, int frameStatus) {if (isEmpty() || getType() == PLI_XSHLEVEL) return TPointD();@@ -2206,7 +2057,6 @@ int TXshSimpleLevel::getImageSubsampling(const TFrameId& fid) const {//------------------------------------------------------------------------------// returns the current dpi of the levelTPointD TXshSimpleLevel::getDpi(const TFrameId& fid, int frameStatus) {TPointD dpi;if (m_properties->getDpiPolicy() == LevelProperties::DP_ImageDpi)@@ -2220,31 +2070,31 @@ TPointD TXshSimpleLevel::getDpi(const TFrameId& fid, int frameStatus) {void TXshSimpleLevel::renumber(const std::vector<TFrameId>& fids) {assert(fids.size() == m_frames.size());- int n = fids.size();+ int n = static_cast<int>(fids.size());- int i = 0;std::vector<TFrameId> oldFids;getFids(oldFids);std::map<TFrameId, TFrameId> table;std::map<TFrameId, TFrameId> newRenumberTable;- for (std::vector<TFrameId>::iterator it = oldFids.begin();- it != oldFids.end(); ++it) {- TFrameId oldFrameId = *it;- TFrameId newFrameId = fids[i++];++ for (int i = 0; i < n; ++i) {+ TFrameId oldFrameId = oldFids[i];+ TFrameId newFrameId = fids[i];table[oldFrameId] = newFrameId;- for (auto const& renumber : m_renumberTable) {+ for (const auto& renumber : m_renumberTable) {if (renumber.second == oldFrameId) {newRenumberTable[renumber.first] = newFrameId;break;}}}- for (auto const& renumber : newRenumberTable) {++ for (const auto& renumber : newRenumberTable) {m_renumberTable[renumber.first] = renumber.second;}m_frames.clear();- for (i = 0; i < n; ++i) {+ for (int i = 0; i < n; ++i) {TFrameId fid(fids[i]);assert(m_frames.count(fid) == 0);m_frames.insert(fid);@@ -2254,9 +2104,9 @@ void TXshSimpleLevel::renumber(const std::vector<TFrameId>& fids) {TImageCache* ic = TImageCache::instance();std::map<TFrameId, TFrameId>::iterator jt;-{- for (i = 0, jt = table.begin(); jt != table.end(); ++jt, ++i) {+ int i = 0;+ for (jt = table.begin(); jt != table.end(); ++jt, ++i) {std::string Id = getImageId(jt->first);ImageLoader::BuildExtData extData(this, jt->first);TImageP img = im->getImage(Id, ImageManager::none, &extData);@@ -2265,7 +2115,8 @@ void TXshSimpleLevel::renumber(const std::vector<TFrameId>& fids) {ic->remap("^icon:" + std::to_string(i), getIconId(jt->first));}- for (i = 0, jt = table.begin(); jt != table.end(); ++jt, ++i) {+ i = 0;+ for (jt = table.begin(); jt != table.end(); ++jt, ++i) {std::string Id = getImageId(jt->second);im->rebind("^" + std::to_string(i), Id);ic->remap(getIconId(jt->second), "^icon:" + std::to_string(i));@@ -2274,22 +2125,26 @@ void TXshSimpleLevel::renumber(const std::vector<TFrameId>& fids) {}if (getType() == PLI_XSHLEVEL) {- for (i = 0, jt = table.begin(); jt != table.end(); ++jt, ++i) {+ int i = 0;+ for (jt = table.begin(); jt != table.end(); ++jt, ++i) {const std::string& id = rasterized(getImageId(jt->first));if (im->isBound(id)) im->rebind(id, rasterized("^" + std::to_string(i)));}- for (i = 0, jt = table.begin(); jt != table.end(); ++jt, ++i) {+ i = 0;+ for (jt = table.begin(); jt != table.end(); ++jt, ++i) {const std::string& id = rasterized("^" + std::to_string(i));if (im->isBound(id)) im->rebind(id, rasterized(getImageId(jt->second)));}}if (getType() & FULLCOLOR_TYPE) {- for (i = 0, jt = table.begin(); jt != table.end(); ++jt, ++i) {+ int i = 0;+ for (jt = table.begin(); jt != table.end(); ++jt, ++i) {const std::string& id = filled(getImageId(jt->first));if (im->isBound(id)) im->rebind(id, filled("^" + std::to_string(i)));}- for (i = 0, jt = table.begin(); jt != table.end(); ++jt, ++i) {+ i = 0;+ for (jt = table.begin(); jt != table.end(); ++jt, ++i) {const std::string& id = filled("^" + std::to_string(i));if (im->isBound(id)) im->rebind(id, filled(getImageId(jt->second)));}@@ -2307,7 +2162,6 @@ void TXshSimpleLevel::copyFiles(const TFilePath& dst, const TFilePath& src) {TSystem::touchParentDir(dst);TSystem::copyFileOrLevel_throw(dst, src);if (dst.getType() == "tlv") {- // Copy the level paletteTFilePath srcPltPath =src.getParentDir() + TFilePath(src.getWideName() + L".tpl");if (TFileStatus(srcPltPath).doesExist())@@ -2316,7 +2170,6 @@ void TXshSimpleLevel::copyFiles(const TFilePath& dst, const TFilePath& src) {srcPltPath, true);}if (dst.getType() == "tzp" || dst.getType() == "tzu") {- // Copy the level paletteTFilePath srcPltPath =src.getParentDir() + TFilePath(src.getWideName() + L".plt");if (TFileStatus(srcPltPath).doesExist())@@ -2365,12 +2218,10 @@ void TXshSimpleLevel::removeFiles(const TFilePath& fp) {if (TFileStatus(tpl).doesExist()) TSystem::moveFileToRecycleBin(tpl);}- // Delete ALL hook files (ie from every Toonz version)const QStringList& hookFiles = TXshSimpleLevel::getHookFiles(fp);-- int f, fCount = hookFiles.size();- for (f = 0; f != fCount; ++f)- TSystem::moveFileToRecycleBin(TFilePath(hookFiles[f].toStdWString()));+ for (const auto& hookFile : hookFiles) {+ TSystem::moveFileToRecycleBin(TFilePath(hookFile.toStdWString()));+ }TFilePath files = fp.getParentDir() + (fp.getName() + "_files");if (TFileStatus(files).doesExist() && TFileStatus(files).isDirectory())@@ -2385,17 +2236,8 @@ void TXshSimpleLevel::getFiles(const TFilePath& fp, TFilePathSet& fpset) {if (TFileStatus(tpl).doesExist()) fpset.push_back(tpl);}- // Store the hooks file if any (NOTE: there could be more than one hooks- // file. I'm retaining the behavior I've seen, but was this really intended?- // Shouldn't we return ALL the hooks files?)const TFilePath& hookFile = getExistingHookFile(fp);if (!hookFile.isEmpty()) fpset.push_back(hookFile);-- // Needed for TAB Manga & Kids and not used in Toonz-- // TFilePath files = fp.getParentDir() + (fp.getName() + "_files");- // if(TFileStatus(files).doesExist() && TFileStatus(files).isDirectory())- // TSystem::rmDirTree(files);}//-----------------------------------------------------------------------------@@ -2417,14 +2259,6 @@ void TXshSimpleLevel::setCompatibilityMasks(int writeMask, int neededMask,//-----------------------------------------------------------------------------TFilePath TXshSimpleLevel::getHookPath(const TFilePath& path) {- // Translates: levelName..ext into levelName_hooks..ext.xml- // levelName.ext into levelName_hooks.ext.xml-- // Observe that retaining the original level extension IS IMPORTANT, as it- // ensures- // the UNICITY of the association between a level path and its hook path (ie- // levels test..png and test..tif have separate hook files).-return TFilePath(path.withName(path.getName() + "_hooks").getWideString() +L".xml");}@@ -2436,47 +2270,43 @@ QStringList TXshSimpleLevel::getHookFiles(const TFilePath& decodedLevelPath) {QDir levelDir(QString::fromStdWString(dirPath.getWideString()));QStringList hookFileFilter(- QString::fromStdWString( // We have to scan for files of the- decodedLevelPath.getWideName() +- L"_hooks*.xml")); // form levelName_hooks*.xml to- // retain backward compatibility- return levelDir.entryList( //- hookFileFilter,- QDir::Files | QDir::NoDotAndDotDot, // Observe that we cleverly sort by- QDir::Time); // mod date :)+ QString::fromStdWString(decodedLevelPath.getWideName() + L"_hooks*.xml"));++ return levelDir.entryList(hookFileFilter, QDir::Files | QDir::NoDotAndDotDot,+ QDir::Time);}//-----------------------------------------------------------------------------TFilePath TXshSimpleLevel::getExistingHookFile(const TFilePath& decodedLevelPath) {- static const int pCount = 3;- static const QRegExp pattern[pCount] = {- // Prioritized in this order- QRegExp(".*\\.\\.?.+\\.xml$"), // whatever.(.)ext.xml- QRegExp(".*\\.xml$"), // whatever.xml- QRegExp(".*\\.\\.?xml$") // whatever.(.)xml+ static const int pCount = 3;+ static const QRegularExpression pattern[pCount] = {+ QRegularExpression(R"(.*\.\.?.+\.xml$)"), // whatever.(.)ext.xml+ QRegularExpression(R"(.*\.xml$)"), // whatever.xml+ QRegularExpression(R"(.*\.\.?xml$)") // whatever.(.)xml};struct locals {static inline int getPattern(const QString& fp) {- for (int p = 0; p != pCount; ++p)- if (pattern[p].exactMatch(fp)) return p;+ for (int p = 0; p != pCount; ++p) {+ if (pattern[p].match(fp).hasMatch()) return p;+ }return -1;}- }; // locals+ };const QStringList& hookFiles = getHookFiles(decodedLevelPath);if (hookFiles.empty()) return TFilePath();- // Return the hook file with the most recent (smallest) identified- // regexp pattern- int fPattern, p = pCount, h = -1;+ int fPattern = 0, p = pCount, h = -1;- int f, fCount = hookFiles.size();- for (f = 0; f != fCount; ++f) {+ for (int f = 0; f < hookFiles.size(); ++f) {fPattern = locals::getPattern(hookFiles[f]);- if (fPattern < p) p = fPattern, h = f;+ if (fPattern < p) {+ p = fPattern;+ h = f;+ }}assert(h >= 0);@@ -2491,11 +2321,9 @@ TRectD TXshSimpleLevel::getBBox(const TFrameId& fid) const {TRectD bbox;double dpiX = Stage::inch, dpiY = dpiX;- // Get the frame bbox in image coordinatesswitch (getType()) {case PLI_XSHLEVEL:case MESH_XSHLEVEL: {- // Load the image and extract its bbox forciblyTImageP img = getFrame(fid, false);if (!img) return TRectD();@@ -2507,7 +2335,6 @@ TRectD TXshSimpleLevel::getBBox(const TFrameId& fid) const {}default: {- // Raster case: retrieve the image info from the ImageManagerconst std::string& imageId = getImageId(fid);const TImageInfo* info =@@ -2525,13 +2352,12 @@ TRectD TXshSimpleLevel::getBBox(const TFrameId& fid) const {}}- // Get the frame's dpi and translate the bbox to inch coordinatesreturn TScale(1.0 / dpiX, 1.0 / dpiY) * bbox;}+//-----------------------------------------------------------------------------+bool TXshSimpleLevel::isFrameReadOnly(TFrameId fid) {- // For Raster and mesh files, check to see if files are marked as read-only- // at the OS levelif (getType() == OVL_XSHLEVEL || getType() == TZI_XSHLEVEL ||getType() == MESH_XSHLEVEL) {if (getProperties()->isStopMotionLevel()) return true;@@ -2544,7 +2370,6 @@ bool TXshSimpleLevel::isFrameReadOnly(TFrameId fid) {return !fs.isWritable();}- // If Level is marked read only, check for editable framesif (m_isReadOnly && !m_editableRange.empty() &&m_editableRange.count(fid) != 0)return false;