18#include "filemanager.h"
22#include <QVersionNumber>
24#include "fileformat.h"
26#include "layercamera.h"
31 srand(
static_cast<uint
>(time(
nullptr)));
37 dd <<
"\n[Project LOAD diagnostics]\n";
41 handleOpenProjectError(Status::FILE_NOT_FOUND, dd);
47 std::unique_ptr<Object> obj(
new Object);
48 obj->setFilePath(sFileName);
49 obj->createWorkingDir();
55 bool isArchive = isArchiveFormat(sFileName);
57 QString fileFormat =
"Project format: %1";
60 dd << fileFormat.
arg(
".pcl");
62 strMainXMLFile = sFileName;
63 strDataFolder = strMainXMLFile +
"." + PFF_OLD_DATA_DIR;
67 QString workingDirPath = obj->workingDir();
69 dd <<
QString(
"Working dir: %1").
arg(workingDirPath);
70 dd << fileFormat.
arg(
".pclx");
72 Status sanityCheck = MiniZ::sanityCheck(sFileName);
75 if (!sanityCheck.ok()) {
76 dd.collect(sanityCheck.details());
77 dd <<
"\nError: Unable to extract project, miniz sanity check failed.";
78 handleOpenProjectError(Status::ERROR_INVALID_XML_FILE, dd);
81 Status unzipStatus = unzip(sFileName, workingDirPath);
82 dd.collect(unzipStatus.details());
84 if(unzipStatus.ok()) {
85 dd <<
QString(
"Unzipped at: %1 ").
arg(workingDirPath);
87 dd <<
QString(
"Error: Unzipping failed: %1 ").
arg(workingDirPath);
88 handleOpenProjectError(Status::ERROR_INVALID_XML_FILE, dd);
93 strMainXMLFile =
QDir(workingDirPath).
filePath(PFF_XML_FILE_NAME);
94 strDataFolder =
QDir(workingDirPath).
filePath(PFF_DATA_DIR);
97 obj->setDataDir(strDataFolder);
98 obj->setMainXMLFile(strMainXMLFile);
101 mMaxProgressValue = totalFileCount;
102 emit progressRangeChanged(mMaxProgressValue);
104 QFile file(strMainXMLFile);
107 dd <<
"Error: No main XML exists!";
108 handleOpenProjectError(Status::ERROR_INVALID_XML_FILE, dd);
113 dd <<
"Error: Main XML file is read only!";
114 handleOpenProjectError(Status::ERROR_FILE_CANNOT_OPEN, dd);
118 dd <<
"Main XML exists: Yes";
123 FILEMANAGER_LOG(
"Couldn't open the main XML file");
124 dd <<
"Error: Unable to parse or open the main XML file";
125 handleOpenProjectError(Status::ERROR_INVALID_XML_FILE, dd);
130 if (!(type.
name() ==
"PencilDocument" || type.
name() ==
"MyObject"))
132 FILEMANAGER_LOG(
"Invalid main XML doctype");
134 handleOpenProjectError(Status::ERROR_INVALID_PENCIL_FILE, dd);
141 dd <<
"Error: Main XML root node is null";
142 handleOpenProjectError(Status::ERROR_INVALID_PENCIL_FILE, dd);
146 loadPalette(obj.get());
150 if (root.
tagName() ==
"document")
152 ok = loadObject(obj.get(), root);
154 else if (root.
tagName() ==
"object" || root.
tagName() ==
"MyOject")
156 ok = loadObjectOldWay(obj.get(), root);
162 dd <<
"Error: Issue occurred during object loading";
163 handleOpenProjectError(Status::ERROR_INVALID_PENCIL_FILE, dd);
167 verifyObject(obj.get());
169 return obj.release();
187 if (element.
tagName() ==
"object")
189 ok =
object->loadXML(element, [
this]{ progressForward(); });
190 if (!ok) FILEMANAGER_LOG(
"Failed to Load object");
193 else if (element.
tagName() ==
"editor" || element.
tagName() ==
"projectdata")
195 object->setData(loadProjectData(element));
197 else if (element.
tagName() ==
"version")
202 if (!fileVersion.
isNull())
204 if (appVersion < fileVersion)
206 qWarning() <<
"You are opening a newer project file in an older version of Pencil2D!";
220 return object->loadXML(root, [
this] { progressForward(); });
223bool FileManager::isArchiveFormat(
const QString& fileName)
const
234 dd <<
"\n[Project SAVE diagnostics]\n";
235 dd << (
"file name:" + sFileName);
237 if (
object ==
nullptr)
239 dd <<
"Error: Object parameter is null";
240 return Status(Status::INVALID_ARGUMENT, dd);
243 dd <<
"Error: File name is empty, unable to save.";
244 return Status(Status::INVALID_ARGUMENT, dd,
245 tr(
"Invalid Save Path"),
246 tr(
"The path is empty."));
249 const int totalCount =
object->totalKeyFrameCount();
250 mMaxProgressValue = totalCount + 5;
251 emit progressRangeChanged(mMaxProgressValue);
256 if (fileInfo.isDir())
258 dd <<
"Error: File name must point to a file, not a directory.";
259 return Status(Status::INVALID_ARGUMENT, dd,
260 tr(
"Invalid Save Path"),
261 tr(
"The path (\"%1\") points to a directory.").arg(fileInfo.absoluteFilePath()));
263 QFileInfo parentDirInfo(fileInfo.dir().absolutePath());
264 if (!parentDirInfo.exists())
266 dd <<
QString(
"Error: The parent directory of %1 does not exist").
arg(sFileName);
267 return Status(Status::INVALID_ARGUMENT, dd,
268 tr(
"Invalid Save Path"),
269 tr(
"The directory (\"%1\") does not exist.").arg(parentDirInfo.absoluteFilePath()));
271 if ((fileInfo.exists() && !fileInfo.isWritable()) || !parentDirInfo.isWritable())
273 dd <<
"Error: File name points to a location that is not writable";
274 return Status(Status::INVALID_ARGUMENT, dd,
275 tr(
"Invalid Save Path"),
276 tr(
"The path (\"%1\") is not writable.").arg(fileInfo.absoluteFilePath()));
284 bool isArchive = isArchiveFormat(sFileName);
287 dd << fileFormat.
arg(
".pcl");
289 sMainXMLFile = sFileName;
290 sDataFolder = sMainXMLFile +
"." + PFF_OLD_DATA_DIR;
294 sTempWorkingFolder =
object->workingDir();
296 dd <<
QString(
"Working dir: %1").
arg(sTempWorkingFolder);
297 dd << fileFormat.
arg(
".pclx");
299 Q_ASSERT(
QDir(sTempWorkingFolder).exists());
301 sMainXMLFile =
QDir(sTempWorkingFolder).
filePath(PFF_XML_FILE_NAME);
302 sDataFolder =
QDir(sTempWorkingFolder).
filePath(PFF_OLD_DATA_DIR);
306 if (!dataInfo.exists())
308 QDir dir(sDataFolder);
310 if (!dir.mkpath(sDataFolder))
312 dd <<
QString(
"Error: Unable to create data directory, tried to save to: %1").
arg(dir.absolutePath());
313 return Status(Status::FAIL, dd,
314 tr(
"Cannot Create Data Directory"),
315 tr(
"Failed to create directory \"%1\". Please make sure you have sufficient permissions.").arg(sDataFolder));
318 if (!dataInfo.isDir())
320 dd <<
QString(
"Error: Expected data to be a directory but found %1 instead").
arg(dataInfo.absoluteFilePath());
321 return Status(Status::FAIL,
323 tr(
"Cannot Create Data Directory"),
324 tr(
"\"%1\" is a file. Please delete the file and try again.").arg(dataInfo.absoluteFilePath()));
328 Status stKeyFrames = writeKeyFrameFiles(
object, sDataFolder, filesToZip);
329 dd.collect(stKeyFrames.details());
331 Status stMainXml = writeMainXml(
object, sMainXMLFile, filesToZip);
332 dd.collect(stMainXml.details());
334 Status stPalette = writePalette(
object, sDataFolder, filesToZip);
335 dd.collect(stPalette.details());
337 const bool saveOk = stKeyFrames.ok() && stMainXml.ok() && stPalette.ok();
343 dd <<
"\n[Archiving diagnostics]\n";
344 QString sBackupFile = backupPreviousFile(sFileName);
347 dd <<
QString(
"\nNote: A backup has been made here: %1").
arg(sBackupFile);
351 return Status(Status::FAIL, dd,
352 tr(
"Internal Error"),
353 tr(
"An internal error occurred. The project could not be saved."));
356 dd <<
"Miniz: Zipping...";
357 Status stMiniz = MiniZ::compressFolder(sFileName, sTempWorkingFolder, filesToZip,
"application/x-pencil2d-pclx");
360 dd.collect(stMiniz.details());
361 dd <<
"\nError: Miniz failed to zip project";
362 return Status(Status::ERROR_MINIZ_FAIL, dd,
364 tr(
"An internal error occurred. The project may not have been saved successfully."));
366 dd <<
"Miniz: Zip file saved successfully";
367 Q_ASSERT(stMiniz.ok());
370 dd <<
"Project saved successfully, deleting backup";
371 deleteBackupFile(sBackupFile);
379 return Status(Status::FAIL, dd,
380 tr(
"Internal Error"),
381 tr(
"An internal error occurred. The project may not have been saved successfully."));
387Status FileManager::writeToWorkingFolder(
const Object*
object)
393 const QString dataFolder =
object->dataDir();
394 const QString mainXml =
object->mainXMLFile();
396 Status stKeyFrames = writeKeyFrameFiles(
object, dataFolder, filesWritten);
397 dd.collect(stKeyFrames.details());
399 Status stMainXml = writeMainXml(
object, mainXml, filesWritten);
400 dd.collect(stMainXml.details());
402 Status stPalette = writePalette(
object, dataFolder, filesWritten);
403 dd.collect(stPalette.details());
405 const bool saveOk = stKeyFrames.ok() && stMainXml.ok() && stPalette.ok();
406 const auto errorCode = (saveOk) ? Status::OK : Status::FAIL;
407 return Status(errorCode, dd);
428 extractProjectData(element, data);
441 currentFrameTag.
setAttribute(
"value", data->getCurrentFrame());
446 QColor color = data->getCurrentColor();
455 currentLayerTag.
setAttribute(
"value", data->getCurrentLayer());
476 tagIsLoop.
setAttribute(
"value", data->isLooping() ?
"true" :
"false");
480 tagRangedPlayback.
setAttribute(
"value", data->isRangedPlayback() ?
"true" :
"false");
484 tagMarkInFrame.
setAttribute(
"value", data->getMarkInFrameNumber());
488 tagMarkOutFrame.
setAttribute(
"value", data->getMarkOutFrameNumber());
497 if (strName ==
"currentFrame")
501 else if (strName ==
"currentColor")
508 data.setCurrentColor(
QColor(r, g, b, a));
510 else if (strName ==
"currentLayer")
514 else if (strName ==
"currentView")
523 data.setCurrentView(
QTransform(m11, m12, m21, m22, dx, dy));
525 else if (strName ==
"fps" || strName ==
"currentFps")
529 else if (strName ==
"isLoop")
531 data.setLooping(element.
attribute(
"value",
"false") ==
"true");
533 else if (strName ==
"isRangedPlayback")
535 data.setRangedPlayback((element.
attribute(
"value",
"false") ==
"true"));
537 else if (strName ==
"markInFrame")
539 data.setMarkInFrameNumber(element.
attribute(
"value",
"0").
toInt());
541 else if (strName ==
"markOutFrame")
543 data.setMarkOutFrameNumber(element.
attribute(
"value",
"15").
toInt());
547void FileManager::handleOpenProjectError(Status::ErrorCode error,
const DebugDetails& dd)
549 QString title =
tr(
"Could not open file");
552 "<li><a href=\"https://discuss.pencil2d.org/c/bugs\">Pencil2D Forum</a></li>"
553 "<li><a href=\"https://github.com/pencil2d/pencil/issues/new\">Github</a></li>"
554 "<li><a href=\"https://discord.gg/8FxdV2g\">Discord<\a></li>"
557 if (error == Status::FILE_NOT_FOUND)
559 errorDesc =
tr(
"The file does not exist, so we are unable to open it."
560 "Please check to make sure the path is correct and try again.");
562 else if (error == Status::ERROR_FILE_CANNOT_OPEN)
564 errorDesc =
tr(
"No permission to read the file. "
565 "Please check you have read permissions for this file and try again.");
570 errorDesc =
tr(
"There was an error processing your file. "
571 "This usually means that your project has been at least partially corrupted. "
572 "Try again with a newer version of Pencil2D, "
573 "or try to use a backup file if you have one. "
574 "If you contact us through one of our official channels we may be able to help you."
575 "For reporting issues, the best places to reach us are:");
578 mError =
Status(error, dd, title, errorDesc + contactLinks);
579 removePFFTmpDirectory(mstrLastTempFolder);
582int FileManager::countExistingBackups(
const QString& fileName)
const
585 QDir directory(fileInfo.absoluteDir());
586 const QString& baseFileName = fileInfo.completeBaseName();
589 for (
const QFileInfo &dirFileInfo : directory.entryInfoList(QDir::Filter::Files)) {
590 QString searchFileAbsPath = dirFileInfo.absoluteFilePath();
591 QString searchFileName = dirFileInfo.baseName();
593 bool sameBaseName = baseFileName.
compare(searchFileName) == 0;
594 if (sameBaseName && searchFileAbsPath.
contains(PFF_BACKUP_IDENTIFIER)) {
608 QString baseName = fileInfo.completeBaseName();
610 int backupCount = countExistingBackups(fileName) + 1;
613 QString sBackupFile = baseName +
"." + PFF_BACKUP_IDENTIFIER + countStr +
"." + fileInfo.suffix();
616 bool ok =
QFile::copy(fileInfo.absoluteFilePath(), sBackupFileFullPath);
619 FILEMANAGER_LOG(
"Cannot backup the previous file");
622 return sBackupFileFullPath;
625void FileManager::deleteBackupFile(
const QString& fileName)
633void FileManager::progressForward()
636 emit progressChanged(mCurrentProgress);
639bool FileManager::loadPalette(
Object* obj)
641 FILEMANAGER_LOG(
"Load Palette..");
643 QString paletteFilePath = validateDataPath(PFF_PALETTE_FILE, obj->dataDir());
644 if (paletteFilePath.
isEmpty() || !obj->importPalette(paletteFilePath))
646 obj->loadDefaultPalette();
654 dd <<
"\n[Keyframes WRITE diagnostics]\n";
656 const int numLayers =
object->getLayerCount();
657 dd <<
QString(
"Total layer count: %1").
arg(numLayers);
659 for (
int i = 0; i < numLayers; ++i)
661 Layer* layer =
object->getLayer(i);
662 layer->presave(dataFolder);
665 bool saveLayersOK =
true;
666 for (
int i = 0; i < numLayers; ++i)
668 Layer* layer =
object->getLayer(i);
670 dd <<
QString(
"Layer[%1] = [id=%2, type=%3, name=%4]").
arg(i).
arg(layer->id()).
arg(layer->type()).
arg(layer->name());
672 Status st = layer->save(dataFolder, filesFlushed, [
this] { progressForward(); });
675 saveLayersOK =
false;
676 dd.collect(st.details());
677 dd <<
QString(
"\nError: Failed to save Layer[%1] %2").
arg(i).
arg(layer->name());
683 auto errorCode = (saveLayersOK) ? Status::OK : Status::FAIL;
686 dd <<
"\nAll Layers saved";
688 dd <<
"\nError: Unable to save all layers";
691 return Status(errorCode, dd);
697 dd <<
"\n[XML WRITE diagnostics]\n";
699 QFile file(mainXmlPath);
702 dd <<
QString(
"Error: Failed to open Main XML at: %1, \nReason: %2").
arg(mainXmlPath).
arg(file.errorString());
703 return Status(Status::ERROR_FILE_CANNOT_OPEN, dd);
718 QDomElement projDataXml = saveProjectData(object->data(), xmlDoc);
722 QDomElement objectElement =
object->saveXML(xmlDoc);
730 dd <<
"Writing main xml file...";
732 const int indentSize = 2;
735 xmlDoc.
save(out, indentSize);
738 dd <<
"Done writing main xml file: " << mainXmlPath;
740 filesWritten.
append(mainXmlPath);
741 return Status(Status::OK, dd);
746 const QString paletteFile =
object->savePalette(dataFolder);
750 dd <<
"\nError: Failed to save palette";
751 return Status(Status::FAIL, dd);
753 filesWritten.
append(paletteFile);
760 removePFFTmpDirectory(strUnzipTarget);
762 Status s = MiniZ::uncompressFolder(strZipFile, strUnzipTarget);
765 mstrLastTempFolder = strUnzipTarget;
772 if (!fileInfo.exists())
784 int curLayer = obj->data()->getCurrentLayer();
785 int maxLayer = obj->getLayerCount();
786 if (curLayer >= maxLayer)
788 obj->data()->setCurrentLayer(maxLayer - 1);
792 std::vector<LayerCamera*> camLayers = obj->getLayersByType<
LayerCamera>();
793 if (camLayers.empty())
795 obj->addNewCameraLayer();
803 bool folderExists = pencil2DTempDir.
cd(
"Pencil2D");
809 const QStringList nameFilter(
"*_" PFF_TMP_DECOMPRESS_EXT
"_*");
813 for (
const QString& path : entries)
816 if (isProjectRecoverable(fullPath))
818 qDebug() <<
"Found debris at" << fullPath;
819 recoverables.
append(fullPath);
825bool FileManager::isProjectRecoverable(
const QString& projectFolder)
827 QDir dir(projectFolder);
828 if (!dir.exists()) {
return false; }
831 if (!dir.exists(
"data")) {
return false; }
833 bool ok = dir.cd(
"data");
837 nameFiler <<
"*.png" <<
"*.vec" <<
"*.xml";
840 return (entries.
size() > 0);
843Object* FileManager::recoverUnsavedProject(
QString intermeidatePath)
845 qDebug() <<
"TODO: recover project" << intermeidatePath;
847 QDir projectDir(intermeidatePath);
848 const QString mainXMLPath = projectDir.filePath(PFF_XML_FILE_NAME);
849 const QString dataFolder = projectDir.filePath(PFF_DATA_DIR);
851 std::unique_ptr<Object> object(
new Object);
852 object->setWorkingDir(intermeidatePath);
853 object->setMainXMLFile(mainXMLPath);
854 object->setDataDir(dataFolder);
856 Status st = recoverObject(
object.get());
863 return object.release();
869 bool mainXmlOK =
true;
871 QFile file(object->mainXMLFile());
872 mainXmlOK &= file.exists();
880 mainXmlOK &= (type.
name() ==
"PencilDocument" || type.
name() ==
"MyObject");
883 mainXmlOK &= (!root.
isNull());
886 mainXmlOK &= (!objectTag.
isNull());
888 if (mainXmlOK ==
false)
894 QFile file(object->mainXMLFile());
902 bool ok = loadObject(
object, root);
903 verifyObject(
object);
905 return ok ? Status::OK : Status::FAIL;
911 QDir dataDir(object->dataDir());
914 nameFiler <<
"*.png" <<
"*.vec";
920 for (
const QString& s : entries)
922 int layerIndex = layerIndexFromFilename(s);
925 keyFrameGroups[layerIndex].append(s);
930 const QString mainXMLPath =
object->mainXMLFile();
931 QFile file(mainXMLPath);
934 return Status::ERROR_FILE_CANNOT_OPEN;
944 QDomElement projDataXml = saveProjectData(object->data(), xmlDoc);
951 for (
const int layerIndex : keyFrameGroups.
keys())
958 xmlDoc.
save(fout, 2);
973 const int layerIndex,
976 Q_ASSERT(frames.
length() > 0);
978 Layer::LAYER_TYPE type = frames[0].
endsWith(
".png") ? Layer::BITMAP : Layer::VECTOR;
982 elemLayer.
setAttribute(
"name", recoverLayerName(type, layerIndex));
987 for (
const QString& s : frames)
989 const int framePos = framePosFromFilename(s);
990 if (framePos < 0) {
continue; }
996 if (type == Layer::BITMAP)
1008QString FileManager::recoverLayerName(Layer::LAYER_TYPE type,
int index)
1013 return tr(
"Bitmap Layer %1").
arg(index);
1015 return tr(
"Vector Layer %1").
arg(index);
1017 return tr(
"Sound Layer %1").
arg(index);
1024int FileManager::layerIndexFromFilename(
const QString& filename)
1027 if (tokens.
length() >= 3)
1029 return tokens[0].toInt();
1034int FileManager::framePosFromFilename(
const QString& filename)
1037 if (tokens.
length() >= 3)
1039 return tokens[1].toInt();
Status rebuildMainXML(Object *object)
Create a new main.xml based on the png/vec filenames left in the data folder.
Status rebuildLayerXmlTag(QDomDocument &doc, QDomElement &elemObject, const int layerIndex, const QStringList &frames)
Rebuild a layer xml tag.
bool cd(const QString &dirName)
QStringList entryList(QDir::Filters filters, QDir::SortFlags sort) const const
QString filePath(const QString &fileName) const const
QDomElement createElement(const QString &tagName)
QDomProcessingInstruction createProcessingInstruction(const QString &target, const QString &data)
QDomText createTextNode(const QString &value)
QDomDocumentType doctype() const const
QDomElement documentElement() const const
bool setContent(const QByteArray &data, bool namespaceProcessing, QString *errorMsg, int *errorLine, int *errorColumn)
QString name() const const
QString attribute(const QString &name, const QString &defValue) const const
void setAttribute(const QString &name, const QString &value)
QString tagName() const const
QString text() const const
QDomNode appendChild(const QDomNode &newChild)
QDomNode firstChild() const const
QDomElement firstChildElement(const QString &tagName) const const
bool isNull() const const
QDomNode nextSibling() const const
void save(QTextStream &stream, int indent, QDomNode::EncodingPolicy encodingPolicy) const const
QDomElement toElement() const const
bool copy(const QString &newName)
bool exists() const const
virtual bool open(QIODevice::OpenMode mode) override
void append(const T &value)
bool endsWith(const T &value) const const
QList< Key > keys() const const
const T value(const Key &key, const T &defaultValue) const const
QString tr(const char *sourceText, const char *disambiguation, int n)
QStringList split(const QString &sep, QString::SplitBehavior behavior, Qt::CaseSensitivity cs) const const
QString & append(QChar ch)
QString arg(qlonglong a, int fieldWidth, int base, QChar fillChar) const const
int compare(const QString &other, Qt::CaseSensitivity cs) const const
bool contains(QChar ch, Qt::CaseSensitivity cs) const const
bool isEmpty() const const
QString number(int n, int base)
double toDouble(bool *ok) const const
int toInt(bool *ok, int base) const const
QVersionNumber fromString(const QString &string, int *suffixIndex)
bool isNull() const const