OpenToonz - An open-source full-featured 2D animation creation software
C
Harden autosave save path
Rodney4c0e5848ea61
diff --git a/toonz/sources/common/tsystem/tsystem.cpp b/toonz/sources/common/tsystem/tsystem.cppindex c18b5c147..1d1f57cff 100644--- a/toonz/sources/common/tsystem/tsystem.cpp+++ b/toonz/sources/common/tsystem/tsystem.cpp@@ -4,6 +4,7 @@#include <set>#include <atomic>+#include <cstdio>#include "tfilepath_io.h"#include "tconvert.h"@@ -28,6 +29,7 @@#include <QHostInfo>#ifdef _WIN32+#include <windows.h>#include <shlobj.h>#include <shellapi.h>#include <winnt.h>@@ -456,6 +458,29 @@ void TSystem::renameFile(const TFilePath &dst, const TFilePath &src,//------------------------------------------------------------+void TSystem::replaceFile(const TFilePath &dst,+ const TFilePath &src) {+ if (dst.isEmpty())+ throw TSystemException(dst, "Destination path is empty!");++ if (dst == src) return;++#ifdef _WIN32+ const std::wstring srcPath = src.getWideString();+ const std::wstring dstPath = dst.getWideString();+ if (!MoveFileExW(srcPath.c_str(), dstPath.c_str(),+ MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH))+ throw TSystemException(dst, "can't replace file!");+#else+ const QByteArray srcPath = QFile::encodeName(toQString(src));+ const QByteArray dstPath = QFile::encodeName(toQString(dst));+ if (std::rename(srcPath.constData(), dstPath.constData()) != 0)+ throw TSystemException(dst, "can't replace file!");+#endif+}++//------------------------------------------------------------+// handle errors with GetLastError?void TSystem::deleteFile(const TFilePath &fp) {if (!QFile::remove(toQString(fp)))diff --git a/toonz/sources/include/toonz/sceneresources.h b/toonz/sources/include/toonz/sceneresources.hindex 92c6e3c54..e3a1fe98b 100644--- a/toonz/sources/include/toonz/sceneresources.h+++ b/toonz/sources/include/toonz/sceneresources.h@@ -101,7 +101,7 @@ Destroys the SceneResource object.//! save the resource to the disk using the updated path. Note: it calls//! SceneResource::updatePath(fp) before- virtual void save() = 0;+ virtual bool save() = 0;//! change the resource internal path, according to the scenevirtual void updatePath() = 0;//! change back the resource internal path to its original value@@ -144,7 +144,7 @@ Constructs SceneLevel with \b ToonzScene \b scene and \b TXshPaletteLevel \b pl./*!Save simple level in right path.*/- void save() override;+ bool save() override;/*!Update simple level path.*/@@ -190,7 +190,7 @@ Constructs SceneLevel with \b ToonzScene \b scene and \b TXshSimpleLevel \b sl./*!Save simple level in right path.*/- void save() override;+ bool save() override;/*!Update simple level path.*/@@ -234,7 +234,7 @@ sl./*!Save sound column in right path.*/- void save() override;+ bool save() override;/*!Update sound track path.*/@@ -249,7 +249,7 @@ Set sound track path to old path.}bool isDirty() override { return false; }- QStringList getResourceName() override { return QStringList(); }+ QStringList getResourceName() override;};//=============================================================================@@ -298,7 +298,7 @@ old save path.If pointer to subXsheet is different from zero save only resourcesused in subXsheet.*/- void save(const TFilePath newScenePath);+ bool save(const TFilePath newScenePath, bool showWarnings = true);/*!Update all resources paths.diff --git a/toonz/sources/include/toonz/toonzscene.h b/toonz/sources/include/toonz/toonzscene.hindex 73e51f896..e0e90dd2d 100644--- a/toonz/sources/include/toonz/toonzscene.h+++ b/toonz/sources/include/toonz/toonzscene.h@@ -100,9 +100,9 @@ public:void clear(); //!< Clears the scene.void save(- const TFilePath &path,- TXsheet *subxsheet = 0); //!< Saves the scene (or a sub-xsheet) at the- //! specified path.+ const TFilePath &path, TXsheet *subxsheet = 0,+ bool saveSceneIcon = true); //!< Saves the scene (or a sub-xsheet) at the+ //! specified path.void loadTnzFile(const TFilePath &path); //!< Loads scene data from file, \a excluding the//! associated project and the scene resources.diff --git a/toonz/sources/include/tsystem.h b/toonz/sources/include/tsystem.hindex 75bb0c5ca..98cb8ab4b 100644--- a/toonz/sources/include/tsystem.h+++ b/toonz/sources/include/tsystem.h@@ -159,6 +159,9 @@ DVAPI void copyFile(const TFilePath &dst, const TFilePath &src,bool overwrite = true);DVAPI void renameFile(const TFilePath &dst, const TFilePath &src,bool overwrite = true);+// Atomically replace dst with src where supported. On failure the+// existing destination is left in place.+DVAPI void replaceFile(const TFilePath &dst, const TFilePath &src);DVAPI void deleteFile(const TFilePath &dst);DVAPI void hideFile(const TFilePath &dst);DVAPI void moveFileToRecycleBin(const TFilePath &fp);diff --git a/toonz/sources/toonz/iocommand.cpp b/toonz/sources/toonz/iocommand.cppindex c34f290f3..7565fabf0 100644--- a/toonz/sources/toonz/iocommand.cpp+++ b/toonz/sources/toonz/iocommand.cpp@@ -107,6 +107,22 @@ TXshLevel *getLevelByPath(ToonzScene *scene, const TFilePath &actualPath);// forward declarationclass RenderingSuspender;+class SaveInProgressGuard {+ bool m_acquired;++public:+ SaveInProgressGuard()+ : m_acquired(!TApp::instance()->isSaveInProgress()) {+ if (m_acquired) TApp::instance()->setSaveInProgress(true);+ }++ ~SaveInProgressGuard() {+ if (m_acquired) TApp::instance()->setSaveInProgress(false);+ }++ bool acquired() const { return m_acquired; }+};+//===========================================================================// class ResourceImportDialog//---------------------------------------------------------------------------@@ -1406,20 +1422,23 @@ bool IoCmd::saveScene(const TFilePath &path, int flags) {TFilePath scenePath = path;if (scenePath.getType() == "") scenePath = scenePath.withType("tnz");if (scenePath.getType() != "tnz") {- error(- QObject::tr("%1 has an invalid file extension.").arg(toQString(path)));+ if (!isAutosave)+ error(QObject::tr("%1 has an invalid file extension.")+ .arg(toQString(path)));return false;}TFileStatus dirStatus(scenePath.getParentDir());if (!(dirStatus.doesExist() && dirStatus.isWritable())) {- error(QObject::tr("%1 is an invalid path.")- .arg(toQString(scenePath.getParentDir())));+ if (!isAutosave)+ error(QObject::tr("%1 is an invalid path.")+ .arg(toQString(scenePath.getParentDir())));return false;}- // notify user if the scene will be saved including any "broken" expression- // reference- if (!ExpressionReferenceManager::instance()->askIfParamIsIgnoredOnSave(+ // Autosave must not enter a modal decision state. Broken-expression+ // references are still reported when the user explicitly saves.+ if (!isAutosave &&+ !ExpressionReferenceManager::instance()->askIfParamIsIgnoredOnSave(saveSubxsheet))return false;@@ -1439,6 +1458,9 @@ bool IoCmd::saveScene(const TFilePath &path, int flags) {TXsheet *xsheet = 0;if (saveSubxsheet) xsheet = TApp::instance()->getCurrentXsheet()->getXsheet();+ SaveInProgressGuard saveGuard;+ if (!saveGuard.acquired()) return false;+// Automatically remove unused levelsif (!saveSubxsheet && !isAutosave &&Preferences::instance()->isAutoRemoveUnusedLevelsEnabled()) {@@ -1483,7 +1505,7 @@ bool IoCmd::saveScene(const TFilePath &path, int flags) {TFilePath oldFullPath = scene->decodeFilePath(scene->getScenePath());TFilePath newFullPath = scene->decodeFilePath(scenePath);- QApplication::setOverrideCursor(Qt::WaitCursor);+ if (!isAutosave) QApplication::setOverrideCursor(Qt::WaitCursor);if (app->getCurrentScene()->getDirtyFlag())scene->getContentHistory(true)->modifiedNow();@@ -1511,18 +1533,18 @@ bool IoCmd::saveScene(const TFilePath &path, int flags) {cp->assign(&CleanupParameters::GlobalParameters, false);}- // Must wait for current save to finish, just in case- while (TApp::instance()->isSaveInProgress());-- TApp::instance()->setSaveInProgress(true);+ bool saveSucceeded = true;try {- scene->save(scenePath, xsheet);+ scene->save(scenePath, xsheet, !isAutosave);} catch (const TSystemException &se) {- DVGui::warning(QString::fromStdWString(se.getMessage()));+ if (!isAutosave)+ DVGui::warning(QString::fromStdWString(se.getMessage()));+ saveSucceeded = false;} catch (...) {- DVGui::error(QObject::tr("Couldn't save %1").arg(toQString(scenePath)));+ if (!isAutosave)+ DVGui::error(QObject::tr("Couldn't save %1").arg(toQString(scenePath)));+ saveSucceeded = false;}- TApp::instance()->setSaveInProgress(false);if (!isAutosave) {// Restore the cleanup settings without replacing the palette object.@@ -1534,6 +1556,11 @@ bool IoCmd::saveScene(const TFilePath &path, int flags) {// in case of saving subxsheet, revert the level paths after savingrevertOrgLevelPaths();+ if (!saveSucceeded) {+ if (!isAutosave) QApplication::restoreOverrideCursor();+ return false;+ }+if (!overwrite && !saveSubxsheet)app->getCurrentScene()->notifyNameSceneChange();FileBrowser::refreshFolder(scenePath.getParentDir());@@ -1556,7 +1583,7 @@ bool IoCmd::saveScene(const TFilePath &path, int flags) {->getName().getName()));- QApplication::restoreOverrideCursor();+ if (!isAutosave) QApplication::restoreOverrideCursor();bool exist = TSystem::doesExistFileOrLevel(scene->decodeFilePath(scene->getScenePath()));@@ -1575,6 +1602,8 @@ bool IoCmd::saveScene(int flags) {TApp::instance()->getCurrentSelection()->getSelection();ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();if (scene->isUntitled()) {+ if (flags & AUTO_SAVE) return false;+static SaveSceneAsPopup *popup = 0;if (!popup) popup = new SaveSceneAsPopup();int ret = popup->exec();@@ -1739,39 +1768,43 @@ bool IoCmd::saveAll(int flags) {// try to save as much as possible// if anything is wrong, return false+ bool isAutosave = (flags & AUTO_SAVE) != 0;QMainWindow *parent = TApp::instance()->getMainWindow();- QLabel *Label = new QLabel("Saving...", parent);- Label->setStyleSheet(- "font-size: 20px;"- "background-color: black; color: white; "- "font-weight: bold; padding: 5px;");- Label->adjustSize();- QPoint pos = parent->rect().bottomRight();- Label->move(pos.x() - Label->width() - 40, pos.y() - Label->height() - 30);- Label->show();-- // NOTE: saveScene already check saveInProgress- bool result = saveScene(flags);-- saveNonSceneFiles();-- // End Label Notice- if (result) {- Label->setText("Saved All");- Label->setStyleSheet(- "font-size: 20px;"- "background-color: black; color: green; "- "font-weight: bold; padding: 5px;");- } else {- Label->setText("Save All Failed");+ QLabel *Label = nullptr;+ if (!isAutosave) {+ Label = new QLabel("Saving...", parent);Label->setStyleSheet("font-size: 20px;"- "background-color: black; color: red; "+ "background-color: black; color: white; ""font-weight: bold; padding: 5px;");+ Label->adjustSize();+ QPoint pos = parent->rect().bottomRight();+ Label->move(pos.x() - Label->width() - 40,+ pos.y() - Label->height() - 30);+ Label->show();+ }++ bool sceneSaved = saveScene(flags);+ bool resourcesSaved = saveNonSceneFiles(flags);+ bool result = sceneSaved && resourcesSaved;++ if (Label) {+ if (result) {+ Label->setText("Saved All");+ Label->setStyleSheet(+ "font-size: 20px;"+ "background-color: black; color: green; "+ "font-weight: bold; padding: 5px;");+ } else {+ Label->setText("Save All Failed");+ Label->setStyleSheet(+ "font-size: 20px;"+ "background-color: black; color: red; "+ "font-weight: bold; padding: 5px;");+ }+ Label->adjustSize();+ QTimer::singleShot(2500, Label, &QLabel::deleteLater);}- Label->adjustSize();-- QTimer::singleShot(2500, Label, &QLabel::deleteLater);return result;}@@ -1779,23 +1812,34 @@ bool IoCmd::saveAll(int flags) {// IoCmd::saveNonSceneFiles()//---------------------------------------------------------------------------// This command should not change any content in scene!-void IoCmd::saveNonSceneFiles() {+bool IoCmd::saveNonSceneFiles(int flags) {// try to save non scene files+ bool isAutosave = (flags & AUTO_SAVE) != 0;TApp *app = TApp::instance();ToonzScene *scene = app->getCurrentScene()->getScene();SceneResources resources(scene, 0);- // Must wait for current save to finish, just in case- while (TApp::instance()->isSaveInProgress());+ SaveInProgressGuard saveGuard;+ if (!saveGuard.acquired()) {+ app->getCurrentScene()->setDirtyFlag(true);+ return false;+ }++ bool result = false;+ try {+ result = resources.save(scene->getScenePath(), !isAutosave);+ if (result) resources.updatePaths();+ } catch (...) {+ if (!isAutosave)+ DVGui::error(QObject::tr("Couldn't save all scene resources."));+ }- TApp::instance()->setSaveInProgress(true);- resources.save(scene->getScenePath());- TApp::instance()->setSaveInProgress(false);- resources.updatePaths();+ if (!result) app->getCurrentScene()->setDirtyFlag(true);// for update title barapp->getCurrentLevel()->notifyLevelTitleChange();app->getCurrentPalette()->notifyPaletteTitleChanged();+ return result;}//===========================================================================diff --git a/toonz/sources/toonz/iocommand.h b/toonz/sources/toonz/iocommand.hindex f23e3c3ef..fb478fc2b 100644--- a/toonz/sources/toonz/iocommand.h+++ b/toonz/sources/toonz/iocommand.h@@ -264,7 +264,7 @@ bool saveLevel(TXshSimpleLevel *sl);bool saveAll(int flags = 0);-void saveNonSceneFiles();+bool saveNonSceneFiles(int flags = 0);bool saveSound(const TFilePath &fp, TXshSoundLevel *sc, bool overwrite);bool saveSound(TXshSoundLevel *sc);diff --git a/toonz/sources/toonz/mainwindow.cpp b/toonz/sources/toonz/mainwindow.cppindex 38f77e9e9..0db405fee 100644--- a/toonz/sources/toonz/mainwindow.cpp+++ b/toonz/sources/toonz/mainwindow.cpp@@ -1021,8 +1021,7 @@ Room *MainWindow::getCurrentRoom() const {//-----------------------------------------------------------------------------void MainWindow::onUndo() {- // Must wait for current save to finish, just in case- while (TApp::instance()->isSaveInProgress());+ if (TApp::instance()->isSaveInProgress()) return;ToolHandle *toolH = TApp::instance()->getCurrentTool();@@ -1036,8 +1035,7 @@ void MainWindow::onUndo() {//-----------------------------------------------------------------------------void MainWindow::onRedo() {- // Must wait for current save to finish, just in case- while (TApp::instance()->isSaveInProgress());+ if (TApp::instance()->isSaveInProgress()) return;bool ret = TUndoManager::manager()->redo();if (!ret) DVGui::error(QObject::tr("No more Redo operations available."));diff --git a/toonz/sources/toonz/tapp.cpp b/toonz/sources/toonz/tapp.cppindex 4497fef59..8d6282a35 100644--- a/toonz/sources/toonz/tapp.cpp+++ b/toonz/sources/toonz/tapp.cpp@@ -711,7 +711,7 @@ void TApp::autosave() {} else if (pref->isAutosaveSceneEnabled()) {IoCmd::saveScene(IoCmd::AUTO_SAVE);} else if (pref->isAutosaveOtherFilesEnabled()) {- IoCmd::saveNonSceneFiles();+ IoCmd::saveNonSceneFiles(IoCmd::AUTO_SAVE);}}diff --git a/toonz/sources/toonzlib/sceneresources.cpp b/toonz/sources/toonzlib/sceneresources.cppindex 3cb58e50e..ec86f1fb0 100644--- a/toonz/sources/toonzlib/sceneresources.cpp+++ b/toonz/sources/toonzlib/sceneresources.cpp@@ -23,6 +23,19 @@namespace {//=============================================================================+class ScenePathRestorer {+ ToonzScene *m_scene;+ TFilePath m_oldPath;++public:+ ScenePathRestorer(ToonzScene *scene, const TFilePath &oldPath)+ : m_scene(scene), m_oldPath(oldPath) {}++ ~ScenePathRestorer() { m_scene->setScenePath(m_oldPath, false); }+};++//-----------------------------------------------------------------------------+// se path e' della forma +folder/<oldSavePath>/name.type// allora sostituisce oldSavePath con newSavePath e ritorna true@@ -206,8 +219,9 @@ SceneLevel::SceneLevel(ToonzScene *scene, TXshSimpleLevel *sl)//------------------------------------------------------------------------------void SceneLevel::save() {- TFilePath fp = m_oldPath;+bool SceneLevel::save() {+ bool saveSucceeded = true;+ TFilePath fp = m_oldPath;SceneResource::updatePath(fp);TFilePath actualFp = m_scene->decodeFilePath(fp);actualFp = restorePsdPath(actualFp);@@ -226,10 +240,7 @@ void SceneLevel::save() {(!m_sl->getPalette() ||(m_sl->getPalette() &&m_sl->getPalette()->getDirtyFlag() == false))) {- try {- TXshSimpleLevel::copyFiles(actualFp, oldActualPath);- } catch (...) {- }+ TXshSimpleLevel::copyFiles(actualFp, oldActualPath);// Must NOT KEEP FRAMES, it generate a level frames bind necessary to// imageBuilder path refresh.m_sl->setPath(fp, false);@@ -284,6 +295,7 @@ void SceneLevel::save() {TSystem::copyFile(unpaintedPalettePath, oldUnpaintedPalettePath);}} catch (...) {+ saveSucceeded = false;}}fp = m_oldScannedPath;@@ -298,9 +310,11 @@ void SceneLevel::save() {m_sl->clearFrames();m_sl->load();} catch (...) {+ saveSucceeded = false;}}}+ return saveSucceeded;}//-----------------------------------------------------------------------------@@ -359,6 +373,8 @@ QStringList SceneLevel::getResourceName() {} else if (levelIsDirty)ret << string;+ if (ret.isEmpty())+ ret << QString::fromStdString(m_sl->getPath().getLevelName());return ret;}@@ -376,7 +392,7 @@ ScenePalette::ScenePalette(ToonzScene *scene, TXshPaletteLevel *pl)//------------------------------------------------------------------------------void ScenePalette::save() {+bool ScenePalette::save() {assert(m_oldPath != TFilePath());TFilePath fp = m_oldPath;SceneResource::updatePath(fp);@@ -388,8 +404,10 @@ void ScenePalette::save() {TSystem::copyFile(actualFp, m_oldActualPath);}m_pl->save(); // actualFp non so perche' era cosi'+ return true;} catch (...) {TLogger::error() << "Can't save " << actualFp;+ return false;}}@@ -431,7 +449,7 @@ SceneSound::SceneSound(ToonzScene *scene, TXshSoundLevel *sl)//------------------------------------------------------------------------------void SceneSound::save() {+bool SceneSound::save() {assert(m_oldPath != TFilePath());TFilePath fp = m_oldPath;SceneResource::updatePath(fp);@@ -443,9 +461,10 @@ void SceneSound::save() {} else if (actualFp != m_oldActualPath) {TSystem::copyFile(actualFp, m_oldActualPath);}+ return true;} catch (...) {- DVGui::warning(QObject::tr("Can't save") +- QString::fromStdWString(L": " + actualFp.getLevelNameW()));+ TLogger::error() << "Can't save " << actualFp;+ return false;}}@@ -461,6 +480,13 @@ void SceneSound::updatePath() {void SceneSound::rollbackPath() { m_sl->setPath(m_oldPath); }+//-----------------------------------------------------------------------------++QStringList SceneSound::getResourceName() {+ return QStringList(+ QString::fromStdString(m_sl->getPath().getLevelName()));+}+//=============================================================================//// SceneResources@@ -511,20 +537,28 @@ void SceneResources::getResources() {//------------------------------------------------------------------------------void SceneResources::save(const TFilePath newScenePath) {+bool SceneResources::save(const TFilePath newScenePath,+ bool showWarnings) {TFilePath oldScenePath = m_scene->getScenePath();+ ScenePathRestorer restorePath(m_scene, oldScenePath);// TODO: The save path of resources should not be decided by changing scene's property,// refactor and remove setScenePathm_scene->setScenePath(newScenePath, false);- bool failedSave = false;++ bool saveSucceeded = true;+ QStringList failedList;for (int i = 0; i < (int)m_resources.size(); i++) {- m_resources[i]->save();+ if (!m_resources[i]->save()) {+ saveSucceeded = false;+ failedList << m_resources[i]->getResourceName();+ }}- QStringList failedList;getDirtyResources(failedList);+ if (!failedList.isEmpty()) saveSucceeded = false;- if (!failedList.isEmpty()) { // didn't save for some reason+ if (showWarnings && !saveSucceeded) {+ failedList.removeDuplicates();// show up to 5 itemsint extraCount = failedList.count() - 5;if (extraCount > 0) {@@ -535,7 +569,7 @@ void SceneResources::save(const TFilePath newScenePath) {DVGui::warning(QObject::tr("Failed to save the following resources:\n") +" " + failedList.join("\n "));}- m_scene->setScenePath(oldScenePath, false);+ return saveSucceeded;}//-----------------------------------------------------------------------------diff --git a/toonz/sources/toonzlib/toonzscene.cpp b/toonz/sources/toonzlib/toonzscene.cppindex 3ca15c1c1..d6b82856d 100644--- a/toonz/sources/toonzlib/toonzscene.cpp+++ b/toonz/sources/toonzlib/toonzscene.cpp@@ -580,7 +580,8 @@ public://------------------------------------------------------------------------------void ToonzScene::save(const TFilePath &fp, TXsheet *subxsh) {+void ToonzScene::save(const TFilePath &fp, TXsheet *subxsh,+ bool saveSceneIcon) {TFilePath oldScenePath = getScenePath();TFilePath newScenePath = fp;@@ -612,7 +613,7 @@ void ToonzScene::save(const TFilePath &fp, TXsheet *subxsh) {// TSystem::touchFile(scenePath);TSystem::touchFile(scenePathTemp);- makeSceneIcon(this);+ if (saveSceneIcon) makeSceneIcon(this);// TOStream os(scenePath, compressionEnabled);// TOStream os(scenePath, false);@@ -683,7 +684,7 @@ void ToonzScene::save(const TFilePath &fp, TXsheet *subxsh) {}if (TFileStatus(scenePathTemp).doesExist())- TSystem::renameFile(scenePath, scenePathTemp, true);+ TSystem::replaceFile(scenePath, scenePathTemp);if (subxsh) {setScenePath(oldScenePath);